3 * Common Library Functions
8 #define RANDOM_SEED 0xACE55052
9 #define RANDOM_A 0x00731ADE
10 #define RANDOM_C 12345
11 #define RANDOM_SPRUCE 0xf12b039
12 // Jan Feb Mar Apr May Jun Jul Aug Sept Oct Nov Dec
13 const short DAYS_BEFORE[] = {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334};
14 #define UNIX_TO_2K ((30*365*3600*24) + (7*3600*24)) //Normal years + leap years
18 int atoi(const char *string);
19 void itoa(char *buf, Uint64 num, int base, int minLength, char pad);
20 int vsnprintf(char *__s, size_t __maxlen, const char *__format, va_list args);
21 int sprintf(char *__s, const char *__format, ...);
25 int strucmp(const char *Str1, const char *Str2);
26 char *strchr(const char *__s, int __c);
27 int strpos(const char *Str, char Ch);
28 Uint8 ByteSum(void *Ptr, int Size);
29 size_t strlen(const char *__s);
30 char *strcpy(char *__str1, const char *__str2);
31 char *strncpy(char *__str1, const char *__str2, size_t max);
32 int strcmp(const char *str1, const char *str2);
33 int strncmp(const char *str1, const char *str2, size_t num);
34 char *_strdup(const char *File, int Line, const char *Str);
35 char **str_split(const char *__str, char __ch);
36 int strpos8(const char *str, Uint32 Search);
37 int ReadUTF8(Uint8 *str, Uint32 *Val);
38 int WriteUTF8(Uint8 *str, Uint32 Val);
39 int DivUp(int num, int dem);
40 Sint64 timestamp(int sec, int mins, int hrs, int day, int month, int year);
43 int CheckString(char *String);
44 int CheckMem(void *Mem, int NumBytes);
46 int ModUtil_LookupString(char **Array, char *Needle);
47 int ModUtil_SetIdent(char *Dest, char *Value);
49 int UnHex(Uint8 *Dest, size_t DestSize, const char *SourceString);
70 EXPORT(_strdup); // Takes File/Line too
79 EXPORT(ModUtil_LookupString);
80 EXPORT(ModUtil_SetIdent);
88 * \brief Convert a string into an integer
90 int atoi(const char *string)
95 //Log("atoi: (string='%s')", string);
97 // Clear non-numeric characters
98 while( !('0' <= *string && *string <= '9') && *string != '-' ) string++;
99 if( *string == '-' ) {
101 while( !('0' <= *string && *string <= '9') ) string++;
113 if('0' <= *string && *string <= '9') {
115 ret += *string - '0';
117 else if('A' <= *string && *string <= 'F') {
119 ret += *string - 'A' + 10;
121 else if('a' <= *string && *string <= 'f') {
123 ret += *string - 'a' + 10;
131 for( ; '0' <= *string && *string <= '7'; string ++ )
134 ret += *string - '0';
140 for( ; '0' <= *string && *string <= '9'; string++)
143 ret += *string - '0';
149 //Log("atoi: RETURN %i", ret);
154 static const char cUCDIGITS[] = "0123456789ABCDEF";
156 * \fn void itoa(char *buf, Uint64 num, int base, int minLength, char pad)
157 * \brief Convert an integer into a character string
159 void itoa(char *buf, Uint64 num, int base, int minLength, char pad)
169 if(base > 16 || base < 2) {
175 while(num > base-1) {
176 num = DivMod64U(num, base, &rem); // Shift `num` and get remainder
177 tmpBuf[pos] = cUCDIGITS[ rem ];
180 tmpBuf[pos++] = cUCDIGITS[ num ]; // Last digit of `num`
185 while(minLength-- > 0) buf[i++] = pad;
186 while(pos-- > 0) buf[i++] = tmpBuf[pos]; // Reverse the order of characters
191 * \brief Append a character the the vsnprintf output
193 #define PUTCH(c) do{\
195 if(pos==__maxlen){return pos;}\
196 if(__s){__s[pos++]=ch;}else{pos++;}\
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 //Log("vsnprintf: (__s=%p, __maxlen=%i, __format='%s', ...)", __s, __maxlen, __format);
219 while((c = *__format++) != 0)
221 // Non control character
222 if(c != '%') { PUTCH(c); continue; }
225 //Log("pos = %i", pos);
228 if(c == '%') { PUTCH('%'); continue; }
230 // Pointer - Done first for debugging
232 Uint ptr = va_arg(args, Uint);
233 PUTCH('*'); PUTCH('0'); PUTCH('x');
234 itoa(tmpBuf, ptr, 16, BITS/4, '0');
239 // - Padding Side Flag
254 if(c == '*') { // Dynamic length
255 minSize = va_arg(args, unsigned int);
258 else if('1' <= c && c <= '9')
261 while('0' <= c && c <= '9')
276 if(c == '*') { // Dynamic length
277 precision = va_arg(args, unsigned int);
280 else if('1' <= c && c <= '9')
283 while('0' <= c && c <= '9')
286 precision += c - '0';
292 // - Default, Long or LongLong?
294 if(c == 'l') // Long is actually the default on x86
303 // - Now get the format code
310 if( isLongLong && val >> 63 ) {
314 else if( !isLongLong && val >> 31 ) {
318 itoa(tmpBuf, val, 10, minSize, pad);
320 case 'u': // Unsigned
322 itoa(tmpBuf, val, 10, minSize, pad);
324 case 'P': // Physical Address
327 if(sizeof(tPAddr) > 4) isLongLong = 1;
329 itoa(tmpBuf, val, 16, minSize, pad);
333 isLongLong = 1; // TODO: Handle non-x86 64-bit archs
335 itoa(tmpBuf, val, 16, minSize, pad);
338 case 'x': // Lower case hex
340 itoa(tmpBuf, val, 16, minSize, pad);
344 itoa(tmpBuf, val, 8, minSize, pad);
348 itoa(tmpBuf, val, 2, minSize, pad);
352 val = va_arg(args, unsigned int);
357 // String - Null Terminated Array
359 p = va_arg(args, char*); // Get Argument
360 if( !p || !CheckString(p) ) p = "(inval)"; // Avoid #PFs
364 if( !bPadLeft ) while(len++ < minSize) PUTCH(pad);
365 while(*p && precision--) PUTCH(*p++);
366 if( bPadLeft ) while(len++ < minSize) PUTCH(pad);
369 case 'C': // Non-Null Terminated Character Array
370 p = va_arg(args, char*);
371 if( !CheckMem(p, minSize) ) continue; // No #PFs please
372 if(!p) goto printString;
373 while(minSize--) PUTCH(*p++);
385 if(__s && pos != __maxlen)
394 int sprintf(char *__s, const char *__format, ...)
399 va_start(args, __format);
400 ret = vsnprintf(__s, -1, __format, args);
407 * \fn int tolower(int c)
408 * \brief Converts a character to lower case
412 if('A' <= c && c <= 'Z')
413 return c - 'A' + 'a';
418 * \fn int strucmp(const char *Str1, const char *Str2)
419 * \brief Compare \a Str1 and \a Str2 case-insensitively
421 int strucmp(const char *Str1, const char *Str2)
423 while(*Str1 && tolower(*Str1) == tolower(*Str2))
425 return tolower(*Str1) - tolower(*Str2);
429 * \brief Locate a byte in a string
431 char *strchr(const char *__s, int __c)
433 for( ; *__s; __s ++ )
435 if( *__s == __c ) return (char*)__s;
441 * \fn int strpos(const char *Str, char Ch)
442 * \brief Search a string for an ascii character
444 int strpos(const char *Str, char Ch)
447 for(pos=0;Str[pos];pos++)
449 if(Str[pos] == Ch) return pos;
455 * \fn Uint8 ByteSum(void *Ptr, int Size)
456 * \brief Adds the bytes in a memory region and returns the sum
458 Uint8 ByteSum(const void *Ptr, int Size)
461 const Uint8 *data = Ptr;
462 while(Size--) sum += *(data++);
467 * \fn size_t strlen(const char *__str)
468 * \brief Get the length of string
470 size_t strlen(const char *__str)
473 while(*__str++) ret++;
478 * \brief Copy a string to a new location
480 char *strcpy(char *__str1, const char *__str2)
483 *__str1++ = *__str2++;
484 *__str1 = '\0'; // Terminate String
489 * \brief Copy a string to a new location
490 * \note Copies at most `max` chars
492 char *strncpy(char *__str1, const char *__str2, size_t max)
494 while(*__str2 && max-- >= 1)
495 *__str1++ = *__str2++;
497 *__str1 = '\0'; // Terminate String
502 * \brief Append a string to another
504 char *strcat(char *__dest, const char *__src)
509 *__dest++ = *__src++;
515 * \brief Append at most \a n chars to a string from another
516 * \note At most n+1 chars are written (the dest is always zero terminated)
518 char *strncat(char *__dest, const char *__src, size_t n)
521 while(*__src && n-- >= 1)
522 *__dest++ = *__src++;
528 * \fn int strcmp(const char *str1, const char *str2)
529 * \brief Compare two strings return the difference between
530 * the first non-matching characters.
532 int strcmp(const char *str1, const char *str2)
534 while(*str1 && *str1 == *str2)
536 return *str1 - *str2;
540 * \fn int strncmp(const char *Str1, const char *Str2, size_t num)
541 * \brief Compare strings \a Str1 and \a Str2 to a maximum of \a num characters
543 int strncmp(const char *Str1, const char *Str2, size_t num)
545 if(num == 0) return 0; // TODO: Check what should officially happen here
546 while(--num && *Str1 && *Str1 == *Str2)
553 * \fn char *strdup(const char *Str)
554 * \brief Duplicates a string
556 char *strdup(const char *Str)
559 ret = malloc(strlen(Str)+1);
560 if( !ret ) return NULL;
567 * \fn char *_strdup(const char *File, int Line, const char *Str)
568 * \brief Duplicates a string
570 char *_strdup(const char *File, int Line, const char *Str)
573 ret = Heap_Allocate(File, Line, strlen(Str)+1);
574 if( !ret ) return NULL;
581 * \brief Split a string using the passed character
582 * \return NULL terminated array of strings on the heap
583 * \param __str String to split
584 * \param __ch Character to split by
586 char **str_split(const char *__str, char __ch)
593 for( i = 0; __str[i]; i++ )
599 ret = malloc( sizeof(char*)*(len+1) + (i + 1) );
600 if( !ret ) return NULL;
603 start = (char *)&ret[len+1];
605 for( i = 0; __str[i]; i++ )
607 if(__str[i] == __ch) {
622 * \fn int DivUp(int num, int dem)
623 * \brief Divide two numbers, rounding up
624 * \param num Numerator
625 * \param dem Denominator
627 int DivUp(int num, int dem)
629 return (num+dem-1)/dem;
633 * \fn int strpos8(const char *str, Uint32 search)
634 * \brief Search a string for a UTF-8 character
636 int strpos8(const char *str, Uint32 Search)
640 for(pos=0;str[pos];pos++)
644 if(str[pos] == Search) return pos;
647 if(*(Uint8*)(str+pos) < 128) continue;
649 pos += ReadUTF8( (Uint8*)&str[pos], &val );
650 if(val == Search) return pos;
656 * \fn int ReadUTF8(Uint8 *str, Uint32 *Val)
657 * \brief Read a UTF-8 character from a string
659 int ReadUTF8(const Uint8 *str, Uint32 *Val)
661 *Val = 0xFFFD; // Assume invalid character
664 if( !(*str & 0x80) ) {
669 // Middle of a sequence
670 if( (*str & 0xC0) == 0x80 ) {
675 if( (*str & 0xE0) == 0xC0 ) {
676 *Val = (*str & 0x1F) << 6; // Upper 6 Bits
678 if( (*str & 0xC0) != 0x80) return -1; // Validity check
679 *Val |= (*str & 0x3F); // Lower 6 Bits
684 if( (*str & 0xF0) == 0xE0 ) {
685 *Val = (*str & 0x0F) << 12; // Upper 4 Bits
687 if( (*str & 0xC0) != 0x80) return -1; // Validity check
688 *Val |= (*str & 0x3F) << 6; // Middle 6 Bits
690 if( (*str & 0xC0) != 0x80) return -1; // Validity check
691 *Val |= (*str & 0x3F); // Lower 6 Bits
696 if( (*str & 0xF1) == 0xF0 ) {
697 *Val = (*str & 0x07) << 18; // Upper 3 Bits
699 if( (*str & 0xC0) != 0x80) return -1; // Validity check
700 *Val |= (*str & 0x3F) << 12; // Middle-upper 6 Bits
702 if( (*str & 0xC0) != 0x80) return -1; // Validity check
703 *Val |= (*str & 0x3F) << 6; // Middle-lower 6 Bits
705 if( (*str & 0xC0) != 0x80) return -1; // Validity check
706 *Val |= (*str & 0x3F); // Lower 6 Bits
710 // UTF-8 Doesn't support more than four bytes
715 * \fn int WriteUTF8(Uint8 *str, Uint32 Val)
716 * \brief Write a UTF-8 character sequence to a string
718 int WriteUTF8(Uint8 *str, Uint32 Val)
728 *str = 0xC0 | (Val >> 6);
730 *str = 0x80 | (Val & 0x3F);
735 if( Val < 0x10000 ) {
736 *str = 0xE0 | (Val >> 12);
738 *str = 0x80 | ((Val >> 6) & 0x3F);
740 *str = 0x80 | (Val & 0x3F);
745 if( Val < 0x110000 ) {
746 *str = 0xF0 | (Val >> 18);
748 *str = 0x80 | ((Val >> 12) & 0x3F);
750 *str = 0x80 | ((Val >> 6) & 0x3F);
752 *str = 0x80 | (Val & 0x3F);
756 // UTF-8 Doesn't support more than four bytes
761 * \fn Uint64 timestamp(int sec, int mins, int hrs, int day, int month, int year)
762 * \brief Converts a date into an Acess Timestamp
764 Sint64 timestamp(int sec, int mins, int hrs, int day, int month, int year)
771 stamp += day*3600*24;
772 stamp += month*DAYS_BEFORE[month]*3600*24;
774 ((year&3) == 0 || year%100 != 0)
775 || (year%100 == 0 && ((year/100)&3) == 0)
776 ) && month > 1) // Leap year and after feb
779 stamp += ((365*4+1) * ((year-2000)&~3)) * 3600*24; // Four Year Segments
780 stamp += ((year-2000)&3) * 365*3600*24; // Inside four year segment
788 * \brief Pseudo random number generator
793 static Uint state = RANDOM_SEED;
795 // Get the next state value
796 giRandomState = (RANDOM_A*state + RANDOM_C);
797 // Check if it has changed, and if it hasn't, change it
798 if(state == old) state += RANDOM_SPRUCE;
801 // http://en.wikipedia.org/wiki/Xorshift
803 static Uint32 x = 123456789;
804 static Uint32 y = 362436069;
805 static Uint32 z = 521288629;
806 static Uint32 w = 88675123;
811 return w = w ^ (w >> 19) ^ t ^ (t >> 8);
816 * \name Memory Validation
820 * \brief Checks if a string resides fully in valid memory
822 int CheckString(const char *String)
824 if( !MM_GetPhysAddr( (tVAddr)String ) )
828 if( MM_IsUser( (tVAddr)String ) )
833 if( !MM_IsUser( (tVAddr)String ) )
835 // Increment string pointer
840 else if( MM_GetPhysAddr( (tVAddr)String ) )
845 if( !MM_GetPhysAddr( (tVAddr)String ) )
847 // Increment string pointer
856 * \brief Check if a sized memory region is valid memory
858 int CheckMem(const void *Mem, int NumBytes)
860 tVAddr addr = (tVAddr)Mem;
862 if( MM_IsUser( addr ) )
866 if( !MM_IsUser( addr ) )
872 else if( MM_GetPhysAddr( addr ) )
876 if( !MM_GetPhysAddr( addr ) )
889 * \brief Search a string array for \a Needle
890 * \note Helper function for eTplDrv_IOCtl::DRV_IOCTL_LOOKUP
892 int ModUtil_LookupString(const char **Array, const char *Needle)
895 if( !CheckString(Needle) ) return -1;
896 for( i = 0; Array[i]; i++ )
898 if(strcmp(Array[i], Needle) == 0) return i;
903 int ModUtil_SetIdent(char *Dest, const char *Value)
905 if( !CheckMem(Dest, 32) ) return -1;
906 strncpy(Dest, Value, 32);
911 * \brief Convert a string of hexadecimal digits into a byte stream
913 int UnHex(Uint8 *Dest, size_t DestSize, const char *SourceString)
917 for( i = 0; i < DestSize*2; i += 2 )
921 if(SourceString[i] == '\0') break;
923 if('0' <= SourceString[i] && SourceString[i] <= '9')
924 val |= (SourceString[i]-'0') << 4;
925 else if('A' <= SourceString[i] && SourceString[i] <= 'F')
926 val |= (SourceString[i]-'A'+10) << 4;
927 else if('a' <= SourceString[i] && SourceString[i] <= 'f')
928 val |= (SourceString[i]-'a'+10) << 4;
930 if(SourceString[i+1] == '\0') break;
932 if('0' <= SourceString[i+1] && SourceString[i+1] <= '9')
933 val |= (SourceString[i+1] - '0');
934 else if('A' <= SourceString[i+1] && SourceString[i+1] <= 'F')
935 val |= (SourceString[i+1] - 'A' + 10);
936 else if('a' <= SourceString[i+1] && SourceString[i+1] <= 'f')
937 val |= (SourceString[i+1] - 'a' + 10);
944 Uint16 SwapEndian16(Uint16 Val)
946 return ((Val&0xFF)<<8) | ((Val>>8)&0xFF);
948 Uint32 SwapEndian32(Uint32 Val)
950 return ((Val&0xFF)<<24) | ((Val&0xFF00)<<8) | ((Val>>8)&0xFF00) | ((Val>>24)&0xFF);
953 void *memmove(void *__dest, const void *__src, size_t len)
957 const char *src = __src;
960 if( (tVAddr)dest > (tVAddr)src + len )
961 return memcpy(dest, src, len);
962 if( (tVAddr)dest + len < (tVAddr)src )
963 return memcpy(dest, src, len);
965 if( (tVAddr)dest < (tVAddr)src )
966 block_size = (tVAddr)src - (tVAddr)dest;
968 block_size = (tVAddr)dest - (tVAddr)src;
972 while(len >= block_size)
974 memcpy(dest, src, block_size);
979 memcpy(dest, src, len);