3 * Common Library Functions
9 #define RANDOM_SEED 0xACE55052
10 #define RANDOM_A 0x00731ADE
11 #define RANDOM_C 12345
12 #define RANDOM_SPRUCE 0xf12b039
13 // Jan Feb Mar Apr May Jun Jul Aug Sept Oct Nov Dec
14 const short DAYS_BEFORE[] = {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334};
15 #define UNIX_TO_2K ((30*365*3600*24) + (7*3600*24)) //Normal years + leap years
19 int atoi(const char *string);
20 void itoa(char *buf, Uint64 num, int base, int minLength, char pad);
21 int vsnprintf(char *__s, size_t __maxlen, const char *__format, va_list args);
22 int sprintf(char *__s, const char *__format, ...);
26 int strucmp(const char *Str1, const char *Str2);
27 char *strchr(const char *__s, int __c);
28 int strpos(const char *Str, char Ch);
29 Uint8 ByteSum(void *Ptr, int Size);
30 size_t strlen(const char *__s);
31 char *strcpy(char *__str1, const char *__str2);
32 char *strncpy(char *__str1, const char *__str2, size_t max);
33 int strcmp(const char *str1, const char *str2);
34 int strncmp(const char *str1, const char *str2, size_t num);
35 char *_strdup(const char *File, int Line, const char *Str);
36 char **str_split(const char *__str, char __ch);
37 int strpos8(const char *str, Uint32 Search);
38 int ReadUTF8(Uint8 *str, Uint32 *Val);
39 int WriteUTF8(Uint8 *str, Uint32 Val);
40 int DivUp(int num, int dem);
41 Sint64 timestamp(int sec, int mins, int hrs, int day, int month, int year);
44 int CheckString(char *String);
45 int CheckMem(void *Mem, int NumBytes);
47 int ModUtil_LookupString(char **Array, char *Needle);
48 int ModUtil_SetIdent(char *Dest, char *Value);
50 int UnHex(Uint8 *Dest, size_t DestSize, const char *SourceString);
71 EXPORT(_strdup); // Takes File/Line too
80 EXPORT(ModUtil_LookupString);
81 EXPORT(ModUtil_SetIdent);
89 * \brief Convert a string into an integer
91 int atoi(const char *string)
96 //Log("atoi: (string='%s')", string);
98 // Clear non-numeric characters
99 while( !('0' <= *string && *string <= '9') && *string != '-' ) string++;
100 if( *string == '-' ) {
102 while( !('0' <= *string && *string <= '9') ) string++;
114 if('0' <= *string && *string <= '9') {
116 ret += *string - '0';
118 else if('A' <= *string && *string <= 'F') {
120 ret += *string - 'A' + 10;
122 else if('a' <= *string && *string <= 'f') {
124 ret += *string - 'a' + 10;
132 for( ; '0' <= *string && *string <= '7'; string ++ )
135 ret += *string - '0';
141 for( ; '0' <= *string && *string <= '9'; string++)
144 ret += *string - '0';
150 //Log("atoi: RETURN %i", ret);
155 static const char cUCDIGITS[] = "0123456789ABCDEF";
157 * \fn void itoa(char *buf, Uint64 num, int base, int minLength, char pad)
158 * \brief Convert an integer into a character string
160 void itoa(char *buf, Uint64 num, int base, int minLength, char pad)
170 if(base > 16 || base < 2) {
176 while(num > base-1) {
177 num = DivMod64U(num, base, &rem); // Shift `num` and get remainder
178 tmpBuf[pos] = cUCDIGITS[ rem ];
181 tmpBuf[pos++] = cUCDIGITS[ num ]; // Last digit of `num`
186 while(minLength-- > 0) buf[i++] = pad;
187 while(pos-- > 0) buf[i++] = tmpBuf[pos]; // Reverse the order of characters
192 * \brief Append a character the the vsnprintf output
194 #define PUTCH(c) do{\
196 if(pos==__maxlen){return pos;}\
197 if(__s){__s[pos++]=ch;}else{pos++;}\
199 #define GETVAL() do {\
200 if(isLongLong) val = va_arg(args, Uint64);\
201 else val = va_arg(args, unsigned int);\
204 * \brief VArg String Number Print Formatted
206 int vsnprintf(char *__s, size_t __maxlen, const char *__format, va_list args)
209 int minSize = 0, precision = -1, len;
210 char tmpBuf[34]; // For Integers
211 const char *p = NULL;
218 //Log("vsnprintf: (__s=%p, __maxlen=%i, __format='%s', ...)", __s, __maxlen, __format);
220 while((c = *__format++) != 0)
222 // Non control character
223 if(c != '%') { PUTCH(c); continue; }
226 //Log("pos = %i", pos);
229 if(c == '%') { PUTCH('%'); continue; }
231 // Pointer - Done first for debugging
233 Uint ptr = va_arg(args, Uint);
234 PUTCH('*'); PUTCH('0'); PUTCH('x');
235 itoa(tmpBuf, ptr, 16, BITS/4, '0');
240 // - Padding Side Flag
255 if(c == '*') { // Dynamic length
256 minSize = va_arg(args, unsigned int);
259 else if('1' <= c && c <= '9')
262 while('0' <= c && c <= '9')
277 if(c == '*') { // Dynamic length
278 precision = va_arg(args, unsigned int);
281 else if('1' <= c && c <= '9')
284 while('0' <= c && c <= '9')
287 precision += c - '0';
293 // - Default, Long or LongLong?
295 if(c == 'l') // Long is actually the default on x86
304 // - Now get the format code
311 if( isLongLong && val >> 63 ) {
315 else if( !isLongLong && val >> 31 ) {
319 itoa(tmpBuf, val, 10, minSize, pad);
321 case 'u': // Unsigned
323 itoa(tmpBuf, val, 10, minSize, pad);
325 case 'P': // Physical Address
328 if(sizeof(tPAddr) > 4) isLongLong = 1;
330 itoa(tmpBuf, val, 16, minSize, pad);
334 isLongLong = 1; // TODO: Handle non-x86 64-bit archs
336 itoa(tmpBuf, val, 16, minSize, pad);
339 case 'x': // Lower case hex
341 itoa(tmpBuf, val, 16, minSize, pad);
345 itoa(tmpBuf, val, 8, minSize, pad);
349 itoa(tmpBuf, val, 2, minSize, pad);
353 val = va_arg(args, unsigned int);
358 // String - Null Terminated Array
360 p = va_arg(args, char*); // Get Argument
361 if( !p || !CheckString(p) ) p = "(inval)"; // Avoid #PFs
365 if( !bPadLeft ) while(len++ < minSize) PUTCH(pad);
366 while(*p && precision--) PUTCH(*p++);
367 if( bPadLeft ) while(len++ < minSize) PUTCH(pad);
370 case 'C': // Non-Null Terminated Character Array
371 p = va_arg(args, char*);
372 if( !CheckMem(p, minSize) ) continue; // No #PFs please
373 if(!p) goto printString;
374 while(minSize--) PUTCH(*p++);
386 if(__s && pos != __maxlen)
395 int sprintf(char *__s, const char *__format, ...)
400 va_start(args, __format);
401 ret = vsnprintf(__s, -1, __format, args);
408 * \fn int tolower(int c)
409 * \brief Converts a character to lower case
413 if('A' <= c && c <= 'Z')
414 return c - 'A' + 'a';
419 * \fn int strucmp(const char *Str1, const char *Str2)
420 * \brief Compare \a Str1 and \a Str2 case-insensitively
422 int strucmp(const char *Str1, const char *Str2)
424 while(*Str1 && tolower(*Str1) == tolower(*Str2))
426 return tolower(*Str1) - tolower(*Str2);
430 * \brief Locate a byte in a string
432 char *strchr(const char *__s, int __c)
434 for( ; *__s; __s ++ )
436 if( *__s == __c ) return (char*)__s;
442 * \fn int strpos(const char *Str, char Ch)
443 * \brief Search a string for an ascii character
445 int strpos(const char *Str, char Ch)
448 for(pos=0;Str[pos];pos++)
450 if(Str[pos] == Ch) return pos;
456 * \fn Uint8 ByteSum(void *Ptr, int Size)
457 * \brief Adds the bytes in a memory region and returns the sum
459 Uint8 ByteSum(const void *Ptr, int Size)
462 const Uint8 *data = Ptr;
463 while(Size--) sum += *(data++);
468 * \fn size_t strlen(const char *__str)
469 * \brief Get the length of string
471 size_t strlen(const char *__str)
474 while(*__str++) ret++;
479 * \brief Copy a string to a new location
481 char *strcpy(char *__str1, const char *__str2)
484 *__str1++ = *__str2++;
485 *__str1 = '\0'; // Terminate String
490 * \brief Copy a string to a new location
491 * \note Copies at most `max` chars
493 char *strncpy(char *__str1, const char *__str2, size_t __max)
495 while(*__str2 && __max-- >= 1)
496 *__str1++ = *__str2++;
498 *__str1 = '\0'; // Terminate String
503 * \brief Append a string to another
505 char *strcat(char *__dest, const char *__src)
510 *__dest++ = *__src++;
516 * \brief Append at most \a n chars to a string from another
517 * \note At most n+1 chars are written (the dest is always zero terminated)
519 char *strncat(char *__dest, const char *__src, size_t n)
522 while(*__src && n-- >= 1)
523 *__dest++ = *__src++;
529 * \fn int strcmp(const char *str1, const char *str2)
530 * \brief Compare two strings return the difference between
531 * the first non-matching characters.
533 int strcmp(const char *str1, const char *str2)
535 while(*str1 && *str1 == *str2)
537 return *str1 - *str2;
541 * \fn int strncmp(const char *Str1, const char *Str2, size_t num)
542 * \brief Compare strings \a Str1 and \a Str2 to a maximum of \a num characters
544 int strncmp(const char *Str1, const char *Str2, size_t num)
546 if(num == 0) return 0; // TODO: Check what should officially happen here
547 while(--num && *Str1 && *Str1 == *Str2)
554 * \fn char *strdup(const char *Str)
555 * \brief Duplicates a string
557 char *strdup(const char *Str)
560 ret = malloc(strlen(Str)+1);
561 if( !ret ) return NULL;
568 * \fn char *_strdup(const char *File, int Line, const char *Str)
569 * \brief Duplicates a string
571 char *_strdup(const char *File, int Line, const char *Str)
574 ret = Heap_Allocate(File, Line, strlen(Str)+1);
575 if( !ret ) return NULL;
582 * \brief Split a string using the passed character
583 * \return NULL terminated array of strings on the heap
584 * \param __str String to split
585 * \param __ch Character to split by
587 char **str_split(const char *__str, char __ch)
594 for( i = 0; __str[i]; i++ )
600 ret = malloc( sizeof(char*)*(len+1) + (i + 1) );
601 if( !ret ) return NULL;
604 start = (char *)&ret[len+1];
606 for( i = 0; __str[i]; i++ )
608 if(__str[i] == __ch) {
623 * \fn int DivUp(int num, int dem)
624 * \brief Divide two numbers, rounding up
625 * \param num Numerator
626 * \param dem Denominator
628 int DivUp(int num, int dem)
630 return (num+dem-1)/dem;
634 * \fn int strpos8(const char *str, Uint32 search)
635 * \brief Search a string for a UTF-8 character
637 int strpos8(const char *str, Uint32 Search)
641 for(pos=0;str[pos];pos++)
645 if(str[pos] == Search) return pos;
648 if(*(Uint8*)(str+pos) < 128) continue;
650 pos += ReadUTF8( (Uint8*)&str[pos], &val );
651 if(val == Search) return pos;
657 * \fn int ReadUTF8(Uint8 *str, Uint32 *Val)
658 * \brief Read a UTF-8 character from a string
660 int ReadUTF8(const Uint8 *str, Uint32 *Val)
662 *Val = 0xFFFD; // Assume invalid character
665 if( !(*str & 0x80) ) {
670 // Middle of a sequence
671 if( (*str & 0xC0) == 0x80 ) {
676 if( (*str & 0xE0) == 0xC0 ) {
677 *Val = (*str & 0x1F) << 6; // Upper 6 Bits
679 if( (*str & 0xC0) != 0x80) return -1; // Validity check
680 *Val |= (*str & 0x3F); // Lower 6 Bits
685 if( (*str & 0xF0) == 0xE0 ) {
686 *Val = (*str & 0x0F) << 12; // Upper 4 Bits
688 if( (*str & 0xC0) != 0x80) return -1; // Validity check
689 *Val |= (*str & 0x3F) << 6; // Middle 6 Bits
691 if( (*str & 0xC0) != 0x80) return -1; // Validity check
692 *Val |= (*str & 0x3F); // Lower 6 Bits
697 if( (*str & 0xF1) == 0xF0 ) {
698 *Val = (*str & 0x07) << 18; // Upper 3 Bits
700 if( (*str & 0xC0) != 0x80) return -1; // Validity check
701 *Val |= (*str & 0x3F) << 12; // Middle-upper 6 Bits
703 if( (*str & 0xC0) != 0x80) return -1; // Validity check
704 *Val |= (*str & 0x3F) << 6; // Middle-lower 6 Bits
706 if( (*str & 0xC0) != 0x80) return -1; // Validity check
707 *Val |= (*str & 0x3F); // Lower 6 Bits
711 // UTF-8 Doesn't support more than four bytes
716 * \fn int WriteUTF8(Uint8 *str, Uint32 Val)
717 * \brief Write a UTF-8 character sequence to a string
719 int WriteUTF8(Uint8 *str, Uint32 Val)
732 *str++ = 0xC0 | (Val >> 6);
733 *str++ = 0x80 | (Val & 0x3F);
739 if( Val < 0x10000 ) {
741 *str++ = 0xE0 | (Val >> 12);
742 *str++ = 0x80 | ((Val >> 6) & 0x3F);
743 *str++ = 0x80 | (Val & 0x3F);
749 if( Val < 0x110000 ) {
751 *str++ = 0xF0 | (Val >> 18);
752 *str++ = 0x80 | ((Val >> 12) & 0x3F);
753 *str++ = 0x80 | ((Val >> 6) & 0x3F);
754 *str++ = 0x80 | (Val & 0x3F);
759 // UTF-8 Doesn't support more than four bytes
764 * \fn Uint64 timestamp(int sec, int mins, int hrs, int day, int month, int year)
765 * \brief Converts a date into an Acess Timestamp
767 Sint64 timestamp(int sec, int mins, int hrs, int day, int month, int year)
774 stamp += day*3600*24;
775 stamp += month*DAYS_BEFORE[month]*3600*24;
777 ((year&3) == 0 || year%100 != 0)
778 || (year%100 == 0 && ((year/100)&3) == 0)
779 ) && month > 1) // Leap year and after feb
782 stamp += ((365*4+1) * ((year-2000)&~3)) * 3600*24; // Four Year Segments
783 stamp += ((year-2000)&3) * 365*3600*24; // Inside four year segment
791 * \brief Pseudo random number generator
796 static Uint state = RANDOM_SEED;
798 // Get the next state value
799 giRandomState = (RANDOM_A*state + RANDOM_C);
800 // Check if it has changed, and if it hasn't, change it
801 if(state == old) state += RANDOM_SPRUCE;
804 // http://en.wikipedia.org/wiki/Xorshift
806 static Uint32 x = 123456789;
807 static Uint32 y = 362436069;
808 static Uint32 z = 521288629;
809 static Uint32 w = 88675123;
814 return w = w ^ (w >> 19) ^ t ^ (t >> 8);
819 * \name Memory Validation
823 * \brief Checks if a string resides fully in valid memory
825 int CheckString(const char *String)
830 addr = (tVAddr)String;
832 if( !MM_GetPhysAddr( addr ) )
836 bUser = MM_IsUser( addr );
838 while( *(char*)addr )
840 if( (addr & (PAGE_SIZE-1)) == 0 )
842 if(bUser && !MM_IsUser(addr) )
844 if(!bUser && !MM_GetPhysAddr(addr) )
853 * \brief Check if a sized memory region is valid memory
854 * \return Boolean success
856 int CheckMem(const void *Mem, int NumBytes)
858 return MM_IsValidBuffer( (tVAddr)Mem, NumBytes );
865 * \brief Search a string array for \a Needle
866 * \note Helper function for eTplDrv_IOCtl::DRV_IOCTL_LOOKUP
868 int ModUtil_LookupString(const char **Array, const char *Needle)
871 if( !CheckString(Needle) ) return -1;
872 for( i = 0; Array[i]; i++ )
874 if(strcmp(Array[i], Needle) == 0) return i;
879 int ModUtil_SetIdent(char *Dest, const char *Value)
881 if( !CheckMem(Dest, 32) ) return -1;
882 strncpy(Dest, Value, 32);
887 * \brief Convert a string of hexadecimal digits into a byte stream
889 int UnHex(Uint8 *Dest, size_t DestSize, const char *SourceString)
893 for( i = 0; i < DestSize*2; i += 2 )
897 if(SourceString[i] == '\0') break;
899 if('0' <= SourceString[i] && SourceString[i] <= '9')
900 val |= (SourceString[i]-'0') << 4;
901 else if('A' <= SourceString[i] && SourceString[i] <= 'F')
902 val |= (SourceString[i]-'A'+10) << 4;
903 else if('a' <= SourceString[i] && SourceString[i] <= 'f')
904 val |= (SourceString[i]-'a'+10) << 4;
906 if(SourceString[i+1] == '\0') break;
908 if('0' <= SourceString[i+1] && SourceString[i+1] <= '9')
909 val |= (SourceString[i+1] - '0');
910 else if('A' <= SourceString[i+1] && SourceString[i+1] <= 'F')
911 val |= (SourceString[i+1] - 'A' + 10);
912 else if('a' <= SourceString[i+1] && SourceString[i+1] <= 'f')
913 val |= (SourceString[i+1] - 'a' + 10);
920 Uint16 SwapEndian16(Uint16 Val)
922 return ((Val&0xFF)<<8) | ((Val>>8)&0xFF);
924 Uint32 SwapEndian32(Uint32 Val)
926 return ((Val&0xFF)<<24) | ((Val&0xFF00)<<8) | ((Val>>8)&0xFF00) | ((Val>>24)&0xFF);
929 void *memmove(void *__dest, const void *__src, size_t len)
933 const char *src = __src;
936 if( len == 0 || dest == src )
939 if( (tVAddr)dest > (tVAddr)src + len )
940 return memcpy(dest, src, len);
941 if( (tVAddr)dest + len < (tVAddr)src )
942 return memcpy(dest, src, len);
944 // NOTE: Assumes memcpy works forward
945 if( (tVAddr)dest < (tVAddr)src )
946 return memcpy(dest, src, len);
948 if( (tVAddr)dest < (tVAddr)src )
949 block_size = (tVAddr)src - (tVAddr)dest;
951 block_size = (tVAddr)dest - (tVAddr)src;
955 while(len >= block_size)
957 memcpy(dest, src, block_size);
962 memcpy(dest, src, len);