3 * Common Library Functions
8 #define RANDOM_SEED 0xACE55052
9 #define RANDOM_A 0x00731ADE
10 #define RANDOM_C 12345
11 #define RANDOM_SPRUCE 0xf12b039
12 // Jan Feb Mar Apr May Jun Jul Aug Sept Oct Nov Dec
13 const short DAYS_BEFORE[] = {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334};
14 #define UNIX_TO_2K ((30*365*3600*24) + (7*3600*24)) //Normal years + leap years
18 int atoi(const char *string);
19 void itoa(char *buf, Uint64 num, int base, int minLength, char pad);
20 int vsnprintf(char *__s, size_t __maxlen, const char *__format, va_list args);
21 int sprintf(char *__s, const char *__format, ...);
25 int strucmp(const char *Str1, const char *Str2);
26 char *strchr(const char *__s, int __c);
27 int strpos(const char *Str, char Ch);
28 Uint8 ByteSum(void *Ptr, int Size);
29 size_t strlen(const char *__s);
30 char *strcpy(char *__str1, const char *__str2);
31 char *strncpy(char *__str1, const char *__str2, size_t max);
32 int strcmp(const char *str1, const char *str2);
33 int strncmp(const char *str1, const char *str2, size_t num);
34 char *_strdup(const char *File, int Line, const char *Str);
35 char **str_split(const char *__str, char __ch);
36 int strpos8(const char *str, Uint32 Search);
37 int ReadUTF8(Uint8 *str, Uint32 *Val);
38 int WriteUTF8(Uint8 *str, Uint32 Val);
39 int DivUp(int num, int dem);
40 Sint64 timestamp(int sec, int mins, int hrs, int day, int month, int year);
43 int CheckString(char *String);
44 int CheckMem(void *Mem, int NumBytes);
46 int ModUtil_LookupString(char **Array, char *Needle);
47 int ModUtil_SetIdent(char *Dest, char *Value);
49 int UnHex(Uint8 *Dest, size_t DestSize, const char *SourceString);
70 EXPORT(_strdup); // Takes File/Line too
79 EXPORT(ModUtil_LookupString);
80 EXPORT(ModUtil_SetIdent);
87 * \brief Convert a string into an integer
89 int atoi(const char *string)
94 //Log("atoi: (string='%s')", string);
96 // Clear non-numeric characters
97 while( !('0' <= *string && *string <= '9') && *string != '-' ) string++;
98 if( *string == '-' ) {
100 while( !('0' <= *string && *string <= '9') ) string++;
112 if('0' <= *string && *string <= '9') {
114 ret += *string - '0';
116 else if('A' <= *string && *string <= 'F') {
118 ret += *string - 'A' + 10;
120 else if('a' <= *string && *string <= 'f') {
122 ret += *string - 'a' + 10;
130 for( ; '0' <= *string && *string <= '7'; string ++ )
133 ret += *string - '0';
139 for( ; '0' <= *string && *string <= '9'; string++)
142 ret += *string - '0';
148 //Log("atoi: RETURN %i", ret);
153 static const char cUCDIGITS[] = "0123456789ABCDEF";
155 * \fn void itoa(char *buf, Uint64 num, int base, int minLength, char pad)
156 * \brief Convert an integer into a character string
158 void itoa(char *buf, Uint64 num, int base, int minLength, char pad)
168 if(base > 16 || base < 2) {
174 while(num > base-1) {
175 num = DivMod64U(num, base, &rem); // Shift `num` and get remainder
176 tmpBuf[pos] = cUCDIGITS[ rem ];
179 tmpBuf[pos++] = cUCDIGITS[ num ]; // Last digit of `num`
184 while(minLength-- > 0) buf[i++] = pad;
185 while(pos-- > 0) buf[i++] = tmpBuf[pos]; // Reverse the order of characters
190 * \brief Append a character the the vsnprintf output
192 #define PUTCH(c) do{\
194 if(pos==__maxlen){return pos;}\
195 if(__s){__s[pos++]=ch;}else{pos++;}\
197 #define GETVAL() do {\
198 if(isLongLong) val = va_arg(args, Uint64);\
199 else val = va_arg(args, unsigned int);\
202 * \brief VArg String Number Print Formatted
204 int vsnprintf(char *__s, size_t __maxlen, const char *__format, va_list args)
207 int minSize = 0, precision = -1, len;
208 char tmpBuf[34]; // For Integers
209 const char *p = NULL;
216 //Log("vsnprintf: (__s=%p, __maxlen=%i, __format='%s', ...)", __s, __maxlen, __format);
218 while((c = *__format++) != 0)
220 // Non control character
221 if(c != '%') { PUTCH(c); continue; }
224 //Log("pos = %i", pos);
227 if(c == '%') { PUTCH('%'); continue; }
229 // Pointer - Done first for debugging
231 Uint ptr = va_arg(args, Uint);
232 PUTCH('*'); PUTCH('0'); PUTCH('x');
233 itoa(tmpBuf, ptr, 16, BITS/4, '0');
238 // - Padding Side Flag
253 if(c == '*') { // Dynamic length
254 minSize = va_arg(args, unsigned int);
257 else if('1' <= c && c <= '9')
260 while('0' <= c && c <= '9')
275 if(c == '*') { // Dynamic length
276 precision = va_arg(args, unsigned int);
279 else if('1' <= c && c <= '9')
282 while('0' <= c && c <= '9')
285 precision += c - '0';
291 // - Default, Long or LongLong?
293 if(c == 'l') // Long is actually the default on x86
302 // - Now get the format code
309 if( isLongLong && val >> 63 ) {
313 else if( !isLongLong && val >> 31 ) {
317 itoa(tmpBuf, val, 10, minSize, pad);
319 case 'u': // Unsigned
321 itoa(tmpBuf, val, 10, minSize, pad);
323 case 'P': // Physical Address
326 if(sizeof(tPAddr) > 4) isLongLong = 1;
328 itoa(tmpBuf, val, 16, minSize, pad);
332 isLongLong = 1; // TODO: Handle non-x86 64-bit archs
334 itoa(tmpBuf, val, 16, minSize, pad);
337 case 'x': // Lower case hex
339 itoa(tmpBuf, val, 16, minSize, pad);
343 itoa(tmpBuf, val, 8, minSize, pad);
347 itoa(tmpBuf, val, 2, minSize, pad);
351 val = va_arg(args, unsigned int);
356 // String - Null Terminated Array
358 p = va_arg(args, char*); // Get Argument
359 if( !CheckString(p) ) p = "(inval)"; // Avoid #PFs
363 if( !bPadLeft ) while(len++ < minSize) PUTCH(pad);
364 while(*p && precision--) PUTCH(*p++);
365 if( bPadLeft ) while(len++ < minSize) PUTCH(pad);
368 case 'C': // Non-Null Terminated Character Array
369 p = va_arg(args, char*);
370 if( !CheckMem(p, minSize) ) continue; // No #PFs please
371 if(!p) goto printString;
372 while(minSize--) PUTCH(*p++);
384 if(__s && pos != __maxlen)
393 int sprintf(char *__s, const char *__format, ...)
398 va_start(args, __format);
399 ret = vsnprintf(__s, -1, __format, args);
406 * \fn int tolower(int c)
407 * \brief Converts a character to lower case
411 if('A' <= c && c <= 'Z')
412 return c - 'A' + 'a';
417 * \fn int strucmp(const char *Str1, const char *Str2)
418 * \brief Compare \a Str1 and \a Str2 case-insensitively
420 int strucmp(const char *Str1, const char *Str2)
422 while(*Str1 && tolower(*Str1) == tolower(*Str2))
424 return tolower(*Str1) - tolower(*Str2);
428 * \brief Locate a byte in a string
430 char *strchr(const char *__s, int __c)
432 for( ; *__s; __s ++ )
434 if( *__s == __c ) return (char*)__s;
440 * \fn int strpos(const char *Str, char Ch)
441 * \brief Search a string for an ascii character
443 int strpos(const char *Str, char Ch)
446 for(pos=0;Str[pos];pos++)
448 if(Str[pos] == Ch) return pos;
454 * \fn Uint8 ByteSum(void *Ptr, int Size)
455 * \brief Adds the bytes in a memory region and returns the sum
457 Uint8 ByteSum(const void *Ptr, int Size)
460 const Uint8 *data = Ptr;
461 while(Size--) sum += *(data++);
466 * \fn size_t strlen(const char *__str)
467 * \brief Get the length of string
469 size_t strlen(const char *__str)
472 while(*__str++) ret++;
477 * \brief Copy a string to a new location
479 char *strcpy(char *__str1, const char *__str2)
482 *__str1++ = *__str2++;
483 *__str1 = '\0'; // Terminate String
488 * \brief Copy a string to a new location
489 * \note Copies at most `max` chars
491 char *strncpy(char *__str1, const char *__str2, size_t max)
493 while(*__str2 && max-- >= 1)
494 *__str1++ = *__str2++;
496 *__str1 = '\0'; // Terminate String
501 * \brief Append a string to another
503 char *strcat(char *__dest, const char *__src)
508 *__dest++ = *__src++;
514 * \brief Append at most \a n chars to a string from another
515 * \note At most n+1 chars are written (the dest is always zero terminated)
517 char *strncat(char *__dest, const char *__src, size_t n)
520 while(*__src && n-- >= 1)
521 *__dest++ = *__src++;
527 * \fn int strcmp(const char *str1, const char *str2)
528 * \brief Compare two strings return the difference between
529 * the first non-matching characters.
531 int strcmp(const char *str1, const char *str2)
533 while(*str1 && *str1 == *str2)
535 return *str1 - *str2;
539 * \fn int strncmp(const char *Str1, const char *Str2, size_t num)
540 * \brief Compare strings \a Str1 and \a Str2 to a maximum of \a num characters
542 int strncmp(const char *Str1, const char *Str2, size_t num)
544 if(num == 0) return 0; // TODO: Check what should officially happen here
545 while(--num && *Str1 && *Str1 == *Str2)
552 * \fn char *strdup(const char *Str)
553 * \brief Duplicates a string
555 char *strdup(const char *Str)
558 ret = malloc(strlen(Str)+1);
559 if( !ret ) return NULL;
566 * \fn char *_strdup(const char *File, int Line, const char *Str)
567 * \brief Duplicates a string
569 char *_strdup(const char *File, int Line, const char *Str)
572 ret = Heap_Allocate(File, Line, strlen(Str)+1);
573 if( !ret ) return NULL;
580 * \brief Split a string using the passed character
581 * \return NULL terminated array of strings on the heap
582 * \param __str String to split
583 * \param __ch Character to split by
585 char **str_split(const char *__str, char __ch)
592 for( i = 0; __str[i]; i++ )
598 ret = malloc( sizeof(char*)*(len+1) + (i + 1) );
599 if( !ret ) return NULL;
602 start = (char *)&ret[len+1];
604 for( i = 0; __str[i]; i++ )
606 if(__str[i] == __ch) {
621 * \fn int DivUp(int num, int dem)
622 * \brief Divide two numbers, rounding up
623 * \param num Numerator
624 * \param dem Denominator
626 int DivUp(int num, int dem)
628 return (num+dem-1)/dem;
632 * \fn int strpos8(const char *str, Uint32 search)
633 * \brief Search a string for a UTF-8 character
635 int strpos8(const char *str, Uint32 Search)
639 for(pos=0;str[pos];pos++)
643 if(str[pos] == Search) return pos;
646 if(*(Uint8*)(str+pos) < 128) continue;
648 pos += ReadUTF8( (Uint8*)&str[pos], &val );
649 if(val == Search) return pos;
655 * \fn int ReadUTF8(Uint8 *str, Uint32 *Val)
656 * \brief Read a UTF-8 character from a string
658 int ReadUTF8(const Uint8 *str, Uint32 *Val)
660 *Val = 0xFFFD; // Assume invalid character
663 if( !(*str & 0x80) ) {
668 // Middle of a sequence
669 if( (*str & 0xC0) == 0x80 ) {
674 if( (*str & 0xE0) == 0xC0 ) {
675 *Val = (*str & 0x1F) << 6; // Upper 6 Bits
677 if( (*str & 0xC0) != 0x80) return -1; // Validity check
678 *Val |= (*str & 0x3F); // Lower 6 Bits
683 if( (*str & 0xF0) == 0xE0 ) {
684 *Val = (*str & 0x0F) << 12; // Upper 4 Bits
686 if( (*str & 0xC0) != 0x80) return -1; // Validity check
687 *Val |= (*str & 0x3F) << 6; // Middle 6 Bits
689 if( (*str & 0xC0) != 0x80) return -1; // Validity check
690 *Val |= (*str & 0x3F); // Lower 6 Bits
695 if( (*str & 0xF1) == 0xF0 ) {
696 *Val = (*str & 0x07) << 18; // Upper 3 Bits
698 if( (*str & 0xC0) != 0x80) return -1; // Validity check
699 *Val |= (*str & 0x3F) << 12; // Middle-upper 6 Bits
701 if( (*str & 0xC0) != 0x80) return -1; // Validity check
702 *Val |= (*str & 0x3F) << 6; // Middle-lower 6 Bits
704 if( (*str & 0xC0) != 0x80) return -1; // Validity check
705 *Val |= (*str & 0x3F); // Lower 6 Bits
709 // UTF-8 Doesn't support more than four bytes
714 * \fn int WriteUTF8(Uint8 *str, Uint32 Val)
715 * \brief Write a UTF-8 character sequence to a string
717 int WriteUTF8(Uint8 *str, Uint32 Val)
727 *str = 0xC0 | (Val >> 6);
729 *str = 0x80 | (Val & 0x3F);
734 if( Val < 0x10000 ) {
735 *str = 0xE0 | (Val >> 12);
737 *str = 0x80 | ((Val >> 6) & 0x3F);
739 *str = 0x80 | (Val & 0x3F);
744 if( Val < 0x110000 ) {
745 *str = 0xF0 | (Val >> 18);
747 *str = 0x80 | ((Val >> 12) & 0x3F);
749 *str = 0x80 | ((Val >> 6) & 0x3F);
751 *str = 0x80 | (Val & 0x3F);
755 // UTF-8 Doesn't support more than four bytes
760 * \fn Uint64 timestamp(int sec, int mins, int hrs, int day, int month, int year)
761 * \brief Converts a date into an Acess Timestamp
763 Sint64 timestamp(int sec, int mins, int hrs, int day, int month, int year)
770 stamp += day*3600*24;
771 stamp += month*DAYS_BEFORE[month]*3600*24;
773 ((year&3) == 0 || year%100 != 0)
774 || (year%100 == 0 && ((year/100)&3) == 0)
775 ) && month > 1) // Leap year and after feb
778 stamp += ((365*4+1) * ((year-2000)&~3)) * 3600*24; // Four Year Segments
779 stamp += ((year-2000)&3) * 365*3600*24; // Inside four year segment
787 * \brief Pseudo random number generator
792 static Uint state = RANDOM_SEED;
794 // Get the next state value
795 giRandomState = (RANDOM_A*state + RANDOM_C);
796 // Check if it has changed, and if it hasn't, change it
797 if(state == old) state += RANDOM_SPRUCE;
800 // http://en.wikipedia.org/wiki/Xorshift
802 static Uint32 x = 123456789;
803 static Uint32 y = 362436069;
804 static Uint32 z = 521288629;
805 static Uint32 w = 88675123;
810 return w = w ^ (w >> 19) ^ t ^ (t >> 8);
815 * \name Memory Validation
819 * \brief Checks if a string resides fully in valid memory
821 int CheckString(const char *String)
823 if( !MM_GetPhysAddr( (tVAddr)String ) )
827 if( MM_IsUser( (tVAddr)String ) )
832 if( !MM_IsUser( (tVAddr)String ) )
834 // Increment string pointer
839 else if( MM_GetPhysAddr( (tVAddr)String ) )
844 if( !MM_GetPhysAddr( (tVAddr)String ) )
846 // Increment string pointer
855 * \brief Check if a sized memory region is valid memory
857 int CheckMem(const void *Mem, int NumBytes)
859 tVAddr addr = (tVAddr)Mem;
861 if( MM_IsUser( addr ) )
865 if( !MM_IsUser( addr ) )
871 else if( MM_GetPhysAddr( addr ) )
875 if( !MM_GetPhysAddr( addr ) )
888 * \brief Search a string array for \a Needle
889 * \note Helper function for eTplDrv_IOCtl::DRV_IOCTL_LOOKUP
891 int ModUtil_LookupString(const char **Array, const char *Needle)
894 if( !CheckString(Needle) ) return -1;
895 for( i = 0; Array[i]; i++ )
897 if(strcmp(Array[i], Needle) == 0) return i;
902 int ModUtil_SetIdent(char *Dest, const char *Value)
904 if( !CheckMem(Dest, 32) ) return -1;
905 strncpy(Dest, Value, 32);
910 * \brief Convert a string of hexadecimal digits into a byte stream
912 int UnHex(Uint8 *Dest, size_t DestSize, const char *SourceString)
916 for( i = 0; i < DestSize*2; i += 2 )
920 if(SourceString[i] == '\0') break;
922 if('0' <= SourceString[i] && SourceString[i] <= '9')
923 val |= (SourceString[i]-'0') << 4;
924 else if('A' <= SourceString[i] && SourceString[i] <= 'F')
925 val |= (SourceString[i]-'A'+10) << 4;
926 else if('a' <= SourceString[i] && SourceString[i] <= 'f')
927 val |= (SourceString[i]-'a'+10) << 4;
929 if(SourceString[i+1] == '\0') break;
931 if('0' <= SourceString[i+1] && SourceString[i+1] <= '9')
932 val |= (SourceString[i+1] - '0');
933 else if('A' <= SourceString[i+1] && SourceString[i+1] <= 'F')
934 val |= (SourceString[i+1] - 'A' + 10);
935 else if('a' <= SourceString[i+1] && SourceString[i+1] <= 'f')
936 val |= (SourceString[i+1] - 'a' + 10);
943 Uint16 SwapEndian16(Uint16 Val)
945 return ((Val&0xFF)<<8) | ((Val>>8)&0xFF);
947 Uint32 SwapEndian32(Uint32 Val)
949 return ((Val&0xFF)<<24) | ((Val&0xFF00)<<8) | ((Val>>8)&0xFF00) | ((Val>>24)&0xFF);