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 int ParseInt(const char *string, int *Val);
21 void itoa(char *buf, Uint64 num, int base, int minLength, char pad);
22 int vsnprintf(char *__s, size_t __maxlen, const char *__format, va_list args);
23 int snprintf(char *__s, size_t __n, const char *__format, ...);
24 int sprintf(char *__s, const char *__format, ...);
28 int strucmp(const char *Str1, const char *Str2);
29 char *strchr(const char *__s, int __c);
30 int strpos(const char *Str, char Ch);
31 Uint8 ByteSum(void *Ptr, int Size);
32 size_t strlen(const char *__s);
33 char *strcpy(char *__str1, const char *__str2);
34 char *strncpy(char *__str1, const char *__str2, size_t max);
35 int strcmp(const char *str1, const char *str2);
36 int strncmp(const char *str1, const char *str2, size_t num);
37 char *_strdup(const char *File, int Line, const char *Str);
38 char **str_split(const char *__str, char __ch);
39 int strpos8(const char *str, Uint32 Search);
40 int ReadUTF8(Uint8 *str, Uint32 *Val);
41 int WriteUTF8(Uint8 *str, Uint32 Val);
42 int DivUp(int num, int dem);
43 Sint64 timestamp(int sec, int mins, int hrs, int day, int month, int year);
44 void format_date(tTime TS, int *year, int *month, int *day, int *hrs, int *mins, int *sec, int *ms);
47 int CheckString(char *String);
48 int CheckMem(void *Mem, int NumBytes);
50 int ModUtil_LookupString(char **Array, char *Needle);
51 int ModUtil_SetIdent(char *Dest, char *Value);
53 int Hex(char *Dest, size_t Size, const Uint8 *SourceData);
54 int UnHex(Uint8 *Dest, size_t DestSize, const char *SourceString);
76 EXPORT(_strdup); // Takes File/Line too
85 EXPORT(ModUtil_LookupString);
86 EXPORT(ModUtil_SetIdent);
95 * \brief Convert a string into an integer
97 int atoi(const char *string)
100 ParseInt(string, &ret);
103 int ParseInt(const char *string, int *Val)
107 const char *orig_string = string;
109 //Log("atoi: (string='%s')", string);
111 // Clear non-numeric characters
112 while( !('0' <= *string && *string <= '9') && *string != '-' ) string++;
113 if( *string == '-' ) {
115 while( !('0' <= *string && *string <= '9') ) string++;
127 if('0' <= *string && *string <= '9') {
129 ret += *string - '0';
131 else if('A' <= *string && *string <= 'F') {
133 ret += *string - 'A' + 10;
135 else if('a' <= *string && *string <= 'f') {
137 ret += *string - 'a' + 10;
145 for( ; '0' <= *string && *string <= '7'; string ++ )
148 ret += *string - '0';
154 for( ; '0' <= *string && *string <= '9'; string++)
157 ret += *string - '0';
160 if( ret == 0 ) return 0;
165 //Log("atoi: RETURN %i", ret);
169 return string - orig_string;
172 static const char cUCDIGITS[] = "0123456789ABCDEF";
174 * \fn void itoa(char *buf, Uint64 num, int base, int minLength, char pad)
175 * \brief Convert an integer into a character string
177 void itoa(char *buf, Uint64 num, int base, int minLength, char pad)
187 if(base > 16 || base < 2) {
193 while(num > base-1) {
194 num = DivMod64U(num, base, &rem); // Shift `num` and get remainder
195 tmpBuf[pos] = cUCDIGITS[ rem ];
198 tmpBuf[pos++] = cUCDIGITS[ num ]; // Last digit of `num`
203 while(minLength-- > 0) buf[i++] = pad;
204 while(pos-- > 0) buf[i++] = tmpBuf[pos]; // Reverse the order of characters
209 * \brief Append a character the the vsnprintf output
211 #define PUTCH(c) _putch(c)
212 #define GETVAL() do {\
213 if(isLongLong) val = va_arg(args, Uint64);\
214 else val = va_arg(args, unsigned int);\
217 * \brief VArg String Number Print Formatted
219 int vsnprintf(char *__s, size_t __maxlen, const char *__format, va_list args)
222 int minSize = 0, precision = -1, len;
223 char tmpBuf[34]; // For Integers
224 const char *p = NULL;
231 auto void _putch(char ch);
237 if(__s) __s[pos] = ch;
242 while((c = *__format++) != 0)
244 // Non control character
245 if(c != '%') { PUTCH(c); continue; }
251 if(c == '%') { PUTCH('%'); continue; }
253 // Pointer - Done first for debugging
255 Uint ptr = va_arg(args, Uint);
256 PUTCH('*'); PUTCH('0'); PUTCH('x');
257 for( len = BITS/4; len --; )
258 PUTCH( cUCDIGITS[ (ptr>>(len*4))&15 ] );
262 // - Padding Side Flag
277 if(c == '*') { // Dynamic length
278 minSize = va_arg(args, unsigned int);
281 else if('1' <= c && c <= '9')
284 while('0' <= c && c <= '9')
299 if(c == '*') { // Dynamic length
300 precision = va_arg(args, unsigned int);
303 else if('1' <= c && c <= '9')
306 while('0' <= c && c <= '9')
309 precision += c - '0';
315 // - Default, Long or LongLong?
317 if(c == 'l') // Long is actually the default on x86
326 // - Now get the format code
333 if( isLongLong && val >> 63 ) {
337 else if( !isLongLong && val >> 31 ) {
341 itoa(tmpBuf, val, 10, minSize, pad);
343 case 'u': // Unsigned
345 itoa(tmpBuf, val, 10, minSize, pad);
347 case 'P': // Physical Address
350 if(sizeof(tPAddr) > 4) isLongLong = 1;
352 itoa(tmpBuf, val, 16, minSize, pad);
356 isLongLong = 1; // TODO: Handle non-x86 64-bit archs
358 itoa(tmpBuf, val, 16, minSize, pad);
361 case 'x': // Lower case hex
363 itoa(tmpBuf, val, 16, minSize, pad);
367 itoa(tmpBuf, val, 8, minSize, pad);
371 itoa(tmpBuf, val, 2, minSize, pad);
375 val = va_arg(args, unsigned int);
380 // String - Null Terminated Array
382 p = va_arg(args, char*); // Get Argument
383 if( !p || !CheckString(p) ) p = "(inval)"; // Avoid #PFs
387 if( !bPadLeft ) while(len++ < minSize) PUTCH(pad);
388 while(*p && precision--) PUTCH(*p++);
389 if( bPadLeft ) while(len++ < minSize) PUTCH(pad);
392 case 'C': // Non-Null Terminated Character Array
393 p = va_arg(args, char*);
394 if( !CheckMem(p, minSize) ) continue; // No #PFs please
395 if(!p) goto printString;
396 while(minSize--) PUTCH(*p++);
408 if(__s && pos != __maxlen)
417 int snprintf(char *__s, size_t __n, const char *__format, ...)
422 va_start(args, __format);
423 ret = vsnprintf(__s, __n, __format, args);
431 int sprintf(char *__s, const char *__format, ...)
436 va_start(args, __format);
437 ret = vsnprintf(__s, -1, __format, args);
444 * \fn int tolower(int c)
445 * \brief Converts a character to lower case
449 if('A' <= c && c <= 'Z')
450 return c - 'A' + 'a';
455 * \fn int strucmp(const char *Str1, const char *Str2)
456 * \brief Compare \a Str1 and \a Str2 case-insensitively
458 int strucmp(const char *Str1, const char *Str2)
460 while(*Str1 && tolower(*Str1) == tolower(*Str2))
462 return tolower(*Str1) - tolower(*Str2);
466 * \brief Locate a byte in a string
468 char *strchr(const char *__s, int __c)
470 for( ; *__s; __s ++ )
472 if( *__s == __c ) return (char*)__s;
478 * \fn int strpos(const char *Str, char Ch)
479 * \brief Search a string for an ascii character
481 int strpos(const char *Str, char Ch)
484 for(pos=0;Str[pos];pos++)
486 if(Str[pos] == Ch) return pos;
492 * \fn Uint8 ByteSum(void *Ptr, int Size)
493 * \brief Adds the bytes in a memory region and returns the sum
495 Uint8 ByteSum(const void *Ptr, int Size)
498 const Uint8 *data = Ptr;
499 while(Size--) sum += *(data++);
504 * \fn size_t strlen(const char *__str)
505 * \brief Get the length of string
507 size_t strlen(const char *__str)
510 while(*__str++) ret++;
515 * \brief Copy a string to a new location
517 char *strcpy(char *__str1, const char *__str2)
520 *__str1++ = *__str2++;
521 *__str1 = '\0'; // Terminate String
526 * \brief Copy a string to a new location
527 * \note Copies at most `max` chars
529 char *strncpy(char *__str1, const char *__str2, size_t __max)
531 while(*__str2 && __max-- >= 1)
532 *__str1++ = *__str2++;
534 *__str1 = '\0'; // Terminate String
539 * \brief Append a string to another
541 char *strcat(char *__dest, const char *__src)
546 *__dest++ = *__src++;
552 * \brief Append at most \a n chars to a string from another
553 * \note At most n+1 chars are written (the dest is always zero terminated)
555 char *strncat(char *__dest, const char *__src, size_t n)
558 while(*__src && n-- >= 1)
559 *__dest++ = *__src++;
565 * \fn int strcmp(const char *str1, const char *str2)
566 * \brief Compare two strings return the difference between
567 * the first non-matching characters.
569 int strcmp(const char *str1, const char *str2)
571 while(*str1 && *str1 == *str2)
573 return *str1 - *str2;
577 * \fn int strncmp(const char *Str1, const char *Str2, size_t num)
578 * \brief Compare strings \a Str1 and \a Str2 to a maximum of \a num characters
580 int strncmp(const char *Str1, const char *Str2, size_t num)
582 if(num == 0) return 0; // TODO: Check what should officially happen here
583 while(--num && *Str1 && *Str1 == *Str2)
590 * \fn char *strdup(const char *Str)
591 * \brief Duplicates a string
593 char *strdup(const char *Str)
596 ret = malloc(strlen(Str)+1);
597 if( !ret ) return NULL;
604 * \fn char *_strdup(const char *File, int Line, const char *Str)
605 * \brief Duplicates a string
607 char *_strdup(const char *File, int Line, const char *Str)
610 ret = Heap_Allocate(File, Line, strlen(Str)+1);
611 if( !ret ) return NULL;
618 * \brief Split a string using the passed character
619 * \return NULL terminated array of strings on the heap
620 * \param __str String to split
621 * \param __ch Character to split by
623 char **str_split(const char *__str, char __ch)
630 for( i = 0; __str[i]; i++ )
636 ret = malloc( sizeof(char*)*(len+1) + (i + 1) );
637 if( !ret ) return NULL;
640 start = (char *)&ret[len+1];
642 for( i = 0; __str[i]; i++ )
644 if(__str[i] == __ch) {
659 * \fn int DivUp(int num, int dem)
660 * \brief Divide two numbers, rounding up
661 * \param num Numerator
662 * \param dem Denominator
664 int DivUp(int num, int dem)
666 return (num+dem-1)/dem;
670 * \fn int strpos8(const char *str, Uint32 search)
671 * \brief Search a string for a UTF-8 character
673 int strpos8(const char *str, Uint32 Search)
677 for(pos=0;str[pos];pos++)
681 if(str[pos] == Search) return pos;
684 if(*(Uint8*)(str+pos) < 128) continue;
686 pos += ReadUTF8( (Uint8*)&str[pos], &val );
687 if(val == Search) return pos;
693 * \fn int ReadUTF8(Uint8 *str, Uint32 *Val)
694 * \brief Read a UTF-8 character from a string
696 int ReadUTF8(const Uint8 *str, Uint32 *Val)
698 *Val = 0xFFFD; // Assume invalid character
701 if( !(*str & 0x80) ) {
706 // Middle of a sequence
707 if( (*str & 0xC0) == 0x80 ) {
712 if( (*str & 0xE0) == 0xC0 ) {
713 *Val = (*str & 0x1F) << 6; // Upper 6 Bits
715 if( (*str & 0xC0) != 0x80) return -1; // Validity check
716 *Val |= (*str & 0x3F); // Lower 6 Bits
721 if( (*str & 0xF0) == 0xE0 ) {
722 *Val = (*str & 0x0F) << 12; // Upper 4 Bits
724 if( (*str & 0xC0) != 0x80) return -1; // Validity check
725 *Val |= (*str & 0x3F) << 6; // Middle 6 Bits
727 if( (*str & 0xC0) != 0x80) return -1; // Validity check
728 *Val |= (*str & 0x3F); // Lower 6 Bits
733 if( (*str & 0xF1) == 0xF0 ) {
734 *Val = (*str & 0x07) << 18; // Upper 3 Bits
736 if( (*str & 0xC0) != 0x80) return -1; // Validity check
737 *Val |= (*str & 0x3F) << 12; // Middle-upper 6 Bits
739 if( (*str & 0xC0) != 0x80) return -1; // Validity check
740 *Val |= (*str & 0x3F) << 6; // Middle-lower 6 Bits
742 if( (*str & 0xC0) != 0x80) return -1; // Validity check
743 *Val |= (*str & 0x3F); // Lower 6 Bits
747 // UTF-8 Doesn't support more than four bytes
752 * \fn int WriteUTF8(Uint8 *str, Uint32 Val)
753 * \brief Write a UTF-8 character sequence to a string
755 int WriteUTF8(Uint8 *str, Uint32 Val)
768 *str++ = 0xC0 | (Val >> 6);
769 *str++ = 0x80 | (Val & 0x3F);
775 if( Val < 0x10000 ) {
777 *str++ = 0xE0 | (Val >> 12);
778 *str++ = 0x80 | ((Val >> 6) & 0x3F);
779 *str++ = 0x80 | (Val & 0x3F);
785 if( Val < 0x110000 ) {
787 *str++ = 0xF0 | (Val >> 18);
788 *str++ = 0x80 | ((Val >> 12) & 0x3F);
789 *str++ = 0x80 | ((Val >> 6) & 0x3F);
790 *str++ = 0x80 | (Val & 0x3F);
795 // UTF-8 Doesn't support more than four bytes
800 * \fn Uint64 timestamp(int sec, int mins, int hrs, int day, int month, int year)
801 * \brief Converts a date into an Acess Timestamp
803 Sint64 timestamp(int sec, int min, int hrs, int day, int month, int year)
808 if( !(0 <= sec && sec < 60) ) return 0;
809 if( !(0 <= min && min < 60) ) return 0;
810 if( !(0 <= hrs && hrs < 24) ) return 0;
811 if( !(0 <= day && day < 31) ) return 0;
812 if( !(0 <= month && month < 12) ) return 0;
814 stamp = DAYS_BEFORE[month] + day;
819 is_leap = (year % 4 == 0) - (year % 100 == 0) + (year % 400 == 0);
820 ASSERT(is_leap == 0 || is_leap == 1);
822 if( is_leap && month > 1 ) // Leap year and after feb
825 // Get seconds before the first of specified year
826 year -= 2000; // Base off Y2K
827 // base year days + total leap year days
828 stamp += year*365 + (year/400) - (year/100) + (year/4);
839 void format_date(tTime TS, int *year, int *month, int *day, int *hrs, int *mins, int *sec, int *ms)
843 auto Sint64 DivMod64(Sint64 N, Sint64 D, Sint64 *R);
845 Sint64 DivMod64(Sint64 N, Sint64 D, Sint64 *R)
847 int sign = (N < 0) != (D < 0);
851 return -DivMod64U(N, D, (Uint64*)R);
853 return DivMod64U(N, D, (Uint64*)R);
857 // TODO: Leap-seconds?
860 TS = DivMod64( TS, 1000, &rem );
862 TS = DivMod64( TS, 60, &rem );
864 TS = DivMod64( TS, 60, &rem );
866 TS = DivMod64( TS, 24, &rem );
871 TS -= UNIX_TO_2K/(3600*24);
873 // Year (400 yr blocks) - (400/4-3) leap years
874 *year = 400 * DivMod64( TS, 365*400 + (400/4-3), &TS );
875 if( TS < 366 ) // First year in 400 is a leap
879 // 100 yr blocks - 100/4-1 leap years
880 *year += 100 * DivMod64( TS, 365*100 + (100/4-1), &TS );
881 if( TS < 366 ) // First year in 100 isn't a leap
885 *year += 4 * DivMod64( TS, 365*4 + 1, &TS );
886 if( TS < 366 ) // First year in 4 is a leap
890 *year += DivMod64( TS, 356, &TS );
899 // Month (if after the first of march, which is 29 Feb in a leap year)
900 if( is_leap && TS > DAYS_BEFORE[2] ) {
901 TS -= 1; // Shifts 29 Feb to 28 Feb
904 // Get what month it is
905 for( i = 0; i < 12; i ++ ) {
906 if( TS < DAYS_BEFORE[i] )
911 TS -= DAYS_BEFORE[i-1];
912 *day += TS; // Plus offset from leap handling above
917 * \brief Pseudo random number generator
922 static Uint state = RANDOM_SEED;
924 // Get the next state value
925 giRandomState = (RANDOM_A*state + RANDOM_C);
926 // Check if it has changed, and if it hasn't, change it
927 if(state == old) state += RANDOM_SPRUCE;
930 // http://en.wikipedia.org/wiki/Xorshift
932 static Uint32 x = 123456789;
933 static Uint32 y = 362436069;
934 static Uint32 z = 521288629;
935 static Uint32 w = 88675123;
940 return w = w ^ (w >> 19) ^ t ^ (t >> 8);
945 * \name Memory Validation
949 * \brief Checks if a string resides fully in valid memory
951 int CheckString(const char *String)
956 addr = (tVAddr)String;
958 if( !MM_GetPhysAddr( addr ) )
962 bUser = MM_IsUser( addr );
964 while( *(char*)addr )
966 if( (addr & (PAGE_SIZE-1)) == 0 )
968 if(bUser && !MM_IsUser(addr) )
970 if(!bUser && !MM_GetPhysAddr(addr) )
979 * \brief Check if a sized memory region is valid memory
980 * \return Boolean success
982 int CheckMem(const void *Mem, int NumBytes)
984 return MM_IsValidBuffer( (tVAddr)Mem, NumBytes );
991 * \brief Search a string array for \a Needle
992 * \note Helper function for eTplDrv_IOCtl::DRV_IOCTL_LOOKUP
994 int ModUtil_LookupString(const char **Array, const char *Needle)
997 if( !CheckString(Needle) ) return -1;
998 for( i = 0; Array[i]; i++ )
1000 if(strcmp(Array[i], Needle) == 0) return i;
1005 int ModUtil_SetIdent(char *Dest, const char *Value)
1007 if( !CheckMem(Dest, 32) ) return -1;
1008 strncpy(Dest, Value, 32);
1012 int Hex(char *Dest, size_t Size, const Uint8 *SourceData)
1015 for( i = 0; i < Size; i ++ )
1017 sprintf(Dest + i*2, "%02x", SourceData[i]);
1023 * \brief Convert a string of hexadecimal digits into a byte stream
1025 int UnHex(Uint8 *Dest, size_t DestSize, const char *SourceString)
1029 for( i = 0; i < DestSize*2; i += 2 )
1033 if(SourceString[i] == '\0') break;
1035 if('0' <= SourceString[i] && SourceString[i] <= '9')
1036 val |= (SourceString[i]-'0') << 4;
1037 else if('A' <= SourceString[i] && SourceString[i] <= 'F')
1038 val |= (SourceString[i]-'A'+10) << 4;
1039 else if('a' <= SourceString[i] && SourceString[i] <= 'f')
1040 val |= (SourceString[i]-'a'+10) << 4;
1042 if(SourceString[i+1] == '\0') break;
1044 if('0' <= SourceString[i+1] && SourceString[i+1] <= '9')
1045 val |= (SourceString[i+1] - '0');
1046 else if('A' <= SourceString[i+1] && SourceString[i+1] <= 'F')
1047 val |= (SourceString[i+1] - 'A' + 10);
1048 else if('a' <= SourceString[i+1] && SourceString[i+1] <= 'f')
1049 val |= (SourceString[i+1] - 'a' + 10);
1056 Uint16 SwapEndian16(Uint16 Val)
1058 return ((Val&0xFF)<<8) | ((Val>>8)&0xFF);
1060 Uint32 SwapEndian32(Uint32 Val)
1062 return ((Val&0xFF)<<24) | ((Val&0xFF00)<<8) | ((Val>>8)&0xFF00) | ((Val>>24)&0xFF);
1064 Uint64 SwapEndian64(Uint64 Val)
1066 return SwapEndian32(Val >> 32) | ((Uint64)SwapEndian32(Val) << 32);
1069 void *memmove(void *__dest, const void *__src, size_t len)
1072 char *dest = __dest;
1073 const char *src = __src;
1076 if( len == 0 || dest == src )
1079 if( (tVAddr)dest > (tVAddr)src + len )
1080 return memcpy(dest, src, len);
1081 if( (tVAddr)dest + len < (tVAddr)src )
1082 return memcpy(dest, src, len);
1084 // NOTE: Assumes memcpy works forward
1085 if( (tVAddr)dest < (tVAddr)src )
1086 return memcpy(dest, src, len);
1088 if( (tVAddr)dest < (tVAddr)src )
1089 block_size = (tVAddr)src - (tVAddr)dest;
1091 block_size = (tVAddr)dest - (tVAddr)src;
1095 while(len >= block_size)
1097 memcpy(dest, src, block_size);
1102 memcpy(dest, src, len);