Fixing up doxygen comments
[tpg/acess2.git] / Kernel / lib.c
1 /*
2  * Acess2
3  * Common Library Functions
4  */
5 #include <acess.h>
6
7 // === CONSTANTS ===
8 #define RANDOM_SEED     0xACE55052
9 #define RANDOM_A        0x00731ADE
10 #define RANDOM_C        12345
11 #define RANDOM_SPRUCE   0xf12b02b
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
15
16 // === PROTOTYPES ===
17  int    atoi(const char *string);
18 void    itoa(char *buf, Uint num, int base, int minLength, char pad);
19  int    vsnprintf(char *__s, size_t __maxlen, const char *__format, va_list args);
20  int    sprintf(char *__s, const char *__format, ...);
21  int    tolower(int c);
22  int    strucmp(const char *Str1, const char *Str2);
23  int    strpos(const char *Str, char Ch);
24  Uint8  ByteSum(void *Ptr, int Size);
25 size_t  strlen(const char *__s);
26 char    *strcpy(char *__str1, const char *__str2);
27 char    *strncpy(char *__str1, const char *__str2, size_t max);
28  int    strcmp(const char *str1, const char *str2);
29  int    strncmp(const char *str1, const char *str2, size_t num);
30 char    *strdup(const char *Str);
31 char    **str_split(const char *__str, char __ch);
32  int    strpos8(const char *str, Uint32 Search);
33  int    ReadUTF8(Uint8 *str, Uint32 *Val);
34  int    WriteUTF8(Uint8 *str, Uint32 Val);
35  int    DivUp(int num, int dem);
36 Sint64  timestamp(int sec, int mins, int hrs, int day, int month, int year);
37 Uint    rand(void);
38  int    CheckString(char *String);
39  int    CheckMem(void *Mem, int NumBytes);
40  int    ModUtil_LookupString(char **Array, char *Needle);
41  int    ModUtil_SetIdent(char *Dest, char *Value);
42
43 // === EXPORTS ===
44 EXPORT(atoi);
45 EXPORT(itoa);
46 EXPORT(vsnprintf);
47 EXPORT(sprintf);
48 EXPORT(tolower);
49 EXPORT(strucmp);
50 EXPORT(strpos);
51 EXPORT(ByteSum);
52 EXPORT(strlen);
53 EXPORT(strcpy);
54 EXPORT(strncpy);
55 EXPORT(strcmp);
56 EXPORT(strncmp);
57 EXPORT(strdup);
58 EXPORT(str_split);
59 EXPORT(strpos8);
60 EXPORT(DivUp);
61 EXPORT(ReadUTF8);
62 EXPORT(WriteUTF8);
63 EXPORT(timestamp);
64 EXPORT(CheckString);
65 EXPORT(CheckMem);
66 EXPORT(ModUtil_LookupString);
67 EXPORT(ModUtil_SetIdent);
68
69 // === GLOBALS ===
70 static Uint     giRandomState = RANDOM_SEED;
71
72 // === CODE ===
73 /**
74  * \brief Convert a string into an integer
75  */
76 int atoi(const char *string)
77 {
78          int    ret = 0;
79          int    bNeg = 0;
80         
81         //Log("atoi: (string='%s')", string);
82         
83         // Clear non-numeric characters
84         while( !('0' <= *string && *string <= '9') && *string != '-' )  string++;
85         if( *string == '-' ) {
86                 bNeg = 1;
87                 while( !('0' <= *string && *string <= '9') )    string++;
88         }
89         
90         if(*string == '0')
91         {
92                 string ++;
93                 if(*string == 'x')
94                 {
95                         // Hex
96                         string ++;
97                         for( ;; string ++ )
98                         {
99                                 if('0' <= *string && *string <= '9') {
100                                         ret *= 16;
101                                         ret += *string - '0';
102                                 }
103                                 else if('A' <= *string && *string <= 'F') {
104                                         ret *= 16;
105                                         ret += *string - 'A' + 10;
106                                 }
107                                 else if('a' <= *string && *string <= 'f') {
108                                         ret *= 16;
109                                         ret += *string - 'a' + 10;
110                                 }
111                                 else
112                                         break;
113                         }
114                 }
115                 else    // Octal
116                 {
117                         for( ; '0' <= *string && *string <= '7'; string ++ )
118                         {
119                                 ret *= 8;
120                                 ret += *string - '0';
121                         }
122                 }
123         }
124         else    // Decimal
125         {
126                 for( ; '0' <= *string && *string <= '9'; string++)
127                 {
128                         ret *= 10;
129                         ret += *string - '0';
130                 }
131         }
132         
133         if(bNeg)        ret = -ret;
134         
135         //Log("atoi: RETURN %i", ret);
136         
137         return ret;
138 }
139
140 static const char cUCDIGITS[] = "0123456789ABCDEF";
141 /**
142  * \fn void itoa(char *buf, Uint num, int base, int minLength, char pad)
143  * \brief Convert an integer into a character string
144  */
145 void itoa(char *buf, Uint num, int base, int minLength, char pad)
146 {
147         char    tmpBuf[BITS];
148          int    pos=0, i;
149
150         // Sanity check
151         if(!buf)        return;
152         
153         // Sanity Check
154         if(base > 16 || base < 2) {
155                 buf[0] = 0;
156                 return;
157         }
158         
159         // Convert 
160         while(num > base-1) {
161                 tmpBuf[pos] = cUCDIGITS[ num % base ];
162                 num /= (Uint)base;              // Shift `num` right 1 digit
163                 pos++;
164         }
165         tmpBuf[pos++] = cUCDIGITS[ num % base ];                // Last digit of `num`
166         
167         // Put in reverse
168         i = 0;
169         minLength -= pos;
170         while(minLength-- > 0)  buf[i++] = pad;
171         while(pos-- > 0)                buf[i++] = tmpBuf[pos]; // Reverse the order of characters
172         buf[i] = 0;
173 }
174
175 /**
176  * \brief Append a character the the vsnprintf output
177  */
178 #define PUTCH(c)        do{\
179         char ch=(c);\
180         if(pos==__maxlen){return pos;}\
181         if(__s){__s[pos++]=ch;}else{pos++;}\
182         }while(0)
183 /**
184  * \brief VArg String Number Print Formatted
185  */
186 int vsnprintf(char *__s, size_t __maxlen, const char *__format, va_list args)
187 {
188         char    c, pad = ' ';
189          int    minSize = 0, len;
190         char    tmpBuf[34];     // For Integers
191         char    *p = NULL;
192          int    isLongLong = 0;
193         Uint64  val;
194         size_t  pos = 0;
195         // Flags
196          int    bPadLeft = 0;
197         
198         //Log("vsnprintf: (__s=%p, __maxlen=%i, __format='%s', ...)", __s, __maxlen, __format);
199         
200         while((c = *__format++) != 0)
201         {
202                 // Non control character
203                 if(c != '%') { PUTCH(c); continue; }
204                 
205                 c = *__format++;
206                 //Log("pos = %i", pos);
207                 
208                 // Literal %
209                 if(c == '%') { PUTCH('%'); continue; }
210                 
211                 // Pointer - Done first for debugging
212                 if(c == 'p') {
213                         Uint    ptr = va_arg(args, Uint);
214                         PUTCH('*');     PUTCH('0');     PUTCH('x');
215                         p = tmpBuf;
216                         itoa(p, ptr, 16, BITS/4, '0');
217                         goto printString;
218                 }
219                 
220                 // Get Argument
221                 val = va_arg(args, Uint);
222                 
223                 // - Padding Side Flag
224                 if(c == '+') {
225                         bPadLeft = 1;
226                         c = *__format++;
227                 }
228                 
229                 // - Padding
230                 if(c == '0') {
231                         pad = '0';
232                         c = *__format++;
233                 }
234                 else
235                         pad = ' ';
236                 
237                 // - Minimum length
238                 if(c == '*') {  // Dynamic length
239                         minSize = val;
240                         val = va_arg(args, Uint);
241                         c = *__format++;
242                 }
243                 else if('1' <= c && c <= '9')
244                 {
245                         minSize = 0;
246                         while('0' <= c && c <= '9')
247                         {
248                                 minSize *= 10;
249                                 minSize += c - '0';
250                                 c = *__format++;
251                         }
252                 }
253                 else
254                         minSize = 1;
255                 
256                 // - Default, Long or LongLong?
257                 isLongLong = 0;
258                 if(c == 'l')    // Long is actually the default on x86
259                 {
260                         c = *__format++;
261                         if(c == 'l') {
262                                 #if BITS == 32
263                                 val |= (Uint64)va_arg(args, Uint) << 32;
264                                 #endif
265                                 c = *__format++;
266                                 isLongLong = 1;
267                         }
268                 }
269                 
270                 // - Now get the format code
271                 p = tmpBuf;
272                 switch(c)
273                 {
274                 case 'd':
275                 case 'i':
276                         if( isLongLong && val >> 63 ) {
277                                 PUTCH('-');
278                                 val = -val;
279                         }
280                         else if( !isLongLong && val >> 31 ) {
281                                 PUTCH('-');
282                                 val = -(Sint32)val;
283                         }
284                         itoa(p, val, 10, minSize, pad);
285                         goto printString;
286                 case 'u':
287                         itoa(p, val, 10, minSize, pad);
288                         goto printString;
289                 case 'x':
290                         itoa(p, val, 16, minSize, pad);
291                         goto printString;
292                 case 'o':
293                         itoa(p, val, 8, minSize, pad);
294                         goto printString;
295                 case 'b':
296                         itoa(p, val, 2, minSize, pad);
297                         goto printString;
298
299                 case 'B':       //Boolean
300                         if(val) p = "True";
301                         else    p = "False";
302                         goto printString;
303                 
304                 // String - Null Terminated Array
305                 case 's':
306                         p = (char*)(tVAddr)val;
307                 printString:
308                         if(!p)          p = "(null)";
309                         len = strlen(p);
310                         if( !bPadLeft ) while(len++ < minSize)  PUTCH(pad);
311                         while(*p)       PUTCH(*p++);
312                         if( bPadLeft )  while(len++ < minSize)  PUTCH(pad);
313                         break;
314                 
315                 case 'C':       // Non-Null Terminated Character Array
316                         p = (char*)(tVAddr)val;
317                         if(!p)  goto printString;
318                         while(minSize--)        PUTCH(*p++);
319                         break;
320                 
321                 // Single Character
322                 case 'c':
323                 default:
324                         PUTCH( (Uint8)val );
325                         break;
326                 }
327         }
328         
329         if(__s && pos != __maxlen)
330                 __s[pos] = '\0';
331         
332         return pos;
333 }
334 #undef PUTCH
335
336 /**
337  */
338 int sprintf(char *__s, const char *__format, ...)
339 {
340         va_list args;
341          int    ret;
342         
343         va_start(args, __format);
344         ret = vsnprintf(__s, -1, __format, args);
345         va_end(args);
346         
347         return ret;
348 }
349
350 /**
351  * \fn int tolower(int c)
352  * \brief Converts a character to lower case
353  */
354 int tolower(int c)
355 {
356         if('A' <= c && c <= 'Z')
357                 return c - 'A' + 'a';
358         return c;
359 }
360
361 /**
362  * \fn int strucmp(const char *Str1, const char *Str2)
363  * \brief Compare \a Str1 and \a Str2 case-insensitively
364  */
365 int strucmp(const char *Str1, const char *Str2)
366 {
367         while(*Str1 && tolower(*Str1) == tolower(*Str2))
368                 Str1++, Str2++;
369         return tolower(*Str1) - tolower(*Str2);
370 }
371
372 /**
373  * \fn int strpos(const char *Str, char Ch)
374  * \brief Search a string for an ascii character
375  */
376 int strpos(const char *Str, char Ch)
377 {
378          int    pos;
379         for(pos=0;Str[pos];pos++)
380         {
381                 if(Str[pos] == Ch)      return pos;
382         }
383         return -1;
384 }
385
386 /**
387  * \fn Uint8 ByteSum(void *Ptr, int Size)
388  * \brief Adds the bytes in a memory region and returns the sum
389  */
390 Uint8 ByteSum(void *Ptr, int Size)
391 {
392         Uint8   sum = 0;
393         while(Size--)   sum += *(Uint8*)Ptr++;
394         return sum;
395 }
396
397 /**
398  * \fn Uint strlen(const char *__str)
399  * \brief Get the length of string
400  */
401 Uint strlen(const char *__str)
402 {
403         Uint    ret = 0;
404         while(*__str++) ret++;
405         return ret;
406 }
407
408 /**
409  * \fn char *strcpy(char *__str1, const char *__str2)
410  * \brief Copy a string to a new location
411  */
412 char *strcpy(char *__str1, const char *__str2)
413 {
414         while(*__str2)
415                 *__str1++ = *__str2++;
416         *__str1 = '\0'; // Terminate String
417         return __str1;
418 }
419
420 /**
421  * \fn char *strncpy(char *__str1, const char *__str2, size_t max)
422  * \brief Copy a string to a new location
423  */
424 char *strncpy(char *__str1, const char *__str2, size_t max)
425 {
426         while(*__str2 && max-- >= 1)
427                 *__str1++ = *__str2++;
428         if(max)
429                 *__str1 = '\0'; // Terminate String
430         return __str1;
431 }
432
433 /**
434  * \fn int strcmp(const char *str1, const char *str2)
435  * \brief Compare two strings return the difference between
436  *        the first non-matching characters.
437  */
438 int strcmp(const char *str1, const char *str2)
439 {
440         while(*str1 && *str1 == *str2)
441                 str1++, str2++;
442         return *str1 - *str2;
443 }
444
445 /**
446  * \fn int strncmp(const char *Str1, const char *Str2, size_t num)
447  * \brief Compare strings \a Str1 and \a Str2 to a maximum of \a num characters
448  */
449 int strncmp(const char *Str1, const char *Str2, size_t num)
450 {
451         if(num == 0)    return 0;       // TODO: Check what should officially happen here
452         while(--num && *Str1 && *Str1 == *Str2)
453                 Str1++, Str2++;
454         return *Str1-*Str2;
455 }
456
457 /**
458  * \fn char *strdup(const char *Str)
459  * \brief Duplicates a string
460  */
461 char *strdup(const char *Str)
462 {
463         char    *ret;
464         ret = malloc(strlen(Str)+1);
465         strcpy(ret, Str);
466         return ret;
467 }
468
469 /**
470  * \brief Split a string using the passed character
471  * \return NULL terminated array of strings on the heap
472  * \param __str String to split
473  * \param __ch  Character to split by
474  */
475 char **str_split(const char *__str, char __ch)
476 {
477          int    i, j;
478          int    len = 1;
479         char    **ret;
480         char    *start;
481         
482         for( i = 0; __str[i]; i++ )
483         {
484                 if(__str[i] == __ch)
485                         len ++;
486         }
487         
488         ret = malloc( sizeof(char*)*(len+1) + (i + 1) );
489         if( !ret )      return NULL;
490         
491         j = 1;
492         start = (char *)&ret[len+1];
493         ret[0] = start;
494         for( i = 0; __str[i]; i++ )
495         {
496                 if(__str[i] == __ch) {
497                         *start++ = '\0';
498                         ret[j++] = start;
499                 }
500                 else {
501                         *start++ = __str[i]; 
502                 }
503         }
504         *start = '\0';
505         ret[j] = NULL;
506         
507         return ret;
508 }
509
510 /**
511  * \fn int DivUp(int num, int dem)
512  * \brief Divide two numbers, rounding up
513  * \param num   Numerator
514  * \param dem   Denominator
515  */
516 int DivUp(int num, int dem)
517 {
518         return (num+dem-1)/dem;
519 }
520
521 /**
522  * \fn int strpos8(const char *str, Uint32 search)
523  * \brief Search a string for a UTF-8 character
524  */
525 int strpos8(const char *str, Uint32 Search)
526 {
527          int    pos;
528         Uint32  val = 0;
529         for(pos=0;str[pos];pos++)
530         {
531                 // ASCII Range
532                 if(Search < 128) {
533                         if(str[pos] == Search)  return pos;
534                         continue;
535                 }
536                 if(*(Uint8*)(str+pos) < 128)    continue;
537                 
538                 pos += ReadUTF8( (Uint8*)&str[pos], &val );
539                 if(val == Search)       return pos;
540         }
541         return -1;
542 }
543
544 /**
545  * \fn int ReadUTF8(Uint8 *str, Uint32 *Val)
546  * \brief Read a UTF-8 character from a string
547  */
548 int ReadUTF8(Uint8 *str, Uint32 *Val)
549 {
550         *Val = 0xFFFD;  // Assume invalid character
551         
552         // ASCII
553         if( !(*str & 0x80) ) {
554                 *Val = *str;
555                 return 1;
556         }
557         
558         // Middle of a sequence
559         if( (*str & 0xC0) == 0x80 ) {
560                 return 1;
561         }
562         
563         // Two Byte
564         if( (*str & 0xE0) == 0xC0 ) {
565                 *Val = (*str & 0x1F) << 6;      // Upper 6 Bits
566                 str ++;
567                 if( (*str & 0xC0) != 0x80)      return -1;      // Validity check
568                 *Val |= (*str & 0x3F);  // Lower 6 Bits
569                 return 2;
570         }
571         
572         // Three Byte
573         if( (*str & 0xF0) == 0xE0 ) {
574                 *Val = (*str & 0x0F) << 12;     // Upper 4 Bits
575                 str ++;
576                 if( (*str & 0xC0) != 0x80)      return -1;      // Validity check
577                 *Val |= (*str & 0x3F) << 6;     // Middle 6 Bits
578                 str ++;
579                 if( (*str & 0xC0) != 0x80)      return -1;      // Validity check
580                 *Val |= (*str & 0x3F);  // Lower 6 Bits
581                 return 3;
582         }
583         
584         // Four Byte
585         if( (*str & 0xF1) == 0xF0 ) {
586                 *Val = (*str & 0x07) << 18;     // Upper 3 Bits
587                 str ++;
588                 if( (*str & 0xC0) != 0x80)      return -1;      // Validity check
589                 *Val |= (*str & 0x3F) << 12;    // Middle-upper 6 Bits
590                 str ++;
591                 if( (*str & 0xC0) != 0x80)      return -1;      // Validity check
592                 *Val |= (*str & 0x3F) << 6;     // Middle-lower 6 Bits
593                 str ++;
594                 if( (*str & 0xC0) != 0x80)      return -1;      // Validity check
595                 *Val |= (*str & 0x3F);  // Lower 6 Bits
596                 return 4;
597         }
598         
599         // UTF-8 Doesn't support more than four bytes
600         return 4;
601 }
602
603 /**
604  * \fn int WriteUTF8(Uint8 *str, Uint32 Val)
605  * \brief Write a UTF-8 character sequence to a string
606  */
607 int WriteUTF8(Uint8 *str, Uint32 Val)
608 {
609         // ASCII
610         if( Val < 128 ) {
611                 *str = Val;
612                 return 1;
613         }
614         
615         // Two Byte
616         if( Val < 0x8000 ) {
617                 *str = 0xC0 | (Val >> 6);
618                 str ++;
619                 *str = 0x80 | (Val & 0x3F);
620                 return 2;
621         }
622         
623         // Three Byte
624         if( Val < 0x10000 ) {
625                 *str = 0xE0 | (Val >> 12);
626                 str ++;
627                 *str = 0x80 | ((Val >> 6) & 0x3F);
628                 str ++;
629                 *str = 0x80 | (Val & 0x3F);
630                 return 3;
631         }
632         
633         // Four Byte
634         if( Val < 0x110000 ) {
635                 *str = 0xF0 | (Val >> 18);
636                 str ++;
637                 *str = 0x80 | ((Val >> 12) & 0x3F);
638                 str ++;
639                 *str = 0x80 | ((Val >> 6) & 0x3F);
640                 str ++;
641                 *str = 0x80 | (Val & 0x3F);
642                 return 4;
643         }
644         
645         // UTF-8 Doesn't support more than four bytes
646         return 0;
647 }
648
649 /**
650  * \fn Uint64 timestamp(int sec, int mins, int hrs, int day, int month, int year)
651  * \brief Converts a date into an Acess Timestamp
652  */
653 Sint64 timestamp(int sec, int mins, int hrs, int day, int month, int year)
654 {
655         Sint64  stamp;
656         stamp = sec;
657         stamp += mins*60;
658         stamp += hrs*3600;
659         
660         stamp += day*3600*24;
661         stamp += month*DAYS_BEFORE[month]*3600*24;
662         if(     (
663                 ((year&3) == 0 || year%100 != 0)
664                 || (year%100 == 0 && ((year/100)&3) == 0)
665                 ) && month > 1) // Leap year and after feb
666                 stamp += 3600*24;
667         
668         stamp += ((365*4+1) * ((year-2000)&~3)) * 3600*24;      // Four Year Segments
669         stamp += ((year-2000)&3) * 365*3600*24; // Inside four year segment
670         stamp += UNIX_TO_2K;
671         
672         return stamp * 1000;
673 }
674
675 /**
676  * \fn Uint rand()
677  * \brief Pseudo random number generator
678  * \note Unknown effectiveness (made up on the spot)
679  */
680 Uint rand(void)
681 {
682         Uint    old = giRandomState;
683         // Get the next state value
684         giRandomState = (RANDOM_A*giRandomState + RANDOM_C) & 0xFFFFFFFF;
685         // Check if it has changed, and if it hasn't, change it
686         if(giRandomState == old)        giRandomState += RANDOM_SPRUCE;
687         return giRandomState;
688 }
689
690 /* *
691  * \name Memory Validation
692  * \{
693  */
694 /**
695  * \brief Checks if a string resides fully in valid memory
696  */
697 int CheckString(char *String)
698 {
699         if( !MM_GetPhysAddr( (tVAddr)String ) )
700                 return 0;
701         
702         // Check 1st page
703         if( MM_IsUser( (tVAddr)String ) )
704         {
705                 // Traverse String
706                 while( *String )
707                 {
708                         if( !MM_IsUser( (tVAddr)String ) )
709                                 return 0;
710                         // Increment string pointer
711                         String ++;
712                 }
713                 return 1;
714         }
715         else if( MM_GetPhysAddr( (tVAddr)String ) )
716         {
717                 // Traverse String
718                 while( *String )
719                 {
720                         if( !MM_GetPhysAddr( (tVAddr)String ) )
721                                 return 0;
722                         // Increment string pointer
723                         String ++;
724                 }
725                 return 1;
726         }
727         return 0;
728 }
729
730 /**
731  * \brief Check if a sized memory region is valid memory
732  */
733 int CheckMem(void *Mem, int NumBytes)
734 {
735         tVAddr  addr = (tVAddr)Mem;
736         
737         if( MM_IsUser( addr ) )
738         {
739                 while( NumBytes-- )
740                 {
741                         if( !MM_IsUser( addr ) )
742                                 return 0;
743                         addr ++;
744                 }
745                 return 1;
746         }
747         else if( MM_GetPhysAddr( addr ) )
748         {
749                 while( NumBytes-- )
750                 {
751                         if( !MM_GetPhysAddr( addr ) )
752                                 return 0;
753                         addr ++;
754                 }
755                 return 1;
756         }
757         return 0;
758 }
759 /* *
760  * \}
761  */
762
763 /**
764  * \brief Search a string array for \a Needle
765  * \note Helper function for eTplDrv_IOCtl::DRV_IOCTL_LOOKUP
766  */
767 int ModUtil_LookupString(char **Array, char *Needle)
768 {
769          int    i;
770         if( !CheckString(Needle) )      return -1;
771         for( i = 0; Array[i]; i++ )
772         {
773                 if(strcmp(Array[i], Needle) == 0)       return i;
774         }
775         return -1;
776 }
777
778 int ModUtil_SetIdent(char *Dest, char *Value)
779 {
780         if( !CheckMem(Dest, 32) )       return -1;
781         strncpy(Dest, Value, 32);
782         return 1;
783 }

UCC git Repository :: git.ucc.asn.au