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);
94 * \brief Convert a string into an integer
96 int atoi(const char *string)
99 ParseInt(string, &ret);
102 int ParseInt(const char *string, int *Val)
106 const char *orig_string = string;
108 //Log("atoi: (string='%s')", string);
110 // Clear non-numeric characters
111 while( !('0' <= *string && *string <= '9') && *string != '-' ) string++;
112 if( *string == '-' ) {
114 while( !('0' <= *string && *string <= '9') ) string++;
126 if('0' <= *string && *string <= '9') {
128 ret += *string - '0';
130 else if('A' <= *string && *string <= 'F') {
132 ret += *string - 'A' + 10;
134 else if('a' <= *string && *string <= 'f') {
136 ret += *string - 'a' + 10;
144 for( ; '0' <= *string && *string <= '7'; string ++ )
147 ret += *string - '0';
153 for( ; '0' <= *string && *string <= '9'; string++)
156 ret += *string - '0';
159 if( ret == 0 ) return 0;
164 //Log("atoi: RETURN %i", ret);
168 return string - orig_string;
171 static const char cUCDIGITS[] = "0123456789ABCDEF";
173 * \fn void itoa(char *buf, Uint64 num, int base, int minLength, char pad)
174 * \brief Convert an integer into a character string
176 void itoa(char *buf, Uint64 num, int base, int minLength, char pad)
186 if(base > 16 || base < 2) {
192 while(num > base-1) {
193 num = DivMod64U(num, base, &rem); // Shift `num` and get remainder
194 tmpBuf[pos] = cUCDIGITS[ rem ];
197 tmpBuf[pos++] = cUCDIGITS[ num ]; // Last digit of `num`
202 while(minLength-- > 0) buf[i++] = pad;
203 while(pos-- > 0) buf[i++] = tmpBuf[pos]; // Reverse the order of characters
208 * \brief Append a character the the vsnprintf output
210 #define PUTCH(c) _putch(c)
211 #define GETVAL() do {\
212 if(isLongLong) val = va_arg(args, Uint64);\
213 else val = va_arg(args, unsigned int);\
216 * \brief VArg String Number Print Formatted
218 int vsnprintf(char *__s, size_t __maxlen, const char *__format, va_list args)
221 int minSize = 0, precision = -1, len;
222 char tmpBuf[34]; // For Integers
223 const char *p = NULL;
230 auto void _putch(char ch);
236 if(__s) __s[pos] = ch;
241 while((c = *__format++) != 0)
243 // Non control character
244 if(c != '%') { PUTCH(c); continue; }
250 if(c == '%') { PUTCH('%'); continue; }
252 // Pointer - Done first for debugging
254 Uint ptr = va_arg(args, Uint);
255 PUTCH('*'); PUTCH('0'); PUTCH('x');
256 for( len = BITS/4; len --; )
257 PUTCH( cUCDIGITS[ (ptr>>(len*4))&15 ] );
261 // - Padding Side Flag
276 if(c == '*') { // Dynamic length
277 minSize = va_arg(args, unsigned int);
280 else if('1' <= c && c <= '9')
283 while('0' <= c && c <= '9')
298 if(c == '*') { // Dynamic length
299 precision = va_arg(args, unsigned int);
302 else if('1' <= c && c <= '9')
305 while('0' <= c && c <= '9')
308 precision += c - '0';
314 // - Default, Long or LongLong?
316 if(c == 'l') // Long is actually the default on x86
325 // - Now get the format code
332 if( isLongLong && val >> 63 ) {
336 else if( !isLongLong && val >> 31 ) {
340 itoa(tmpBuf, val, 10, minSize, pad);
342 case 'u': // Unsigned
344 itoa(tmpBuf, val, 10, minSize, pad);
346 case 'P': // Physical Address
349 if(sizeof(tPAddr) > 4) isLongLong = 1;
351 itoa(tmpBuf, val, 16, minSize, pad);
355 isLongLong = 1; // TODO: Handle non-x86 64-bit archs
357 itoa(tmpBuf, val, 16, minSize, pad);
360 case 'x': // Lower case hex
362 itoa(tmpBuf, val, 16, minSize, pad);
366 itoa(tmpBuf, val, 8, minSize, pad);
370 itoa(tmpBuf, val, 2, minSize, pad);
374 val = va_arg(args, unsigned int);
379 // String - Null Terminated Array
381 p = va_arg(args, char*); // Get Argument
382 if( !p || !CheckString(p) ) p = "(inval)"; // Avoid #PFs
386 if( !bPadLeft ) while(len++ < minSize) PUTCH(pad);
387 while(*p && precision--) PUTCH(*p++);
388 if( bPadLeft ) while(len++ < minSize) PUTCH(pad);
391 case 'C': // Non-Null Terminated Character Array
392 p = va_arg(args, char*);
393 if( !CheckMem(p, minSize) ) continue; // No #PFs please
394 if(!p) goto printString;
395 while(minSize--) PUTCH(*p++);
407 if(__s && pos != __maxlen)
416 int snprintf(char *__s, size_t __n, const char *__format, ...)
421 va_start(args, __format);
422 ret = vsnprintf(__s, __n, __format, args);
430 int sprintf(char *__s, const char *__format, ...)
435 va_start(args, __format);
436 ret = vsnprintf(__s, -1, __format, args);
443 * \fn int tolower(int c)
444 * \brief Converts a character to lower case
448 if('A' <= c && c <= 'Z')
449 return c - 'A' + 'a';
454 * \fn int strucmp(const char *Str1, const char *Str2)
455 * \brief Compare \a Str1 and \a Str2 case-insensitively
457 int strucmp(const char *Str1, const char *Str2)
459 while(*Str1 && tolower(*Str1) == tolower(*Str2))
461 return tolower(*Str1) - tolower(*Str2);
465 * \brief Locate a byte in a string
467 char *strchr(const char *__s, int __c)
469 for( ; *__s; __s ++ )
471 if( *__s == __c ) return (char*)__s;
477 * \fn int strpos(const char *Str, char Ch)
478 * \brief Search a string for an ascii character
480 int strpos(const char *Str, char Ch)
483 for(pos=0;Str[pos];pos++)
485 if(Str[pos] == Ch) return pos;
491 * \fn Uint8 ByteSum(void *Ptr, int Size)
492 * \brief Adds the bytes in a memory region and returns the sum
494 Uint8 ByteSum(const void *Ptr, int Size)
497 const Uint8 *data = Ptr;
498 while(Size--) sum += *(data++);
503 * \fn size_t strlen(const char *__str)
504 * \brief Get the length of string
506 size_t strlen(const char *__str)
509 while(*__str++) ret++;
514 * \brief Copy a string to a new location
516 char *strcpy(char *__str1, const char *__str2)
519 *__str1++ = *__str2++;
520 *__str1 = '\0'; // Terminate String
525 * \brief Copy a string to a new location
526 * \note Copies at most `max` chars
528 char *strncpy(char *__str1, const char *__str2, size_t __max)
530 while(*__str2 && __max-- >= 1)
531 *__str1++ = *__str2++;
533 *__str1 = '\0'; // Terminate String
538 * \brief Append a string to another
540 char *strcat(char *__dest, const char *__src)
545 *__dest++ = *__src++;
551 * \brief Append at most \a n chars to a string from another
552 * \note At most n+1 chars are written (the dest is always zero terminated)
554 char *strncat(char *__dest, const char *__src, size_t n)
557 while(*__src && n-- >= 1)
558 *__dest++ = *__src++;
564 * \fn int strcmp(const char *str1, const char *str2)
565 * \brief Compare two strings return the difference between
566 * the first non-matching characters.
568 int strcmp(const char *str1, const char *str2)
570 while(*str1 && *str1 == *str2)
572 return *str1 - *str2;
576 * \fn int strncmp(const char *Str1, const char *Str2, size_t num)
577 * \brief Compare strings \a Str1 and \a Str2 to a maximum of \a num characters
579 int strncmp(const char *Str1, const char *Str2, size_t num)
581 if(num == 0) return 0; // TODO: Check what should officially happen here
582 while(--num && *Str1 && *Str1 == *Str2)
589 * \fn char *strdup(const char *Str)
590 * \brief Duplicates a string
592 char *strdup(const char *Str)
595 ret = malloc(strlen(Str)+1);
596 if( !ret ) return NULL;
603 * \fn char *_strdup(const char *File, int Line, const char *Str)
604 * \brief Duplicates a string
606 char *_strdup(const char *File, int Line, const char *Str)
609 ret = Heap_Allocate(File, Line, strlen(Str)+1);
610 if( !ret ) return NULL;
617 * \brief Split a string using the passed character
618 * \return NULL terminated array of strings on the heap
619 * \param __str String to split
620 * \param __ch Character to split by
622 char **str_split(const char *__str, char __ch)
629 for( i = 0; __str[i]; i++ )
635 ret = malloc( sizeof(char*)*(len+1) + (i + 1) );
636 if( !ret ) return NULL;
639 start = (char *)&ret[len+1];
641 for( i = 0; __str[i]; i++ )
643 if(__str[i] == __ch) {
658 * \fn int DivUp(int num, int dem)
659 * \brief Divide two numbers, rounding up
660 * \param num Numerator
661 * \param dem Denominator
663 int DivUp(int num, int dem)
665 return (num+dem-1)/dem;
669 * \fn int strpos8(const char *str, Uint32 search)
670 * \brief Search a string for a UTF-8 character
672 int strpos8(const char *str, Uint32 Search)
676 for(pos=0;str[pos];pos++)
680 if(str[pos] == Search) return pos;
683 if(*(Uint8*)(str+pos) < 128) continue;
685 pos += ReadUTF8( (Uint8*)&str[pos], &val );
686 if(val == Search) return pos;
692 * \fn int ReadUTF8(Uint8 *str, Uint32 *Val)
693 * \brief Read a UTF-8 character from a string
695 int ReadUTF8(const Uint8 *str, Uint32 *Val)
697 *Val = 0xFFFD; // Assume invalid character
700 if( !(*str & 0x80) ) {
705 // Middle of a sequence
706 if( (*str & 0xC0) == 0x80 ) {
711 if( (*str & 0xE0) == 0xC0 ) {
712 *Val = (*str & 0x1F) << 6; // Upper 6 Bits
714 if( (*str & 0xC0) != 0x80) return -1; // Validity check
715 *Val |= (*str & 0x3F); // Lower 6 Bits
720 if( (*str & 0xF0) == 0xE0 ) {
721 *Val = (*str & 0x0F) << 12; // Upper 4 Bits
723 if( (*str & 0xC0) != 0x80) return -1; // Validity check
724 *Val |= (*str & 0x3F) << 6; // Middle 6 Bits
726 if( (*str & 0xC0) != 0x80) return -1; // Validity check
727 *Val |= (*str & 0x3F); // Lower 6 Bits
732 if( (*str & 0xF1) == 0xF0 ) {
733 *Val = (*str & 0x07) << 18; // Upper 3 Bits
735 if( (*str & 0xC0) != 0x80) return -1; // Validity check
736 *Val |= (*str & 0x3F) << 12; // Middle-upper 6 Bits
738 if( (*str & 0xC0) != 0x80) return -1; // Validity check
739 *Val |= (*str & 0x3F) << 6; // Middle-lower 6 Bits
741 if( (*str & 0xC0) != 0x80) return -1; // Validity check
742 *Val |= (*str & 0x3F); // Lower 6 Bits
746 // UTF-8 Doesn't support more than four bytes
751 * \fn int WriteUTF8(Uint8 *str, Uint32 Val)
752 * \brief Write a UTF-8 character sequence to a string
754 int WriteUTF8(Uint8 *str, Uint32 Val)
767 *str++ = 0xC0 | (Val >> 6);
768 *str++ = 0x80 | (Val & 0x3F);
774 if( Val < 0x10000 ) {
776 *str++ = 0xE0 | (Val >> 12);
777 *str++ = 0x80 | ((Val >> 6) & 0x3F);
778 *str++ = 0x80 | (Val & 0x3F);
784 if( Val < 0x110000 ) {
786 *str++ = 0xF0 | (Val >> 18);
787 *str++ = 0x80 | ((Val >> 12) & 0x3F);
788 *str++ = 0x80 | ((Val >> 6) & 0x3F);
789 *str++ = 0x80 | (Val & 0x3F);
794 // UTF-8 Doesn't support more than four bytes
799 * \fn Uint64 timestamp(int sec, int mins, int hrs, int day, int month, int year)
800 * \brief Converts a date into an Acess Timestamp
802 Sint64 timestamp(int sec, int min, int hrs, int day, int month, int year)
807 if( !(0 <= sec && sec < 60) ) return 0;
808 if( !(0 <= min && min < 60) ) return 0;
809 if( !(0 <= hrs && hrs < 24) ) return 0;
810 if( !(0 <= day && day < 31) ) return 0;
811 if( !(0 <= month && month < 12) ) return 0;
813 stamp = DAYS_BEFORE[month] + day;
818 is_leap = (year % 4 == 0) - (year % 100 == 0) + (year % 400 == 0);
819 ASSERT(is_leap == 0 || is_leap == 1);
821 if( is_leap && month > 1 ) // Leap year and after feb
824 // Get seconds before the first of specified year
825 year -= 2000; // Base off Y2K
826 // base year days + total leap year days
827 stamp += year*365 + (year/400) - (year/100) + (year/4);
838 void format_date(tTime TS, int *year, int *month, int *day, int *hrs, int *mins, int *sec, int *ms)
842 auto Sint64 DivMod64(Sint64 N, Sint64 D, Sint64 *R);
844 Sint64 DivMod64(Sint64 N, Sint64 D, Sint64 *R)
846 int sign = (N < 0) != (D < 0);
850 return -DivMod64U(N, D, (Uint64*)R);
852 return DivMod64U(N, D, (Uint64*)R);
856 // TODO: Leap-seconds?
859 TS = DivMod64( TS, 1000, &rem );
861 TS = DivMod64( TS, 60, &rem );
863 TS = DivMod64( TS, 60, &rem );
865 TS = DivMod64( TS, 24, &rem );
870 TS -= UNIX_TO_2K/(3600*24);
872 // Year (400 yr blocks) - (400/4-3) leap years
873 *year = 400 * DivMod64( TS, 365*400 + (400/4-3), &TS );
874 if( TS < 366 ) // First year in 400 is a leap
878 // 100 yr blocks - 100/4-1 leap years
879 *year += 100 * DivMod64( TS, 365*100 + (100/4-1), &TS );
880 if( TS < 366 ) // First year in 100 isn't a leap
884 *year += 4 * DivMod64( TS, 365*4 + 1, &TS );
885 if( TS < 366 ) // First year in 4 is a leap
889 *year += DivMod64( TS, 356, &TS );
898 // Month (if after the first of march, which is 29 Feb in a leap year)
899 if( is_leap && TS > DAYS_BEFORE[2] ) {
900 TS -= 1; // Shifts 29 Feb to 28 Feb
903 // Get what month it is
904 for( i = 0; i < 12; i ++ ) {
905 if( TS < DAYS_BEFORE[i] )
910 TS -= DAYS_BEFORE[i-1];
911 *day += TS; // Plus offset from leap handling above
916 * \brief Pseudo random number generator
921 static Uint state = RANDOM_SEED;
923 // Get the next state value
924 giRandomState = (RANDOM_A*state + RANDOM_C);
925 // Check if it has changed, and if it hasn't, change it
926 if(state == old) state += RANDOM_SPRUCE;
929 // http://en.wikipedia.org/wiki/Xorshift
931 static Uint32 x = 123456789;
932 static Uint32 y = 362436069;
933 static Uint32 z = 521288629;
934 static Uint32 w = 88675123;
939 return w = w ^ (w >> 19) ^ t ^ (t >> 8);
944 * \name Memory Validation
948 * \brief Checks if a string resides fully in valid memory
950 int CheckString(const char *String)
955 addr = (tVAddr)String;
957 if( !MM_GetPhysAddr( addr ) )
961 bUser = MM_IsUser( addr );
963 while( *(char*)addr )
965 if( (addr & (PAGE_SIZE-1)) == 0 )
967 if(bUser && !MM_IsUser(addr) )
969 if(!bUser && !MM_GetPhysAddr(addr) )
978 * \brief Check if a sized memory region is valid memory
979 * \return Boolean success
981 int CheckMem(const void *Mem, int NumBytes)
983 return MM_IsValidBuffer( (tVAddr)Mem, NumBytes );
990 * \brief Search a string array for \a Needle
991 * \note Helper function for eTplDrv_IOCtl::DRV_IOCTL_LOOKUP
993 int ModUtil_LookupString(const char **Array, const char *Needle)
996 if( !CheckString(Needle) ) return -1;
997 for( i = 0; Array[i]; i++ )
999 if(strcmp(Array[i], Needle) == 0) return i;
1004 int ModUtil_SetIdent(char *Dest, const char *Value)
1006 if( !CheckMem(Dest, 32) ) return -1;
1007 strncpy(Dest, Value, 32);
1011 int Hex(char *Dest, size_t Size, const Uint8 *SourceData)
1014 for( i = 0; i < Size; i ++ )
1016 sprintf(Dest + i*2, "%02x", SourceData[i]);
1022 * \brief Convert a string of hexadecimal digits into a byte stream
1024 int UnHex(Uint8 *Dest, size_t DestSize, const char *SourceString)
1028 for( i = 0; i < DestSize*2; i += 2 )
1032 if(SourceString[i] == '\0') break;
1034 if('0' <= SourceString[i] && SourceString[i] <= '9')
1035 val |= (SourceString[i]-'0') << 4;
1036 else if('A' <= SourceString[i] && SourceString[i] <= 'F')
1037 val |= (SourceString[i]-'A'+10) << 4;
1038 else if('a' <= SourceString[i] && SourceString[i] <= 'f')
1039 val |= (SourceString[i]-'a'+10) << 4;
1041 if(SourceString[i+1] == '\0') break;
1043 if('0' <= SourceString[i+1] && SourceString[i+1] <= '9')
1044 val |= (SourceString[i+1] - '0');
1045 else if('A' <= SourceString[i+1] && SourceString[i+1] <= 'F')
1046 val |= (SourceString[i+1] - 'A' + 10);
1047 else if('a' <= SourceString[i+1] && SourceString[i+1] <= 'f')
1048 val |= (SourceString[i+1] - 'a' + 10);
1055 Uint16 SwapEndian16(Uint16 Val)
1057 return ((Val&0xFF)<<8) | ((Val>>8)&0xFF);
1059 Uint32 SwapEndian32(Uint32 Val)
1061 return ((Val&0xFF)<<24) | ((Val&0xFF00)<<8) | ((Val>>8)&0xFF00) | ((Val>>24)&0xFF);
1064 void *memmove(void *__dest, const void *__src, size_t len)
1067 char *dest = __dest;
1068 const char *src = __src;
1071 if( len == 0 || dest == src )
1074 if( (tVAddr)dest > (tVAddr)src + len )
1075 return memcpy(dest, src, len);
1076 if( (tVAddr)dest + len < (tVAddr)src )
1077 return memcpy(dest, src, len);
1079 // NOTE: Assumes memcpy works forward
1080 if( (tVAddr)dest < (tVAddr)src )
1081 return memcpy(dest, src, len);
1083 if( (tVAddr)dest < (tVAddr)src )
1084 block_size = (tVAddr)src - (tVAddr)dest;
1086 block_size = (tVAddr)dest - (tVAddr)src;
1090 while(len >= block_size)
1092 memcpy(dest, src, block_size);
1097 memcpy(dest, src, len);