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);
44 int CheckString(char *String);
45 int CheckMem(void *Mem, int NumBytes);
47 int ModUtil_LookupString(char **Array, char *Needle);
48 int ModUtil_SetIdent(char *Dest, char *Value);
50 int UnHex(Uint8 *Dest, size_t DestSize, const char *SourceString);
71 EXPORT(_strdup); // Takes File/Line too
80 EXPORT(ModUtil_LookupString);
81 EXPORT(ModUtil_SetIdent);
89 * \brief Convert a string into an integer
91 int atoi(const char *string)
96 //Log("atoi: (string='%s')", string);
98 // Clear non-numeric characters
99 while( !('0' <= *string && *string <= '9') && *string != '-' ) string++;
100 if( *string == '-' ) {
102 while( !('0' <= *string && *string <= '9') ) string++;
114 if('0' <= *string && *string <= '9') {
116 ret += *string - '0';
118 else if('A' <= *string && *string <= 'F') {
120 ret += *string - 'A' + 10;
122 else if('a' <= *string && *string <= 'f') {
124 ret += *string - 'a' + 10;
132 for( ; '0' <= *string && *string <= '7'; string ++ )
135 ret += *string - '0';
141 for( ; '0' <= *string && *string <= '9'; string++)
144 ret += *string - '0';
150 //Log("atoi: RETURN %i", ret);
155 static const char cUCDIGITS[] = "0123456789ABCDEF";
157 * \fn void itoa(char *buf, Uint64 num, int base, int minLength, char pad)
158 * \brief Convert an integer into a character string
160 void itoa(char *buf, Uint64 num, int base, int minLength, char pad)
170 if(base > 16 || base < 2) {
176 while(num > base-1) {
177 num = DivMod64U(num, base, &rem); // Shift `num` and get remainder
178 tmpBuf[pos] = cUCDIGITS[ rem ];
181 tmpBuf[pos++] = cUCDIGITS[ num ]; // Last digit of `num`
186 while(minLength-- > 0) buf[i++] = pad;
187 while(pos-- > 0) buf[i++] = tmpBuf[pos]; // Reverse the order of characters
192 * \brief Append a character the the vsnprintf output
194 #define PUTCH(c) _putch(c)
195 #define GETVAL() do {\
196 if(isLongLong) val = va_arg(args, Uint64);\
197 else val = va_arg(args, unsigned int);\
200 * \brief VArg String Number Print Formatted
202 int vsnprintf(char *__s, size_t __maxlen, const char *__format, va_list args)
205 int minSize = 0, precision = -1, len;
206 char tmpBuf[34]; // For Integers
207 const char *p = NULL;
214 inline void _putch(char ch)
218 if(__s) __s[pos] = ch;
223 while((c = *__format++) != 0)
225 // Non control character
226 if(c != '%') { PUTCH(c); continue; }
232 if(c == '%') { PUTCH('%'); continue; }
234 // Pointer - Done first for debugging
236 Uint ptr = va_arg(args, Uint);
237 PUTCH('*'); PUTCH('0'); PUTCH('x');
238 for( len = BITS/4; len --; )
239 PUTCH( cUCDIGITS[ (ptr>>(len*4))&15 ] );
243 // - Padding Side Flag
258 if(c == '*') { // Dynamic length
259 minSize = va_arg(args, unsigned int);
262 else if('1' <= c && c <= '9')
265 while('0' <= c && c <= '9')
280 if(c == '*') { // Dynamic length
281 precision = va_arg(args, unsigned int);
284 else if('1' <= c && c <= '9')
287 while('0' <= c && c <= '9')
290 precision += c - '0';
296 // - Default, Long or LongLong?
298 if(c == 'l') // Long is actually the default on x86
307 // - Now get the format code
314 if( isLongLong && val >> 63 ) {
318 else if( !isLongLong && val >> 31 ) {
322 itoa(tmpBuf, val, 10, minSize, pad);
324 case 'u': // Unsigned
326 itoa(tmpBuf, val, 10, minSize, pad);
328 case 'P': // Physical Address
331 if(sizeof(tPAddr) > 4) isLongLong = 1;
333 itoa(tmpBuf, val, 16, minSize, pad);
337 isLongLong = 1; // TODO: Handle non-x86 64-bit archs
339 itoa(tmpBuf, val, 16, minSize, pad);
342 case 'x': // Lower case hex
344 itoa(tmpBuf, val, 16, minSize, pad);
348 itoa(tmpBuf, val, 8, minSize, pad);
352 itoa(tmpBuf, val, 2, minSize, pad);
356 val = va_arg(args, unsigned int);
361 // String - Null Terminated Array
363 p = va_arg(args, char*); // Get Argument
364 if( !p || !CheckString(p) ) p = "(inval)"; // Avoid #PFs
368 if( !bPadLeft ) while(len++ < minSize) PUTCH(pad);
369 while(*p && precision--) PUTCH(*p++);
370 if( bPadLeft ) while(len++ < minSize) PUTCH(pad);
373 case 'C': // Non-Null Terminated Character Array
374 p = va_arg(args, char*);
375 if( !CheckMem(p, minSize) ) continue; // No #PFs please
376 if(!p) goto printString;
377 while(minSize--) PUTCH(*p++);
389 if(__s && pos != __maxlen)
398 int sprintf(char *__s, const char *__format, ...)
403 va_start(args, __format);
404 ret = vsnprintf(__s, -1, __format, args);
411 * \fn int tolower(int c)
412 * \brief Converts a character to lower case
416 if('A' <= c && c <= 'Z')
417 return c - 'A' + 'a';
422 * \fn int strucmp(const char *Str1, const char *Str2)
423 * \brief Compare \a Str1 and \a Str2 case-insensitively
425 int strucmp(const char *Str1, const char *Str2)
427 while(*Str1 && tolower(*Str1) == tolower(*Str2))
429 return tolower(*Str1) - tolower(*Str2);
433 * \brief Locate a byte in a string
435 char *strchr(const char *__s, int __c)
437 for( ; *__s; __s ++ )
439 if( *__s == __c ) return (char*)__s;
445 * \fn int strpos(const char *Str, char Ch)
446 * \brief Search a string for an ascii character
448 int strpos(const char *Str, char Ch)
451 for(pos=0;Str[pos];pos++)
453 if(Str[pos] == Ch) return pos;
459 * \fn Uint8 ByteSum(void *Ptr, int Size)
460 * \brief Adds the bytes in a memory region and returns the sum
462 Uint8 ByteSum(const void *Ptr, int Size)
465 const Uint8 *data = Ptr;
466 while(Size--) sum += *(data++);
471 * \fn size_t strlen(const char *__str)
472 * \brief Get the length of string
474 size_t strlen(const char *__str)
477 while(*__str++) ret++;
482 * \brief Copy a string to a new location
484 char *strcpy(char *__str1, const char *__str2)
487 *__str1++ = *__str2++;
488 *__str1 = '\0'; // Terminate String
493 * \brief Copy a string to a new location
494 * \note Copies at most `max` chars
496 char *strncpy(char *__str1, const char *__str2, size_t __max)
498 while(*__str2 && __max-- >= 1)
499 *__str1++ = *__str2++;
501 *__str1 = '\0'; // Terminate String
506 * \brief Append a string to another
508 char *strcat(char *__dest, const char *__src)
513 *__dest++ = *__src++;
519 * \brief Append at most \a n chars to a string from another
520 * \note At most n+1 chars are written (the dest is always zero terminated)
522 char *strncat(char *__dest, const char *__src, size_t n)
525 while(*__src && n-- >= 1)
526 *__dest++ = *__src++;
532 * \fn int strcmp(const char *str1, const char *str2)
533 * \brief Compare two strings return the difference between
534 * the first non-matching characters.
536 int strcmp(const char *str1, const char *str2)
538 while(*str1 && *str1 == *str2)
540 return *str1 - *str2;
544 * \fn int strncmp(const char *Str1, const char *Str2, size_t num)
545 * \brief Compare strings \a Str1 and \a Str2 to a maximum of \a num characters
547 int strncmp(const char *Str1, const char *Str2, size_t num)
549 if(num == 0) return 0; // TODO: Check what should officially happen here
550 while(--num && *Str1 && *Str1 == *Str2)
557 * \fn char *strdup(const char *Str)
558 * \brief Duplicates a string
560 char *strdup(const char *Str)
563 ret = malloc(strlen(Str)+1);
564 if( !ret ) return NULL;
571 * \fn char *_strdup(const char *File, int Line, const char *Str)
572 * \brief Duplicates a string
574 char *_strdup(const char *File, int Line, const char *Str)
577 ret = Heap_Allocate(File, Line, strlen(Str)+1);
578 if( !ret ) return NULL;
585 * \brief Split a string using the passed character
586 * \return NULL terminated array of strings on the heap
587 * \param __str String to split
588 * \param __ch Character to split by
590 char **str_split(const char *__str, char __ch)
597 for( i = 0; __str[i]; i++ )
603 ret = malloc( sizeof(char*)*(len+1) + (i + 1) );
604 if( !ret ) return NULL;
607 start = (char *)&ret[len+1];
609 for( i = 0; __str[i]; i++ )
611 if(__str[i] == __ch) {
626 * \fn int DivUp(int num, int dem)
627 * \brief Divide two numbers, rounding up
628 * \param num Numerator
629 * \param dem Denominator
631 int DivUp(int num, int dem)
633 return (num+dem-1)/dem;
637 * \fn int strpos8(const char *str, Uint32 search)
638 * \brief Search a string for a UTF-8 character
640 int strpos8(const char *str, Uint32 Search)
644 for(pos=0;str[pos];pos++)
648 if(str[pos] == Search) return pos;
651 if(*(Uint8*)(str+pos) < 128) continue;
653 pos += ReadUTF8( (Uint8*)&str[pos], &val );
654 if(val == Search) return pos;
660 * \fn int ReadUTF8(Uint8 *str, Uint32 *Val)
661 * \brief Read a UTF-8 character from a string
663 int ReadUTF8(const Uint8 *str, Uint32 *Val)
665 *Val = 0xFFFD; // Assume invalid character
668 if( !(*str & 0x80) ) {
673 // Middle of a sequence
674 if( (*str & 0xC0) == 0x80 ) {
679 if( (*str & 0xE0) == 0xC0 ) {
680 *Val = (*str & 0x1F) << 6; // Upper 6 Bits
682 if( (*str & 0xC0) != 0x80) return -1; // Validity check
683 *Val |= (*str & 0x3F); // Lower 6 Bits
688 if( (*str & 0xF0) == 0xE0 ) {
689 *Val = (*str & 0x0F) << 12; // Upper 4 Bits
691 if( (*str & 0xC0) != 0x80) return -1; // Validity check
692 *Val |= (*str & 0x3F) << 6; // Middle 6 Bits
694 if( (*str & 0xC0) != 0x80) return -1; // Validity check
695 *Val |= (*str & 0x3F); // Lower 6 Bits
700 if( (*str & 0xF1) == 0xF0 ) {
701 *Val = (*str & 0x07) << 18; // Upper 3 Bits
703 if( (*str & 0xC0) != 0x80) return -1; // Validity check
704 *Val |= (*str & 0x3F) << 12; // Middle-upper 6 Bits
706 if( (*str & 0xC0) != 0x80) return -1; // Validity check
707 *Val |= (*str & 0x3F) << 6; // Middle-lower 6 Bits
709 if( (*str & 0xC0) != 0x80) return -1; // Validity check
710 *Val |= (*str & 0x3F); // Lower 6 Bits
714 // UTF-8 Doesn't support more than four bytes
719 * \fn int WriteUTF8(Uint8 *str, Uint32 Val)
720 * \brief Write a UTF-8 character sequence to a string
722 int WriteUTF8(Uint8 *str, Uint32 Val)
735 *str++ = 0xC0 | (Val >> 6);
736 *str++ = 0x80 | (Val & 0x3F);
742 if( Val < 0x10000 ) {
744 *str++ = 0xE0 | (Val >> 12);
745 *str++ = 0x80 | ((Val >> 6) & 0x3F);
746 *str++ = 0x80 | (Val & 0x3F);
752 if( Val < 0x110000 ) {
754 *str++ = 0xF0 | (Val >> 18);
755 *str++ = 0x80 | ((Val >> 12) & 0x3F);
756 *str++ = 0x80 | ((Val >> 6) & 0x3F);
757 *str++ = 0x80 | (Val & 0x3F);
762 // UTF-8 Doesn't support more than four bytes
767 * \fn Uint64 timestamp(int sec, int mins, int hrs, int day, int month, int year)
768 * \brief Converts a date into an Acess Timestamp
770 Sint64 timestamp(int sec, int mins, int hrs, int day, int month, int year)
777 stamp += day*3600*24;
778 stamp += month*DAYS_BEFORE[month]*3600*24;
780 ((year&3) == 0 || year%100 != 0)
781 || (year%100 == 0 && ((year/100)&3) == 0)
782 ) && month > 1) // Leap year and after feb
785 stamp += ((365*4+1) * ((year-2000)&~3)) * 3600*24; // Four Year Segments
786 stamp += ((year-2000)&3) * 365*3600*24; // Inside four year segment
794 * \brief Pseudo random number generator
799 static Uint state = RANDOM_SEED;
801 // Get the next state value
802 giRandomState = (RANDOM_A*state + RANDOM_C);
803 // Check if it has changed, and if it hasn't, change it
804 if(state == old) state += RANDOM_SPRUCE;
807 // http://en.wikipedia.org/wiki/Xorshift
809 static Uint32 x = 123456789;
810 static Uint32 y = 362436069;
811 static Uint32 z = 521288629;
812 static Uint32 w = 88675123;
817 return w = w ^ (w >> 19) ^ t ^ (t >> 8);
822 * \name Memory Validation
826 * \brief Checks if a string resides fully in valid memory
828 int CheckString(const char *String)
833 addr = (tVAddr)String;
835 if( !MM_GetPhysAddr( addr ) )
839 bUser = MM_IsUser( addr );
841 while( *(char*)addr )
843 if( (addr & (PAGE_SIZE-1)) == 0 )
845 if(bUser && !MM_IsUser(addr) )
847 if(!bUser && !MM_GetPhysAddr(addr) )
856 * \brief Check if a sized memory region is valid memory
857 * \return Boolean success
859 int CheckMem(const void *Mem, int NumBytes)
861 return MM_IsValidBuffer( (tVAddr)Mem, NumBytes );
868 * \brief Search a string array for \a Needle
869 * \note Helper function for eTplDrv_IOCtl::DRV_IOCTL_LOOKUP
871 int ModUtil_LookupString(const char **Array, const char *Needle)
874 if( !CheckString(Needle) ) return -1;
875 for( i = 0; Array[i]; i++ )
877 if(strcmp(Array[i], Needle) == 0) return i;
882 int ModUtil_SetIdent(char *Dest, const char *Value)
884 if( !CheckMem(Dest, 32) ) return -1;
885 strncpy(Dest, Value, 32);
890 * \brief Convert a string of hexadecimal digits into a byte stream
892 int UnHex(Uint8 *Dest, size_t DestSize, const char *SourceString)
896 for( i = 0; i < DestSize*2; i += 2 )
900 if(SourceString[i] == '\0') break;
902 if('0' <= SourceString[i] && SourceString[i] <= '9')
903 val |= (SourceString[i]-'0') << 4;
904 else if('A' <= SourceString[i] && SourceString[i] <= 'F')
905 val |= (SourceString[i]-'A'+10) << 4;
906 else if('a' <= SourceString[i] && SourceString[i] <= 'f')
907 val |= (SourceString[i]-'a'+10) << 4;
909 if(SourceString[i+1] == '\0') break;
911 if('0' <= SourceString[i+1] && SourceString[i+1] <= '9')
912 val |= (SourceString[i+1] - '0');
913 else if('A' <= SourceString[i+1] && SourceString[i+1] <= 'F')
914 val |= (SourceString[i+1] - 'A' + 10);
915 else if('a' <= SourceString[i+1] && SourceString[i+1] <= 'f')
916 val |= (SourceString[i+1] - 'a' + 10);
923 Uint16 SwapEndian16(Uint16 Val)
925 return ((Val&0xFF)<<8) | ((Val>>8)&0xFF);
927 Uint32 SwapEndian32(Uint32 Val)
929 return ((Val&0xFF)<<24) | ((Val&0xFF00)<<8) | ((Val>>8)&0xFF00) | ((Val>>24)&0xFF);
932 void *memmove(void *__dest, const void *__src, size_t len)
936 const char *src = __src;
939 if( len == 0 || dest == src )
942 if( (tVAddr)dest > (tVAddr)src + len )
943 return memcpy(dest, src, len);
944 if( (tVAddr)dest + len < (tVAddr)src )
945 return memcpy(dest, src, len);
947 // NOTE: Assumes memcpy works forward
948 if( (tVAddr)dest < (tVAddr)src )
949 return memcpy(dest, src, len);
951 if( (tVAddr)dest < (tVAddr)src )
952 block_size = (tVAddr)src - (tVAddr)dest;
954 block_size = (tVAddr)dest - (tVAddr)src;
958 while(len >= block_size)
960 memcpy(dest, src, block_size);
965 memcpy(dest, src, len);