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 Hex(char *Dest, size_t Size, const Uint8 *SourceData);
54 int UnHex(Uint8 *Dest, size_t DestSize, const char *SourceString);
75 EXPORT(_strdup); // Takes File/Line too
84 EXPORT(ModUtil_LookupString);
85 EXPORT(ModUtil_SetIdent);
93 * \brief Convert a string into an integer
95 int atoi(const char *string)
98 ParseInt(string, &ret);
101 int ParseInt(const char *string, int *Val)
105 const char *orig_string = string;
107 //Log("atoi: (string='%s')", string);
109 // Clear non-numeric characters
110 while( !('0' <= *string && *string <= '9') && *string != '-' ) string++;
111 if( *string == '-' ) {
113 while( !('0' <= *string && *string <= '9') ) string++;
125 if('0' <= *string && *string <= '9') {
127 ret += *string - '0';
129 else if('A' <= *string && *string <= 'F') {
131 ret += *string - 'A' + 10;
133 else if('a' <= *string && *string <= 'f') {
135 ret += *string - 'a' + 10;
143 for( ; '0' <= *string && *string <= '7'; string ++ )
146 ret += *string - '0';
152 for( ; '0' <= *string && *string <= '9'; string++)
155 ret += *string - '0';
158 if( ret == 0 ) return 0;
163 //Log("atoi: RETURN %i", ret);
167 return string - orig_string;
170 static const char cUCDIGITS[] = "0123456789ABCDEF";
172 * \fn void itoa(char *buf, Uint64 num, int base, int minLength, char pad)
173 * \brief Convert an integer into a character string
175 void itoa(char *buf, Uint64 num, int base, int minLength, char pad)
185 if(base > 16 || base < 2) {
191 while(num > base-1) {
192 num = DivMod64U(num, base, &rem); // Shift `num` and get remainder
193 tmpBuf[pos] = cUCDIGITS[ rem ];
196 tmpBuf[pos++] = cUCDIGITS[ num ]; // Last digit of `num`
201 while(minLength-- > 0) buf[i++] = pad;
202 while(pos-- > 0) buf[i++] = tmpBuf[pos]; // Reverse the order of characters
207 * \brief Append a character the the vsnprintf output
209 #define PUTCH(c) _putch(c)
210 #define GETVAL() do {\
211 if(isLongLong) val = va_arg(args, Uint64);\
212 else val = va_arg(args, unsigned int);\
215 * \brief VArg String Number Print Formatted
217 int vsnprintf(char *__s, size_t __maxlen, const char *__format, va_list args)
220 int minSize = 0, precision = -1, len;
221 char tmpBuf[34]; // For Integers
222 const char *p = NULL;
229 auto void _putch(char ch);
235 if(__s) __s[pos] = ch;
240 while((c = *__format++) != 0)
242 // Non control character
243 if(c != '%') { PUTCH(c); continue; }
249 if(c == '%') { PUTCH('%'); continue; }
251 // Pointer - Done first for debugging
253 Uint ptr = va_arg(args, Uint);
254 PUTCH('*'); PUTCH('0'); PUTCH('x');
255 for( len = BITS/4; len --; )
256 PUTCH( cUCDIGITS[ (ptr>>(len*4))&15 ] );
260 // - Padding Side Flag
275 if(c == '*') { // Dynamic length
276 minSize = va_arg(args, unsigned int);
279 else if('1' <= c && c <= '9')
282 while('0' <= c && c <= '9')
297 if(c == '*') { // Dynamic length
298 precision = va_arg(args, unsigned int);
301 else if('1' <= c && c <= '9')
304 while('0' <= c && c <= '9')
307 precision += c - '0';
313 // - Default, Long or LongLong?
315 if(c == 'l') // Long is actually the default on x86
324 // - Now get the format code
331 if( isLongLong && val >> 63 ) {
335 else if( !isLongLong && val >> 31 ) {
339 itoa(tmpBuf, val, 10, minSize, pad);
341 case 'u': // Unsigned
343 itoa(tmpBuf, val, 10, minSize, pad);
345 case 'P': // Physical Address
348 if(sizeof(tPAddr) > 4) isLongLong = 1;
350 itoa(tmpBuf, val, 16, minSize, pad);
354 isLongLong = 1; // TODO: Handle non-x86 64-bit archs
356 itoa(tmpBuf, val, 16, minSize, pad);
359 case 'x': // Lower case hex
361 itoa(tmpBuf, val, 16, minSize, pad);
365 itoa(tmpBuf, val, 8, minSize, pad);
369 itoa(tmpBuf, val, 2, minSize, pad);
373 val = va_arg(args, unsigned int);
378 // String - Null Terminated Array
380 p = va_arg(args, char*); // Get Argument
381 if( !p || !CheckString(p) ) p = "(inval)"; // Avoid #PFs
385 if( !bPadLeft ) while(len++ < minSize) PUTCH(pad);
386 while(*p && precision--) PUTCH(*p++);
387 if( bPadLeft ) while(len++ < minSize) PUTCH(pad);
390 case 'C': // Non-Null Terminated Character Array
391 p = va_arg(args, char*);
392 if( !CheckMem(p, minSize) ) continue; // No #PFs please
393 if(!p) goto printString;
394 while(minSize--) PUTCH(*p++);
406 if(__s && pos != __maxlen)
415 int sprintf(char *__s, const char *__format, ...)
420 va_start(args, __format);
421 ret = vsnprintf(__s, -1, __format, args);
428 * \fn int tolower(int c)
429 * \brief Converts a character to lower case
433 if('A' <= c && c <= 'Z')
434 return c - 'A' + 'a';
439 * \fn int strucmp(const char *Str1, const char *Str2)
440 * \brief Compare \a Str1 and \a Str2 case-insensitively
442 int strucmp(const char *Str1, const char *Str2)
444 while(*Str1 && tolower(*Str1) == tolower(*Str2))
446 return tolower(*Str1) - tolower(*Str2);
450 * \brief Locate a byte in a string
452 char *strchr(const char *__s, int __c)
454 for( ; *__s; __s ++ )
456 if( *__s == __c ) return (char*)__s;
462 * \fn int strpos(const char *Str, char Ch)
463 * \brief Search a string for an ascii character
465 int strpos(const char *Str, char Ch)
468 for(pos=0;Str[pos];pos++)
470 if(Str[pos] == Ch) return pos;
476 * \fn Uint8 ByteSum(void *Ptr, int Size)
477 * \brief Adds the bytes in a memory region and returns the sum
479 Uint8 ByteSum(const void *Ptr, int Size)
482 const Uint8 *data = Ptr;
483 while(Size--) sum += *(data++);
488 * \fn size_t strlen(const char *__str)
489 * \brief Get the length of string
491 size_t strlen(const char *__str)
494 while(*__str++) ret++;
499 * \brief Copy a string to a new location
501 char *strcpy(char *__str1, const char *__str2)
504 *__str1++ = *__str2++;
505 *__str1 = '\0'; // Terminate String
510 * \brief Copy a string to a new location
511 * \note Copies at most `max` chars
513 char *strncpy(char *__str1, const char *__str2, size_t __max)
515 while(*__str2 && __max-- >= 1)
516 *__str1++ = *__str2++;
518 *__str1 = '\0'; // Terminate String
523 * \brief Append a string to another
525 char *strcat(char *__dest, const char *__src)
530 *__dest++ = *__src++;
536 * \brief Append at most \a n chars to a string from another
537 * \note At most n+1 chars are written (the dest is always zero terminated)
539 char *strncat(char *__dest, const char *__src, size_t n)
542 while(*__src && n-- >= 1)
543 *__dest++ = *__src++;
549 * \fn int strcmp(const char *str1, const char *str2)
550 * \brief Compare two strings return the difference between
551 * the first non-matching characters.
553 int strcmp(const char *str1, const char *str2)
555 while(*str1 && *str1 == *str2)
557 return *str1 - *str2;
561 * \fn int strncmp(const char *Str1, const char *Str2, size_t num)
562 * \brief Compare strings \a Str1 and \a Str2 to a maximum of \a num characters
564 int strncmp(const char *Str1, const char *Str2, size_t num)
566 if(num == 0) return 0; // TODO: Check what should officially happen here
567 while(--num && *Str1 && *Str1 == *Str2)
574 * \fn char *strdup(const char *Str)
575 * \brief Duplicates a string
577 char *strdup(const char *Str)
580 ret = malloc(strlen(Str)+1);
581 if( !ret ) return NULL;
588 * \fn char *_strdup(const char *File, int Line, const char *Str)
589 * \brief Duplicates a string
591 char *_strdup(const char *File, int Line, const char *Str)
594 ret = Heap_Allocate(File, Line, strlen(Str)+1);
595 if( !ret ) return NULL;
602 * \brief Split a string using the passed character
603 * \return NULL terminated array of strings on the heap
604 * \param __str String to split
605 * \param __ch Character to split by
607 char **str_split(const char *__str, char __ch)
614 for( i = 0; __str[i]; i++ )
620 ret = malloc( sizeof(char*)*(len+1) + (i + 1) );
621 if( !ret ) return NULL;
624 start = (char *)&ret[len+1];
626 for( i = 0; __str[i]; i++ )
628 if(__str[i] == __ch) {
643 * \fn int DivUp(int num, int dem)
644 * \brief Divide two numbers, rounding up
645 * \param num Numerator
646 * \param dem Denominator
648 int DivUp(int num, int dem)
650 return (num+dem-1)/dem;
654 * \fn int strpos8(const char *str, Uint32 search)
655 * \brief Search a string for a UTF-8 character
657 int strpos8(const char *str, Uint32 Search)
661 for(pos=0;str[pos];pos++)
665 if(str[pos] == Search) return pos;
668 if(*(Uint8*)(str+pos) < 128) continue;
670 pos += ReadUTF8( (Uint8*)&str[pos], &val );
671 if(val == Search) return pos;
677 * \fn int ReadUTF8(Uint8 *str, Uint32 *Val)
678 * \brief Read a UTF-8 character from a string
680 int ReadUTF8(const Uint8 *str, Uint32 *Val)
682 *Val = 0xFFFD; // Assume invalid character
685 if( !(*str & 0x80) ) {
690 // Middle of a sequence
691 if( (*str & 0xC0) == 0x80 ) {
696 if( (*str & 0xE0) == 0xC0 ) {
697 *Val = (*str & 0x1F) << 6; // Upper 6 Bits
699 if( (*str & 0xC0) != 0x80) return -1; // Validity check
700 *Val |= (*str & 0x3F); // Lower 6 Bits
705 if( (*str & 0xF0) == 0xE0 ) {
706 *Val = (*str & 0x0F) << 12; // Upper 4 Bits
708 if( (*str & 0xC0) != 0x80) return -1; // Validity check
709 *Val |= (*str & 0x3F) << 6; // Middle 6 Bits
711 if( (*str & 0xC0) != 0x80) return -1; // Validity check
712 *Val |= (*str & 0x3F); // Lower 6 Bits
717 if( (*str & 0xF1) == 0xF0 ) {
718 *Val = (*str & 0x07) << 18; // Upper 3 Bits
720 if( (*str & 0xC0) != 0x80) return -1; // Validity check
721 *Val |= (*str & 0x3F) << 12; // Middle-upper 6 Bits
723 if( (*str & 0xC0) != 0x80) return -1; // Validity check
724 *Val |= (*str & 0x3F) << 6; // Middle-lower 6 Bits
726 if( (*str & 0xC0) != 0x80) return -1; // Validity check
727 *Val |= (*str & 0x3F); // Lower 6 Bits
731 // UTF-8 Doesn't support more than four bytes
736 * \fn int WriteUTF8(Uint8 *str, Uint32 Val)
737 * \brief Write a UTF-8 character sequence to a string
739 int WriteUTF8(Uint8 *str, Uint32 Val)
752 *str++ = 0xC0 | (Val >> 6);
753 *str++ = 0x80 | (Val & 0x3F);
759 if( Val < 0x10000 ) {
761 *str++ = 0xE0 | (Val >> 12);
762 *str++ = 0x80 | ((Val >> 6) & 0x3F);
763 *str++ = 0x80 | (Val & 0x3F);
769 if( Val < 0x110000 ) {
771 *str++ = 0xF0 | (Val >> 18);
772 *str++ = 0x80 | ((Val >> 12) & 0x3F);
773 *str++ = 0x80 | ((Val >> 6) & 0x3F);
774 *str++ = 0x80 | (Val & 0x3F);
779 // UTF-8 Doesn't support more than four bytes
784 * \fn Uint64 timestamp(int sec, int mins, int hrs, int day, int month, int year)
785 * \brief Converts a date into an Acess Timestamp
787 Sint64 timestamp(int sec, int min, int hrs, int day, int month, int year)
792 if( !(0 <= sec && sec < 60) ) return 0;
793 if( !(0 <= min && min < 60) ) return 0;
794 if( !(0 <= hrs && hrs < 24) ) return 0;
795 if( !(0 <= day && day < 31) ) return 0;
796 if( !(0 <= month && month < 12) ) return 0;
798 stamp = DAYS_BEFORE[month] + day;
803 is_leap = (year % 4 == 0) - (year % 100 == 0) + (year % 400 == 0);
804 ASSERT(is_leap == 0 || is_leap == 1);
806 if( is_leap && month > 1 ) // Leap year and after feb
809 // Get seconds before the first of specified year
810 year -= 2000; // Base off Y2K
811 // base year days + total leap year days
812 stamp += year*365 + (year/400) - (year/100) + (year/4);
823 void format_date(tTime TS, int *year, int *month, int *day, int *hrs, int *mins, int *sec, int *ms)
827 auto Sint64 DivMod64(Sint64 N, Sint64 D, Sint64 *R);
829 Sint64 DivMod64(Sint64 N, Sint64 D, Sint64 *R)
831 int sign = (N < 0) != (D < 0);
835 return -DivMod64U(N, D, (Uint64*)R);
837 return DivMod64U(N, D, (Uint64*)R);
841 // TODO: Leap-seconds?
844 TS = DivMod64( TS, 1000, &rem );
846 TS = DivMod64( TS, 60, &rem );
848 TS = DivMod64( TS, 60, &rem );
850 TS = DivMod64( TS, 24, &rem );
855 TS -= UNIX_TO_2K/(3600*24);
857 // Year (400 yr blocks) - (400/4-3) leap years
858 *year = 400 * DivMod64( TS, 365*400 + (400/4-3), &TS );
859 if( TS < 366 ) // First year in 400 is a leap
863 // 100 yr blocks - 100/4-1 leap years
864 *year += 100 * DivMod64( TS, 365*100 + (100/4-1), &TS );
865 if( TS < 366 ) // First year in 100 isn't a leap
869 *year += 4 * DivMod64( TS, 365*4 + 1, &TS );
870 if( TS < 366 ) // First year in 4 is a leap
874 *year += DivMod64( TS, 356, &TS );
883 // Month (if after the first of march, which is 29 Feb in a leap year)
884 if( is_leap && TS > DAYS_BEFORE[2] ) {
885 TS -= 1; // Shifts 29 Feb to 28 Feb
888 // Get what month it is
889 for( i = 0; i < 12; i ++ ) {
890 if( TS < DAYS_BEFORE[i] )
895 TS -= DAYS_BEFORE[i-1];
896 *day += TS; // Plus offset from leap handling above
901 * \brief Pseudo random number generator
906 static Uint state = RANDOM_SEED;
908 // Get the next state value
909 giRandomState = (RANDOM_A*state + RANDOM_C);
910 // Check if it has changed, and if it hasn't, change it
911 if(state == old) state += RANDOM_SPRUCE;
914 // http://en.wikipedia.org/wiki/Xorshift
916 static Uint32 x = 123456789;
917 static Uint32 y = 362436069;
918 static Uint32 z = 521288629;
919 static Uint32 w = 88675123;
924 return w = w ^ (w >> 19) ^ t ^ (t >> 8);
929 * \name Memory Validation
933 * \brief Checks if a string resides fully in valid memory
935 int CheckString(const char *String)
940 addr = (tVAddr)String;
942 if( !MM_GetPhysAddr( addr ) )
946 bUser = MM_IsUser( addr );
948 while( *(char*)addr )
950 if( (addr & (PAGE_SIZE-1)) == 0 )
952 if(bUser && !MM_IsUser(addr) )
954 if(!bUser && !MM_GetPhysAddr(addr) )
963 * \brief Check if a sized memory region is valid memory
964 * \return Boolean success
966 int CheckMem(const void *Mem, int NumBytes)
968 return MM_IsValidBuffer( (tVAddr)Mem, NumBytes );
975 * \brief Search a string array for \a Needle
976 * \note Helper function for eTplDrv_IOCtl::DRV_IOCTL_LOOKUP
978 int ModUtil_LookupString(const char **Array, const char *Needle)
981 if( !CheckString(Needle) ) return -1;
982 for( i = 0; Array[i]; i++ )
984 if(strcmp(Array[i], Needle) == 0) return i;
989 int ModUtil_SetIdent(char *Dest, const char *Value)
991 if( !CheckMem(Dest, 32) ) return -1;
992 strncpy(Dest, Value, 32);
996 int Hex(char *Dest, size_t Size, const Uint8 *SourceData)
999 for( i = 0; i < Size; i ++ )
1001 sprintf(Dest + i*2, "%02x", SourceData[i]);
1007 * \brief Convert a string of hexadecimal digits into a byte stream
1009 int UnHex(Uint8 *Dest, size_t DestSize, const char *SourceString)
1013 for( i = 0; i < DestSize*2; i += 2 )
1017 if(SourceString[i] == '\0') break;
1019 if('0' <= SourceString[i] && SourceString[i] <= '9')
1020 val |= (SourceString[i]-'0') << 4;
1021 else if('A' <= SourceString[i] && SourceString[i] <= 'F')
1022 val |= (SourceString[i]-'A'+10) << 4;
1023 else if('a' <= SourceString[i] && SourceString[i] <= 'f')
1024 val |= (SourceString[i]-'a'+10) << 4;
1026 if(SourceString[i+1] == '\0') break;
1028 if('0' <= SourceString[i+1] && SourceString[i+1] <= '9')
1029 val |= (SourceString[i+1] - '0');
1030 else if('A' <= SourceString[i+1] && SourceString[i+1] <= 'F')
1031 val |= (SourceString[i+1] - 'A' + 10);
1032 else if('a' <= SourceString[i+1] && SourceString[i+1] <= 'f')
1033 val |= (SourceString[i+1] - 'a' + 10);
1040 Uint16 SwapEndian16(Uint16 Val)
1042 return ((Val&0xFF)<<8) | ((Val>>8)&0xFF);
1044 Uint32 SwapEndian32(Uint32 Val)
1046 return ((Val&0xFF)<<24) | ((Val&0xFF00)<<8) | ((Val>>8)&0xFF00) | ((Val>>24)&0xFF);
1049 void *memmove(void *__dest, const void *__src, size_t len)
1052 char *dest = __dest;
1053 const char *src = __src;
1056 if( len == 0 || dest == src )
1059 if( (tVAddr)dest > (tVAddr)src + len )
1060 return memcpy(dest, src, len);
1061 if( (tVAddr)dest + len < (tVAddr)src )
1062 return memcpy(dest, src, len);
1064 // NOTE: Assumes memcpy works forward
1065 if( (tVAddr)dest < (tVAddr)src )
1066 return memcpy(dest, src, len);
1068 if( (tVAddr)dest < (tVAddr)src )
1069 block_size = (tVAddr)src - (tVAddr)dest;
1071 block_size = (tVAddr)dest - (tVAddr)src;
1075 while(len >= block_size)
1077 memcpy(dest, src, block_size);
1082 memcpy(dest, src, len);