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

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