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)
167 if(base > 16 || base < 2) {
173 while(num > base-1) {
174 tmpBuf[pos] = cUCDIGITS[ num % base ];
175 num /= (Uint)base; // Shift `num` right 1 digit
178 tmpBuf[pos++] = cUCDIGITS[ num % base ]; // Last digit of `num`
183 while(minLength-- > 0) buf[i++] = pad;
184 while(pos-- > 0) buf[i++] = tmpBuf[pos]; // Reverse the order of characters
189 * \brief Append a character the the vsnprintf output
191 #define PUTCH(c) do{\
193 if(pos==__maxlen){return pos;}\
194 if(__s){__s[pos++]=ch;}else{pos++;}\
196 #define GETVAL() do {\
197 if(isLongLong) val = va_arg(args, Uint64);\
198 else val = va_arg(args, unsigned int);\
201 * \brief VArg String Number Print Formatted
203 int vsnprintf(char *__s, size_t __maxlen, const char *__format, va_list args)
206 int minSize = 0, precision = -1, len;
207 char tmpBuf[34]; // For Integers
208 const char *p = NULL;
215 //Log("vsnprintf: (__s=%p, __maxlen=%i, __format='%s', ...)", __s, __maxlen, __format);
217 while((c = *__format++) != 0)
219 // Non control character
220 if(c != '%') { PUTCH(c); continue; }
223 //Log("pos = %i", pos);
226 if(c == '%') { PUTCH('%'); continue; }
228 // Pointer - Done first for debugging
230 Uint ptr = va_arg(args, Uint);
231 PUTCH('*'); PUTCH('0'); PUTCH('x');
232 itoa(tmpBuf, ptr, 16, BITS/4, '0');
237 // - Padding Side Flag
252 if(c == '*') { // Dynamic length
253 minSize = va_arg(args, unsigned int);
256 else if('1' <= c && c <= '9')
259 while('0' <= c && c <= '9')
274 if(c == '*') { // Dynamic length
275 precision = va_arg(args, unsigned int);
278 else if('1' <= c && c <= '9')
281 while('0' <= c && c <= '9')
284 precision += c - '0';
290 // - Default, Long or LongLong?
292 if(c == 'l') // Long is actually the default on x86
301 // - Now get the format code
308 if( isLongLong && val >> 63 ) {
312 else if( !isLongLong && val >> 31 ) {
316 itoa(tmpBuf, val, 10, minSize, pad);
318 case 'u': // Unsigned
320 itoa(tmpBuf, val, 10, minSize, pad);
322 case 'P': // Physical Address
325 if(sizeof(tPAddr) > 4) isLongLong = 1;
327 itoa(tmpBuf, val, 16, minSize, pad);
331 isLongLong = 1; // TODO: Handle non-x86 64-bit archs
333 itoa(tmpBuf, val, 16, minSize, pad);
336 case 'x': // Lower case hex
338 itoa(tmpBuf, val, 16, minSize, pad);
342 itoa(tmpBuf, val, 8, minSize, pad);
346 itoa(tmpBuf, val, 2, minSize, pad);
350 val = va_arg(args, unsigned int);
355 // String - Null Terminated Array
357 p = va_arg(args, char*); // Get Argument
358 if( !CheckString(p) ) p = "(inval)"; // Avoid #PFs
362 if( !bPadLeft ) while(len++ < minSize) PUTCH(pad);
363 while(*p && precision--) PUTCH(*p++);
364 if( bPadLeft ) while(len++ < minSize) PUTCH(pad);
367 case 'C': // Non-Null Terminated Character Array
368 p = va_arg(args, char*);
369 if( !CheckMem(p, minSize) ) continue; // No #PFs please
370 if(!p) goto printString;
371 while(minSize--) PUTCH(*p++);
383 if(__s && pos != __maxlen)
392 int sprintf(char *__s, const char *__format, ...)
397 va_start(args, __format);
398 ret = vsnprintf(__s, -1, __format, args);
405 * \fn int tolower(int c)
406 * \brief Converts a character to lower case
410 if('A' <= c && c <= 'Z')
411 return c - 'A' + 'a';
416 * \fn int strucmp(const char *Str1, const char *Str2)
417 * \brief Compare \a Str1 and \a Str2 case-insensitively
419 int strucmp(const char *Str1, const char *Str2)
421 while(*Str1 && tolower(*Str1) == tolower(*Str2))
423 return tolower(*Str1) - tolower(*Str2);
427 * \brief Locate a byte in a string
429 char *strchr(const char *__s, int __c)
431 for( ; *__s; __s ++ )
433 if( *__s == __c ) return (char*)__s;
439 * \fn int strpos(const char *Str, char Ch)
440 * \brief Search a string for an ascii character
442 int strpos(const char *Str, char Ch)
445 for(pos=0;Str[pos];pos++)
447 if(Str[pos] == Ch) return pos;
453 * \fn Uint8 ByteSum(void *Ptr, int Size)
454 * \brief Adds the bytes in a memory region and returns the sum
456 Uint8 ByteSum(const void *Ptr, int Size)
459 const Uint8 *data = Ptr;
460 while(Size--) sum += *(data++);
465 * \fn size_t strlen(const char *__str)
466 * \brief Get the length of string
468 size_t strlen(const char *__str)
471 while(*__str++) ret++;
476 * \brief Copy a string to a new location
478 char *strcpy(char *__str1, const char *__str2)
481 *__str1++ = *__str2++;
482 *__str1 = '\0'; // Terminate String
487 * \brief Copy a string to a new location
488 * \note Copies at most `max` chars
490 char *strncpy(char *__str1, const char *__str2, size_t max)
492 while(*__str2 && max-- >= 1)
493 *__str1++ = *__str2++;
495 *__str1 = '\0'; // Terminate String
500 * \brief Append a string to another
502 char *strcat(char *__dest, const char *__src)
507 *__dest++ = *__src++;
513 * \brief Append at most \a n chars to a string from another
514 * \note At most n+1 chars are written (the dest is always zero terminated)
516 char *strncat(char *__dest, const char *__src, size_t n)
519 while(*__src && n-- >= 1)
520 *__dest++ = *__src++;
526 * \fn int strcmp(const char *str1, const char *str2)
527 * \brief Compare two strings return the difference between
528 * the first non-matching characters.
530 int strcmp(const char *str1, const char *str2)
532 while(*str1 && *str1 == *str2)
534 return *str1 - *str2;
538 * \fn int strncmp(const char *Str1, const char *Str2, size_t num)
539 * \brief Compare strings \a Str1 and \a Str2 to a maximum of \a num characters
541 int strncmp(const char *Str1, const char *Str2, size_t num)
543 if(num == 0) return 0; // TODO: Check what should officially happen here
544 while(--num && *Str1 && *Str1 == *Str2)
551 * \fn char *strdup(const char *Str)
552 * \brief Duplicates a string
554 char *strdup(const char *Str)
557 ret = malloc(strlen(Str)+1);
558 if( !ret ) return NULL;
565 * \fn char *_strdup(const char *File, int Line, const char *Str)
566 * \brief Duplicates a string
568 char *_strdup(const char *File, int Line, const char *Str)
571 ret = Heap_Allocate(File, Line, strlen(Str)+1);
572 if( !ret ) return NULL;
579 * \brief Split a string using the passed character
580 * \return NULL terminated array of strings on the heap
581 * \param __str String to split
582 * \param __ch Character to split by
584 char **str_split(const char *__str, char __ch)
591 for( i = 0; __str[i]; i++ )
597 ret = malloc( sizeof(char*)*(len+1) + (i + 1) );
598 if( !ret ) return NULL;
601 start = (char *)&ret[len+1];
603 for( i = 0; __str[i]; i++ )
605 if(__str[i] == __ch) {
620 * \fn int DivUp(int num, int dem)
621 * \brief Divide two numbers, rounding up
622 * \param num Numerator
623 * \param dem Denominator
625 int DivUp(int num, int dem)
627 return (num+dem-1)/dem;
631 * \fn int strpos8(const char *str, Uint32 search)
632 * \brief Search a string for a UTF-8 character
634 int strpos8(const char *str, Uint32 Search)
638 for(pos=0;str[pos];pos++)
642 if(str[pos] == Search) return pos;
645 if(*(Uint8*)(str+pos) < 128) continue;
647 pos += ReadUTF8( (Uint8*)&str[pos], &val );
648 if(val == Search) return pos;
654 * \fn int ReadUTF8(Uint8 *str, Uint32 *Val)
655 * \brief Read a UTF-8 character from a string
657 int ReadUTF8(const Uint8 *str, Uint32 *Val)
659 *Val = 0xFFFD; // Assume invalid character
662 if( !(*str & 0x80) ) {
667 // Middle of a sequence
668 if( (*str & 0xC0) == 0x80 ) {
673 if( (*str & 0xE0) == 0xC0 ) {
674 *Val = (*str & 0x1F) << 6; // Upper 6 Bits
676 if( (*str & 0xC0) != 0x80) return -1; // Validity check
677 *Val |= (*str & 0x3F); // Lower 6 Bits
682 if( (*str & 0xF0) == 0xE0 ) {
683 *Val = (*str & 0x0F) << 12; // Upper 4 Bits
685 if( (*str & 0xC0) != 0x80) return -1; // Validity check
686 *Val |= (*str & 0x3F) << 6; // Middle 6 Bits
688 if( (*str & 0xC0) != 0x80) return -1; // Validity check
689 *Val |= (*str & 0x3F); // Lower 6 Bits
694 if( (*str & 0xF1) == 0xF0 ) {
695 *Val = (*str & 0x07) << 18; // Upper 3 Bits
697 if( (*str & 0xC0) != 0x80) return -1; // Validity check
698 *Val |= (*str & 0x3F) << 12; // Middle-upper 6 Bits
700 if( (*str & 0xC0) != 0x80) return -1; // Validity check
701 *Val |= (*str & 0x3F) << 6; // Middle-lower 6 Bits
703 if( (*str & 0xC0) != 0x80) return -1; // Validity check
704 *Val |= (*str & 0x3F); // Lower 6 Bits
708 // UTF-8 Doesn't support more than four bytes
713 * \fn int WriteUTF8(Uint8 *str, Uint32 Val)
714 * \brief Write a UTF-8 character sequence to a string
716 int WriteUTF8(Uint8 *str, Uint32 Val)
726 *str = 0xC0 | (Val >> 6);
728 *str = 0x80 | (Val & 0x3F);
733 if( Val < 0x10000 ) {
734 *str = 0xE0 | (Val >> 12);
736 *str = 0x80 | ((Val >> 6) & 0x3F);
738 *str = 0x80 | (Val & 0x3F);
743 if( Val < 0x110000 ) {
744 *str = 0xF0 | (Val >> 18);
746 *str = 0x80 | ((Val >> 12) & 0x3F);
748 *str = 0x80 | ((Val >> 6) & 0x3F);
750 *str = 0x80 | (Val & 0x3F);
754 // UTF-8 Doesn't support more than four bytes
759 * \fn Uint64 timestamp(int sec, int mins, int hrs, int day, int month, int year)
760 * \brief Converts a date into an Acess Timestamp
762 Sint64 timestamp(int sec, int mins, int hrs, int day, int month, int year)
769 stamp += day*3600*24;
770 stamp += month*DAYS_BEFORE[month]*3600*24;
772 ((year&3) == 0 || year%100 != 0)
773 || (year%100 == 0 && ((year/100)&3) == 0)
774 ) && month > 1) // Leap year and after feb
777 stamp += ((365*4+1) * ((year-2000)&~3)) * 3600*24; // Four Year Segments
778 stamp += ((year-2000)&3) * 365*3600*24; // Inside four year segment
786 * \brief Pseudo random number generator
791 static Uint state = RANDOM_SEED;
793 // Get the next state value
794 giRandomState = (RANDOM_A*state + RANDOM_C);
795 // Check if it has changed, and if it hasn't, change it
796 if(state == old) state += RANDOM_SPRUCE;
799 // http://en.wikipedia.org/wiki/Xorshift
801 static Uint32 x = 123456789;
802 static Uint32 y = 362436069;
803 static Uint32 z = 521288629;
804 static Uint32 w = 88675123;
809 return w = w ^ (w >> 19) ^ t ^ (t >> 8);
814 * \name Memory Validation
818 * \brief Checks if a string resides fully in valid memory
820 int CheckString(const char *String)
822 if( !MM_GetPhysAddr( (tVAddr)String ) )
826 if( MM_IsUser( (tVAddr)String ) )
831 if( !MM_IsUser( (tVAddr)String ) )
833 // Increment string pointer
838 else if( MM_GetPhysAddr( (tVAddr)String ) )
843 if( !MM_GetPhysAddr( (tVAddr)String ) )
845 // Increment string pointer
854 * \brief Check if a sized memory region is valid memory
856 int CheckMem(const void *Mem, int NumBytes)
858 tVAddr addr = (tVAddr)Mem;
860 if( MM_IsUser( addr ) )
864 if( !MM_IsUser( addr ) )
870 else if( MM_GetPhysAddr( addr ) )
874 if( !MM_GetPhysAddr( addr ) )
887 * \brief Search a string array for \a Needle
888 * \note Helper function for eTplDrv_IOCtl::DRV_IOCTL_LOOKUP
890 int ModUtil_LookupString(const char **Array, const char *Needle)
893 if( !CheckString(Needle) ) return -1;
894 for( i = 0; Array[i]; i++ )
896 if(strcmp(Array[i], Needle) == 0) return i;
901 int ModUtil_SetIdent(char *Dest, const char *Value)
903 if( !CheckMem(Dest, 32) ) return -1;
904 strncpy(Dest, Value, 32);
909 * \brief Convert a string of hexadecimal digits into a byte stream
911 int UnHex(Uint8 *Dest, size_t DestSize, const char *SourceString)
915 for( i = 0; i < DestSize*2; i += 2 )
919 if(SourceString[i] == '\0') break;
921 if('0' <= SourceString[i] && SourceString[i] <= '9')
922 val |= (SourceString[i]-'0') << 4;
923 else if('A' <= SourceString[i] && SourceString[i] <= 'F')
924 val |= (SourceString[i]-'A'+10) << 4;
925 else if('a' <= SourceString[i] && SourceString[i] <= 'f')
926 val |= (SourceString[i]-'a'+10) << 4;
928 if(SourceString[i+1] == '\0') break;
930 if('0' <= SourceString[i+1] && SourceString[i+1] <= '9')
931 val |= (SourceString[i+1] - '0');
932 else if('A' <= SourceString[i+1] && SourceString[i+1] <= 'F')
933 val |= (SourceString[i+1] - 'A' + 10);
934 else if('a' <= SourceString[i+1] && SourceString[i+1] <= 'f')
935 val |= (SourceString[i+1] - 'a' + 10);
942 Uint16 SwapEndian16(Uint16 Val)
944 return ((Val&0xFF)<<8) | ((Val>>8)&0xFF);
946 Uint32 SwapEndian32(Uint32 Val)
948 return ((Val&0xFF)<<24) | ((Val&0xFF00)<<8) | ((Val>>8)&0xFF00) | ((Val>>24)&0xFF);