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);
42 void format_date(tTime TS, int *year, int *month, int *day, int *hrs, int *mins, int *sec, int *ms);
45 int CheckString(char *String);
46 int CheckMem(void *Mem, int NumBytes);
48 int ModUtil_LookupString(char **Array, char *Needle);
49 int ModUtil_SetIdent(char *Dest, char *Value);
51 int Hex(char *Dest, size_t Size, const Uint8 *SourceData);
52 int UnHex(Uint8 *Dest, size_t DestSize, const char *SourceString);
73 EXPORT(_strdup); // Takes File/Line too
82 EXPORT(ModUtil_LookupString);
83 EXPORT(ModUtil_SetIdent);
91 * \brief Convert a string into an integer
93 int atoi(const char *string)
96 ParseInt(string, &ret);
99 int ParseInt(const char *string, int *Val)
103 const char *orig_string = string;
105 //Log("atoi: (string='%s')", string);
107 // Clear non-numeric characters
108 while( !('0' <= *string && *string <= '9') && *string != '-' ) string++;
109 if( *string == '-' ) {
111 while( !('0' <= *string && *string <= '9') ) string++;
123 if('0' <= *string && *string <= '9') {
125 ret += *string - '0';
127 else if('A' <= *string && *string <= 'F') {
129 ret += *string - 'A' + 10;
131 else if('a' <= *string && *string <= 'f') {
133 ret += *string - 'a' + 10;
141 for( ; '0' <= *string && *string <= '7'; string ++ )
144 ret += *string - '0';
150 for( ; '0' <= *string && *string <= '9'; string++)
153 ret += *string - '0';
156 if( ret == 0 ) return 0;
161 //Log("atoi: RETURN %i", ret);
165 return string - orig_string;
168 static const char cUCDIGITS[] = "0123456789ABCDEF";
170 * \fn void itoa(char *buf, Uint64 num, int base, int minLength, char pad)
171 * \brief Convert an integer into a character string
173 void itoa(char *buf, Uint64 num, int base, int minLength, char pad)
183 if(base > 16 || base < 2) {
189 while(num > base-1) {
190 num = DivMod64U(num, base, &rem); // Shift `num` and get remainder
191 tmpBuf[pos] = cUCDIGITS[ rem ];
194 tmpBuf[pos++] = cUCDIGITS[ num ]; // Last digit of `num`
199 while(minLength-- > 0) buf[i++] = pad;
200 while(pos-- > 0) buf[i++] = tmpBuf[pos]; // Reverse the order of characters
205 * \brief Append a character the the vsnprintf output
207 #define PUTCH(c) _putch(c)
208 #define GETVAL() do {\
209 if(isLongLong) val = va_arg(args, Uint64);\
210 else val = va_arg(args, unsigned int);\
213 * \brief VArg String Number Print Formatted
215 int vsnprintf(char *__s, size_t __maxlen, const char *__format, va_list args)
218 int minSize = 0, precision = -1, len;
219 char tmpBuf[34]; // For Integers
220 const char *p = NULL;
227 auto void _putch(char ch);
233 if(__s) __s[pos] = ch;
238 while((c = *__format++) != 0)
240 // Non control character
241 if(c != '%') { PUTCH(c); continue; }
247 if(c == '%') { PUTCH('%'); continue; }
249 // Pointer - Done first for debugging
251 Uint ptr = va_arg(args, Uint);
252 PUTCH('*'); PUTCH('0'); PUTCH('x');
253 for( len = BITS/4; len --; )
254 PUTCH( cUCDIGITS[ (ptr>>(len*4))&15 ] );
258 // - Padding Side Flag
273 if(c == '*') { // Dynamic length
274 minSize = va_arg(args, unsigned int);
277 else if('1' <= c && c <= '9')
280 while('0' <= c && c <= '9')
295 if(c == '*') { // Dynamic length
296 precision = va_arg(args, unsigned int);
299 else if('1' <= c && c <= '9')
302 while('0' <= c && c <= '9')
305 precision += c - '0';
311 // - Default, Long or LongLong?
313 if(c == 'l') // Long is actually the default on x86
322 // - Now get the format code
329 if( isLongLong && val >> 63 ) {
333 else if( !isLongLong && val >> 31 ) {
337 itoa(tmpBuf, val, 10, minSize, pad);
339 case 'u': // Unsigned
341 itoa(tmpBuf, val, 10, minSize, pad);
343 case 'P': // Physical Address
346 if(sizeof(tPAddr) > 4) isLongLong = 1;
348 itoa(tmpBuf, val, 16, minSize, pad);
352 isLongLong = 1; // TODO: Handle non-x86 64-bit archs
354 itoa(tmpBuf, val, 16, minSize, pad);
357 case 'x': // Lower case hex
359 itoa(tmpBuf, val, 16, minSize, pad);
363 itoa(tmpBuf, val, 8, minSize, pad);
367 itoa(tmpBuf, val, 2, minSize, pad);
371 val = va_arg(args, unsigned int);
376 // String - Null Terminated Array
378 p = va_arg(args, char*); // Get Argument
379 if( !p || !CheckString(p) ) p = "(inval)"; // Avoid #PFs
383 if( !bPadLeft ) while(len++ < minSize) PUTCH(pad);
384 while(*p && precision--) PUTCH(*p++);
385 if( bPadLeft ) while(len++ < minSize) PUTCH(pad);
388 case 'C': // Non-Null Terminated Character Array
389 p = va_arg(args, char*);
390 if( !CheckMem(p, minSize) ) continue; // No #PFs please
391 if(!p) goto printString;
392 while(minSize--) PUTCH(*p++);
404 if(__s && pos != __maxlen)
413 int sprintf(char *__s, const char *__format, ...)
418 va_start(args, __format);
419 ret = vsnprintf(__s, -1, __format, args);
426 * \fn int tolower(int c)
427 * \brief Converts a character to lower case
431 if('A' <= c && c <= 'Z')
432 return c - 'A' + 'a';
437 * \fn int strucmp(const char *Str1, const char *Str2)
438 * \brief Compare \a Str1 and \a Str2 case-insensitively
440 int strucmp(const char *Str1, const char *Str2)
442 while(*Str1 && tolower(*Str1) == tolower(*Str2))
444 return tolower(*Str1) - tolower(*Str2);
448 * \brief Locate a byte in a string
450 char *strchr(const char *__s, int __c)
452 for( ; *__s; __s ++ )
454 if( *__s == __c ) return (char*)__s;
460 * \fn int strpos(const char *Str, char Ch)
461 * \brief Search a string for an ascii character
463 int strpos(const char *Str, char Ch)
466 for(pos=0;Str[pos];pos++)
468 if(Str[pos] == Ch) return pos;
474 * \fn Uint8 ByteSum(void *Ptr, int Size)
475 * \brief Adds the bytes in a memory region and returns the sum
477 Uint8 ByteSum(const void *Ptr, int Size)
480 const Uint8 *data = Ptr;
481 while(Size--) sum += *(data++);
486 * \fn size_t strlen(const char *__str)
487 * \brief Get the length of string
489 size_t strlen(const char *__str)
492 while(*__str++) ret++;
497 * \brief Copy a string to a new location
499 char *strcpy(char *__str1, const char *__str2)
502 *__str1++ = *__str2++;
503 *__str1 = '\0'; // Terminate String
508 * \brief Copy a string to a new location
509 * \note Copies at most `max` chars
511 char *strncpy(char *__str1, const char *__str2, size_t __max)
513 while(*__str2 && __max-- >= 1)
514 *__str1++ = *__str2++;
516 *__str1 = '\0'; // Terminate String
521 * \brief Append a string to another
523 char *strcat(char *__dest, const char *__src)
528 *__dest++ = *__src++;
534 * \brief Append at most \a n chars to a string from another
535 * \note At most n+1 chars are written (the dest is always zero terminated)
537 char *strncat(char *__dest, const char *__src, size_t n)
540 while(*__src && n-- >= 1)
541 *__dest++ = *__src++;
547 * \fn int strcmp(const char *str1, const char *str2)
548 * \brief Compare two strings return the difference between
549 * the first non-matching characters.
551 int strcmp(const char *str1, const char *str2)
553 while(*str1 && *str1 == *str2)
555 return *str1 - *str2;
559 * \fn int strncmp(const char *Str1, const char *Str2, size_t num)
560 * \brief Compare strings \a Str1 and \a Str2 to a maximum of \a num characters
562 int strncmp(const char *Str1, const char *Str2, size_t num)
564 if(num == 0) return 0; // TODO: Check what should officially happen here
565 while(--num && *Str1 && *Str1 == *Str2)
572 * \fn char *strdup(const char *Str)
573 * \brief Duplicates a string
575 char *strdup(const char *Str)
578 ret = malloc(strlen(Str)+1);
579 if( !ret ) return NULL;
586 * \fn char *_strdup(const char *File, int Line, const char *Str)
587 * \brief Duplicates a string
589 char *_strdup(const char *File, int Line, const char *Str)
592 ret = Heap_Allocate(File, Line, strlen(Str)+1);
593 if( !ret ) return NULL;
600 * \brief Split a string using the passed character
601 * \return NULL terminated array of strings on the heap
602 * \param __str String to split
603 * \param __ch Character to split by
605 char **str_split(const char *__str, char __ch)
612 for( i = 0; __str[i]; i++ )
618 ret = malloc( sizeof(char*)*(len+1) + (i + 1) );
619 if( !ret ) return NULL;
622 start = (char *)&ret[len+1];
624 for( i = 0; __str[i]; i++ )
626 if(__str[i] == __ch) {
641 * \fn int DivUp(int num, int dem)
642 * \brief Divide two numbers, rounding up
643 * \param num Numerator
644 * \param dem Denominator
646 int DivUp(int num, int dem)
648 return (num+dem-1)/dem;
652 * \fn int strpos8(const char *str, Uint32 search)
653 * \brief Search a string for a UTF-8 character
655 int strpos8(const char *str, Uint32 Search)
659 for(pos=0;str[pos];pos++)
663 if(str[pos] == Search) return pos;
666 if(*(Uint8*)(str+pos) < 128) continue;
668 pos += ReadUTF8( (Uint8*)&str[pos], &val );
669 if(val == Search) return pos;
675 * \fn int ReadUTF8(Uint8 *str, Uint32 *Val)
676 * \brief Read a UTF-8 character from a string
678 int ReadUTF8(const Uint8 *str, Uint32 *Val)
680 *Val = 0xFFFD; // Assume invalid character
683 if( !(*str & 0x80) ) {
688 // Middle of a sequence
689 if( (*str & 0xC0) == 0x80 ) {
694 if( (*str & 0xE0) == 0xC0 ) {
695 *Val = (*str & 0x1F) << 6; // Upper 6 Bits
697 if( (*str & 0xC0) != 0x80) return -1; // Validity check
698 *Val |= (*str & 0x3F); // Lower 6 Bits
703 if( (*str & 0xF0) == 0xE0 ) {
704 *Val = (*str & 0x0F) << 12; // Upper 4 Bits
706 if( (*str & 0xC0) != 0x80) return -1; // Validity check
707 *Val |= (*str & 0x3F) << 6; // Middle 6 Bits
709 if( (*str & 0xC0) != 0x80) return -1; // Validity check
710 *Val |= (*str & 0x3F); // Lower 6 Bits
715 if( (*str & 0xF1) == 0xF0 ) {
716 *Val = (*str & 0x07) << 18; // Upper 3 Bits
718 if( (*str & 0xC0) != 0x80) return -1; // Validity check
719 *Val |= (*str & 0x3F) << 12; // Middle-upper 6 Bits
721 if( (*str & 0xC0) != 0x80) return -1; // Validity check
722 *Val |= (*str & 0x3F) << 6; // Middle-lower 6 Bits
724 if( (*str & 0xC0) != 0x80) return -1; // Validity check
725 *Val |= (*str & 0x3F); // Lower 6 Bits
729 // UTF-8 Doesn't support more than four bytes
734 * \fn int WriteUTF8(Uint8 *str, Uint32 Val)
735 * \brief Write a UTF-8 character sequence to a string
737 int WriteUTF8(Uint8 *str, Uint32 Val)
750 *str++ = 0xC0 | (Val >> 6);
751 *str++ = 0x80 | (Val & 0x3F);
757 if( Val < 0x10000 ) {
759 *str++ = 0xE0 | (Val >> 12);
760 *str++ = 0x80 | ((Val >> 6) & 0x3F);
761 *str++ = 0x80 | (Val & 0x3F);
767 if( Val < 0x110000 ) {
769 *str++ = 0xF0 | (Val >> 18);
770 *str++ = 0x80 | ((Val >> 12) & 0x3F);
771 *str++ = 0x80 | ((Val >> 6) & 0x3F);
772 *str++ = 0x80 | (Val & 0x3F);
777 // UTF-8 Doesn't support more than four bytes
782 * \fn Uint64 timestamp(int sec, int mins, int hrs, int day, int month, int year)
783 * \brief Converts a date into an Acess Timestamp
785 Sint64 timestamp(int sec, int min, int hrs, int day, int month, int year)
790 if( !(0 <= sec && sec < 60) ) return 0;
791 if( !(0 <= min && min < 60) ) return 0;
792 if( !(0 <= hrs && hrs < 24) ) return 0;
793 if( !(0 <= day && day < 31) ) return 0;
794 if( !(0 <= month && month < 12) ) return 0;
796 stamp = DAYS_BEFORE[month] + day;
801 is_leap = (year % 4 == 0) - (year % 100 == 0) + (year % 400 == 0);
802 ASSERT(is_leap == 0 || is_leap == 1);
804 if( is_leap && month > 1 ) // Leap year and after feb
807 // Get seconds before the first of specified year
808 year -= 2000; // Base off Y2K
809 // base year days + total leap year days
810 stamp += year*365 + (year/400) - (year/100) + (year/4);
821 void format_date(tTime TS, int *year, int *month, int *day, int *hrs, int *mins, int *sec, int *ms)
825 auto Sint64 DivMod64(Sint64 N, Sint64 D, Sint64 *R);
827 Sint64 DivMod64(Sint64 N, Sint64 D, Sint64 *R)
829 int sign = (N < 0) != (D < 0);
833 return -DivMod64U(N, D, (Uint64*)R);
835 return DivMod64U(N, D, (Uint64*)R);
839 // TODO: Leap-seconds?
842 TS = DivMod64( TS, 1000, &rem );
844 TS = DivMod64( TS, 60, &rem );
846 TS = DivMod64( TS, 60, &rem );
848 TS = DivMod64( TS, 24, &rem );
853 TS -= UNIX_TO_2K/(3600*24);
855 // Year (400 yr blocks) - (400/4-3) leap years
856 *year = 400 * DivMod64( TS, 365*400 + (400/4-3), &TS );
857 if( TS < 366 ) // First year in 400 is a leap
861 // 100 yr blocks - 100/4-1 leap years
862 *year += 100 * DivMod64( TS, 365*100 + (100/4-1), &TS );
863 if( TS < 366 ) // First year in 100 isn't a leap
867 *year += 4 * DivMod64( TS, 365*4 + 1, &TS );
868 if( TS < 366 ) // First year in 4 is a leap
872 *year += DivMod64( TS, 356, &TS );
881 // Month (if after the first of march, which is 29 Feb in a leap year)
882 if( is_leap && TS > DAYS_BEFORE[2] ) {
883 TS -= 1; // Shifts 29 Feb to 28 Feb
886 // Get what month it is
887 for( i = 0; i < 12; i ++ ) {
888 if( TS < DAYS_BEFORE[i] )
893 TS -= DAYS_BEFORE[i-1];
894 *day += TS; // Plus offset from leap handling above
899 * \brief Pseudo random number generator
904 static Uint state = RANDOM_SEED;
906 // Get the next state value
907 giRandomState = (RANDOM_A*state + RANDOM_C);
908 // Check if it has changed, and if it hasn't, change it
909 if(state == old) state += RANDOM_SPRUCE;
912 // http://en.wikipedia.org/wiki/Xorshift
914 static Uint32 x = 123456789;
915 static Uint32 y = 362436069;
916 static Uint32 z = 521288629;
917 static Uint32 w = 88675123;
922 return w = w ^ (w >> 19) ^ t ^ (t >> 8);
927 * \name Memory Validation
931 * \brief Checks if a string resides fully in valid memory
933 int CheckString(const char *String)
938 addr = (tVAddr)String;
940 if( !MM_GetPhysAddr( addr ) )
944 bUser = MM_IsUser( addr );
946 while( *(char*)addr )
948 if( (addr & (PAGE_SIZE-1)) == 0 )
950 if(bUser && !MM_IsUser(addr) )
952 if(!bUser && !MM_GetPhysAddr(addr) )
961 * \brief Check if a sized memory region is valid memory
962 * \return Boolean success
964 int CheckMem(const void *Mem, int NumBytes)
966 return MM_IsValidBuffer( (tVAddr)Mem, NumBytes );
973 * \brief Search a string array for \a Needle
974 * \note Helper function for eTplDrv_IOCtl::DRV_IOCTL_LOOKUP
976 int ModUtil_LookupString(const char **Array, const char *Needle)
979 if( !CheckString(Needle) ) return -1;
980 for( i = 0; Array[i]; i++ )
982 if(strcmp(Array[i], Needle) == 0) return i;
987 int ModUtil_SetIdent(char *Dest, const char *Value)
989 if( !CheckMem(Dest, 32) ) return -1;
990 strncpy(Dest, Value, 32);
994 int Hex(char *Dest, size_t Size, const Uint8 *SourceData)
997 for( i = 0; i < Size; i ++ )
999 sprintf(Dest + i*2, "%02x", SourceData[i]);
1005 * \brief Convert a string of hexadecimal digits into a byte stream
1007 int UnHex(Uint8 *Dest, size_t DestSize, const char *SourceString)
1011 for( i = 0; i < DestSize*2; i += 2 )
1015 if(SourceString[i] == '\0') break;
1017 if('0' <= SourceString[i] && SourceString[i] <= '9')
1018 val |= (SourceString[i]-'0') << 4;
1019 else if('A' <= SourceString[i] && SourceString[i] <= 'F')
1020 val |= (SourceString[i]-'A'+10) << 4;
1021 else if('a' <= SourceString[i] && SourceString[i] <= 'f')
1022 val |= (SourceString[i]-'a'+10) << 4;
1024 if(SourceString[i+1] == '\0') break;
1026 if('0' <= SourceString[i+1] && SourceString[i+1] <= '9')
1027 val |= (SourceString[i+1] - '0');
1028 else if('A' <= SourceString[i+1] && SourceString[i+1] <= 'F')
1029 val |= (SourceString[i+1] - 'A' + 10);
1030 else if('a' <= SourceString[i+1] && SourceString[i+1] <= 'f')
1031 val |= (SourceString[i+1] - 'a' + 10);
1038 Uint16 SwapEndian16(Uint16 Val)
1040 return ((Val&0xFF)<<8) | ((Val>>8)&0xFF);
1042 Uint32 SwapEndian32(Uint32 Val)
1044 return ((Val&0xFF)<<24) | ((Val&0xFF00)<<8) | ((Val>>8)&0xFF00) | ((Val>>24)&0xFF);
1047 void *memmove(void *__dest, const void *__src, size_t len)
1050 char *dest = __dest;
1051 const char *src = __src;
1054 if( len == 0 || dest == src )
1057 if( (tVAddr)dest > (tVAddr)src + len )
1058 return memcpy(dest, src, len);
1059 if( (tVAddr)dest + len < (tVAddr)src )
1060 return memcpy(dest, src, len);
1062 // NOTE: Assumes memcpy works forward
1063 if( (tVAddr)dest < (tVAddr)src )
1064 return memcpy(dest, src, len);
1066 if( (tVAddr)dest < (tVAddr)src )
1067 block_size = (tVAddr)src - (tVAddr)dest;
1069 block_size = (tVAddr)dest - (tVAddr)src;
1073 while(len >= block_size)
1075 memcpy(dest, src, block_size);
1080 memcpy(dest, src, len);