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 auto void _putch(char ch);
220 if(__s) __s[pos] = ch;
225 while((c = *__format++) != 0)
227 // Non control character
228 if(c != '%') { PUTCH(c); continue; }
234 if(c == '%') { PUTCH('%'); continue; }
236 // Pointer - Done first for debugging
238 Uint ptr = va_arg(args, Uint);
239 PUTCH('*'); PUTCH('0'); PUTCH('x');
240 for( len = BITS/4; len --; )
241 PUTCH( cUCDIGITS[ (ptr>>(len*4))&15 ] );
245 // - Padding Side Flag
260 if(c == '*') { // Dynamic length
261 minSize = va_arg(args, unsigned int);
264 else if('1' <= c && c <= '9')
267 while('0' <= c && c <= '9')
282 if(c == '*') { // Dynamic length
283 precision = va_arg(args, unsigned int);
286 else if('1' <= c && c <= '9')
289 while('0' <= c && c <= '9')
292 precision += c - '0';
298 // - Default, Long or LongLong?
300 if(c == 'l') // Long is actually the default on x86
309 // - Now get the format code
316 if( isLongLong && val >> 63 ) {
320 else if( !isLongLong && val >> 31 ) {
324 itoa(tmpBuf, val, 10, minSize, pad);
326 case 'u': // Unsigned
328 itoa(tmpBuf, val, 10, minSize, pad);
330 case 'P': // Physical Address
333 if(sizeof(tPAddr) > 4) isLongLong = 1;
335 itoa(tmpBuf, val, 16, minSize, pad);
339 isLongLong = 1; // TODO: Handle non-x86 64-bit archs
341 itoa(tmpBuf, val, 16, minSize, pad);
344 case 'x': // Lower case hex
346 itoa(tmpBuf, val, 16, minSize, pad);
350 itoa(tmpBuf, val, 8, minSize, pad);
354 itoa(tmpBuf, val, 2, minSize, pad);
358 val = va_arg(args, unsigned int);
363 // String - Null Terminated Array
365 p = va_arg(args, char*); // Get Argument
366 if( !p || !CheckString(p) ) p = "(inval)"; // Avoid #PFs
370 if( !bPadLeft ) while(len++ < minSize) PUTCH(pad);
371 while(*p && precision--) PUTCH(*p++);
372 if( bPadLeft ) while(len++ < minSize) PUTCH(pad);
375 case 'C': // Non-Null Terminated Character Array
376 p = va_arg(args, char*);
377 if( !CheckMem(p, minSize) ) continue; // No #PFs please
378 if(!p) goto printString;
379 while(minSize--) PUTCH(*p++);
391 if(__s && pos != __maxlen)
400 int sprintf(char *__s, const char *__format, ...)
405 va_start(args, __format);
406 ret = vsnprintf(__s, -1, __format, args);
413 * \fn int tolower(int c)
414 * \brief Converts a character to lower case
418 if('A' <= c && c <= 'Z')
419 return c - 'A' + 'a';
424 * \fn int strucmp(const char *Str1, const char *Str2)
425 * \brief Compare \a Str1 and \a Str2 case-insensitively
427 int strucmp(const char *Str1, const char *Str2)
429 while(*Str1 && tolower(*Str1) == tolower(*Str2))
431 return tolower(*Str1) - tolower(*Str2);
435 * \brief Locate a byte in a string
437 char *strchr(const char *__s, int __c)
439 for( ; *__s; __s ++ )
441 if( *__s == __c ) return (char*)__s;
447 * \fn int strpos(const char *Str, char Ch)
448 * \brief Search a string for an ascii character
450 int strpos(const char *Str, char Ch)
453 for(pos=0;Str[pos];pos++)
455 if(Str[pos] == Ch) return pos;
461 * \fn Uint8 ByteSum(void *Ptr, int Size)
462 * \brief Adds the bytes in a memory region and returns the sum
464 Uint8 ByteSum(const void *Ptr, int Size)
467 const Uint8 *data = Ptr;
468 while(Size--) sum += *(data++);
473 * \fn size_t strlen(const char *__str)
474 * \brief Get the length of string
476 size_t strlen(const char *__str)
479 while(*__str++) ret++;
484 * \brief Copy a string to a new location
486 char *strcpy(char *__str1, const char *__str2)
489 *__str1++ = *__str2++;
490 *__str1 = '\0'; // Terminate String
495 * \brief Copy a string to a new location
496 * \note Copies at most `max` chars
498 char *strncpy(char *__str1, const char *__str2, size_t __max)
500 while(*__str2 && __max-- >= 1)
501 *__str1++ = *__str2++;
503 *__str1 = '\0'; // Terminate String
508 * \brief Append a string to another
510 char *strcat(char *__dest, const char *__src)
515 *__dest++ = *__src++;
521 * \brief Append at most \a n chars to a string from another
522 * \note At most n+1 chars are written (the dest is always zero terminated)
524 char *strncat(char *__dest, const char *__src, size_t n)
527 while(*__src && n-- >= 1)
528 *__dest++ = *__src++;
534 * \fn int strcmp(const char *str1, const char *str2)
535 * \brief Compare two strings return the difference between
536 * the first non-matching characters.
538 int strcmp(const char *str1, const char *str2)
540 while(*str1 && *str1 == *str2)
542 return *str1 - *str2;
546 * \fn int strncmp(const char *Str1, const char *Str2, size_t num)
547 * \brief Compare strings \a Str1 and \a Str2 to a maximum of \a num characters
549 int strncmp(const char *Str1, const char *Str2, size_t num)
551 if(num == 0) return 0; // TODO: Check what should officially happen here
552 while(--num && *Str1 && *Str1 == *Str2)
559 * \fn char *strdup(const char *Str)
560 * \brief Duplicates a string
562 char *strdup(const char *Str)
565 ret = malloc(strlen(Str)+1);
566 if( !ret ) return NULL;
573 * \fn char *_strdup(const char *File, int Line, const char *Str)
574 * \brief Duplicates a string
576 char *_strdup(const char *File, int Line, const char *Str)
579 ret = Heap_Allocate(File, Line, strlen(Str)+1);
580 if( !ret ) return NULL;
587 * \brief Split a string using the passed character
588 * \return NULL terminated array of strings on the heap
589 * \param __str String to split
590 * \param __ch Character to split by
592 char **str_split(const char *__str, char __ch)
599 for( i = 0; __str[i]; i++ )
605 ret = malloc( sizeof(char*)*(len+1) + (i + 1) );
606 if( !ret ) return NULL;
609 start = (char *)&ret[len+1];
611 for( i = 0; __str[i]; i++ )
613 if(__str[i] == __ch) {
628 * \fn int DivUp(int num, int dem)
629 * \brief Divide two numbers, rounding up
630 * \param num Numerator
631 * \param dem Denominator
633 int DivUp(int num, int dem)
635 return (num+dem-1)/dem;
639 * \fn int strpos8(const char *str, Uint32 search)
640 * \brief Search a string for a UTF-8 character
642 int strpos8(const char *str, Uint32 Search)
646 for(pos=0;str[pos];pos++)
650 if(str[pos] == Search) return pos;
653 if(*(Uint8*)(str+pos) < 128) continue;
655 pos += ReadUTF8( (Uint8*)&str[pos], &val );
656 if(val == Search) return pos;
662 * \fn int ReadUTF8(Uint8 *str, Uint32 *Val)
663 * \brief Read a UTF-8 character from a string
665 int ReadUTF8(const Uint8 *str, Uint32 *Val)
667 *Val = 0xFFFD; // Assume invalid character
670 if( !(*str & 0x80) ) {
675 // Middle of a sequence
676 if( (*str & 0xC0) == 0x80 ) {
681 if( (*str & 0xE0) == 0xC0 ) {
682 *Val = (*str & 0x1F) << 6; // Upper 6 Bits
684 if( (*str & 0xC0) != 0x80) return -1; // Validity check
685 *Val |= (*str & 0x3F); // Lower 6 Bits
690 if( (*str & 0xF0) == 0xE0 ) {
691 *Val = (*str & 0x0F) << 12; // Upper 4 Bits
693 if( (*str & 0xC0) != 0x80) return -1; // Validity check
694 *Val |= (*str & 0x3F) << 6; // Middle 6 Bits
696 if( (*str & 0xC0) != 0x80) return -1; // Validity check
697 *Val |= (*str & 0x3F); // Lower 6 Bits
702 if( (*str & 0xF1) == 0xF0 ) {
703 *Val = (*str & 0x07) << 18; // Upper 3 Bits
705 if( (*str & 0xC0) != 0x80) return -1; // Validity check
706 *Val |= (*str & 0x3F) << 12; // Middle-upper 6 Bits
708 if( (*str & 0xC0) != 0x80) return -1; // Validity check
709 *Val |= (*str & 0x3F) << 6; // Middle-lower 6 Bits
711 if( (*str & 0xC0) != 0x80) return -1; // Validity check
712 *Val |= (*str & 0x3F); // Lower 6 Bits
716 // UTF-8 Doesn't support more than four bytes
721 * \fn int WriteUTF8(Uint8 *str, Uint32 Val)
722 * \brief Write a UTF-8 character sequence to a string
724 int WriteUTF8(Uint8 *str, Uint32 Val)
737 *str++ = 0xC0 | (Val >> 6);
738 *str++ = 0x80 | (Val & 0x3F);
744 if( Val < 0x10000 ) {
746 *str++ = 0xE0 | (Val >> 12);
747 *str++ = 0x80 | ((Val >> 6) & 0x3F);
748 *str++ = 0x80 | (Val & 0x3F);
754 if( Val < 0x110000 ) {
756 *str++ = 0xF0 | (Val >> 18);
757 *str++ = 0x80 | ((Val >> 12) & 0x3F);
758 *str++ = 0x80 | ((Val >> 6) & 0x3F);
759 *str++ = 0x80 | (Val & 0x3F);
764 // UTF-8 Doesn't support more than four bytes
769 * \fn Uint64 timestamp(int sec, int mins, int hrs, int day, int month, int year)
770 * \brief Converts a date into an Acess Timestamp
772 Sint64 timestamp(int sec, int mins, int hrs, int day, int month, int year)
779 stamp += day*3600*24;
780 stamp += month*DAYS_BEFORE[month]*3600*24;
782 ((year&3) == 0 || year%100 != 0)
783 || (year%100 == 0 && ((year/100)&3) == 0)
784 ) && month > 1) // Leap year and after feb
787 stamp += ((365*4+1) * ((year-2000)&~3)) * 3600*24; // Four Year Segments
788 stamp += ((year-2000)&3) * 365*3600*24; // Inside four year segment
796 * \brief Pseudo random number generator
801 static Uint state = RANDOM_SEED;
803 // Get the next state value
804 giRandomState = (RANDOM_A*state + RANDOM_C);
805 // Check if it has changed, and if it hasn't, change it
806 if(state == old) state += RANDOM_SPRUCE;
809 // http://en.wikipedia.org/wiki/Xorshift
811 static Uint32 x = 123456789;
812 static Uint32 y = 362436069;
813 static Uint32 z = 521288629;
814 static Uint32 w = 88675123;
819 return w = w ^ (w >> 19) ^ t ^ (t >> 8);
824 * \name Memory Validation
828 * \brief Checks if a string resides fully in valid memory
830 int CheckString(const char *String)
835 addr = (tVAddr)String;
837 if( !MM_GetPhysAddr( addr ) )
841 bUser = MM_IsUser( addr );
843 while( *(char*)addr )
845 if( (addr & (PAGE_SIZE-1)) == 0 )
847 if(bUser && !MM_IsUser(addr) )
849 if(!bUser && !MM_GetPhysAddr(addr) )
858 * \brief Check if a sized memory region is valid memory
859 * \return Boolean success
861 int CheckMem(const void *Mem, int NumBytes)
863 return MM_IsValidBuffer( (tVAddr)Mem, NumBytes );
870 * \brief Search a string array for \a Needle
871 * \note Helper function for eTplDrv_IOCtl::DRV_IOCTL_LOOKUP
873 int ModUtil_LookupString(const char **Array, const char *Needle)
876 if( !CheckString(Needle) ) return -1;
877 for( i = 0; Array[i]; i++ )
879 if(strcmp(Array[i], Needle) == 0) return i;
884 int ModUtil_SetIdent(char *Dest, const char *Value)
886 if( !CheckMem(Dest, 32) ) return -1;
887 strncpy(Dest, Value, 32);
892 * \brief Convert a string of hexadecimal digits into a byte stream
894 int UnHex(Uint8 *Dest, size_t DestSize, const char *SourceString)
898 for( i = 0; i < DestSize*2; i += 2 )
902 if(SourceString[i] == '\0') break;
904 if('0' <= SourceString[i] && SourceString[i] <= '9')
905 val |= (SourceString[i]-'0') << 4;
906 else if('A' <= SourceString[i] && SourceString[i] <= 'F')
907 val |= (SourceString[i]-'A'+10) << 4;
908 else if('a' <= SourceString[i] && SourceString[i] <= 'f')
909 val |= (SourceString[i]-'a'+10) << 4;
911 if(SourceString[i+1] == '\0') break;
913 if('0' <= SourceString[i+1] && SourceString[i+1] <= '9')
914 val |= (SourceString[i+1] - '0');
915 else if('A' <= SourceString[i+1] && SourceString[i+1] <= 'F')
916 val |= (SourceString[i+1] - 'A' + 10);
917 else if('a' <= SourceString[i+1] && SourceString[i+1] <= 'f')
918 val |= (SourceString[i+1] - 'a' + 10);
925 Uint16 SwapEndian16(Uint16 Val)
927 return ((Val&0xFF)<<8) | ((Val>>8)&0xFF);
929 Uint32 SwapEndian32(Uint32 Val)
931 return ((Val&0xFF)<<24) | ((Val&0xFF00)<<8) | ((Val>>8)&0xFF00) | ((Val>>24)&0xFF);
934 void *memmove(void *__dest, const void *__src, size_t len)
938 const char *src = __src;
941 if( len == 0 || dest == src )
944 if( (tVAddr)dest > (tVAddr)src + len )
945 return memcpy(dest, src, len);
946 if( (tVAddr)dest + len < (tVAddr)src )
947 return memcpy(dest, src, len);
949 // NOTE: Assumes memcpy works forward
950 if( (tVAddr)dest < (tVAddr)src )
951 return memcpy(dest, src, len);
953 if( (tVAddr)dest < (tVAddr)src )
954 block_size = (tVAddr)src - (tVAddr)dest;
956 block_size = (tVAddr)dest - (tVAddr)src;
960 while(len >= block_size)
962 memcpy(dest, src, block_size);
967 memcpy(dest, src, len);