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);
43 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 UnHex(Uint8 *Dest, size_t DestSize, const char *SourceString);
74 EXPORT(_strdup); // Takes File/Line too
83 EXPORT(ModUtil_LookupString);
84 EXPORT(ModUtil_SetIdent);
92 * \brief Convert a string into an integer
94 int atoi(const char *string)
99 //Log("atoi: (string='%s')", string);
101 // Clear non-numeric characters
102 while( !('0' <= *string && *string <= '9') && *string != '-' ) string++;
103 if( *string == '-' ) {
105 while( !('0' <= *string && *string <= '9') ) string++;
117 if('0' <= *string && *string <= '9') {
119 ret += *string - '0';
121 else if('A' <= *string && *string <= 'F') {
123 ret += *string - 'A' + 10;
125 else if('a' <= *string && *string <= 'f') {
127 ret += *string - 'a' + 10;
135 for( ; '0' <= *string && *string <= '7'; string ++ )
138 ret += *string - '0';
144 for( ; '0' <= *string && *string <= '9'; string++)
147 ret += *string - '0';
153 //Log("atoi: RETURN %i", ret);
158 static const char cUCDIGITS[] = "0123456789ABCDEF";
160 * \fn void itoa(char *buf, Uint64 num, int base, int minLength, char pad)
161 * \brief Convert an integer into a character string
163 void itoa(char *buf, Uint64 num, int base, int minLength, char pad)
173 if(base > 16 || base < 2) {
179 while(num > base-1) {
180 num = DivMod64U(num, base, &rem); // Shift `num` and get remainder
181 tmpBuf[pos] = cUCDIGITS[ rem ];
184 tmpBuf[pos++] = cUCDIGITS[ num ]; // Last digit of `num`
189 while(minLength-- > 0) buf[i++] = pad;
190 while(pos-- > 0) buf[i++] = tmpBuf[pos]; // Reverse the order of characters
195 * \brief Append a character the the vsnprintf output
197 #define PUTCH(c) _putch(c)
198 #define GETVAL() do {\
199 if(isLongLong) val = va_arg(args, Uint64);\
200 else val = va_arg(args, unsigned int);\
203 * \brief VArg String Number Print Formatted
205 int vsnprintf(char *__s, size_t __maxlen, const char *__format, va_list args)
208 int minSize = 0, precision = -1, len;
209 char tmpBuf[34]; // For Integers
210 const char *p = NULL;
217 auto void _putch(char ch);
223 if(__s) __s[pos] = ch;
228 while((c = *__format++) != 0)
230 // Non control character
231 if(c != '%') { PUTCH(c); continue; }
237 if(c == '%') { PUTCH('%'); continue; }
239 // Pointer - Done first for debugging
241 Uint ptr = va_arg(args, Uint);
242 PUTCH('*'); PUTCH('0'); PUTCH('x');
243 for( len = BITS/4; len --; )
244 PUTCH( cUCDIGITS[ (ptr>>(len*4))&15 ] );
248 // - Padding Side Flag
263 if(c == '*') { // Dynamic length
264 minSize = va_arg(args, unsigned int);
267 else if('1' <= c && c <= '9')
270 while('0' <= c && c <= '9')
285 if(c == '*') { // Dynamic length
286 precision = va_arg(args, unsigned int);
289 else if('1' <= c && c <= '9')
292 while('0' <= c && c <= '9')
295 precision += c - '0';
301 // - Default, Long or LongLong?
303 if(c == 'l') // Long is actually the default on x86
312 // - Now get the format code
319 if( isLongLong && val >> 63 ) {
323 else if( !isLongLong && val >> 31 ) {
327 itoa(tmpBuf, val, 10, minSize, pad);
329 case 'u': // Unsigned
331 itoa(tmpBuf, val, 10, minSize, pad);
333 case 'P': // Physical Address
336 if(sizeof(tPAddr) > 4) isLongLong = 1;
338 itoa(tmpBuf, val, 16, minSize, pad);
342 isLongLong = 1; // TODO: Handle non-x86 64-bit archs
344 itoa(tmpBuf, val, 16, minSize, pad);
347 case 'x': // Lower case hex
349 itoa(tmpBuf, val, 16, minSize, pad);
353 itoa(tmpBuf, val, 8, minSize, pad);
357 itoa(tmpBuf, val, 2, minSize, pad);
361 val = va_arg(args, unsigned int);
366 // String - Null Terminated Array
368 p = va_arg(args, char*); // Get Argument
369 if( !p || !CheckString(p) ) p = "(inval)"; // Avoid #PFs
373 if( !bPadLeft ) while(len++ < minSize) PUTCH(pad);
374 while(*p && precision--) PUTCH(*p++);
375 if( bPadLeft ) while(len++ < minSize) PUTCH(pad);
378 case 'C': // Non-Null Terminated Character Array
379 p = va_arg(args, char*);
380 if( !CheckMem(p, minSize) ) continue; // No #PFs please
381 if(!p) goto printString;
382 while(minSize--) PUTCH(*p++);
394 if(__s && pos != __maxlen)
403 int sprintf(char *__s, const char *__format, ...)
408 va_start(args, __format);
409 ret = vsnprintf(__s, -1, __format, args);
416 * \fn int tolower(int c)
417 * \brief Converts a character to lower case
421 if('A' <= c && c <= 'Z')
422 return c - 'A' + 'a';
427 * \fn int strucmp(const char *Str1, const char *Str2)
428 * \brief Compare \a Str1 and \a Str2 case-insensitively
430 int strucmp(const char *Str1, const char *Str2)
432 while(*Str1 && tolower(*Str1) == tolower(*Str2))
434 return tolower(*Str1) - tolower(*Str2);
438 * \brief Locate a byte in a string
440 char *strchr(const char *__s, int __c)
442 for( ; *__s; __s ++ )
444 if( *__s == __c ) return (char*)__s;
450 * \fn int strpos(const char *Str, char Ch)
451 * \brief Search a string for an ascii character
453 int strpos(const char *Str, char Ch)
456 for(pos=0;Str[pos];pos++)
458 if(Str[pos] == Ch) return pos;
464 * \fn Uint8 ByteSum(void *Ptr, int Size)
465 * \brief Adds the bytes in a memory region and returns the sum
467 Uint8 ByteSum(const void *Ptr, int Size)
470 const Uint8 *data = Ptr;
471 while(Size--) sum += *(data++);
476 * \fn size_t strlen(const char *__str)
477 * \brief Get the length of string
479 size_t strlen(const char *__str)
482 while(*__str++) ret++;
487 * \brief Copy a string to a new location
489 char *strcpy(char *__str1, const char *__str2)
492 *__str1++ = *__str2++;
493 *__str1 = '\0'; // Terminate String
498 * \brief Copy a string to a new location
499 * \note Copies at most `max` chars
501 char *strncpy(char *__str1, const char *__str2, size_t __max)
503 while(*__str2 && __max-- >= 1)
504 *__str1++ = *__str2++;
506 *__str1 = '\0'; // Terminate String
511 * \brief Append a string to another
513 char *strcat(char *__dest, const char *__src)
518 *__dest++ = *__src++;
524 * \brief Append at most \a n chars to a string from another
525 * \note At most n+1 chars are written (the dest is always zero terminated)
527 char *strncat(char *__dest, const char *__src, size_t n)
530 while(*__src && n-- >= 1)
531 *__dest++ = *__src++;
537 * \fn int strcmp(const char *str1, const char *str2)
538 * \brief Compare two strings return the difference between
539 * the first non-matching characters.
541 int strcmp(const char *str1, const char *str2)
543 while(*str1 && *str1 == *str2)
545 return *str1 - *str2;
549 * \fn int strncmp(const char *Str1, const char *Str2, size_t num)
550 * \brief Compare strings \a Str1 and \a Str2 to a maximum of \a num characters
552 int strncmp(const char *Str1, const char *Str2, size_t num)
554 if(num == 0) return 0; // TODO: Check what should officially happen here
555 while(--num && *Str1 && *Str1 == *Str2)
562 * \fn char *strdup(const char *Str)
563 * \brief Duplicates a string
565 char *strdup(const char *Str)
568 ret = malloc(strlen(Str)+1);
569 if( !ret ) return NULL;
576 * \fn char *_strdup(const char *File, int Line, const char *Str)
577 * \brief Duplicates a string
579 char *_strdup(const char *File, int Line, const char *Str)
582 ret = Heap_Allocate(File, Line, strlen(Str)+1);
583 if( !ret ) return NULL;
590 * \brief Split a string using the passed character
591 * \return NULL terminated array of strings on the heap
592 * \param __str String to split
593 * \param __ch Character to split by
595 char **str_split(const char *__str, char __ch)
602 for( i = 0; __str[i]; i++ )
608 ret = malloc( sizeof(char*)*(len+1) + (i + 1) );
609 if( !ret ) return NULL;
612 start = (char *)&ret[len+1];
614 for( i = 0; __str[i]; i++ )
616 if(__str[i] == __ch) {
631 * \fn int DivUp(int num, int dem)
632 * \brief Divide two numbers, rounding up
633 * \param num Numerator
634 * \param dem Denominator
636 int DivUp(int num, int dem)
638 return (num+dem-1)/dem;
642 * \fn int strpos8(const char *str, Uint32 search)
643 * \brief Search a string for a UTF-8 character
645 int strpos8(const char *str, Uint32 Search)
649 for(pos=0;str[pos];pos++)
653 if(str[pos] == Search) return pos;
656 if(*(Uint8*)(str+pos) < 128) continue;
658 pos += ReadUTF8( (Uint8*)&str[pos], &val );
659 if(val == Search) return pos;
665 * \fn int ReadUTF8(Uint8 *str, Uint32 *Val)
666 * \brief Read a UTF-8 character from a string
668 int ReadUTF8(const Uint8 *str, Uint32 *Val)
670 *Val = 0xFFFD; // Assume invalid character
673 if( !(*str & 0x80) ) {
678 // Middle of a sequence
679 if( (*str & 0xC0) == 0x80 ) {
684 if( (*str & 0xE0) == 0xC0 ) {
685 *Val = (*str & 0x1F) << 6; // Upper 6 Bits
687 if( (*str & 0xC0) != 0x80) return -1; // Validity check
688 *Val |= (*str & 0x3F); // Lower 6 Bits
693 if( (*str & 0xF0) == 0xE0 ) {
694 *Val = (*str & 0x0F) << 12; // Upper 4 Bits
696 if( (*str & 0xC0) != 0x80) return -1; // Validity check
697 *Val |= (*str & 0x3F) << 6; // Middle 6 Bits
699 if( (*str & 0xC0) != 0x80) return -1; // Validity check
700 *Val |= (*str & 0x3F); // Lower 6 Bits
705 if( (*str & 0xF1) == 0xF0 ) {
706 *Val = (*str & 0x07) << 18; // Upper 3 Bits
708 if( (*str & 0xC0) != 0x80) return -1; // Validity check
709 *Val |= (*str & 0x3F) << 12; // Middle-upper 6 Bits
711 if( (*str & 0xC0) != 0x80) return -1; // Validity check
712 *Val |= (*str & 0x3F) << 6; // Middle-lower 6 Bits
714 if( (*str & 0xC0) != 0x80) return -1; // Validity check
715 *Val |= (*str & 0x3F); // Lower 6 Bits
719 // UTF-8 Doesn't support more than four bytes
724 * \fn int WriteUTF8(Uint8 *str, Uint32 Val)
725 * \brief Write a UTF-8 character sequence to a string
727 int WriteUTF8(Uint8 *str, Uint32 Val)
740 *str++ = 0xC0 | (Val >> 6);
741 *str++ = 0x80 | (Val & 0x3F);
747 if( Val < 0x10000 ) {
749 *str++ = 0xE0 | (Val >> 12);
750 *str++ = 0x80 | ((Val >> 6) & 0x3F);
751 *str++ = 0x80 | (Val & 0x3F);
757 if( Val < 0x110000 ) {
759 *str++ = 0xF0 | (Val >> 18);
760 *str++ = 0x80 | ((Val >> 12) & 0x3F);
761 *str++ = 0x80 | ((Val >> 6) & 0x3F);
762 *str++ = 0x80 | (Val & 0x3F);
767 // UTF-8 Doesn't support more than four bytes
772 * \fn Uint64 timestamp(int sec, int mins, int hrs, int day, int month, int year)
773 * \brief Converts a date into an Acess Timestamp
775 Sint64 timestamp(int sec, int min, int hrs, int day, int month, int year)
780 if( !(0 <= sec && sec < 60) ) return 0;
781 if( !(0 <= min && min < 60) ) return 0;
782 if( !(0 <= hrs && hrs < 24) ) return 0;
783 if( !(0 <= day && day < 31) ) return 0;
784 if( !(0 <= month && month < 12) ) return 0;
786 stamp = DAYS_BEFORE[month] + day;
791 is_leap = (year % 4 == 0) - (year % 100 == 0) + (year % 400 == 0);
792 ASSERT(is_leap == 0 || is_leap == 1);
794 if( is_leap && month > 1 ) // Leap year and after feb
797 // Get seconds before the first of specified year
798 year -= 2000; // Base off Y2K
799 // base year days + total leap year days
800 stamp += year*365 + (year/400) - (year/100) + (year/4);
811 void format_date(tTime TS, int *year, int *month, int *day, int *hrs, int *mins, int *sec, int *ms)
815 inline Sint64 DivMod64(Sint64 N, Sint64 D, Sint64 *R)
817 int sign = (N < 0) != (D < 0);
821 return -DivMod64U(N, D, (Uint64*)R);
823 return DivMod64U(N, D, (Uint64*)R);
826 // Get within-day time
827 // TODO: Leap-seconds?
830 TS = DivMod64( TS, 1000, &rem );
832 TS = DivMod64( TS, 60, &rem );
834 TS = DivMod64( TS, 60, &rem );
836 TS = DivMod64( TS, 24, &rem );
841 TS -= UNIX_TO_2K/(3600*24);
843 // Year (400 yr blocks) - (400/4-3) leap years
844 *year = 400 * DivMod64( TS, 365*400 + (400/4-3), &TS );
845 if( TS < 366 ) // First year in 400 is a leap
849 // 100 yr blocks - 100/4-1 leap years
850 *year += 100 * DivMod64( TS, 365*100 + (100/4-1), &TS );
851 if( TS < 366 ) // First year in 100 isn't a leap
855 *year += 4 * DivMod64( TS, 365*4 + 1, &TS );
856 if( TS < 366 ) // First year in 4 is a leap
860 *year += DivMod64( TS, 356, &TS );
869 // Month (if after the first of march, which is 29 Feb in a leap year)
870 if( is_leap && TS > DAYS_BEFORE[2] ) {
871 TS -= 1; // Shifts 29 Feb to 28 Feb
874 // Get what month it is
875 for( i = 0; i < 12; i ++ ) {
876 if( TS < DAYS_BEFORE[i] )
881 TS -= DAYS_BEFORE[i-1];
882 *day += TS; // Plus offset from leap handling above
887 * \brief Pseudo random number generator
892 static Uint state = RANDOM_SEED;
894 // Get the next state value
895 giRandomState = (RANDOM_A*state + RANDOM_C);
896 // Check if it has changed, and if it hasn't, change it
897 if(state == old) state += RANDOM_SPRUCE;
900 // http://en.wikipedia.org/wiki/Xorshift
902 static Uint32 x = 123456789;
903 static Uint32 y = 362436069;
904 static Uint32 z = 521288629;
905 static Uint32 w = 88675123;
910 return w = w ^ (w >> 19) ^ t ^ (t >> 8);
915 * \name Memory Validation
919 * \brief Checks if a string resides fully in valid memory
921 int CheckString(const char *String)
926 addr = (tVAddr)String;
928 if( !MM_GetPhysAddr( addr ) )
932 bUser = MM_IsUser( addr );
934 while( *(char*)addr )
936 if( (addr & (PAGE_SIZE-1)) == 0 )
938 if(bUser && !MM_IsUser(addr) )
940 if(!bUser && !MM_GetPhysAddr(addr) )
949 * \brief Check if a sized memory region is valid memory
950 * \return Boolean success
952 int CheckMem(const void *Mem, int NumBytes)
954 return MM_IsValidBuffer( (tVAddr)Mem, NumBytes );
961 * \brief Search a string array for \a Needle
962 * \note Helper function for eTplDrv_IOCtl::DRV_IOCTL_LOOKUP
964 int ModUtil_LookupString(const char **Array, const char *Needle)
967 if( !CheckString(Needle) ) return -1;
968 for( i = 0; Array[i]; i++ )
970 if(strcmp(Array[i], Needle) == 0) return i;
975 int ModUtil_SetIdent(char *Dest, const char *Value)
977 if( !CheckMem(Dest, 32) ) return -1;
978 strncpy(Dest, Value, 32);
983 * \brief Convert a string of hexadecimal digits into a byte stream
985 int UnHex(Uint8 *Dest, size_t DestSize, const char *SourceString)
989 for( i = 0; i < DestSize*2; i += 2 )
993 if(SourceString[i] == '\0') break;
995 if('0' <= SourceString[i] && SourceString[i] <= '9')
996 val |= (SourceString[i]-'0') << 4;
997 else if('A' <= SourceString[i] && SourceString[i] <= 'F')
998 val |= (SourceString[i]-'A'+10) << 4;
999 else if('a' <= SourceString[i] && SourceString[i] <= 'f')
1000 val |= (SourceString[i]-'a'+10) << 4;
1002 if(SourceString[i+1] == '\0') break;
1004 if('0' <= SourceString[i+1] && SourceString[i+1] <= '9')
1005 val |= (SourceString[i+1] - '0');
1006 else if('A' <= SourceString[i+1] && SourceString[i+1] <= 'F')
1007 val |= (SourceString[i+1] - 'A' + 10);
1008 else if('a' <= SourceString[i+1] && SourceString[i+1] <= 'f')
1009 val |= (SourceString[i+1] - 'a' + 10);
1016 Uint16 SwapEndian16(Uint16 Val)
1018 return ((Val&0xFF)<<8) | ((Val>>8)&0xFF);
1020 Uint32 SwapEndian32(Uint32 Val)
1022 return ((Val&0xFF)<<24) | ((Val&0xFF00)<<8) | ((Val>>8)&0xFF00) | ((Val>>24)&0xFF);
1025 void *memmove(void *__dest, const void *__src, size_t len)
1028 char *dest = __dest;
1029 const char *src = __src;
1032 if( len == 0 || dest == src )
1035 if( (tVAddr)dest > (tVAddr)src + len )
1036 return memcpy(dest, src, len);
1037 if( (tVAddr)dest + len < (tVAddr)src )
1038 return memcpy(dest, src, len);
1040 // NOTE: Assumes memcpy works forward
1041 if( (tVAddr)dest < (tVAddr)src )
1042 return memcpy(dest, src, len);
1044 if( (tVAddr)dest < (tVAddr)src )
1045 block_size = (tVAddr)src - (tVAddr)dest;
1047 block_size = (tVAddr)dest - (tVAddr)src;
1051 while(len >= block_size)
1053 memcpy(dest, src, block_size);
1058 memcpy(dest, src, len);