]> git.proxmox.com Git - mirror_edk2.git/blob - BaseTools/Source/C/Common/CommonLib.c
BaseTools/CommonLib: get rid of 'native' type string parsing routines
[mirror_edk2.git] / BaseTools / Source / C / Common / CommonLib.c
1 /** @file
2 Common basic Library Functions
3
4 Copyright (c) 2004 - 2018, Intel Corporation. All rights reserved.<BR>
5 This program and the accompanying materials
6 are licensed and made available under the terms and conditions of the BSD License
7 which accompanies this distribution. The full text of the license may be found at
8 http://opensource.org/licenses/bsd-license.php
9
10 THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
11 WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
12
13 **/
14
15 #include <stdio.h>
16 #include <string.h>
17 #include <stdlib.h>
18 #include <ctype.h>
19 #ifdef __GNUC__
20 #include <unistd.h>
21 #else
22 #include <direct.h>
23 #endif
24 #include "CommonLib.h"
25 #include "EfiUtilityMsgs.h"
26
27 #define SAFE_STRING_CONSTRAINT_CHECK(Expression, Status) \
28 do { \
29 ASSERT (Expression); \
30 if (!(Expression)) { \
31 return Status; \
32 } \
33 } while (FALSE)
34
35 VOID
36 PeiZeroMem (
37 IN VOID *Buffer,
38 IN UINTN Size
39 )
40 /*++
41
42 Routine Description:
43
44 Set Buffer to zero for Size bytes.
45
46 Arguments:
47
48 Buffer - Memory to set.
49
50 Size - Number of bytes to set
51
52 Returns:
53
54 None
55
56 --*/
57 {
58 INT8 *Ptr;
59
60 Ptr = Buffer;
61 while (Size--) {
62 *(Ptr++) = 0;
63 }
64 }
65
66 VOID
67 PeiCopyMem (
68 IN VOID *Destination,
69 IN VOID *Source,
70 IN UINTN Length
71 )
72 /*++
73
74 Routine Description:
75
76 Copy Length bytes from Source to Destination.
77
78 Arguments:
79
80 Destination - Target of copy
81
82 Source - Place to copy from
83
84 Length - Number of bytes to copy
85
86 Returns:
87
88 None
89
90 --*/
91 {
92 CHAR8 *Destination8;
93 CHAR8 *Source8;
94
95 Destination8 = Destination;
96 Source8 = Source;
97 while (Length--) {
98 *(Destination8++) = *(Source8++);
99 }
100 }
101
102 VOID
103 ZeroMem (
104 IN VOID *Buffer,
105 IN UINTN Size
106 )
107 {
108 PeiZeroMem (Buffer, Size);
109 }
110
111 VOID
112 CopyMem (
113 IN VOID *Destination,
114 IN VOID *Source,
115 IN UINTN Length
116 )
117 {
118 PeiCopyMem (Destination, Source, Length);
119 }
120
121 INTN
122 CompareGuid (
123 IN EFI_GUID *Guid1,
124 IN EFI_GUID *Guid2
125 )
126 /*++
127
128 Routine Description:
129
130 Compares to GUIDs
131
132 Arguments:
133
134 Guid1 - guid to compare
135 Guid2 - guid to compare
136
137 Returns:
138 = 0 if Guid1 == Guid2
139 != 0 if Guid1 != Guid2
140
141 --*/
142 {
143 INT32 *g1;
144 INT32 *g2;
145 INT32 r;
146
147 //
148 // Compare 32 bits at a time
149 //
150 g1 = (INT32 *) Guid1;
151 g2 = (INT32 *) Guid2;
152
153 r = g1[0] - g2[0];
154 r |= g1[1] - g2[1];
155 r |= g1[2] - g2[2];
156 r |= g1[3] - g2[3];
157
158 return r;
159 }
160
161
162 EFI_STATUS
163 GetFileImage (
164 IN CHAR8 *InputFileName,
165 OUT CHAR8 **InputFileImage,
166 OUT UINT32 *BytesRead
167 )
168 /*++
169
170 Routine Description:
171
172 This function opens a file and reads it into a memory buffer. The function
173 will allocate the memory buffer and returns the size of the buffer.
174
175 Arguments:
176
177 InputFileName The name of the file to read.
178 InputFileImage A pointer to the memory buffer.
179 BytesRead The size of the memory buffer.
180
181 Returns:
182
183 EFI_SUCCESS The function completed successfully.
184 EFI_INVALID_PARAMETER One of the input parameters was invalid.
185 EFI_ABORTED An error occurred.
186 EFI_OUT_OF_RESOURCES No resource to complete operations.
187
188 --*/
189 {
190 FILE *InputFile;
191 UINT32 FileSize;
192
193 //
194 // Verify input parameters.
195 //
196 if (InputFileName == NULL || strlen (InputFileName) == 0 || InputFileImage == NULL) {
197 return EFI_INVALID_PARAMETER;
198 }
199 //
200 // Open the file and copy contents into a memory buffer.
201 //
202 //
203 // Open the file
204 //
205 InputFile = fopen (LongFilePath (InputFileName), "rb");
206 if (InputFile == NULL) {
207 Error (NULL, 0, 0001, "Error opening the input file", InputFileName);
208 return EFI_ABORTED;
209 }
210 //
211 // Go to the end so that we can determine the file size
212 //
213 if (fseek (InputFile, 0, SEEK_END)) {
214 Error (NULL, 0, 0004, "Error reading the input file", InputFileName);
215 fclose (InputFile);
216 return EFI_ABORTED;
217 }
218 //
219 // Get the file size
220 //
221 FileSize = ftell (InputFile);
222 if (FileSize == -1) {
223 Error (NULL, 0, 0003, "Error parsing the input file", InputFileName);
224 fclose (InputFile);
225 return EFI_ABORTED;
226 }
227 //
228 // Allocate a buffer
229 //
230 *InputFileImage = malloc (FileSize);
231 if (*InputFileImage == NULL) {
232 fclose (InputFile);
233 return EFI_OUT_OF_RESOURCES;
234 }
235 //
236 // Reset to the beginning of the file
237 //
238 if (fseek (InputFile, 0, SEEK_SET)) {
239 Error (NULL, 0, 0004, "Error reading the input file", InputFileName);
240 fclose (InputFile);
241 free (*InputFileImage);
242 *InputFileImage = NULL;
243 return EFI_ABORTED;
244 }
245 //
246 // Read all of the file contents.
247 //
248 *BytesRead = fread (*InputFileImage, sizeof (UINT8), FileSize, InputFile);
249 if (*BytesRead != sizeof (UINT8) * FileSize) {
250 Error (NULL, 0, 0004, "Error reading the input file", InputFileName);
251 fclose (InputFile);
252 free (*InputFileImage);
253 *InputFileImage = NULL;
254 return EFI_ABORTED;
255 }
256 //
257 // Close the file
258 //
259 fclose (InputFile);
260
261 return EFI_SUCCESS;
262 }
263
264 EFI_STATUS
265 PutFileImage (
266 IN CHAR8 *OutputFileName,
267 IN CHAR8 *OutputFileImage,
268 IN UINT32 BytesToWrite
269 )
270 /*++
271
272 Routine Description:
273
274 This function opens a file and writes OutputFileImage into the file.
275
276 Arguments:
277
278 OutputFileName The name of the file to write.
279 OutputFileImage A pointer to the memory buffer.
280 BytesToWrite The size of the memory buffer.
281
282 Returns:
283
284 EFI_SUCCESS The function completed successfully.
285 EFI_INVALID_PARAMETER One of the input parameters was invalid.
286 EFI_ABORTED An error occurred.
287 EFI_OUT_OF_RESOURCES No resource to complete operations.
288
289 --*/
290 {
291 FILE *OutputFile;
292 UINT32 BytesWrote;
293
294 //
295 // Verify input parameters.
296 //
297 if (OutputFileName == NULL || strlen (OutputFileName) == 0 || OutputFileImage == NULL) {
298 return EFI_INVALID_PARAMETER;
299 }
300 //
301 // Open the file and copy contents into a memory buffer.
302 //
303 //
304 // Open the file
305 //
306 OutputFile = fopen (LongFilePath (OutputFileName), "wb");
307 if (OutputFile == NULL) {
308 Error (NULL, 0, 0001, "Error opening the output file", OutputFileName);
309 return EFI_ABORTED;
310 }
311
312 //
313 // Write all of the file contents.
314 //
315 BytesWrote = fwrite (OutputFileImage, sizeof (UINT8), BytesToWrite, OutputFile);
316 if (BytesWrote != sizeof (UINT8) * BytesToWrite) {
317 Error (NULL, 0, 0002, "Error writing the output file", OutputFileName);
318 fclose (OutputFile);
319 return EFI_ABORTED;
320 }
321 //
322 // Close the file
323 //
324 fclose (OutputFile);
325
326 return EFI_SUCCESS;
327 }
328
329 UINT8
330 CalculateChecksum8 (
331 IN UINT8 *Buffer,
332 IN UINTN Size
333 )
334 /*++
335
336 Routine Description:
337
338 This function calculates the value needed for a valid UINT8 checksum
339
340 Arguments:
341
342 Buffer Pointer to buffer containing byte data of component.
343 Size Size of the buffer
344
345 Returns:
346
347 The 8 bit checksum value needed.
348
349 --*/
350 {
351 return (UINT8) (0x100 - CalculateSum8 (Buffer, Size));
352 }
353
354 UINT8
355 CalculateSum8 (
356 IN UINT8 *Buffer,
357 IN UINTN Size
358 )
359 /*++
360
361 Routine Description::
362
363 This function calculates the UINT8 sum for the requested region.
364
365 Arguments:
366
367 Buffer Pointer to buffer containing byte data of component.
368 Size Size of the buffer
369
370 Returns:
371
372 The 8 bit checksum value needed.
373
374 --*/
375 {
376 UINTN Index;
377 UINT8 Sum;
378
379 Sum = 0;
380
381 //
382 // Perform the byte sum for buffer
383 //
384 for (Index = 0; Index < Size; Index++) {
385 Sum = (UINT8) (Sum + Buffer[Index]);
386 }
387
388 return Sum;
389 }
390
391 UINT16
392 CalculateChecksum16 (
393 IN UINT16 *Buffer,
394 IN UINTN Size
395 )
396 /*++
397
398 Routine Description::
399
400 This function calculates the value needed for a valid UINT16 checksum
401
402 Arguments:
403
404 Buffer Pointer to buffer containing byte data of component.
405 Size Size of the buffer
406
407 Returns:
408
409 The 16 bit checksum value needed.
410
411 --*/
412 {
413 return (UINT16) (0x10000 - CalculateSum16 (Buffer, Size));
414 }
415
416 UINT16
417 CalculateSum16 (
418 IN UINT16 *Buffer,
419 IN UINTN Size
420 )
421 /*++
422
423 Routine Description:
424
425 This function calculates the UINT16 sum for the requested region.
426
427 Arguments:
428
429 Buffer Pointer to buffer containing byte data of component.
430 Size Size of the buffer
431
432 Returns:
433
434 The 16 bit checksum
435
436 --*/
437 {
438 UINTN Index;
439 UINT16 Sum;
440
441 Sum = 0;
442
443 //
444 // Perform the word sum for buffer
445 //
446 for (Index = 0; Index < Size; Index++) {
447 Sum = (UINT16) (Sum + Buffer[Index]);
448 }
449
450 return (UINT16) Sum;
451 }
452
453 EFI_STATUS
454 PrintGuid (
455 IN EFI_GUID *Guid
456 )
457 /*++
458
459 Routine Description:
460
461 This function prints a GUID to STDOUT.
462
463 Arguments:
464
465 Guid Pointer to a GUID to print.
466
467 Returns:
468
469 EFI_SUCCESS The GUID was printed.
470 EFI_INVALID_PARAMETER The input was NULL.
471
472 --*/
473 {
474 if (Guid == NULL) {
475 Error (NULL, 0, 2000, "Invalid parameter", "PrintGuidToBuffer() called with a NULL value");
476 return EFI_INVALID_PARAMETER;
477 }
478
479 printf (
480 "%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x\n",
481 (unsigned) Guid->Data1,
482 Guid->Data2,
483 Guid->Data3,
484 Guid->Data4[0],
485 Guid->Data4[1],
486 Guid->Data4[2],
487 Guid->Data4[3],
488 Guid->Data4[4],
489 Guid->Data4[5],
490 Guid->Data4[6],
491 Guid->Data4[7]
492 );
493 return EFI_SUCCESS;
494 }
495
496 EFI_STATUS
497 PrintGuidToBuffer (
498 IN EFI_GUID *Guid,
499 IN OUT UINT8 *Buffer,
500 IN UINT32 BufferLen,
501 IN BOOLEAN Uppercase
502 )
503 /*++
504
505 Routine Description:
506
507 This function prints a GUID to a buffer
508
509 Arguments:
510
511 Guid - Pointer to a GUID to print.
512 Buffer - Pointer to a user-provided buffer to print to
513 BufferLen - Size of the Buffer
514 Uppercase - If use upper case.
515
516 Returns:
517
518 EFI_SUCCESS The GUID was printed.
519 EFI_INVALID_PARAMETER The input was NULL.
520 EFI_BUFFER_TOO_SMALL The input buffer was not big enough
521
522 --*/
523 {
524 if (Guid == NULL) {
525 Error (NULL, 0, 2000, "Invalid parameter", "PrintGuidToBuffer() called with a NULL value");
526 return EFI_INVALID_PARAMETER;
527 }
528
529 if (BufferLen < PRINTED_GUID_BUFFER_SIZE) {
530 Error (NULL, 0, 2000, "Invalid parameter", "PrintGuidToBuffer() called with invalid buffer size");
531 return EFI_BUFFER_TOO_SMALL;
532 }
533
534 if (Uppercase) {
535 sprintf (
536 (CHAR8 *)Buffer,
537 "%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X",
538 (unsigned) Guid->Data1,
539 Guid->Data2,
540 Guid->Data3,
541 Guid->Data4[0],
542 Guid->Data4[1],
543 Guid->Data4[2],
544 Guid->Data4[3],
545 Guid->Data4[4],
546 Guid->Data4[5],
547 Guid->Data4[6],
548 Guid->Data4[7]
549 );
550 } else {
551 sprintf (
552 (CHAR8 *)Buffer,
553 "%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x",
554 (unsigned) Guid->Data1,
555 Guid->Data2,
556 Guid->Data3,
557 Guid->Data4[0],
558 Guid->Data4[1],
559 Guid->Data4[2],
560 Guid->Data4[3],
561 Guid->Data4[4],
562 Guid->Data4[5],
563 Guid->Data4[6],
564 Guid->Data4[7]
565 );
566 }
567
568 return EFI_SUCCESS;
569 }
570
571 #ifdef __GNUC__
572
573 size_t _filelength(int fd)
574 {
575 struct stat stat_buf;
576 fstat(fd, &stat_buf);
577 return stat_buf.st_size;
578 }
579
580 #ifndef __CYGWIN__
581 char *strlwr(char *s)
582 {
583 char *p = s;
584 for(;*s;s++) {
585 *s = tolower(*s);
586 }
587 return p;
588 }
589 #endif
590 #endif
591
592 #define WINDOWS_EXTENSION_PATH "\\\\?\\"
593 #define WINDOWS_UNC_EXTENSION_PATH "\\\\?\\UNC"
594
595 //
596 // Global data to store full file path. It is not required to be free.
597 //
598 CHAR8 mCommonLibFullPath[MAX_LONG_FILE_PATH];
599
600 CHAR8 *
601 LongFilePath (
602 IN CHAR8 *FileName
603 )
604 /*++
605
606 Routine Description:
607 Convert FileName to the long file path, which can support larger than 260 length.
608
609 Arguments:
610 FileName - FileName.
611
612 Returns:
613 LongFilePath A pointer to the converted long file path.
614
615 --*/
616 {
617 #ifdef __GNUC__
618 //
619 // __GNUC__ may not be good way to differentiate unix and windows. Need more investigation here.
620 // unix has no limitation on file path. Just return FileName.
621 //
622 return FileName;
623 #else
624 CHAR8 *RootPath;
625 CHAR8 *PathPointer;
626 CHAR8 *NextPointer;
627
628 PathPointer = (CHAR8 *) FileName;
629
630 if (FileName != NULL) {
631 //
632 // Add the extension string first to support long file path.
633 //
634 mCommonLibFullPath[0] = 0;
635 strcpy (mCommonLibFullPath, WINDOWS_EXTENSION_PATH);
636
637 if (strlen (FileName) > 1 && FileName[0] == '\\' && FileName[1] == '\\') {
638 //
639 // network path like \\server\share to \\?\UNC\server\share
640 //
641 strcpy (mCommonLibFullPath, WINDOWS_UNC_EXTENSION_PATH);
642 FileName ++;
643 } else if (strlen (FileName) < 3 || FileName[1] != ':' || (FileName[2] != '\\' && FileName[2] != '/')) {
644 //
645 // Relative file path. Convert it to absolute path.
646 //
647 RootPath = getcwd (NULL, 0);
648 if (RootPath != NULL) {
649 if (strlen (mCommonLibFullPath) + strlen (RootPath) > MAX_LONG_FILE_PATH - 1) {
650 Error (NULL, 0, 2000, "Invalid parameter", "RootPath is too long!");
651 free (RootPath);
652 return NULL;
653 }
654 strncat (mCommonLibFullPath, RootPath, MAX_LONG_FILE_PATH - strlen (mCommonLibFullPath) - 1);
655 if (FileName[0] != '\\' && FileName[0] != '/') {
656 if (strlen (mCommonLibFullPath) + 1 > MAX_LONG_FILE_PATH - 1) {
657 Error (NULL, 0, 2000, "Invalid parameter", "RootPath is too long!");
658 free (RootPath);
659 return NULL;
660 }
661 //
662 // Attach directory separator
663 //
664 strncat (mCommonLibFullPath, "\\", MAX_LONG_FILE_PATH - strlen (mCommonLibFullPath) - 1);
665 }
666 free (RootPath);
667 }
668 }
669
670 //
671 // Construct the full file path
672 //
673 if (strlen (mCommonLibFullPath) + strlen (FileName) > MAX_LONG_FILE_PATH - 1) {
674 Error (NULL, 0, 2000, "Invalid parameter", "FileName %s is too long!", FileName);
675 return NULL;
676 }
677 strncat (mCommonLibFullPath, FileName, MAX_LONG_FILE_PATH - strlen (mCommonLibFullPath) - 1);
678
679 //
680 // Convert directory separator '/' to '\\'
681 //
682 PathPointer = (CHAR8 *) mCommonLibFullPath;
683 do {
684 if (*PathPointer == '/') {
685 *PathPointer = '\\';
686 }
687 } while (*PathPointer ++ != '\0');
688
689 //
690 // Convert ":\\\\" to ":\\", because it doesn't work with WINDOWS_EXTENSION_PATH.
691 //
692 if ((PathPointer = strstr (mCommonLibFullPath, ":\\\\")) != NULL) {
693 *(PathPointer + 2) = '\0';
694 strncat (mCommonLibFullPath, PathPointer + 3, MAX_LONG_FILE_PATH - strlen (mCommonLibFullPath) - 1);
695 }
696
697 //
698 // Convert ".\\" to "", because it doesn't work with WINDOWS_EXTENSION_PATH.
699 //
700 while ((PathPointer = strstr (mCommonLibFullPath, ".\\")) != NULL) {
701 *PathPointer = '\0';
702 strncat (mCommonLibFullPath, PathPointer + 2, MAX_LONG_FILE_PATH - strlen (mCommonLibFullPath) - 1);
703 }
704
705 //
706 // Convert "\\.\\" to "\\", because it doesn't work with WINDOWS_EXTENSION_PATH.
707 //
708 while ((PathPointer = strstr (mCommonLibFullPath, "\\.\\")) != NULL) {
709 *PathPointer = '\0';
710 strncat (mCommonLibFullPath, PathPointer + 2, MAX_LONG_FILE_PATH - strlen (mCommonLibFullPath) - 1);
711 }
712
713 //
714 // Convert "\\..\\" to last directory, because it doesn't work with WINDOWS_EXTENSION_PATH.
715 //
716 while ((PathPointer = strstr (mCommonLibFullPath, "\\..\\")) != NULL) {
717 NextPointer = PathPointer + 3;
718 do {
719 PathPointer --;
720 } while (PathPointer > mCommonLibFullPath && *PathPointer != ':' && *PathPointer != '\\');
721
722 if (*PathPointer == '\\') {
723 //
724 // Skip one directory
725 //
726 *PathPointer = '\0';
727 strncat (mCommonLibFullPath, NextPointer, MAX_LONG_FILE_PATH - strlen (mCommonLibFullPath) - 1);
728 } else {
729 //
730 // No directory is found. Just break.
731 //
732 break;
733 }
734 }
735
736 PathPointer = mCommonLibFullPath;
737 }
738
739 return PathPointer;
740 #endif
741 }
742
743 CHAR16
744 InternalCharToUpper (
745 CHAR16 Char
746 )
747 {
748 if (Char >= L'a' && Char <= L'z') {
749 return (CHAR16) (Char - (L'a' - L'A'));
750 }
751
752 return Char;
753 }
754
755 UINTN
756 StrnLenS (
757 CONST CHAR16 *String,
758 UINTN MaxSize
759 )
760 {
761 UINTN Length;
762
763 ASSERT (((UINTN) String & BIT0) == 0);
764
765 //
766 // If String is a null pointer or MaxSize is 0, then the StrnLenS function returns zero.
767 //
768 if ((String == NULL) || (MaxSize == 0)) {
769 return 0;
770 }
771
772 Length = 0;
773 while (String[Length] != 0) {
774 if (Length >= MaxSize - 1) {
775 return MaxSize;
776 }
777 Length++;
778 }
779 return Length;
780 }
781
782
783 VOID *
784 InternalAllocatePool (
785 UINTN AllocationSize
786 )
787 {
788 VOID * Memory;
789
790 Memory = malloc(AllocationSize);
791 ASSERT(Memory != NULL);
792 return Memory;
793 }
794
795
796 VOID *
797 InternalReallocatePool (
798 UINTN OldSize,
799 UINTN NewSize,
800 VOID *OldBuffer OPTIONAL
801 )
802 {
803 VOID *NewBuffer;
804
805 NewBuffer = AllocateZeroPool (NewSize);
806 if (NewBuffer != NULL && OldBuffer != NULL) {
807 memcpy (NewBuffer, OldBuffer, MIN (OldSize, NewSize));
808 free(OldBuffer);
809 }
810 return NewBuffer;
811 }
812
813 VOID *
814 ReallocatePool (
815 UINTN OldSize,
816 UINTN NewSize,
817 VOID *OldBuffer OPTIONAL
818 )
819 {
820 return InternalReallocatePool (OldSize, NewSize, OldBuffer);
821 }
822
823 /**
824 Returns the length of a Null-terminated Unicode string.
825
826 This function returns the number of Unicode characters in the Null-terminated
827 Unicode string specified by String.
828
829 If String is NULL, then ASSERT().
830 If String is not aligned on a 16-bit boundary, then ASSERT().
831 If PcdMaximumUnicodeStringLength is not zero, and String contains more than
832 PcdMaximumUnicodeStringLength Unicode characters, not including the
833 Null-terminator, then ASSERT().
834
835 @param String A pointer to a Null-terminated Unicode string.
836
837 @return The length of String.
838
839 **/
840 UINTN
841 StrLen (
842 CONST CHAR16 *String
843 )
844 {
845 UINTN Length;
846
847 ASSERT (String != NULL);
848 ASSERT (((UINTN) String & BIT0) == 0);
849
850 for (Length = 0; *String != L'\0'; String++, Length++) {
851 //
852 // If PcdMaximumUnicodeStringLength is not zero,
853 // length should not more than PcdMaximumUnicodeStringLength
854 //
855 }
856 return Length;
857 }
858
859 BOOLEAN
860 InternalSafeStringIsOverlap (
861 IN VOID *Base1,
862 IN UINTN Size1,
863 IN VOID *Base2,
864 IN UINTN Size2
865 )
866 {
867 if ((((UINTN)Base1 >= (UINTN)Base2) && ((UINTN)Base1 < (UINTN)Base2 + Size2)) ||
868 (((UINTN)Base2 >= (UINTN)Base1) && ((UINTN)Base2 < (UINTN)Base1 + Size1))) {
869 return TRUE;
870 }
871 return FALSE;
872 }
873
874 BOOLEAN
875 InternalSafeStringNoStrOverlap (
876 IN CHAR16 *Str1,
877 IN UINTN Size1,
878 IN CHAR16 *Str2,
879 IN UINTN Size2
880 )
881 {
882 return !InternalSafeStringIsOverlap (Str1, Size1 * sizeof(CHAR16), Str2, Size2 * sizeof(CHAR16));
883 }
884
885 /**
886 Convert a Null-terminated Unicode decimal string to a value of type UINT64.
887
888 This function outputs a value of type UINT64 by interpreting the contents of
889 the Unicode string specified by String as a decimal number. The format of the
890 input Unicode string String is:
891
892 [spaces] [decimal digits].
893
894 The valid decimal digit character is in the range [0-9]. The function will
895 ignore the pad space, which includes spaces or tab characters, before
896 [decimal digits]. The running zero in the beginning of [decimal digits] will
897 be ignored. Then, the function stops at the first character that is a not a
898 valid decimal character or a Null-terminator, whichever one comes first.
899
900 If String is NULL, then ASSERT().
901 If Data is NULL, then ASSERT().
902 If String is not aligned in a 16-bit boundary, then ASSERT().
903 If PcdMaximumUnicodeStringLength is not zero, and String contains more than
904 PcdMaximumUnicodeStringLength Unicode characters, not including the
905 Null-terminator, then ASSERT().
906
907 If String has no valid decimal digits in the above format, then 0 is stored
908 at the location pointed to by Data.
909 If the number represented by String exceeds the range defined by UINT64, then
910 MAX_UINT64 is stored at the location pointed to by Data.
911
912 If EndPointer is not NULL, a pointer to the character that stopped the scan
913 is stored at the location pointed to by EndPointer. If String has no valid
914 decimal digits right after the optional pad spaces, the value of String is
915 stored at the location pointed to by EndPointer.
916
917 @param String Pointer to a Null-terminated Unicode string.
918 @param EndPointer Pointer to character that stops scan.
919 @param Data Pointer to the converted value.
920
921 @retval RETURN_SUCCESS Value is translated from String.
922 @retval RETURN_INVALID_PARAMETER If String is NULL.
923 If Data is NULL.
924 If PcdMaximumUnicodeStringLength is not
925 zero, and String contains more than
926 PcdMaximumUnicodeStringLength Unicode
927 characters, not including the
928 Null-terminator.
929 @retval RETURN_UNSUPPORTED If the number represented by String exceeds
930 the range defined by UINT64.
931
932 **/
933 RETURN_STATUS
934 StrDecimalToUint64S (
935 CONST CHAR16 *String,
936 CHAR16 **EndPointer, OPTIONAL
937 UINT64 *Data
938 )
939 {
940 ASSERT (((UINTN) String & BIT0) == 0);
941
942 //
943 // 1. Neither String nor Data shall be a null pointer.
944 //
945 SAFE_STRING_CONSTRAINT_CHECK ((String != NULL), RETURN_INVALID_PARAMETER);
946 SAFE_STRING_CONSTRAINT_CHECK ((Data != NULL), RETURN_INVALID_PARAMETER);
947
948 //
949 // 2. The length of String shall not be greater than RSIZE_MAX.
950 //
951 if (RSIZE_MAX != 0) {
952 SAFE_STRING_CONSTRAINT_CHECK ((StrnLenS (String, RSIZE_MAX + 1) <= RSIZE_MAX), RETURN_INVALID_PARAMETER);
953 }
954
955 if (EndPointer != NULL) {
956 *EndPointer = (CHAR16 *) String;
957 }
958
959 //
960 // Ignore the pad spaces (space or tab)
961 //
962 while ((*String == L' ') || (*String == L'\t')) {
963 String++;
964 }
965
966 //
967 // Ignore leading Zeros after the spaces
968 //
969 while (*String == L'0') {
970 String++;
971 }
972
973 *Data = 0;
974
975 while (InternalIsDecimalDigitCharacter (*String)) {
976 //
977 // If the number represented by String overflows according to the range
978 // defined by UINT64, then MAX_UINT64 is stored in *Data and
979 // RETURN_UNSUPPORTED is returned.
980 //
981 if (*Data > ((MAX_UINT64 - (*String - L'0'))/10)) {
982 *Data = MAX_UINT64;
983 if (EndPointer != NULL) {
984 *EndPointer = (CHAR16 *) String;
985 }
986 return RETURN_UNSUPPORTED;
987 }
988
989 *Data = (*Data) * 10 + (*String - L'0');
990 String++;
991 }
992
993 if (EndPointer != NULL) {
994 *EndPointer = (CHAR16 *) String;
995 }
996 return RETURN_SUCCESS;
997 }
998
999 /**
1000 Convert a Null-terminated Unicode hexadecimal string to a value of type
1001 UINT64.
1002
1003 This function outputs a value of type UINT64 by interpreting the contents of
1004 the Unicode string specified by String as a hexadecimal number. The format of
1005 the input Unicode string String is:
1006
1007 [spaces][zeros][x][hexadecimal digits].
1008
1009 The valid hexadecimal digit character is in the range [0-9], [a-f] and [A-F].
1010 The prefix "0x" is optional. Both "x" and "X" is allowed in "0x" prefix.
1011 If "x" appears in the input string, it must be prefixed with at least one 0.
1012 The function will ignore the pad space, which includes spaces or tab
1013 characters, before [zeros], [x] or [hexadecimal digit]. The running zero
1014 before [x] or [hexadecimal digit] will be ignored. Then, the decoding starts
1015 after [x] or the first valid hexadecimal digit. Then, the function stops at
1016 the first character that is a not a valid hexadecimal character or NULL,
1017 whichever one comes first.
1018
1019 If String is NULL, then ASSERT().
1020 If Data is NULL, then ASSERT().
1021 If String is not aligned in a 16-bit boundary, then ASSERT().
1022 If PcdMaximumUnicodeStringLength is not zero, and String contains more than
1023 PcdMaximumUnicodeStringLength Unicode characters, not including the
1024 Null-terminator, then ASSERT().
1025
1026 If String has no valid hexadecimal digits in the above format, then 0 is
1027 stored at the location pointed to by Data.
1028 If the number represented by String exceeds the range defined by UINT64, then
1029 MAX_UINT64 is stored at the location pointed to by Data.
1030
1031 If EndPointer is not NULL, a pointer to the character that stopped the scan
1032 is stored at the location pointed to by EndPointer. If String has no valid
1033 hexadecimal digits right after the optional pad spaces, the value of String
1034 is stored at the location pointed to by EndPointer.
1035
1036 @param String Pointer to a Null-terminated Unicode string.
1037 @param EndPointer Pointer to character that stops scan.
1038 @param Data Pointer to the converted value.
1039
1040 @retval RETURN_SUCCESS Value is translated from String.
1041 @retval RETURN_INVALID_PARAMETER If String is NULL.
1042 If Data is NULL.
1043 If PcdMaximumUnicodeStringLength is not
1044 zero, and String contains more than
1045 PcdMaximumUnicodeStringLength Unicode
1046 characters, not including the
1047 Null-terminator.
1048 @retval RETURN_UNSUPPORTED If the number represented by String exceeds
1049 the range defined by UINT64.
1050
1051 **/
1052 RETURN_STATUS
1053 StrHexToUint64S (
1054 CONST CHAR16 *String,
1055 CHAR16 **EndPointer, OPTIONAL
1056 UINT64 *Data
1057 )
1058 {
1059 ASSERT (((UINTN) String & BIT0) == 0);
1060
1061 //
1062 // 1. Neither String nor Data shall be a null pointer.
1063 //
1064 SAFE_STRING_CONSTRAINT_CHECK ((String != NULL), RETURN_INVALID_PARAMETER);
1065 SAFE_STRING_CONSTRAINT_CHECK ((Data != NULL), RETURN_INVALID_PARAMETER);
1066
1067 //
1068 // 2. The length of String shall not be greater than RSIZE_MAX.
1069 //
1070 if (RSIZE_MAX != 0) {
1071 SAFE_STRING_CONSTRAINT_CHECK ((StrnLenS (String, RSIZE_MAX + 1) <= RSIZE_MAX), RETURN_INVALID_PARAMETER);
1072 }
1073
1074 if (EndPointer != NULL) {
1075 *EndPointer = (CHAR16 *) String;
1076 }
1077
1078 //
1079 // Ignore the pad spaces (space or tab)
1080 //
1081 while ((*String == L' ') || (*String == L'\t')) {
1082 String++;
1083 }
1084
1085 //
1086 // Ignore leading Zeros after the spaces
1087 //
1088 while (*String == L'0') {
1089 String++;
1090 }
1091
1092 if (InternalCharToUpper (*String) == L'X') {
1093 if (*(String - 1) != L'0') {
1094 *Data = 0;
1095 return RETURN_SUCCESS;
1096 }
1097 //
1098 // Skip the 'X'
1099 //
1100 String++;
1101 }
1102
1103 *Data = 0;
1104
1105 while (InternalIsHexaDecimalDigitCharacter (*String)) {
1106 //
1107 // If the number represented by String overflows according to the range
1108 // defined by UINT64, then MAX_UINT64 is stored in *Data and
1109 // RETURN_UNSUPPORTED is returned.
1110 //
1111 if (*Data > ((MAX_UINT64 - InternalHexCharToUintn (*String))>>4)) {
1112 *Data = MAX_UINT64;
1113 if (EndPointer != NULL) {
1114 *EndPointer = (CHAR16 *) String;
1115 }
1116 return RETURN_UNSUPPORTED;
1117 }
1118
1119 *Data = ((*Data) << 4) + InternalHexCharToUintn (*String);
1120 String++;
1121 }
1122
1123 if (EndPointer != NULL) {
1124 *EndPointer = (CHAR16 *) String;
1125 }
1126 return RETURN_SUCCESS;
1127 }
1128
1129 UINT64
1130 StrDecimalToUint64 (
1131 CONST CHAR16 *String
1132 )
1133 {
1134 UINT64 Result;
1135
1136 StrDecimalToUint64S (String, (CHAR16 **) NULL, &Result);
1137 return Result;
1138 }
1139
1140
1141 UINT64
1142 StrHexToUint64 (
1143 CONST CHAR16 *String
1144 )
1145 {
1146 UINT64 Result;
1147
1148 StrHexToUint64S (String, (CHAR16 **) NULL, &Result);
1149 return Result;
1150 }
1151
1152 UINTN
1153 StrSize (
1154 CONST CHAR16 *String
1155 )
1156 {
1157 return (StrLen (String) + 1) * sizeof (*String);
1158 }
1159
1160
1161 UINT64
1162 ReadUnaligned64 (
1163 CONST UINT64 *Buffer
1164 )
1165 {
1166 ASSERT (Buffer != NULL);
1167
1168 return *Buffer;
1169 }
1170
1171 UINT64
1172 WriteUnaligned64 (
1173 UINT64 *Buffer,
1174 UINT64 Value
1175 )
1176 {
1177 ASSERT (Buffer != NULL);
1178
1179 return *Buffer = Value;
1180 }
1181
1182
1183 EFI_GUID *
1184 CopyGuid (
1185 EFI_GUID *DestinationGuid,
1186 CONST EFI_GUID *SourceGuid
1187 )
1188 {
1189 WriteUnaligned64 (
1190 (UINT64*)DestinationGuid,
1191 ReadUnaligned64 ((CONST UINT64*)SourceGuid)
1192 );
1193 WriteUnaligned64 (
1194 (UINT64*)DestinationGuid + 1,
1195 ReadUnaligned64 ((CONST UINT64*)SourceGuid + 1)
1196 );
1197 return DestinationGuid;
1198 }
1199
1200 UINT16
1201 SwapBytes16 (
1202 UINT16 Value
1203 )
1204 {
1205 return (UINT16) ((Value<< 8) | (Value>> 8));
1206 }
1207
1208
1209 UINT32
1210 SwapBytes32 (
1211 UINT32 Value
1212 )
1213 {
1214 UINT32 LowerBytes;
1215 UINT32 HigherBytes;
1216
1217 LowerBytes = (UINT32) SwapBytes16 ((UINT16) Value);
1218 HigherBytes = (UINT32) SwapBytes16 ((UINT16) (Value >> 16));
1219 return (LowerBytes << 16 | HigherBytes);
1220 }
1221
1222 BOOLEAN
1223 InternalIsDecimalDigitCharacter (
1224 CHAR16 Char
1225 )
1226 {
1227 return (BOOLEAN) (Char >= L'0' && Char <= L'9');
1228 }
1229
1230 VOID *
1231 InternalAllocateCopyPool (
1232 UINTN AllocationSize,
1233 CONST VOID *Buffer
1234 )
1235 {
1236 VOID *Memory;
1237
1238 ASSERT (Buffer != NULL);
1239 ASSERT (AllocationSize <= (MAX_ADDRESS - (UINTN) Buffer + 1));
1240
1241 Memory = malloc (AllocationSize);
1242 if (Memory != NULL) {
1243 Memory = memcpy (Memory, Buffer, AllocationSize);
1244 }
1245 return Memory;
1246 }
1247
1248 BOOLEAN
1249 InternalIsHexaDecimalDigitCharacter (
1250 CHAR16 Char
1251 )
1252 {
1253
1254 return (BOOLEAN) (InternalIsDecimalDigitCharacter (Char) ||
1255 (Char >= L'A' && Char <= L'F') ||
1256 (Char >= L'a' && Char <= L'f'));
1257 }
1258
1259 UINTN
1260 InternalHexCharToUintn (
1261 CHAR16 Char
1262 )
1263 {
1264 if (InternalIsDecimalDigitCharacter (Char)) {
1265 return Char - L'0';
1266 }
1267
1268 return (10 + InternalCharToUpper (Char) - L'A');
1269 }
1270
1271
1272 /**
1273 Convert a Null-terminated Unicode hexadecimal string to a byte array.
1274
1275 This function outputs a byte array by interpreting the contents of
1276 the Unicode string specified by String in hexadecimal format. The format of
1277 the input Unicode string String is:
1278
1279 [XX]*
1280
1281 X is a hexadecimal digit character in the range [0-9], [a-f] and [A-F].
1282 The function decodes every two hexadecimal digit characters as one byte. The
1283 decoding stops after Length of characters and outputs Buffer containing
1284 (Length / 2) bytes.
1285
1286 If String is not aligned in a 16-bit boundary, then ASSERT().
1287
1288 If String is NULL, then ASSERT().
1289
1290 If Buffer is NULL, then ASSERT().
1291
1292 If Length is not multiple of 2, then ASSERT().
1293
1294 If PcdMaximumUnicodeStringLength is not zero and Length is greater than
1295 PcdMaximumUnicodeStringLength, then ASSERT().
1296
1297 If MaxBufferSize is less than (Length / 2), then ASSERT().
1298
1299 @param String Pointer to a Null-terminated Unicode string.
1300 @param Length The number of Unicode characters to decode.
1301 @param Buffer Pointer to the converted bytes array.
1302 @param MaxBufferSize The maximum size of Buffer.
1303
1304 @retval RETURN_SUCCESS Buffer is translated from String.
1305 @retval RETURN_INVALID_PARAMETER If String is NULL.
1306 If Data is NULL.
1307 If Length is not multiple of 2.
1308 If PcdMaximumUnicodeStringLength is not zero,
1309 and Length is greater than
1310 PcdMaximumUnicodeStringLength.
1311 @retval RETURN_UNSUPPORTED If Length of characters from String contain
1312 a character that is not valid hexadecimal
1313 digit characters, or a Null-terminator.
1314 @retval RETURN_BUFFER_TOO_SMALL If MaxBufferSize is less than (Length / 2).
1315 **/
1316 RETURN_STATUS
1317 StrHexToBytes (
1318 CONST CHAR16 *String,
1319 UINTN Length,
1320 UINT8 *Buffer,
1321 UINTN MaxBufferSize
1322 )
1323 {
1324 UINTN Index;
1325
1326 ASSERT (((UINTN) String & BIT0) == 0);
1327
1328 //
1329 // 1. None of String or Buffer shall be a null pointer.
1330 //
1331 SAFE_STRING_CONSTRAINT_CHECK ((String != NULL), RETURN_INVALID_PARAMETER);
1332 SAFE_STRING_CONSTRAINT_CHECK ((Buffer != NULL), RETURN_INVALID_PARAMETER);
1333
1334 //
1335 // 2. Length shall not be greater than RSIZE_MAX.
1336 //
1337 if (RSIZE_MAX != 0) {
1338 SAFE_STRING_CONSTRAINT_CHECK ((Length <= RSIZE_MAX), RETURN_INVALID_PARAMETER);
1339 }
1340
1341 //
1342 // 3. Length shall not be odd.
1343 //
1344 SAFE_STRING_CONSTRAINT_CHECK (((Length & BIT0) == 0), RETURN_INVALID_PARAMETER);
1345
1346 //
1347 // 4. MaxBufferSize shall equal to or greater than Length / 2.
1348 //
1349 SAFE_STRING_CONSTRAINT_CHECK ((MaxBufferSize >= Length / 2), RETURN_BUFFER_TOO_SMALL);
1350
1351 //
1352 // 5. String shall not contains invalid hexadecimal digits.
1353 //
1354 for (Index = 0; Index < Length; Index++) {
1355 if (!InternalIsHexaDecimalDigitCharacter (String[Index])) {
1356 break;
1357 }
1358 }
1359 if (Index != Length) {
1360 return RETURN_UNSUPPORTED;
1361 }
1362
1363 //
1364 // Convert the hex string to bytes.
1365 //
1366 for(Index = 0; Index < Length; Index++) {
1367
1368 //
1369 // For even characters, write the upper nibble for each buffer byte,
1370 // and for even characters, the lower nibble.
1371 //
1372 if ((Index & BIT0) == 0) {
1373 Buffer[Index / 2] = (UINT8) InternalHexCharToUintn (String[Index]) << 4;
1374 } else {
1375 Buffer[Index / 2] |= (UINT8) InternalHexCharToUintn (String[Index]);
1376 }
1377 }
1378 return RETURN_SUCCESS;
1379 }
1380
1381 /**
1382 Convert a Null-terminated Unicode GUID string to a value of type
1383 EFI_GUID.
1384
1385 This function outputs a GUID value by interpreting the contents of
1386 the Unicode string specified by String. The format of the input
1387 Unicode string String consists of 36 characters, as follows:
1388
1389 aabbccdd-eeff-gghh-iijj-kkllmmnnoopp
1390
1391 The pairs aa - pp are two characters in the range [0-9], [a-f] and
1392 [A-F], with each pair representing a single byte hexadecimal value.
1393
1394 The mapping between String and the EFI_GUID structure is as follows:
1395 aa Data1[24:31]
1396 bb Data1[16:23]
1397 cc Data1[8:15]
1398 dd Data1[0:7]
1399 ee Data2[8:15]
1400 ff Data2[0:7]
1401 gg Data3[8:15]
1402 hh Data3[0:7]
1403 ii Data4[0:7]
1404 jj Data4[8:15]
1405 kk Data4[16:23]
1406 ll Data4[24:31]
1407 mm Data4[32:39]
1408 nn Data4[40:47]
1409 oo Data4[48:55]
1410 pp Data4[56:63]
1411
1412 If String is NULL, then ASSERT().
1413 If Guid is NULL, then ASSERT().
1414 If String is not aligned in a 16-bit boundary, then ASSERT().
1415
1416 @param String Pointer to a Null-terminated Unicode string.
1417 @param Guid Pointer to the converted GUID.
1418
1419 @retval RETURN_SUCCESS Guid is translated from String.
1420 @retval RETURN_INVALID_PARAMETER If String is NULL.
1421 If Data is NULL.
1422 @retval RETURN_UNSUPPORTED If String is not as the above format.
1423
1424 **/
1425 RETURN_STATUS
1426 StrToGuid (
1427 CONST CHAR16 *String,
1428 EFI_GUID *Guid
1429 )
1430 {
1431 RETURN_STATUS Status;
1432 EFI_GUID LocalGuid;
1433
1434 ASSERT (((UINTN) String & BIT0) == 0);
1435
1436 //
1437 // 1. None of String or Guid shall be a null pointer.
1438 //
1439 SAFE_STRING_CONSTRAINT_CHECK ((String != NULL), RETURN_INVALID_PARAMETER);
1440 SAFE_STRING_CONSTRAINT_CHECK ((Guid != NULL), RETURN_INVALID_PARAMETER);
1441
1442 //
1443 // Get aabbccdd in big-endian.
1444 //
1445 Status = StrHexToBytes (String, 2 * sizeof (LocalGuid.Data1), (UINT8 *) &LocalGuid.Data1, sizeof (LocalGuid.Data1));
1446 if (RETURN_ERROR (Status) || String[2 * sizeof (LocalGuid.Data1)] != L'-') {
1447 return RETURN_UNSUPPORTED;
1448 }
1449 //
1450 // Convert big-endian to little-endian.
1451 //
1452 LocalGuid.Data1 = SwapBytes32 (LocalGuid.Data1);
1453 String += 2 * sizeof (LocalGuid.Data1) + 1;
1454
1455 //
1456 // Get eeff in big-endian.
1457 //
1458 Status = StrHexToBytes (String, 2 * sizeof (LocalGuid.Data2), (UINT8 *) &LocalGuid.Data2, sizeof (LocalGuid.Data2));
1459 if (RETURN_ERROR (Status) || String[2 * sizeof (LocalGuid.Data2)] != L'-') {
1460 return RETURN_UNSUPPORTED;
1461 }
1462 //
1463 // Convert big-endian to little-endian.
1464 //
1465 LocalGuid.Data2 = SwapBytes16 (LocalGuid.Data2);
1466 String += 2 * sizeof (LocalGuid.Data2) + 1;
1467
1468 //
1469 // Get gghh in big-endian.
1470 //
1471 Status = StrHexToBytes (String, 2 * sizeof (LocalGuid.Data3), (UINT8 *) &LocalGuid.Data3, sizeof (LocalGuid.Data3));
1472 if (RETURN_ERROR (Status) || String[2 * sizeof (LocalGuid.Data3)] != L'-') {
1473 return RETURN_UNSUPPORTED;
1474 }
1475 //
1476 // Convert big-endian to little-endian.
1477 //
1478 LocalGuid.Data3 = SwapBytes16 (LocalGuid.Data3);
1479 String += 2 * sizeof (LocalGuid.Data3) + 1;
1480
1481 //
1482 // Get iijj.
1483 //
1484 Status = StrHexToBytes (String, 2 * 2, &LocalGuid.Data4[0], 2);
1485 if (RETURN_ERROR (Status) || String[2 * 2] != L'-') {
1486 return RETURN_UNSUPPORTED;
1487 }
1488 String += 2 * 2 + 1;
1489
1490 //
1491 // Get kkllmmnnoopp.
1492 //
1493 Status = StrHexToBytes (String, 2 * 6, &LocalGuid.Data4[2], 6);
1494 if (RETURN_ERROR (Status)) {
1495 return RETURN_UNSUPPORTED;
1496 }
1497
1498 CopyGuid (Guid, &LocalGuid);
1499 return RETURN_SUCCESS;
1500 }
1501
1502 /**
1503 Compares up to a specified length the contents of two Null-terminated Unicode strings,
1504 and returns the difference between the first mismatched Unicode characters.
1505
1506 This function compares the Null-terminated Unicode string FirstString to the
1507 Null-terminated Unicode string SecondString. At most, Length Unicode
1508 characters will be compared. If Length is 0, then 0 is returned. If
1509 FirstString is identical to SecondString, then 0 is returned. Otherwise, the
1510 value returned is the first mismatched Unicode character in SecondString
1511 subtracted from the first mismatched Unicode character in FirstString.
1512
1513 If Length > 0 and FirstString is NULL, then ASSERT().
1514 If Length > 0 and FirstString is not aligned on a 16-bit boundary, then ASSERT().
1515 If Length > 0 and SecondString is NULL, then ASSERT().
1516 If Length > 0 and SecondString is not aligned on a 16-bit boundary, then ASSERT().
1517 If PcdMaximumUnicodeStringLength is not zero, and Length is greater than
1518 PcdMaximumUnicodeStringLength, then ASSERT().
1519 If PcdMaximumUnicodeStringLength is not zero, and FirstString contains more than
1520 PcdMaximumUnicodeStringLength Unicode characters, not including the Null-terminator,
1521 then ASSERT().
1522 If PcdMaximumUnicodeStringLength is not zero, and SecondString contains more than
1523 PcdMaximumUnicodeStringLength Unicode characters, not including the Null-terminator,
1524 then ASSERT().
1525
1526 @param FirstString A pointer to a Null-terminated Unicode string.
1527 @param SecondString A pointer to a Null-terminated Unicode string.
1528 @param Length The maximum number of Unicode characters to compare.
1529
1530 @retval 0 FirstString is identical to SecondString.
1531 @return others FirstString is not identical to SecondString.
1532
1533 **/
1534 INTN
1535 StrnCmp (
1536 CONST CHAR16 *FirstString,
1537 CONST CHAR16 *SecondString,
1538 UINTN Length
1539 )
1540 {
1541 if (Length == 0) {
1542 return 0;
1543 }
1544
1545 //
1546 // ASSERT both strings are less long than PcdMaximumUnicodeStringLength.
1547 // Length tests are performed inside StrLen().
1548 //
1549 ASSERT (StrSize (FirstString) != 0);
1550 ASSERT (StrSize (SecondString) != 0);
1551
1552 while ((*FirstString != L'\0') &&
1553 (*SecondString != L'\0') &&
1554 (*FirstString == *SecondString) &&
1555 (Length > 1)) {
1556 FirstString++;
1557 SecondString++;
1558 Length--;
1559 }
1560
1561 return *FirstString - *SecondString;
1562 }
1563
1564 VOID *
1565 AllocateCopyPool (
1566 UINTN AllocationSize,
1567 CONST VOID *Buffer
1568 )
1569 {
1570 return InternalAllocateCopyPool (AllocationSize, Buffer);
1571 }
1572
1573 INTN
1574 StrCmp (
1575 CONST CHAR16 *FirstString,
1576 CONST CHAR16 *SecondString
1577 )
1578 {
1579 //
1580 // ASSERT both strings are less long than PcdMaximumUnicodeStringLength
1581 //
1582 ASSERT (StrSize (FirstString) != 0);
1583 ASSERT (StrSize (SecondString) != 0);
1584
1585 while ((*FirstString != L'\0') && (*FirstString == *SecondString)) {
1586 FirstString++;
1587 SecondString++;
1588 }
1589 return *FirstString - *SecondString;
1590 }
1591
1592 UINT64
1593 SwapBytes64 (
1594 UINT64 Value
1595 )
1596 {
1597 return InternalMathSwapBytes64 (Value);
1598 }
1599
1600 UINT64
1601 InternalMathSwapBytes64 (
1602 UINT64 Operand
1603 )
1604 {
1605 UINT64 LowerBytes;
1606 UINT64 HigherBytes;
1607
1608 LowerBytes = (UINT64) SwapBytes32 ((UINT32) Operand);
1609 HigherBytes = (UINT64) SwapBytes32 ((UINT32) (Operand >> 32));
1610
1611 return (LowerBytes << 32 | HigherBytes);
1612 }
1613
1614 RETURN_STATUS
1615 StrToIpv4Address (
1616 CONST CHAR16 *String,
1617 CHAR16 **EndPointer,
1618 EFI_IPv4_ADDRESS *Address,
1619 UINT8 *PrefixLength
1620 )
1621 {
1622 RETURN_STATUS Status;
1623 UINTN AddressIndex;
1624 UINT64 Uint64;
1625 EFI_IPv4_ADDRESS LocalAddress;
1626 UINT8 LocalPrefixLength;
1627 CHAR16 *Pointer;
1628
1629 LocalPrefixLength = MAX_UINT8;
1630 LocalAddress.Addr[0] = 0;
1631
1632 ASSERT (((UINTN) String & BIT0) == 0);
1633
1634 //
1635 // 1. None of String or Guid shall be a null pointer.
1636 //
1637 SAFE_STRING_CONSTRAINT_CHECK ((String != NULL), RETURN_INVALID_PARAMETER);
1638 SAFE_STRING_CONSTRAINT_CHECK ((Address != NULL), RETURN_INVALID_PARAMETER);
1639
1640 for (Pointer = (CHAR16 *) String, AddressIndex = 0; AddressIndex < ARRAY_SIZE (Address->Addr) + 1;) {
1641 if (!InternalIsDecimalDigitCharacter (*Pointer)) {
1642 //
1643 // D or P contains invalid characters.
1644 //
1645 break;
1646 }
1647
1648 //
1649 // Get D or P.
1650 //
1651 Status = StrDecimalToUint64S ((CONST CHAR16 *) Pointer, &Pointer, &Uint64);
1652 if (RETURN_ERROR (Status)) {
1653 return RETURN_UNSUPPORTED;
1654 }
1655 if (AddressIndex == ARRAY_SIZE (Address->Addr)) {
1656 //
1657 // It's P.
1658 //
1659 if (Uint64 > 32) {
1660 return RETURN_UNSUPPORTED;
1661 }
1662 LocalPrefixLength = (UINT8) Uint64;
1663 } else {
1664 //
1665 // It's D.
1666 //
1667 if (Uint64 > MAX_UINT8) {
1668 return RETURN_UNSUPPORTED;
1669 }
1670 LocalAddress.Addr[AddressIndex] = (UINT8) Uint64;
1671 AddressIndex++;
1672 }
1673
1674 //
1675 // Check the '.' or '/', depending on the AddressIndex.
1676 //
1677 if (AddressIndex == ARRAY_SIZE (Address->Addr)) {
1678 if (*Pointer == L'/') {
1679 //
1680 // '/P' is in the String.
1681 // Skip "/" and get P in next loop.
1682 //
1683 Pointer++;
1684 } else {
1685 //
1686 // '/P' is not in the String.
1687 //
1688 break;
1689 }
1690 } else if (AddressIndex < ARRAY_SIZE (Address->Addr)) {
1691 if (*Pointer == L'.') {
1692 //
1693 // D should be followed by '.'
1694 //
1695 Pointer++;
1696 } else {
1697 return RETURN_UNSUPPORTED;
1698 }
1699 }
1700 }
1701
1702 if (AddressIndex < ARRAY_SIZE (Address->Addr)) {
1703 return RETURN_UNSUPPORTED;
1704 }
1705
1706 memcpy (Address, &LocalAddress, sizeof (*Address));
1707 if (PrefixLength != NULL) {
1708 *PrefixLength = LocalPrefixLength;
1709 }
1710 if (EndPointer != NULL) {
1711 *EndPointer = Pointer;
1712 }
1713
1714 return RETURN_SUCCESS;
1715 }
1716
1717 RETURN_STATUS
1718 StrToIpv6Address (
1719 CONST CHAR16 *String,
1720 CHAR16 **EndPointer,
1721 EFI_IPv6_ADDRESS *Address,
1722 UINT8 *PrefixLength
1723 )
1724 {
1725 RETURN_STATUS Status;
1726 UINTN AddressIndex;
1727 UINT64 Uint64;
1728 EFI_IPv6_ADDRESS LocalAddress;
1729 UINT8 LocalPrefixLength;
1730 CONST CHAR16 *Pointer;
1731 CHAR16 *End;
1732 UINTN CompressStart;
1733 BOOLEAN ExpectPrefix;
1734
1735 LocalPrefixLength = MAX_UINT8;
1736 CompressStart = ARRAY_SIZE (Address->Addr);
1737 ExpectPrefix = FALSE;
1738
1739 ASSERT (((UINTN) String & BIT0) == 0);
1740
1741 //
1742 // 1. None of String or Guid shall be a null pointer.
1743 //
1744 SAFE_STRING_CONSTRAINT_CHECK ((String != NULL), RETURN_INVALID_PARAMETER);
1745 SAFE_STRING_CONSTRAINT_CHECK ((Address != NULL), RETURN_INVALID_PARAMETER);
1746
1747 for (Pointer = String, AddressIndex = 0; AddressIndex < ARRAY_SIZE (Address->Addr) + 1;) {
1748 if (!InternalIsHexaDecimalDigitCharacter (*Pointer)) {
1749 if (*Pointer != L':') {
1750 //
1751 // ":" or "/" should be followed by digit characters.
1752 //
1753 return RETURN_UNSUPPORTED;
1754 }
1755
1756 //
1757 // Meet second ":" after previous ":" or "/"
1758 // or meet first ":" in the beginning of String.
1759 //
1760 if (ExpectPrefix) {
1761 //
1762 // ":" shall not be after "/"
1763 //
1764 return RETURN_UNSUPPORTED;
1765 }
1766
1767 if (CompressStart != ARRAY_SIZE (Address->Addr) || AddressIndex == ARRAY_SIZE (Address->Addr)) {
1768 //
1769 // "::" can only appear once.
1770 // "::" can only appear when address is not full length.
1771 //
1772 return RETURN_UNSUPPORTED;
1773 } else {
1774 //
1775 // Remember the start of zero compressing.
1776 //
1777 CompressStart = AddressIndex;
1778 Pointer++;
1779
1780 if (CompressStart == 0) {
1781 if (*Pointer != L':') {
1782 //
1783 // Single ":" shall not be in the beginning of String.
1784 //
1785 return RETURN_UNSUPPORTED;
1786 }
1787 Pointer++;
1788 }
1789 }
1790 }
1791
1792 if (!InternalIsHexaDecimalDigitCharacter (*Pointer)) {
1793 if (*Pointer == L'/') {
1794 //
1795 // Might be optional "/P" after "::".
1796 //
1797 if (CompressStart != AddressIndex) {
1798 return RETURN_UNSUPPORTED;
1799 }
1800 } else {
1801 break;
1802 }
1803 } else {
1804 if (!ExpectPrefix) {
1805 //
1806 // Get X.
1807 //
1808 Status = StrHexToUint64S (Pointer, &End, &Uint64);
1809 if (RETURN_ERROR (Status) || End - Pointer > 4) {
1810 //
1811 // Number of hexadecimal digit characters is no more than 4.
1812 //
1813 return RETURN_UNSUPPORTED;
1814 }
1815 Pointer = End;
1816 //
1817 // Uint64 won't exceed MAX_UINT16 if number of hexadecimal digit characters is no more than 4.
1818 //
1819 ASSERT (AddressIndex + 1 < ARRAY_SIZE (Address->Addr));
1820 LocalAddress.Addr[AddressIndex] = (UINT8) ((UINT16) Uint64 >> 8);
1821 LocalAddress.Addr[AddressIndex + 1] = (UINT8) Uint64;
1822 AddressIndex += 2;
1823 } else {
1824 //
1825 // Get P, then exit the loop.
1826 //
1827 Status = StrDecimalToUint64S (Pointer, &End, &Uint64);
1828 if (RETURN_ERROR (Status) || End == Pointer || Uint64 > 128) {
1829 //
1830 // Prefix length should not exceed 128.
1831 //
1832 return RETURN_UNSUPPORTED;
1833 }
1834 LocalPrefixLength = (UINT8) Uint64;
1835 Pointer = End;
1836 break;
1837 }
1838 }
1839
1840 //
1841 // Skip ':' or "/"
1842 //
1843 if (*Pointer == L'/') {
1844 ExpectPrefix = TRUE;
1845 } else if (*Pointer == L':') {
1846 if (AddressIndex == ARRAY_SIZE (Address->Addr)) {
1847 //
1848 // Meet additional ":" after all 8 16-bit address
1849 //
1850 break;
1851 }
1852 } else {
1853 //
1854 // Meet other character that is not "/" or ":" after all 8 16-bit address
1855 //
1856 break;
1857 }
1858 Pointer++;
1859 }
1860
1861 if ((AddressIndex == ARRAY_SIZE (Address->Addr) && CompressStart != ARRAY_SIZE (Address->Addr)) ||
1862 (AddressIndex != ARRAY_SIZE (Address->Addr) && CompressStart == ARRAY_SIZE (Address->Addr))
1863 ) {
1864 //
1865 // Full length of address shall not have compressing zeros.
1866 // Non-full length of address shall have compressing zeros.
1867 //
1868 return RETURN_UNSUPPORTED;
1869 }
1870 memcpy (&Address->Addr[0], &LocalAddress.Addr[0], CompressStart);
1871 if (AddressIndex > CompressStart) {
1872 memset (&Address->Addr[CompressStart], 0, ARRAY_SIZE (Address->Addr) - AddressIndex);
1873 memcpy (
1874 &Address->Addr[CompressStart + ARRAY_SIZE (Address->Addr) - AddressIndex],
1875 &LocalAddress.Addr[CompressStart],
1876 AddressIndex - CompressStart
1877 );
1878 }
1879
1880 if (PrefixLength != NULL) {
1881 *PrefixLength = LocalPrefixLength;
1882 }
1883 if (EndPointer != NULL) {
1884 *EndPointer = (CHAR16 *) Pointer;
1885 }
1886
1887 return RETURN_SUCCESS;
1888 }
1889
1890
1891 RETURN_STATUS
1892 UnicodeStrToAsciiStrS (
1893 CONST CHAR16 *Source,
1894 CHAR8 *Destination,
1895 UINTN DestMax
1896 )
1897 {
1898 UINTN SourceLen;
1899
1900 ASSERT (((UINTN) Source & BIT0) == 0);
1901
1902 //
1903 // 1. Neither Destination nor Source shall be a null pointer.
1904 //
1905 SAFE_STRING_CONSTRAINT_CHECK ((Destination != NULL), RETURN_INVALID_PARAMETER);
1906 SAFE_STRING_CONSTRAINT_CHECK ((Source != NULL), RETURN_INVALID_PARAMETER);
1907
1908 //
1909 // 2. DestMax shall not be greater than ASCII_RSIZE_MAX or RSIZE_MAX.
1910 //
1911 if (ASCII_RSIZE_MAX != 0) {
1912 SAFE_STRING_CONSTRAINT_CHECK ((DestMax <= ASCII_RSIZE_MAX), RETURN_INVALID_PARAMETER);
1913 }
1914 if (RSIZE_MAX != 0) {
1915 SAFE_STRING_CONSTRAINT_CHECK ((DestMax <= RSIZE_MAX), RETURN_INVALID_PARAMETER);
1916 }
1917
1918 //
1919 // 3. DestMax shall not equal zero.
1920 //
1921 SAFE_STRING_CONSTRAINT_CHECK ((DestMax != 0), RETURN_INVALID_PARAMETER);
1922
1923 //
1924 // 4. DestMax shall be greater than StrnLenS (Source, DestMax).
1925 //
1926 SourceLen = StrnLenS (Source, DestMax);
1927 SAFE_STRING_CONSTRAINT_CHECK ((DestMax > SourceLen), RETURN_BUFFER_TOO_SMALL);
1928
1929 //
1930 // 5. Copying shall not take place between objects that overlap.
1931 //
1932 SAFE_STRING_CONSTRAINT_CHECK (!InternalSafeStringIsOverlap (Destination, DestMax, (VOID *)Source, (SourceLen + 1) * sizeof(CHAR16)), RETURN_ACCESS_DENIED);
1933
1934 //
1935 // convert string
1936 //
1937 while (*Source != '\0') {
1938 //
1939 // If any Unicode characters in Source contain
1940 // non-zero value in the upper 8 bits, then ASSERT().
1941 //
1942 ASSERT (*Source < 0x100);
1943 *(Destination++) = (CHAR8) *(Source++);
1944 }
1945 *Destination = '\0';
1946
1947 return RETURN_SUCCESS;
1948 }
1949
1950 RETURN_STATUS
1951 StrCpyS (
1952 CHAR16 *Destination,
1953 UINTN DestMax,
1954 CONST CHAR16 *Source
1955 )
1956 {
1957 UINTN SourceLen;
1958
1959 ASSERT (((UINTN) Destination & BIT0) == 0);
1960 ASSERT (((UINTN) Source & BIT0) == 0);
1961
1962 //
1963 // 1. Neither Destination nor Source shall be a null pointer.
1964 //
1965 SAFE_STRING_CONSTRAINT_CHECK ((Destination != NULL), RETURN_INVALID_PARAMETER);
1966 SAFE_STRING_CONSTRAINT_CHECK ((Source != NULL), RETURN_INVALID_PARAMETER);
1967
1968 //
1969 // 2. DestMax shall not be greater than RSIZE_MAX.
1970 //
1971 if (RSIZE_MAX != 0) {
1972 SAFE_STRING_CONSTRAINT_CHECK ((DestMax <= RSIZE_MAX), RETURN_INVALID_PARAMETER);
1973 }
1974
1975 //
1976 // 3. DestMax shall not equal zero.
1977 //
1978 SAFE_STRING_CONSTRAINT_CHECK ((DestMax != 0), RETURN_INVALID_PARAMETER);
1979
1980 //
1981 // 4. DestMax shall be greater than StrnLenS(Source, DestMax).
1982 //
1983 SourceLen = StrnLenS (Source, DestMax);
1984 SAFE_STRING_CONSTRAINT_CHECK ((DestMax > SourceLen), RETURN_BUFFER_TOO_SMALL);
1985
1986 //
1987 // 5. Copying shall not take place between objects that overlap.
1988 //
1989 SAFE_STRING_CONSTRAINT_CHECK (InternalSafeStringNoStrOverlap (Destination, DestMax, (CHAR16 *)Source, SourceLen + 1), RETURN_ACCESS_DENIED);
1990
1991 //
1992 // The StrCpyS function copies the string pointed to by Source (including the terminating
1993 // null character) into the array pointed to by Destination.
1994 //
1995 while (*Source != 0) {
1996 *(Destination++) = *(Source++);
1997 }
1998 *Destination = 0;
1999
2000 return RETURN_SUCCESS;
2001 }
2002
2003 VOID *
2004 AllocateZeroPool (
2005 UINTN AllocationSize
2006 )
2007 {
2008 VOID * Memory;
2009 Memory = malloc(AllocationSize);
2010 ASSERT (Memory != NULL);
2011 if (Memory == NULL) {
2012 fprintf(stderr, "Not memory for malloc\n");
2013 }
2014 memset(Memory, 0, AllocationSize);
2015 return Memory;
2016 }
2017
2018 VOID *
2019 AllocatePool (
2020 UINTN AllocationSize
2021 )
2022 {
2023 return InternalAllocatePool (AllocationSize);
2024 }
2025
2026 UINT16
2027 WriteUnaligned16 (
2028 UINT16 *Buffer,
2029 UINT16 Value
2030 )
2031 {
2032 ASSERT (Buffer != NULL);
2033
2034 return *Buffer = Value;
2035 }
2036
2037 UINT16
2038 ReadUnaligned16 (
2039 CONST UINT16 *Buffer
2040 )
2041 {
2042 ASSERT (Buffer != NULL);
2043
2044 return *Buffer;
2045 }
2046 /**
2047 Return whether the integer string is a hex string.
2048
2049 @param Str The integer string
2050
2051 @retval TRUE Hex string
2052 @retval FALSE Decimal string
2053
2054 **/
2055 BOOLEAN
2056 IsHexStr (
2057 CHAR16 *Str
2058 )
2059 {
2060 //
2061 // skip preceeding white space
2062 //
2063 while ((*Str != 0) && *Str == L' ') {
2064 Str ++;
2065 }
2066 //
2067 // skip preceeding zeros
2068 //
2069 while ((*Str != 0) && *Str == L'0') {
2070 Str ++;
2071 }
2072
2073 return (BOOLEAN) (*Str == L'x' || *Str == L'X');
2074 }
2075
2076 /**
2077
2078 Convert integer string to uint.
2079
2080 @param Str The integer string. If leading with "0x" or "0X", it's hexadecimal.
2081
2082 @return A UINTN value represented by Str
2083
2084 **/
2085 UINTN
2086 Strtoi (
2087 CHAR16 *Str
2088 )
2089 {
2090 if (IsHexStr (Str)) {
2091 return (UINTN)StrHexToUint64 (Str);
2092 } else {
2093 return (UINTN)StrDecimalToUint64 (Str);
2094 }
2095 }
2096
2097 /**
2098
2099 Convert integer string to 64 bit data.
2100
2101 @param Str The integer string. If leading with "0x" or "0X", it's hexadecimal.
2102 @param Data A pointer to the UINT64 value represented by Str
2103
2104 **/
2105 VOID
2106 Strtoi64 (
2107 CHAR16 *Str,
2108 UINT64 *Data
2109 )
2110 {
2111 if (IsHexStr (Str)) {
2112 *Data = StrHexToUint64 (Str);
2113 } else {
2114 *Data = StrDecimalToUint64 (Str);
2115 }
2116 }
2117
2118 /**
2119 Converts a Unicode string to ASCII string.
2120
2121 @param Str The equivalent Unicode string
2122 @param AsciiStr On input, it points to destination ASCII string buffer; on output, it points
2123 to the next ASCII string next to it
2124
2125 **/
2126 VOID
2127 StrToAscii (
2128 CHAR16 *Str,
2129 CHAR8 **AsciiStr
2130 )
2131 {
2132 CHAR8 *Dest;
2133
2134 Dest = *AsciiStr;
2135 while (!IS_NULL (*Str)) {
2136 *(Dest++) = (CHAR8) *(Str++);
2137 }
2138 *Dest = 0;
2139
2140 //
2141 // Return the string next to it
2142 //
2143 *AsciiStr = Dest + 1;
2144 }
2145
2146 /**
2147 Gets current sub-string from a string list, before return
2148 the list header is moved to next sub-string. The sub-string is separated
2149 by the specified character. For example, the separator is ',', the string
2150 list is "2,0,3", it returns "2", the remain list move to "0,3"
2151
2152 @param List A string list separated by the specified separator
2153 @param Separator The separator character
2154
2155 @return A pointer to the current sub-string
2156
2157 **/
2158 CHAR16 *
2159 SplitStr (
2160 CHAR16 **List,
2161 CHAR16 Separator
2162 )
2163 {
2164 CHAR16 *Str;
2165 CHAR16 *ReturnStr;
2166
2167 Str = *List;
2168 ReturnStr = Str;
2169
2170 if (IS_NULL (*Str)) {
2171 return ReturnStr;
2172 }
2173
2174 //
2175 // Find first occurrence of the separator
2176 //
2177 while (!IS_NULL (*Str)) {
2178 if (*Str == Separator) {
2179 break;
2180 }
2181 Str++;
2182 }
2183
2184 if (*Str == Separator) {
2185 //
2186 // Find a sub-string, terminate it
2187 //
2188 *Str = L'\0';
2189 Str++;
2190 }
2191
2192 //
2193 // Move to next sub-string
2194 //
2195 *List = Str;
2196 return ReturnStr;
2197 }
2198