]> git.proxmox.com Git - mirror_edk2.git/blob - ShellPkg/Library/UefiShellLib/UefiShellLib.c
ShellPkg: Expand special output file to include "NULL" and case insensitive
[mirror_edk2.git] / ShellPkg / Library / UefiShellLib / UefiShellLib.c
1 /** @file
2 Provides interface to shell functionality for shell commands and applications.
3
4 (C) Copyright 2016 Hewlett Packard Enterprise Development LP<BR>
5 Copyright 2016 Dell Inc.
6 Copyright (c) 2006 - 2016, Intel Corporation. All rights reserved.<BR>
7 This program and the accompanying materials
8 are licensed and made available under the terms and conditions of the BSD License
9 which accompanies this distribution. The full text of the license may be found at
10 http://opensource.org/licenses/bsd-license.php
11
12 THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
13 WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
14
15 **/
16
17 #include "UefiShellLib.h"
18 #include <ShellBase.h>
19 #include <Library/SortLib.h>
20 #include <Library/BaseLib.h>
21
22 #define FIND_XXXXX_FILE_BUFFER_SIZE (SIZE_OF_EFI_FILE_INFO + MAX_FILE_NAME_LEN)
23
24 //
25 // globals...
26 //
27 SHELL_PARAM_ITEM EmptyParamList[] = {
28 {NULL, TypeMax}
29 };
30 SHELL_PARAM_ITEM SfoParamList[] = {
31 {L"-sfo", TypeFlag},
32 {NULL, TypeMax}
33 };
34 EFI_SHELL_ENVIRONMENT2 *mEfiShellEnvironment2;
35 EFI_SHELL_INTERFACE *mEfiShellInterface;
36 EFI_SHELL_PROTOCOL *gEfiShellProtocol;
37 EFI_SHELL_PARAMETERS_PROTOCOL *gEfiShellParametersProtocol;
38 EFI_HANDLE mEfiShellEnvironment2Handle;
39 FILE_HANDLE_FUNCTION_MAP FileFunctionMap;
40 EFI_UNICODE_COLLATION_PROTOCOL *mUnicodeCollationProtocol;
41
42 /**
43 Check if a Unicode character is a hexadecimal character.
44
45 This internal function checks if a Unicode character is a
46 numeric character. The valid hexadecimal characters are
47 L'0' to L'9', L'a' to L'f', or L'A' to L'F'.
48
49 @param Char The character to check against.
50
51 @retval TRUE If the Char is a hexadecmial character.
52 @retval FALSE If the Char is not a hexadecmial character.
53
54 **/
55 BOOLEAN
56 EFIAPI
57 ShellIsHexaDecimalDigitCharacter (
58 IN CHAR16 Char
59 )
60 {
61 return (BOOLEAN) ((Char >= L'0' && Char <= L'9') || (Char >= L'A' && Char <= L'F') || (Char >= L'a' && Char <= L'f'));
62 }
63
64 /**
65 Check if a Unicode character is a decimal character.
66
67 This internal function checks if a Unicode character is a
68 decimal character. The valid characters are
69 L'0' to L'9'.
70
71
72 @param Char The character to check against.
73
74 @retval TRUE If the Char is a hexadecmial character.
75 @retval FALSE If the Char is not a hexadecmial character.
76
77 **/
78 BOOLEAN
79 EFIAPI
80 ShellIsDecimalDigitCharacter (
81 IN CHAR16 Char
82 )
83 {
84 return (BOOLEAN) (Char >= L'0' && Char <= L'9');
85 }
86
87 /**
88 Helper function to find ShellEnvironment2 for constructor.
89
90 @param[in] ImageHandle A copy of the calling image's handle.
91
92 @retval EFI_OUT_OF_RESOURCES Memory allocation failed.
93 **/
94 EFI_STATUS
95 EFIAPI
96 ShellFindSE2 (
97 IN EFI_HANDLE ImageHandle
98 )
99 {
100 EFI_STATUS Status;
101 EFI_HANDLE *Buffer;
102 UINTN BufferSize;
103 UINTN HandleIndex;
104
105 BufferSize = 0;
106 Buffer = NULL;
107 Status = gBS->OpenProtocol(ImageHandle,
108 &gEfiShellEnvironment2Guid,
109 (VOID **)&mEfiShellEnvironment2,
110 ImageHandle,
111 NULL,
112 EFI_OPEN_PROTOCOL_GET_PROTOCOL
113 );
114 //
115 // look for the mEfiShellEnvironment2 protocol at a higher level
116 //
117 if (EFI_ERROR (Status) || !(CompareGuid (&mEfiShellEnvironment2->SESGuid, &gEfiShellEnvironment2ExtGuid))){
118 //
119 // figure out how big of a buffer we need.
120 //
121 Status = gBS->LocateHandle (ByProtocol,
122 &gEfiShellEnvironment2Guid,
123 NULL, // ignored for ByProtocol
124 &BufferSize,
125 Buffer
126 );
127 //
128 // maybe it's not there???
129 //
130 if (Status == EFI_BUFFER_TOO_SMALL) {
131 Buffer = (EFI_HANDLE*)AllocateZeroPool(BufferSize);
132 if (Buffer == NULL) {
133 return (EFI_OUT_OF_RESOURCES);
134 }
135 Status = gBS->LocateHandle (ByProtocol,
136 &gEfiShellEnvironment2Guid,
137 NULL, // ignored for ByProtocol
138 &BufferSize,
139 Buffer
140 );
141 }
142 if (!EFI_ERROR (Status) && Buffer != NULL) {
143 //
144 // now parse the list of returned handles
145 //
146 Status = EFI_NOT_FOUND;
147 for (HandleIndex = 0; HandleIndex < (BufferSize/sizeof(Buffer[0])); HandleIndex++) {
148 Status = gBS->OpenProtocol(Buffer[HandleIndex],
149 &gEfiShellEnvironment2Guid,
150 (VOID **)&mEfiShellEnvironment2,
151 ImageHandle,
152 NULL,
153 EFI_OPEN_PROTOCOL_GET_PROTOCOL
154 );
155 if (CompareGuid (&mEfiShellEnvironment2->SESGuid, &gEfiShellEnvironment2ExtGuid)) {
156 mEfiShellEnvironment2Handle = Buffer[HandleIndex];
157 Status = EFI_SUCCESS;
158 break;
159 }
160 }
161 }
162 }
163 if (Buffer != NULL) {
164 FreePool (Buffer);
165 }
166 return (Status);
167 }
168
169 /**
170 Function to do most of the work of the constructor. Allows for calling
171 multiple times without complete re-initialization.
172
173 @param[in] ImageHandle A copy of the ImageHandle.
174 @param[in] SystemTable A pointer to the SystemTable for the application.
175
176 @retval EFI_SUCCESS The operationw as successful.
177 **/
178 EFI_STATUS
179 EFIAPI
180 ShellLibConstructorWorker (
181 IN EFI_HANDLE ImageHandle,
182 IN EFI_SYSTEM_TABLE *SystemTable
183 )
184 {
185 EFI_STATUS Status;
186
187 //
188 // UEFI 2.0 shell interfaces (used preferentially)
189 //
190 Status = gBS->OpenProtocol(
191 ImageHandle,
192 &gEfiShellProtocolGuid,
193 (VOID **)&gEfiShellProtocol,
194 ImageHandle,
195 NULL,
196 EFI_OPEN_PROTOCOL_GET_PROTOCOL
197 );
198 if (EFI_ERROR(Status)) {
199 //
200 // Search for the shell protocol
201 //
202 Status = gBS->LocateProtocol(
203 &gEfiShellProtocolGuid,
204 NULL,
205 (VOID **)&gEfiShellProtocol
206 );
207 if (EFI_ERROR(Status)) {
208 gEfiShellProtocol = NULL;
209 }
210 }
211 Status = gBS->OpenProtocol(
212 ImageHandle,
213 &gEfiShellParametersProtocolGuid,
214 (VOID **)&gEfiShellParametersProtocol,
215 ImageHandle,
216 NULL,
217 EFI_OPEN_PROTOCOL_GET_PROTOCOL
218 );
219 if (EFI_ERROR(Status)) {
220 gEfiShellParametersProtocol = NULL;
221 }
222
223 if (gEfiShellParametersProtocol == NULL || gEfiShellProtocol == NULL) {
224 //
225 // Moved to seperate function due to complexity
226 //
227 Status = ShellFindSE2(ImageHandle);
228
229 if (EFI_ERROR(Status)) {
230 DEBUG((DEBUG_ERROR, "Status: 0x%08x\r\n", Status));
231 mEfiShellEnvironment2 = NULL;
232 }
233 Status = gBS->OpenProtocol(ImageHandle,
234 &gEfiShellInterfaceGuid,
235 (VOID **)&mEfiShellInterface,
236 ImageHandle,
237 NULL,
238 EFI_OPEN_PROTOCOL_GET_PROTOCOL
239 );
240 if (EFI_ERROR(Status)) {
241 mEfiShellInterface = NULL;
242 }
243 }
244
245 //
246 // only success getting 2 of either the old or new, but no 1/2 and 1/2
247 //
248 if ((mEfiShellEnvironment2 != NULL && mEfiShellInterface != NULL) ||
249 (gEfiShellProtocol != NULL && gEfiShellParametersProtocol != NULL) ) {
250 if (gEfiShellProtocol != NULL) {
251 FileFunctionMap.GetFileInfo = gEfiShellProtocol->GetFileInfo;
252 FileFunctionMap.SetFileInfo = gEfiShellProtocol->SetFileInfo;
253 FileFunctionMap.ReadFile = gEfiShellProtocol->ReadFile;
254 FileFunctionMap.WriteFile = gEfiShellProtocol->WriteFile;
255 FileFunctionMap.CloseFile = gEfiShellProtocol->CloseFile;
256 FileFunctionMap.DeleteFile = gEfiShellProtocol->DeleteFile;
257 FileFunctionMap.GetFilePosition = gEfiShellProtocol->GetFilePosition;
258 FileFunctionMap.SetFilePosition = gEfiShellProtocol->SetFilePosition;
259 FileFunctionMap.FlushFile = gEfiShellProtocol->FlushFile;
260 FileFunctionMap.GetFileSize = gEfiShellProtocol->GetFileSize;
261 } else {
262 FileFunctionMap.GetFileInfo = (EFI_SHELL_GET_FILE_INFO)FileHandleGetInfo;
263 FileFunctionMap.SetFileInfo = (EFI_SHELL_SET_FILE_INFO)FileHandleSetInfo;
264 FileFunctionMap.ReadFile = (EFI_SHELL_READ_FILE)FileHandleRead;
265 FileFunctionMap.WriteFile = (EFI_SHELL_WRITE_FILE)FileHandleWrite;
266 FileFunctionMap.CloseFile = (EFI_SHELL_CLOSE_FILE)FileHandleClose;
267 FileFunctionMap.DeleteFile = (EFI_SHELL_DELETE_FILE)FileHandleDelete;
268 FileFunctionMap.GetFilePosition = (EFI_SHELL_GET_FILE_POSITION)FileHandleGetPosition;
269 FileFunctionMap.SetFilePosition = (EFI_SHELL_SET_FILE_POSITION)FileHandleSetPosition;
270 FileFunctionMap.FlushFile = (EFI_SHELL_FLUSH_FILE)FileHandleFlush;
271 FileFunctionMap.GetFileSize = (EFI_SHELL_GET_FILE_SIZE)FileHandleGetSize;
272 }
273 return (EFI_SUCCESS);
274 }
275 return (EFI_NOT_FOUND);
276 }
277 /**
278 Constructor for the Shell library.
279
280 Initialize the library and determine if the underlying is a UEFI Shell 2.0 or an EFI shell.
281
282 @param ImageHandle the image handle of the process
283 @param SystemTable the EFI System Table pointer
284
285 @retval EFI_SUCCESS the initialization was complete sucessfully
286 @return others an error ocurred during initialization
287 **/
288 EFI_STATUS
289 EFIAPI
290 ShellLibConstructor (
291 IN EFI_HANDLE ImageHandle,
292 IN EFI_SYSTEM_TABLE *SystemTable
293 )
294 {
295 EFI_STATUS Status;
296
297 mEfiShellEnvironment2 = NULL;
298 gEfiShellProtocol = NULL;
299 gEfiShellParametersProtocol = NULL;
300 mEfiShellInterface = NULL;
301 mEfiShellEnvironment2Handle = NULL;
302
303 if (mUnicodeCollationProtocol == NULL) {
304 Status = gBS->LocateProtocol (&gEfiUnicodeCollation2ProtocolGuid, NULL, (VOID**)&mUnicodeCollationProtocol);
305 ASSERT_EFI_ERROR (Status);
306 }
307
308 //
309 // verify that auto initialize is not set false
310 //
311 if (PcdGetBool(PcdShellLibAutoInitialize) == 0) {
312 return (EFI_SUCCESS);
313 }
314
315 return (ShellLibConstructorWorker(ImageHandle, SystemTable));
316 }
317
318 /**
319 Destructor for the library. free any resources.
320
321 @param[in] ImageHandle A copy of the ImageHandle.
322 @param[in] SystemTable A pointer to the SystemTable for the application.
323
324 @retval EFI_SUCCESS The operation was successful.
325 @return An error from the CloseProtocol function.
326 **/
327 EFI_STATUS
328 EFIAPI
329 ShellLibDestructor (
330 IN EFI_HANDLE ImageHandle,
331 IN EFI_SYSTEM_TABLE *SystemTable
332 )
333 {
334 if (mEfiShellEnvironment2 != NULL) {
335 gBS->CloseProtocol(mEfiShellEnvironment2Handle==NULL?ImageHandle:mEfiShellEnvironment2Handle,
336 &gEfiShellEnvironment2Guid,
337 ImageHandle,
338 NULL);
339 mEfiShellEnvironment2 = NULL;
340 }
341 if (mEfiShellInterface != NULL) {
342 gBS->CloseProtocol(ImageHandle,
343 &gEfiShellInterfaceGuid,
344 ImageHandle,
345 NULL);
346 mEfiShellInterface = NULL;
347 }
348 if (gEfiShellProtocol != NULL) {
349 gBS->CloseProtocol(ImageHandle,
350 &gEfiShellProtocolGuid,
351 ImageHandle,
352 NULL);
353 gEfiShellProtocol = NULL;
354 }
355 if (gEfiShellParametersProtocol != NULL) {
356 gBS->CloseProtocol(ImageHandle,
357 &gEfiShellParametersProtocolGuid,
358 ImageHandle,
359 NULL);
360 gEfiShellParametersProtocol = NULL;
361 }
362 mEfiShellEnvironment2Handle = NULL;
363
364 return (EFI_SUCCESS);
365 }
366
367 /**
368 This function causes the shell library to initialize itself. If the shell library
369 is already initialized it will de-initialize all the current protocol poitners and
370 re-populate them again.
371
372 When the library is used with PcdShellLibAutoInitialize set to true this function
373 will return EFI_SUCCESS and perform no actions.
374
375 This function is intended for internal access for shell commands only.
376
377 @retval EFI_SUCCESS the initialization was complete sucessfully
378
379 **/
380 EFI_STATUS
381 EFIAPI
382 ShellInitialize (
383 )
384 {
385 EFI_STATUS Status;
386
387 //
388 // if auto initialize is not false then skip
389 //
390 if (PcdGetBool(PcdShellLibAutoInitialize) != 0) {
391 return (EFI_SUCCESS);
392 }
393
394 //
395 // deinit the current stuff
396 //
397 Status = ShellLibDestructor (gImageHandle, gST);
398 ASSERT_EFI_ERROR (Status);
399
400 //
401 // init the new stuff
402 //
403 return (ShellLibConstructorWorker(gImageHandle, gST));
404 }
405
406 /**
407 This function will retrieve the information about the file for the handle
408 specified and store it in allocated pool memory.
409
410 This function allocates a buffer to store the file's information. It is the
411 caller's responsibility to free the buffer
412
413 @param FileHandle The file handle of the file for which information is
414 being requested.
415
416 @retval NULL information could not be retrieved.
417
418 @return the information about the file
419 **/
420 EFI_FILE_INFO*
421 EFIAPI
422 ShellGetFileInfo (
423 IN SHELL_FILE_HANDLE FileHandle
424 )
425 {
426 return (FileFunctionMap.GetFileInfo(FileHandle));
427 }
428
429 /**
430 This function sets the information about the file for the opened handle
431 specified.
432
433 @param[in] FileHandle The file handle of the file for which information
434 is being set.
435
436 @param[in] FileInfo The information to set.
437
438 @retval EFI_SUCCESS The information was set.
439 @retval EFI_INVALID_PARAMETER A parameter was out of range or invalid.
440 @retval EFI_UNSUPPORTED The FileHandle does not support FileInfo.
441 @retval EFI_NO_MEDIA The device has no medium.
442 @retval EFI_DEVICE_ERROR The device reported an error.
443 @retval EFI_VOLUME_CORRUPTED The file system structures are corrupted.
444 @retval EFI_WRITE_PROTECTED The file or medium is write protected.
445 @retval EFI_ACCESS_DENIED The file was opened read only.
446 @retval EFI_VOLUME_FULL The volume is full.
447 **/
448 EFI_STATUS
449 EFIAPI
450 ShellSetFileInfo (
451 IN SHELL_FILE_HANDLE FileHandle,
452 IN EFI_FILE_INFO *FileInfo
453 )
454 {
455 return (FileFunctionMap.SetFileInfo(FileHandle, FileInfo));
456 }
457
458 /**
459 This function will open a file or directory referenced by DevicePath.
460
461 This function opens a file with the open mode according to the file path. The
462 Attributes is valid only for EFI_FILE_MODE_CREATE.
463
464 @param FilePath on input the device path to the file. On output
465 the remaining device path.
466 @param DeviceHandle pointer to the system device handle.
467 @param FileHandle pointer to the file handle.
468 @param OpenMode the mode to open the file with.
469 @param Attributes the file's file attributes.
470
471 @retval EFI_SUCCESS The information was set.
472 @retval EFI_INVALID_PARAMETER One of the parameters has an invalid value.
473 @retval EFI_UNSUPPORTED Could not open the file path.
474 @retval EFI_NOT_FOUND The specified file could not be found on the
475 device or the file system could not be found on
476 the device.
477 @retval EFI_NO_MEDIA The device has no medium.
478 @retval EFI_MEDIA_CHANGED The device has a different medium in it or the
479 medium is no longer supported.
480 @retval EFI_DEVICE_ERROR The device reported an error.
481 @retval EFI_VOLUME_CORRUPTED The file system structures are corrupted.
482 @retval EFI_WRITE_PROTECTED The file or medium is write protected.
483 @retval EFI_ACCESS_DENIED The file was opened read only.
484 @retval EFI_OUT_OF_RESOURCES Not enough resources were available to open the
485 file.
486 @retval EFI_VOLUME_FULL The volume is full.
487 **/
488 EFI_STATUS
489 EFIAPI
490 ShellOpenFileByDevicePath(
491 IN OUT EFI_DEVICE_PATH_PROTOCOL **FilePath,
492 OUT EFI_HANDLE *DeviceHandle,
493 OUT SHELL_FILE_HANDLE *FileHandle,
494 IN UINT64 OpenMode,
495 IN UINT64 Attributes
496 )
497 {
498 CHAR16 *FileName;
499 EFI_STATUS Status;
500 EFI_SIMPLE_FILE_SYSTEM_PROTOCOL *EfiSimpleFileSystemProtocol;
501 EFI_FILE_PROTOCOL *Handle1;
502 EFI_FILE_PROTOCOL *Handle2;
503 CHAR16 *FnafPathName;
504 UINTN PathLen;
505
506 if (FilePath == NULL || FileHandle == NULL || DeviceHandle == NULL) {
507 return (EFI_INVALID_PARAMETER);
508 }
509
510 //
511 // which shell interface should we use
512 //
513 if (gEfiShellProtocol != NULL) {
514 //
515 // use UEFI Shell 2.0 method.
516 //
517 FileName = gEfiShellProtocol->GetFilePathFromDevicePath(*FilePath);
518 if (FileName == NULL) {
519 return (EFI_INVALID_PARAMETER);
520 }
521 Status = ShellOpenFileByName(FileName, FileHandle, OpenMode, Attributes);
522 FreePool(FileName);
523 return (Status);
524 }
525
526
527 //
528 // use old shell method.
529 //
530 Status = gBS->LocateDevicePath (&gEfiSimpleFileSystemProtocolGuid,
531 FilePath,
532 DeviceHandle);
533 if (EFI_ERROR (Status)) {
534 return Status;
535 }
536 Status = gBS->OpenProtocol(*DeviceHandle,
537 &gEfiSimpleFileSystemProtocolGuid,
538 (VOID**)&EfiSimpleFileSystemProtocol,
539 gImageHandle,
540 NULL,
541 EFI_OPEN_PROTOCOL_GET_PROTOCOL);
542 if (EFI_ERROR (Status)) {
543 return Status;
544 }
545 Status = EfiSimpleFileSystemProtocol->OpenVolume(EfiSimpleFileSystemProtocol, &Handle1);
546 if (EFI_ERROR (Status)) {
547 FileHandle = NULL;
548 return Status;
549 }
550
551 //
552 // go down directories one node at a time.
553 //
554 while (!IsDevicePathEnd (*FilePath)) {
555 //
556 // For file system access each node should be a file path component
557 //
558 if (DevicePathType (*FilePath) != MEDIA_DEVICE_PATH ||
559 DevicePathSubType (*FilePath) != MEDIA_FILEPATH_DP
560 ) {
561 FileHandle = NULL;
562 return (EFI_INVALID_PARAMETER);
563 }
564 //
565 // Open this file path node
566 //
567 Handle2 = Handle1;
568 Handle1 = NULL;
569
570 //
571 // File Name Alignment Fix (FNAF)
572 // Handle2->Open may be incapable of handling a unaligned CHAR16 data.
573 // The structure pointed to by FilePath may be not CHAR16 aligned.
574 // This code copies the potentially unaligned PathName data from the
575 // FilePath structure to the aligned FnafPathName for use in the
576 // calls to Handl2->Open.
577 //
578
579 //
580 // Determine length of PathName, in bytes.
581 //
582 PathLen = DevicePathNodeLength (*FilePath) - SIZE_OF_FILEPATH_DEVICE_PATH;
583
584 //
585 // Allocate memory for the aligned copy of the string Extra allocation is to allow for forced alignment
586 // Copy bytes from possibly unaligned location to aligned location
587 //
588 FnafPathName = AllocateCopyPool(PathLen, (UINT8 *)((FILEPATH_DEVICE_PATH*)*FilePath)->PathName);
589 if (FnafPathName == NULL) {
590 return EFI_OUT_OF_RESOURCES;
591 }
592
593 //
594 // Try to test opening an existing file
595 //
596 Status = Handle2->Open (
597 Handle2,
598 &Handle1,
599 FnafPathName,
600 OpenMode &~EFI_FILE_MODE_CREATE,
601 0
602 );
603
604 //
605 // see if the error was that it needs to be created
606 //
607 if ((EFI_ERROR (Status)) && (OpenMode != (OpenMode &~EFI_FILE_MODE_CREATE))) {
608 Status = Handle2->Open (
609 Handle2,
610 &Handle1,
611 FnafPathName,
612 OpenMode,
613 Attributes
614 );
615 }
616
617 //
618 // Free the alignment buffer
619 //
620 FreePool(FnafPathName);
621
622 //
623 // Close the last node
624 //
625 Handle2->Close (Handle2);
626
627 if (EFI_ERROR(Status)) {
628 return (Status);
629 }
630
631 //
632 // Get the next node
633 //
634 *FilePath = NextDevicePathNode (*FilePath);
635 }
636
637 //
638 // This is a weak spot since if the undefined SHELL_FILE_HANDLE format changes this must change also!
639 //
640 *FileHandle = (VOID*)Handle1;
641 return (EFI_SUCCESS);
642 }
643
644 /**
645 This function will open a file or directory referenced by filename.
646
647 If return is EFI_SUCCESS, the Filehandle is the opened file's handle;
648 otherwise, the Filehandle is NULL. The Attributes is valid only for
649 EFI_FILE_MODE_CREATE.
650
651 if FileName is NULL then ASSERT()
652
653 @param FileName pointer to file name
654 @param FileHandle pointer to the file handle.
655 @param OpenMode the mode to open the file with.
656 @param Attributes the file's file attributes.
657
658 @retval EFI_SUCCESS The information was set.
659 @retval EFI_INVALID_PARAMETER One of the parameters has an invalid value.
660 @retval EFI_UNSUPPORTED Could not open the file path.
661 @retval EFI_NOT_FOUND The specified file could not be found on the
662 device or the file system could not be found
663 on the device.
664 @retval EFI_NO_MEDIA The device has no medium.
665 @retval EFI_MEDIA_CHANGED The device has a different medium in it or the
666 medium is no longer supported.
667 @retval EFI_DEVICE_ERROR The device reported an error.
668 @retval EFI_VOLUME_CORRUPTED The file system structures are corrupted.
669 @retval EFI_WRITE_PROTECTED The file or medium is write protected.
670 @retval EFI_ACCESS_DENIED The file was opened read only.
671 @retval EFI_OUT_OF_RESOURCES Not enough resources were available to open the
672 file.
673 @retval EFI_VOLUME_FULL The volume is full.
674 **/
675 EFI_STATUS
676 EFIAPI
677 ShellOpenFileByName(
678 IN CONST CHAR16 *FileName,
679 OUT SHELL_FILE_HANDLE *FileHandle,
680 IN UINT64 OpenMode,
681 IN UINT64 Attributes
682 )
683 {
684 EFI_HANDLE DeviceHandle;
685 EFI_DEVICE_PATH_PROTOCOL *FilePath;
686 EFI_STATUS Status;
687 EFI_FILE_INFO *FileInfo;
688 CHAR16 *FileNameCopy;
689 EFI_STATUS Status2;
690
691 //
692 // ASSERT if FileName is NULL
693 //
694 ASSERT(FileName != NULL);
695
696 if (FileName == NULL) {
697 return (EFI_INVALID_PARAMETER);
698 }
699
700 if (gEfiShellProtocol != NULL) {
701 if ((OpenMode & EFI_FILE_MODE_CREATE) == EFI_FILE_MODE_CREATE) {
702
703 //
704 // Create only a directory
705 //
706 if ((Attributes & EFI_FILE_DIRECTORY) == EFI_FILE_DIRECTORY) {
707 return ShellCreateDirectory(FileName, FileHandle);
708 }
709
710 //
711 // Create the directory to create the file in
712 //
713 FileNameCopy = AllocateCopyPool (StrSize (FileName), FileName);
714 if (FileName == NULL) {
715 return (EFI_OUT_OF_RESOURCES);
716 }
717 PathCleanUpDirectories (FileNameCopy);
718 if (PathRemoveLastItem (FileNameCopy)) {
719 if (!EFI_ERROR(ShellCreateDirectory (FileNameCopy, FileHandle))) {
720 ShellCloseFile (FileHandle);
721 }
722 }
723 SHELL_FREE_NON_NULL (FileNameCopy);
724 }
725
726 //
727 // Use UEFI Shell 2.0 method to create the file
728 //
729 Status = gEfiShellProtocol->OpenFileByName(FileName,
730 FileHandle,
731 OpenMode);
732
733 if ((mUnicodeCollationProtocol->StriColl (mUnicodeCollationProtocol, (CHAR16*)FileName, L"NUL") != 0) &&
734 (mUnicodeCollationProtocol->StriColl (mUnicodeCollationProtocol, (CHAR16*)FileName, L"NULL") != 0) &&
735 !EFI_ERROR(Status) && ((OpenMode & EFI_FILE_MODE_CREATE) != 0)){
736 FileInfo = FileFunctionMap.GetFileInfo(*FileHandle);
737 ASSERT(FileInfo != NULL);
738 FileInfo->Attribute = Attributes;
739 Status2 = FileFunctionMap.SetFileInfo(*FileHandle, FileInfo);
740 FreePool(FileInfo);
741 if (EFI_ERROR (Status2)) {
742 gEfiShellProtocol->CloseFile(*FileHandle);
743 }
744 Status = Status2;
745 }
746 return (Status);
747 }
748 //
749 // Using EFI Shell version
750 // this means convert name to path and call that function
751 // since this will use EFI method again that will open it.
752 //
753 ASSERT(mEfiShellEnvironment2 != NULL);
754 FilePath = mEfiShellEnvironment2->NameToPath ((CHAR16*)FileName);
755 if (FilePath != NULL) {
756 return (ShellOpenFileByDevicePath(&FilePath,
757 &DeviceHandle,
758 FileHandle,
759 OpenMode,
760 Attributes));
761 }
762 return (EFI_DEVICE_ERROR);
763 }
764 /**
765 This function create a directory
766
767 If return is EFI_SUCCESS, the Filehandle is the opened directory's handle;
768 otherwise, the Filehandle is NULL. If the directory already existed, this
769 function opens the existing directory.
770
771 @param DirectoryName pointer to directory name
772 @param FileHandle pointer to the file handle.
773
774 @retval EFI_SUCCESS The information was set.
775 @retval EFI_INVALID_PARAMETER One of the parameters has an invalid value.
776 @retval EFI_UNSUPPORTED Could not open the file path.
777 @retval EFI_NOT_FOUND The specified file could not be found on the
778 device or the file system could not be found
779 on the device.
780 @retval EFI_NO_MEDIA The device has no medium.
781 @retval EFI_MEDIA_CHANGED The device has a different medium in it or the
782 medium is no longer supported.
783 @retval EFI_DEVICE_ERROR The device reported an error.
784 @retval EFI_VOLUME_CORRUPTED The file system structures are corrupted.
785 @retval EFI_WRITE_PROTECTED The file or medium is write protected.
786 @retval EFI_ACCESS_DENIED The file was opened read only.
787 @retval EFI_OUT_OF_RESOURCES Not enough resources were available to open the
788 file.
789 @retval EFI_VOLUME_FULL The volume is full.
790 @sa ShellOpenFileByName
791 **/
792 EFI_STATUS
793 EFIAPI
794 ShellCreateDirectory(
795 IN CONST CHAR16 *DirectoryName,
796 OUT SHELL_FILE_HANDLE *FileHandle
797 )
798 {
799 if (gEfiShellProtocol != NULL) {
800 //
801 // Use UEFI Shell 2.0 method
802 //
803 return (gEfiShellProtocol->CreateFile(DirectoryName,
804 EFI_FILE_DIRECTORY,
805 FileHandle
806 ));
807 } else {
808 return (ShellOpenFileByName(DirectoryName,
809 FileHandle,
810 EFI_FILE_MODE_READ | EFI_FILE_MODE_WRITE | EFI_FILE_MODE_CREATE,
811 EFI_FILE_DIRECTORY
812 ));
813 }
814 }
815
816 /**
817 This function reads information from an opened file.
818
819 If FileHandle is not a directory, the function reads the requested number of
820 bytes from the file at the file's current position and returns them in Buffer.
821 If the read goes beyond the end of the file, the read length is truncated to the
822 end of the file. The file's current position is increased by the number of bytes
823 returned. If FileHandle is a directory, the function reads the directory entry
824 at the file's current position and returns the entry in Buffer. If the Buffer
825 is not large enough to hold the current directory entry, then
826 EFI_BUFFER_TOO_SMALL is returned and the current file position is not updated.
827 BufferSize is set to be the size of the buffer needed to read the entry. On
828 success, the current position is updated to the next directory entry. If there
829 are no more directory entries, the read returns a zero-length buffer.
830 EFI_FILE_INFO is the structure returned as the directory entry.
831
832 @param FileHandle the opened file handle
833 @param BufferSize on input the size of buffer in bytes. on return
834 the number of bytes written.
835 @param Buffer the buffer to put read data into.
836
837 @retval EFI_SUCCESS Data was read.
838 @retval EFI_NO_MEDIA The device has no media.
839 @retval EFI_DEVICE_ERROR The device reported an error.
840 @retval EFI_VOLUME_CORRUPTED The file system structures are corrupted.
841 @retval EFI_BUFFER_TO_SMALL Buffer is too small. ReadSize contains required
842 size.
843
844 **/
845 EFI_STATUS
846 EFIAPI
847 ShellReadFile(
848 IN SHELL_FILE_HANDLE FileHandle,
849 IN OUT UINTN *BufferSize,
850 OUT VOID *Buffer
851 )
852 {
853 return (FileFunctionMap.ReadFile(FileHandle, BufferSize, Buffer));
854 }
855
856
857 /**
858 Write data to a file.
859
860 This function writes the specified number of bytes to the file at the current
861 file position. The current file position is advanced the actual number of bytes
862 written, which is returned in BufferSize. Partial writes only occur when there
863 has been a data error during the write attempt (such as "volume space full").
864 The file is automatically grown to hold the data if required. Direct writes to
865 opened directories are not supported.
866
867 @param FileHandle The opened file for writing
868 @param BufferSize on input the number of bytes in Buffer. On output
869 the number of bytes written.
870 @param Buffer the buffer containing data to write is stored.
871
872 @retval EFI_SUCCESS Data was written.
873 @retval EFI_UNSUPPORTED Writes to an open directory are not supported.
874 @retval EFI_NO_MEDIA The device has no media.
875 @retval EFI_DEVICE_ERROR The device reported an error.
876 @retval EFI_VOLUME_CORRUPTED The file system structures are corrupted.
877 @retval EFI_WRITE_PROTECTED The device is write-protected.
878 @retval EFI_ACCESS_DENIED The file was open for read only.
879 @retval EFI_VOLUME_FULL The volume is full.
880 **/
881 EFI_STATUS
882 EFIAPI
883 ShellWriteFile(
884 IN SHELL_FILE_HANDLE FileHandle,
885 IN OUT UINTN *BufferSize,
886 IN VOID *Buffer
887 )
888 {
889 return (FileFunctionMap.WriteFile(FileHandle, BufferSize, Buffer));
890 }
891
892 /**
893 Close an open file handle.
894
895 This function closes a specified file handle. All "dirty" cached file data is
896 flushed to the device, and the file is closed. In all cases the handle is
897 closed.
898
899 @param FileHandle the file handle to close.
900
901 @retval EFI_SUCCESS the file handle was closed sucessfully.
902 **/
903 EFI_STATUS
904 EFIAPI
905 ShellCloseFile (
906 IN SHELL_FILE_HANDLE *FileHandle
907 )
908 {
909 return (FileFunctionMap.CloseFile(*FileHandle));
910 }
911
912 /**
913 Delete a file and close the handle
914
915 This function closes and deletes a file. In all cases the file handle is closed.
916 If the file cannot be deleted, the warning code EFI_WARN_DELETE_FAILURE is
917 returned, but the handle is still closed.
918
919 @param FileHandle the file handle to delete
920
921 @retval EFI_SUCCESS the file was closed sucessfully
922 @retval EFI_WARN_DELETE_FAILURE the handle was closed, but the file was not
923 deleted
924 @retval INVALID_PARAMETER One of the parameters has an invalid value.
925 **/
926 EFI_STATUS
927 EFIAPI
928 ShellDeleteFile (
929 IN SHELL_FILE_HANDLE *FileHandle
930 )
931 {
932 return (FileFunctionMap.DeleteFile(*FileHandle));
933 }
934
935 /**
936 Set the current position in a file.
937
938 This function sets the current file position for the handle to the position
939 supplied. With the exception of seeking to position 0xFFFFFFFFFFFFFFFF, only
940 absolute positioning is supported, and seeking past the end of the file is
941 allowed (a subsequent write would grow the file). Seeking to position
942 0xFFFFFFFFFFFFFFFF causes the current position to be set to the end of the file.
943 If FileHandle is a directory, the only position that may be set is zero. This
944 has the effect of starting the read process of the directory entries over.
945
946 @param FileHandle The file handle on which the position is being set
947 @param Position Byte position from begining of file
948
949 @retval EFI_SUCCESS Operation completed sucessfully.
950 @retval EFI_UNSUPPORTED the seek request for non-zero is not valid on
951 directories.
952 @retval INVALID_PARAMETER One of the parameters has an invalid value.
953 **/
954 EFI_STATUS
955 EFIAPI
956 ShellSetFilePosition (
957 IN SHELL_FILE_HANDLE FileHandle,
958 IN UINT64 Position
959 )
960 {
961 return (FileFunctionMap.SetFilePosition(FileHandle, Position));
962 }
963
964 /**
965 Gets a file's current position
966
967 This function retrieves the current file position for the file handle. For
968 directories, the current file position has no meaning outside of the file
969 system driver and as such the operation is not supported. An error is returned
970 if FileHandle is a directory.
971
972 @param FileHandle The open file handle on which to get the position.
973 @param Position Byte position from begining of file.
974
975 @retval EFI_SUCCESS the operation completed sucessfully.
976 @retval INVALID_PARAMETER One of the parameters has an invalid value.
977 @retval EFI_UNSUPPORTED the request is not valid on directories.
978 **/
979 EFI_STATUS
980 EFIAPI
981 ShellGetFilePosition (
982 IN SHELL_FILE_HANDLE FileHandle,
983 OUT UINT64 *Position
984 )
985 {
986 return (FileFunctionMap.GetFilePosition(FileHandle, Position));
987 }
988 /**
989 Flushes data on a file
990
991 This function flushes all modified data associated with a file to a device.
992
993 @param FileHandle The file handle on which to flush data
994
995 @retval EFI_SUCCESS The data was flushed.
996 @retval EFI_NO_MEDIA The device has no media.
997 @retval EFI_DEVICE_ERROR The device reported an error.
998 @retval EFI_VOLUME_CORRUPTED The file system structures are corrupted.
999 @retval EFI_WRITE_PROTECTED The file or medium is write protected.
1000 @retval EFI_ACCESS_DENIED The file was opened for read only.
1001 **/
1002 EFI_STATUS
1003 EFIAPI
1004 ShellFlushFile (
1005 IN SHELL_FILE_HANDLE FileHandle
1006 )
1007 {
1008 return (FileFunctionMap.FlushFile(FileHandle));
1009 }
1010
1011 /** Retrieve first entry from a directory.
1012
1013 This function takes an open directory handle and gets information from the
1014 first entry in the directory. A buffer is allocated to contain
1015 the information and a pointer to the buffer is returned in *Buffer. The
1016 caller can use ShellFindNextFile() to get subsequent directory entries.
1017
1018 The buffer will be freed by ShellFindNextFile() when the last directory
1019 entry is read. Otherwise, the caller must free the buffer, using FreePool,
1020 when finished with it.
1021
1022 @param[in] DirHandle The file handle of the directory to search.
1023 @param[out] Buffer The pointer to the buffer for the file's information.
1024
1025 @retval EFI_SUCCESS Found the first file.
1026 @retval EFI_NOT_FOUND Cannot find the directory.
1027 @retval EFI_NO_MEDIA The device has no media.
1028 @retval EFI_DEVICE_ERROR The device reported an error.
1029 @retval EFI_VOLUME_CORRUPTED The file system structures are corrupted.
1030 @return Others status of ShellGetFileInfo, ShellSetFilePosition,
1031 or ShellReadFile
1032 **/
1033 EFI_STATUS
1034 EFIAPI
1035 ShellFindFirstFile (
1036 IN SHELL_FILE_HANDLE DirHandle,
1037 OUT EFI_FILE_INFO **Buffer
1038 )
1039 {
1040 //
1041 // pass to file handle lib
1042 //
1043 return (FileHandleFindFirstFile(DirHandle, Buffer));
1044 }
1045 /** Retrieve next entries from a directory.
1046
1047 To use this function, the caller must first call the ShellFindFirstFile()
1048 function to get the first directory entry. Subsequent directory entries are
1049 retrieved by using the ShellFindNextFile() function. This function can
1050 be called several times to get each entry from the directory. If the call of
1051 ShellFindNextFile() retrieved the last directory entry, the next call of
1052 this function will set *NoFile to TRUE and free the buffer.
1053
1054 @param[in] DirHandle The file handle of the directory.
1055 @param[out] Buffer The pointer to buffer for file's information.
1056 @param[out] NoFile The pointer to boolean when last file is found.
1057
1058 @retval EFI_SUCCESS Found the next file, or reached last file
1059 @retval EFI_NO_MEDIA The device has no media.
1060 @retval EFI_DEVICE_ERROR The device reported an error.
1061 @retval EFI_VOLUME_CORRUPTED The file system structures are corrupted.
1062 **/
1063 EFI_STATUS
1064 EFIAPI
1065 ShellFindNextFile(
1066 IN SHELL_FILE_HANDLE DirHandle,
1067 OUT EFI_FILE_INFO *Buffer,
1068 OUT BOOLEAN *NoFile
1069 )
1070 {
1071 //
1072 // pass to file handle lib
1073 //
1074 return (FileHandleFindNextFile(DirHandle, Buffer, NoFile));
1075 }
1076 /**
1077 Retrieve the size of a file.
1078
1079 if FileHandle is NULL then ASSERT()
1080 if Size is NULL then ASSERT()
1081
1082 This function extracts the file size info from the FileHandle's EFI_FILE_INFO
1083 data.
1084
1085 @param FileHandle file handle from which size is retrieved
1086 @param Size pointer to size
1087
1088 @retval EFI_SUCCESS operation was completed sucessfully
1089 @retval EFI_DEVICE_ERROR cannot access the file
1090 **/
1091 EFI_STATUS
1092 EFIAPI
1093 ShellGetFileSize (
1094 IN SHELL_FILE_HANDLE FileHandle,
1095 OUT UINT64 *Size
1096 )
1097 {
1098 return (FileFunctionMap.GetFileSize(FileHandle, Size));
1099 }
1100 /**
1101 Retrieves the status of the break execution flag
1102
1103 this function is useful to check whether the application is being asked to halt by the shell.
1104
1105 @retval TRUE the execution break is enabled
1106 @retval FALSE the execution break is not enabled
1107 **/
1108 BOOLEAN
1109 EFIAPI
1110 ShellGetExecutionBreakFlag(
1111 VOID
1112 )
1113 {
1114 //
1115 // Check for UEFI Shell 2.0 protocols
1116 //
1117 if (gEfiShellProtocol != NULL) {
1118
1119 //
1120 // We are using UEFI Shell 2.0; see if the event has been triggered
1121 //
1122 if (gBS->CheckEvent(gEfiShellProtocol->ExecutionBreak) != EFI_SUCCESS) {
1123 return (FALSE);
1124 }
1125 return (TRUE);
1126 }
1127
1128 //
1129 // using EFI Shell; call the function to check
1130 //
1131 if (mEfiShellEnvironment2 != NULL) {
1132 return (mEfiShellEnvironment2->GetExecutionBreak());
1133 }
1134
1135 return (FALSE);
1136 }
1137 /**
1138 return the value of an environment variable
1139
1140 this function gets the value of the environment variable set by the
1141 ShellSetEnvironmentVariable function
1142
1143 @param EnvKey The key name of the environment variable.
1144
1145 @retval NULL the named environment variable does not exist.
1146 @return != NULL pointer to the value of the environment variable
1147 **/
1148 CONST CHAR16*
1149 EFIAPI
1150 ShellGetEnvironmentVariable (
1151 IN CONST CHAR16 *EnvKey
1152 )
1153 {
1154 //
1155 // Check for UEFI Shell 2.0 protocols
1156 //
1157 if (gEfiShellProtocol != NULL) {
1158 return (gEfiShellProtocol->GetEnv(EnvKey));
1159 }
1160
1161 //
1162 // Check for EFI shell
1163 //
1164 if (mEfiShellEnvironment2 != NULL) {
1165 return (mEfiShellEnvironment2->GetEnv((CHAR16*)EnvKey));
1166 }
1167
1168 return NULL;
1169 }
1170 /**
1171 set the value of an environment variable
1172
1173 This function changes the current value of the specified environment variable. If the
1174 environment variable exists and the Value is an empty string, then the environment
1175 variable is deleted. If the environment variable exists and the Value is not an empty
1176 string, then the value of the environment variable is changed. If the environment
1177 variable does not exist and the Value is an empty string, there is no action. If the
1178 environment variable does not exist and the Value is a non-empty string, then the
1179 environment variable is created and assigned the specified value.
1180
1181 This is not supported pre-UEFI Shell 2.0.
1182
1183 @param EnvKey The key name of the environment variable.
1184 @param EnvVal The Value of the environment variable
1185 @param Volatile Indicates whether the variable is non-volatile (FALSE) or volatile (TRUE).
1186
1187 @retval EFI_SUCCESS the operation was completed sucessfully
1188 @retval EFI_UNSUPPORTED This operation is not allowed in pre UEFI 2.0 Shell environments
1189 **/
1190 EFI_STATUS
1191 EFIAPI
1192 ShellSetEnvironmentVariable (
1193 IN CONST CHAR16 *EnvKey,
1194 IN CONST CHAR16 *EnvVal,
1195 IN BOOLEAN Volatile
1196 )
1197 {
1198 //
1199 // Check for UEFI Shell 2.0 protocols
1200 //
1201 if (gEfiShellProtocol != NULL) {
1202 return (gEfiShellProtocol->SetEnv(EnvKey, EnvVal, Volatile));
1203 }
1204
1205 //
1206 // This feature does not exist under EFI shell
1207 //
1208 return (EFI_UNSUPPORTED);
1209 }
1210
1211 /**
1212 Cause the shell to parse and execute a command line.
1213
1214 This function creates a nested instance of the shell and executes the specified
1215 command (CommandLine) with the specified environment (Environment). Upon return,
1216 the status code returned by the specified command is placed in StatusCode.
1217 If Environment is NULL, then the current environment is used and all changes made
1218 by the commands executed will be reflected in the current environment. If the
1219 Environment is non-NULL, then the changes made will be discarded.
1220 The CommandLine is executed from the current working directory on the current
1221 device.
1222
1223 The EnvironmentVariables pararemeter is ignored in a pre-UEFI Shell 2.0
1224 environment. The values pointed to by the parameters will be unchanged by the
1225 ShellExecute() function. The Output parameter has no effect in a
1226 UEFI Shell 2.0 environment.
1227
1228 @param[in] ParentHandle The parent image starting the operation.
1229 @param[in] CommandLine The pointer to a NULL terminated command line.
1230 @param[in] Output True to display debug output. False to hide it.
1231 @param[in] EnvironmentVariables Optional pointer to array of environment variables
1232 in the form "x=y". If NULL, the current set is used.
1233 @param[out] Status The status of the run command line.
1234
1235 @retval EFI_SUCCESS The operation completed sucessfully. Status
1236 contains the status code returned.
1237 @retval EFI_INVALID_PARAMETER A parameter contains an invalid value.
1238 @retval EFI_OUT_OF_RESOURCES Out of resources.
1239 @retval EFI_UNSUPPORTED The operation is not allowed.
1240 **/
1241 EFI_STATUS
1242 EFIAPI
1243 ShellExecute (
1244 IN EFI_HANDLE *ParentHandle,
1245 IN CHAR16 *CommandLine OPTIONAL,
1246 IN BOOLEAN Output OPTIONAL,
1247 IN CHAR16 **EnvironmentVariables OPTIONAL,
1248 OUT EFI_STATUS *Status OPTIONAL
1249 )
1250 {
1251 EFI_STATUS CmdStatus;
1252 //
1253 // Check for UEFI Shell 2.0 protocols
1254 //
1255 if (gEfiShellProtocol != NULL) {
1256 //
1257 // Call UEFI Shell 2.0 version (not using Output parameter)
1258 //
1259 return (gEfiShellProtocol->Execute(ParentHandle,
1260 CommandLine,
1261 EnvironmentVariables,
1262 Status));
1263 }
1264
1265 //
1266 // Check for EFI shell
1267 //
1268 if (mEfiShellEnvironment2 != NULL) {
1269 //
1270 // Call EFI Shell version.
1271 // Due to oddity in the EFI shell we want to dereference the ParentHandle here
1272 //
1273 CmdStatus = (mEfiShellEnvironment2->Execute(*ParentHandle,
1274 CommandLine,
1275 Output));
1276 //
1277 // No Status output parameter so just use the returned status
1278 //
1279 if (Status != NULL) {
1280 *Status = CmdStatus;
1281 }
1282 //
1283 // If there was an error, we can't tell if it was from the command or from
1284 // the Execute() function, so we'll just assume the shell ran successfully
1285 // and the error came from the command.
1286 //
1287 return EFI_SUCCESS;
1288 }
1289
1290 return (EFI_UNSUPPORTED);
1291 }
1292
1293 /**
1294 Retreives the current directory path
1295
1296 If the DeviceName is NULL, it returns the current device's current directory
1297 name. If the DeviceName is not NULL, it returns the current directory name
1298 on specified drive.
1299
1300 Note that the current directory string should exclude the tailing backslash character.
1301
1302 @param DeviceName the name of the drive to get directory on
1303
1304 @retval NULL the directory does not exist
1305 @return != NULL the directory
1306 **/
1307 CONST CHAR16*
1308 EFIAPI
1309 ShellGetCurrentDir (
1310 IN CHAR16 * CONST DeviceName OPTIONAL
1311 )
1312 {
1313 //
1314 // Check for UEFI Shell 2.0 protocols
1315 //
1316 if (gEfiShellProtocol != NULL) {
1317 return (gEfiShellProtocol->GetCurDir(DeviceName));
1318 }
1319
1320 //
1321 // Check for EFI shell
1322 //
1323 if (mEfiShellEnvironment2 != NULL) {
1324 return (mEfiShellEnvironment2->CurDir(DeviceName));
1325 }
1326
1327 return (NULL);
1328 }
1329 /**
1330 sets (enabled or disabled) the page break mode
1331
1332 when page break mode is enabled the screen will stop scrolling
1333 and wait for operator input before scrolling a subsequent screen.
1334
1335 @param CurrentState TRUE to enable and FALSE to disable
1336 **/
1337 VOID
1338 EFIAPI
1339 ShellSetPageBreakMode (
1340 IN BOOLEAN CurrentState
1341 )
1342 {
1343 //
1344 // check for enabling
1345 //
1346 if (CurrentState != 0x00) {
1347 //
1348 // check for UEFI Shell 2.0
1349 //
1350 if (gEfiShellProtocol != NULL) {
1351 //
1352 // Enable with UEFI 2.0 Shell
1353 //
1354 gEfiShellProtocol->EnablePageBreak();
1355 return;
1356 } else {
1357 //
1358 // Check for EFI shell
1359 //
1360 if (mEfiShellEnvironment2 != NULL) {
1361 //
1362 // Enable with EFI Shell
1363 //
1364 mEfiShellEnvironment2->EnablePageBreak (DEFAULT_INIT_ROW, DEFAULT_AUTO_LF);
1365 return;
1366 }
1367 }
1368 } else {
1369 //
1370 // check for UEFI Shell 2.0
1371 //
1372 if (gEfiShellProtocol != NULL) {
1373 //
1374 // Disable with UEFI 2.0 Shell
1375 //
1376 gEfiShellProtocol->DisablePageBreak();
1377 return;
1378 } else {
1379 //
1380 // Check for EFI shell
1381 //
1382 if (mEfiShellEnvironment2 != NULL) {
1383 //
1384 // Disable with EFI Shell
1385 //
1386 mEfiShellEnvironment2->DisablePageBreak ();
1387 return;
1388 }
1389 }
1390 }
1391 }
1392
1393 ///
1394 /// version of EFI_SHELL_FILE_INFO struct, except has no CONST pointers.
1395 /// This allows for the struct to be populated.
1396 ///
1397 typedef struct {
1398 LIST_ENTRY Link;
1399 EFI_STATUS Status;
1400 CHAR16 *FullName;
1401 CHAR16 *FileName;
1402 SHELL_FILE_HANDLE Handle;
1403 EFI_FILE_INFO *Info;
1404 } EFI_SHELL_FILE_INFO_NO_CONST;
1405
1406 /**
1407 Converts a EFI shell list of structures to the coresponding UEFI Shell 2.0 type of list.
1408
1409 if OldStyleFileList is NULL then ASSERT()
1410
1411 this function will convert a SHELL_FILE_ARG based list into a callee allocated
1412 EFI_SHELL_FILE_INFO based list. it is up to the caller to free the memory via
1413 the ShellCloseFileMetaArg function.
1414
1415 @param[in] FileList the EFI shell list type
1416 @param[in, out] ListHead the list to add to
1417
1418 @retval the resultant head of the double linked new format list;
1419 **/
1420 LIST_ENTRY*
1421 EFIAPI
1422 InternalShellConvertFileListType (
1423 IN LIST_ENTRY *FileList,
1424 IN OUT LIST_ENTRY *ListHead
1425 )
1426 {
1427 SHELL_FILE_ARG *OldInfo;
1428 LIST_ENTRY *Link;
1429 EFI_SHELL_FILE_INFO_NO_CONST *NewInfo;
1430
1431 //
1432 // ASSERTs
1433 //
1434 ASSERT(FileList != NULL);
1435 ASSERT(ListHead != NULL);
1436
1437 //
1438 // enumerate through each member of the old list and copy
1439 //
1440 for (Link = FileList->ForwardLink; Link != FileList; Link = Link->ForwardLink) {
1441 OldInfo = CR (Link, SHELL_FILE_ARG, Link, SHELL_FILE_ARG_SIGNATURE);
1442 ASSERT(OldInfo != NULL);
1443
1444 //
1445 // Skip ones that failed to open...
1446 //
1447 if (OldInfo->Status != EFI_SUCCESS) {
1448 continue;
1449 }
1450
1451 //
1452 // make sure the old list was valid
1453 //
1454 ASSERT(OldInfo->Info != NULL);
1455 ASSERT(OldInfo->FullName != NULL);
1456 ASSERT(OldInfo->FileName != NULL);
1457
1458 //
1459 // allocate a new EFI_SHELL_FILE_INFO object
1460 //
1461 NewInfo = AllocateZeroPool(sizeof(EFI_SHELL_FILE_INFO));
1462 if (NewInfo == NULL) {
1463 ShellCloseFileMetaArg((EFI_SHELL_FILE_INFO**)(&ListHead));
1464 ListHead = NULL;
1465 break;
1466 }
1467
1468 //
1469 // copy the simple items
1470 //
1471 NewInfo->Handle = OldInfo->Handle;
1472 NewInfo->Status = OldInfo->Status;
1473
1474 // old shell checks for 0 not NULL
1475 OldInfo->Handle = 0;
1476
1477 //
1478 // allocate new space to copy strings and structure
1479 //
1480 NewInfo->FullName = AllocateCopyPool(StrSize(OldInfo->FullName), OldInfo->FullName);
1481 NewInfo->FileName = AllocateCopyPool(StrSize(OldInfo->FileName), OldInfo->FileName);
1482 NewInfo->Info = AllocateCopyPool((UINTN)OldInfo->Info->Size, OldInfo->Info);
1483
1484 //
1485 // make sure all the memory allocations were sucessful
1486 //
1487 if (NULL == NewInfo->FullName || NewInfo->FileName == NULL || NewInfo->Info == NULL) {
1488 //
1489 // Free the partially allocated new node
1490 //
1491 SHELL_FREE_NON_NULL(NewInfo->FullName);
1492 SHELL_FREE_NON_NULL(NewInfo->FileName);
1493 SHELL_FREE_NON_NULL(NewInfo->Info);
1494 SHELL_FREE_NON_NULL(NewInfo);
1495
1496 //
1497 // Free the previously converted stuff
1498 //
1499 ShellCloseFileMetaArg((EFI_SHELL_FILE_INFO**)(&ListHead));
1500 ListHead = NULL;
1501 break;
1502 }
1503
1504 //
1505 // add that to the list
1506 //
1507 InsertTailList(ListHead, &NewInfo->Link);
1508 }
1509 return (ListHead);
1510 }
1511 /**
1512 Opens a group of files based on a path.
1513
1514 This function uses the Arg to open all the matching files. Each matched
1515 file has a SHELL_FILE_INFO structure to record the file information. These
1516 structures are placed on the list ListHead. Users can get the SHELL_FILE_INFO
1517 structures from ListHead to access each file. This function supports wildcards
1518 and will process '?' and '*' as such. the list must be freed with a call to
1519 ShellCloseFileMetaArg().
1520
1521 If you are NOT appending to an existing list *ListHead must be NULL. If
1522 *ListHead is NULL then it must be callee freed.
1523
1524 @param Arg pointer to path string
1525 @param OpenMode mode to open files with
1526 @param ListHead head of linked list of results
1527
1528 @retval EFI_SUCCESS the operation was sucessful and the list head
1529 contains the list of opened files
1530 @return != EFI_SUCCESS the operation failed
1531
1532 @sa InternalShellConvertFileListType
1533 **/
1534 EFI_STATUS
1535 EFIAPI
1536 ShellOpenFileMetaArg (
1537 IN CHAR16 *Arg,
1538 IN UINT64 OpenMode,
1539 IN OUT EFI_SHELL_FILE_INFO **ListHead
1540 )
1541 {
1542 EFI_STATUS Status;
1543 LIST_ENTRY mOldStyleFileList;
1544 CHAR16 *CleanFilePathStr;
1545
1546 //
1547 // ASSERT that Arg and ListHead are not NULL
1548 //
1549 ASSERT(Arg != NULL);
1550 ASSERT(ListHead != NULL);
1551
1552 CleanFilePathStr = NULL;
1553
1554 Status = InternalShellStripQuotes (Arg, &CleanFilePathStr);
1555 if (EFI_ERROR (Status)) {
1556 return Status;
1557 }
1558
1559 //
1560 // Check for UEFI Shell 2.0 protocols
1561 //
1562 if (gEfiShellProtocol != NULL) {
1563 if (*ListHead == NULL) {
1564 *ListHead = (EFI_SHELL_FILE_INFO*)AllocateZeroPool(sizeof(EFI_SHELL_FILE_INFO));
1565 if (*ListHead == NULL) {
1566 FreePool(CleanFilePathStr);
1567 return (EFI_OUT_OF_RESOURCES);
1568 }
1569 InitializeListHead(&((*ListHead)->Link));
1570 }
1571 Status = gEfiShellProtocol->OpenFileList(CleanFilePathStr,
1572 OpenMode,
1573 ListHead);
1574 if (EFI_ERROR(Status)) {
1575 gEfiShellProtocol->RemoveDupInFileList(ListHead);
1576 } else {
1577 Status = gEfiShellProtocol->RemoveDupInFileList(ListHead);
1578 }
1579 if (*ListHead != NULL && IsListEmpty(&(*ListHead)->Link)) {
1580 FreePool(*ListHead);
1581 FreePool(CleanFilePathStr);
1582 *ListHead = NULL;
1583 return (EFI_NOT_FOUND);
1584 }
1585 FreePool(CleanFilePathStr);
1586 return (Status);
1587 }
1588
1589 //
1590 // Check for EFI shell
1591 //
1592 if (mEfiShellEnvironment2 != NULL) {
1593 //
1594 // make sure the list head is initialized
1595 //
1596 InitializeListHead(&mOldStyleFileList);
1597
1598 //
1599 // Get the EFI Shell list of files
1600 //
1601 Status = mEfiShellEnvironment2->FileMetaArg(CleanFilePathStr, &mOldStyleFileList);
1602 if (EFI_ERROR(Status)) {
1603 *ListHead = NULL;
1604 FreePool(CleanFilePathStr);
1605 return (Status);
1606 }
1607
1608 if (*ListHead == NULL) {
1609 *ListHead = (EFI_SHELL_FILE_INFO *)AllocateZeroPool(sizeof(EFI_SHELL_FILE_INFO));
1610 if (*ListHead == NULL) {
1611 FreePool(CleanFilePathStr);
1612 return (EFI_OUT_OF_RESOURCES);
1613 }
1614 InitializeListHead(&((*ListHead)->Link));
1615 }
1616
1617 //
1618 // Convert that to equivalent of UEFI Shell 2.0 structure
1619 //
1620 InternalShellConvertFileListType(&mOldStyleFileList, &(*ListHead)->Link);
1621
1622 //
1623 // Free the EFI Shell version that was converted.
1624 //
1625 mEfiShellEnvironment2->FreeFileList(&mOldStyleFileList);
1626
1627 if ((*ListHead)->Link.ForwardLink == (*ListHead)->Link.BackLink && (*ListHead)->Link.BackLink == &((*ListHead)->Link)) {
1628 FreePool(*ListHead);
1629 *ListHead = NULL;
1630 Status = EFI_NOT_FOUND;
1631 }
1632 FreePool(CleanFilePathStr);
1633 return (Status);
1634 }
1635
1636 FreePool(CleanFilePathStr);
1637 return (EFI_UNSUPPORTED);
1638 }
1639 /**
1640 Free the linked list returned from ShellOpenFileMetaArg.
1641
1642 if ListHead is NULL then ASSERT().
1643
1644 @param ListHead the pointer to free.
1645
1646 @retval EFI_SUCCESS the operation was sucessful.
1647 **/
1648 EFI_STATUS
1649 EFIAPI
1650 ShellCloseFileMetaArg (
1651 IN OUT EFI_SHELL_FILE_INFO **ListHead
1652 )
1653 {
1654 LIST_ENTRY *Node;
1655
1656 //
1657 // ASSERT that ListHead is not NULL
1658 //
1659 ASSERT(ListHead != NULL);
1660
1661 //
1662 // Check for UEFI Shell 2.0 protocols
1663 //
1664 if (gEfiShellProtocol != NULL) {
1665 return (gEfiShellProtocol->FreeFileList(ListHead));
1666 } else if (mEfiShellEnvironment2 != NULL) {
1667 //
1668 // Since this is EFI Shell version we need to free our internally made copy
1669 // of the list
1670 //
1671 for ( Node = GetFirstNode(&(*ListHead)->Link)
1672 ; *ListHead != NULL && !IsListEmpty(&(*ListHead)->Link)
1673 ; Node = GetFirstNode(&(*ListHead)->Link)) {
1674 RemoveEntryList(Node);
1675 ((EFI_FILE_PROTOCOL*)((EFI_SHELL_FILE_INFO_NO_CONST*)Node)->Handle)->Close(((EFI_SHELL_FILE_INFO_NO_CONST*)Node)->Handle);
1676 FreePool(((EFI_SHELL_FILE_INFO_NO_CONST*)Node)->FullName);
1677 FreePool(((EFI_SHELL_FILE_INFO_NO_CONST*)Node)->FileName);
1678 FreePool(((EFI_SHELL_FILE_INFO_NO_CONST*)Node)->Info);
1679 FreePool((EFI_SHELL_FILE_INFO_NO_CONST*)Node);
1680 }
1681 SHELL_FREE_NON_NULL(*ListHead);
1682 return EFI_SUCCESS;
1683 }
1684
1685 return (EFI_UNSUPPORTED);
1686 }
1687
1688 /**
1689 Find a file by searching the CWD and then the path.
1690
1691 If FileName is NULL then ASSERT.
1692
1693 If the return value is not NULL then the memory must be caller freed.
1694
1695 @param FileName Filename string.
1696
1697 @retval NULL the file was not found
1698 @return !NULL the full path to the file.
1699 **/
1700 CHAR16 *
1701 EFIAPI
1702 ShellFindFilePath (
1703 IN CONST CHAR16 *FileName
1704 )
1705 {
1706 CONST CHAR16 *Path;
1707 SHELL_FILE_HANDLE Handle;
1708 EFI_STATUS Status;
1709 CHAR16 *RetVal;
1710 CHAR16 *TestPath;
1711 CONST CHAR16 *Walker;
1712 UINTN Size;
1713 CHAR16 *TempChar;
1714
1715 RetVal = NULL;
1716
1717 //
1718 // First make sure its not an absolute path.
1719 //
1720 Status = ShellOpenFileByName(FileName, &Handle, EFI_FILE_MODE_READ, 0);
1721 if (!EFI_ERROR(Status)){
1722 if (FileHandleIsDirectory(Handle) != EFI_SUCCESS) {
1723 ASSERT(RetVal == NULL);
1724 RetVal = StrnCatGrow(&RetVal, NULL, FileName, 0);
1725 ShellCloseFile(&Handle);
1726 return (RetVal);
1727 } else {
1728 ShellCloseFile(&Handle);
1729 }
1730 }
1731
1732 Path = ShellGetEnvironmentVariable(L"cwd");
1733 if (Path != NULL) {
1734 Size = StrSize(Path) + sizeof(CHAR16);
1735 Size += StrSize(FileName);
1736 TestPath = AllocateZeroPool(Size);
1737 if (TestPath == NULL) {
1738 return (NULL);
1739 }
1740 StrCpyS(TestPath, Size/sizeof(CHAR16), Path);
1741 StrCatS(TestPath, Size/sizeof(CHAR16), L"\\");
1742 StrCatS(TestPath, Size/sizeof(CHAR16), FileName);
1743 Status = ShellOpenFileByName(TestPath, &Handle, EFI_FILE_MODE_READ, 0);
1744 if (!EFI_ERROR(Status)){
1745 if (FileHandleIsDirectory(Handle) != EFI_SUCCESS) {
1746 ASSERT(RetVal == NULL);
1747 RetVal = StrnCatGrow(&RetVal, NULL, TestPath, 0);
1748 ShellCloseFile(&Handle);
1749 FreePool(TestPath);
1750 return (RetVal);
1751 } else {
1752 ShellCloseFile(&Handle);
1753 }
1754 }
1755 FreePool(TestPath);
1756 }
1757 Path = ShellGetEnvironmentVariable(L"path");
1758 if (Path != NULL) {
1759 Size = StrSize(Path)+sizeof(CHAR16);
1760 Size += StrSize(FileName);
1761 TestPath = AllocateZeroPool(Size);
1762 if (TestPath == NULL) {
1763 return (NULL);
1764 }
1765 Walker = (CHAR16*)Path;
1766 do {
1767 CopyMem(TestPath, Walker, StrSize(Walker));
1768 if (TestPath != NULL) {
1769 TempChar = StrStr(TestPath, L";");
1770 if (TempChar != NULL) {
1771 *TempChar = CHAR_NULL;
1772 }
1773 if (TestPath[StrLen(TestPath)-1] != L'\\') {
1774 StrCatS(TestPath, Size/sizeof(CHAR16), L"\\");
1775 }
1776 if (FileName[0] == L'\\') {
1777 FileName++;
1778 }
1779 StrCatS(TestPath, Size/sizeof(CHAR16), FileName);
1780 if (StrStr(Walker, L";") != NULL) {
1781 Walker = StrStr(Walker, L";") + 1;
1782 } else {
1783 Walker = NULL;
1784 }
1785 Status = ShellOpenFileByName(TestPath, &Handle, EFI_FILE_MODE_READ, 0);
1786 if (!EFI_ERROR(Status)){
1787 if (FileHandleIsDirectory(Handle) != EFI_SUCCESS) {
1788 ASSERT(RetVal == NULL);
1789 RetVal = StrnCatGrow(&RetVal, NULL, TestPath, 0);
1790 ShellCloseFile(&Handle);
1791 break;
1792 } else {
1793 ShellCloseFile(&Handle);
1794 }
1795 }
1796 }
1797 } while (Walker != NULL && Walker[0] != CHAR_NULL);
1798 FreePool(TestPath);
1799 }
1800 return (RetVal);
1801 }
1802
1803 /**
1804 Find a file by searching the CWD and then the path with a variable set of file
1805 extensions. If the file is not found it will append each extension in the list
1806 in the order provided and return the first one that is successful.
1807
1808 If FileName is NULL, then ASSERT.
1809 If FileExtension is NULL, then behavior is identical to ShellFindFilePath.
1810
1811 If the return value is not NULL then the memory must be caller freed.
1812
1813 @param[in] FileName Filename string.
1814 @param[in] FileExtension Semi-colon delimeted list of possible extensions.
1815
1816 @retval NULL The file was not found.
1817 @retval !NULL The path to the file.
1818 **/
1819 CHAR16 *
1820 EFIAPI
1821 ShellFindFilePathEx (
1822 IN CONST CHAR16 *FileName,
1823 IN CONST CHAR16 *FileExtension
1824 )
1825 {
1826 CHAR16 *TestPath;
1827 CHAR16 *RetVal;
1828 CONST CHAR16 *ExtensionWalker;
1829 UINTN Size;
1830 CHAR16 *TempChar;
1831 CHAR16 *TempChar2;
1832
1833 ASSERT(FileName != NULL);
1834 if (FileExtension == NULL) {
1835 return (ShellFindFilePath(FileName));
1836 }
1837 RetVal = ShellFindFilePath(FileName);
1838 if (RetVal != NULL) {
1839 return (RetVal);
1840 }
1841 Size = StrSize(FileName);
1842 Size += StrSize(FileExtension);
1843 TestPath = AllocateZeroPool(Size);
1844 if (TestPath == NULL) {
1845 return (NULL);
1846 }
1847 for (ExtensionWalker = FileExtension, TempChar2 = (CHAR16*)FileExtension; TempChar2 != NULL ; ExtensionWalker = TempChar2 + 1){
1848 StrCpyS(TestPath, Size/sizeof(CHAR16), FileName);
1849 if (ExtensionWalker != NULL) {
1850 StrCatS(TestPath, Size/sizeof(CHAR16), ExtensionWalker);
1851 }
1852 TempChar = StrStr(TestPath, L";");
1853 if (TempChar != NULL) {
1854 *TempChar = CHAR_NULL;
1855 }
1856 RetVal = ShellFindFilePath(TestPath);
1857 if (RetVal != NULL) {
1858 break;
1859 }
1860 ASSERT(ExtensionWalker != NULL);
1861 TempChar2 = StrStr(ExtensionWalker, L";");
1862 }
1863 FreePool(TestPath);
1864 return (RetVal);
1865 }
1866
1867 typedef struct {
1868 LIST_ENTRY Link;
1869 CHAR16 *Name;
1870 SHELL_PARAM_TYPE Type;
1871 CHAR16 *Value;
1872 UINTN OriginalPosition;
1873 } SHELL_PARAM_PACKAGE;
1874
1875 /**
1876 Checks the list of valid arguments and returns TRUE if the item was found. If the
1877 return value is TRUE then the type parameter is set also.
1878
1879 if CheckList is NULL then ASSERT();
1880 if Name is NULL then ASSERT();
1881 if Type is NULL then ASSERT();
1882
1883 @param Name pointer to Name of parameter found
1884 @param CheckList List to check against
1885 @param Type pointer to type of parameter if it was found
1886
1887 @retval TRUE the Parameter was found. Type is valid.
1888 @retval FALSE the Parameter was not found. Type is not valid.
1889 **/
1890 BOOLEAN
1891 EFIAPI
1892 InternalIsOnCheckList (
1893 IN CONST CHAR16 *Name,
1894 IN CONST SHELL_PARAM_ITEM *CheckList,
1895 OUT SHELL_PARAM_TYPE *Type
1896 )
1897 {
1898 SHELL_PARAM_ITEM *TempListItem;
1899 CHAR16 *TempString;
1900
1901 //
1902 // ASSERT that all 3 pointer parameters aren't NULL
1903 //
1904 ASSERT(CheckList != NULL);
1905 ASSERT(Type != NULL);
1906 ASSERT(Name != NULL);
1907
1908 //
1909 // question mark and page break mode are always supported
1910 //
1911 if ((StrCmp(Name, L"-?") == 0) ||
1912 (StrCmp(Name, L"-b") == 0)
1913 ) {
1914 *Type = TypeFlag;
1915 return (TRUE);
1916 }
1917
1918 //
1919 // Enumerate through the list
1920 //
1921 for (TempListItem = (SHELL_PARAM_ITEM*)CheckList ; TempListItem->Name != NULL ; TempListItem++) {
1922 //
1923 // If the Type is TypeStart only check the first characters of the passed in param
1924 // If it matches set the type and return TRUE
1925 //
1926 if (TempListItem->Type == TypeStart) {
1927 if (StrnCmp(Name, TempListItem->Name, StrLen(TempListItem->Name)) == 0) {
1928 *Type = TempListItem->Type;
1929 return (TRUE);
1930 }
1931 TempString = NULL;
1932 TempString = StrnCatGrow(&TempString, NULL, Name, StrLen(TempListItem->Name));
1933 if (TempString != NULL) {
1934 if (StringNoCaseCompare(&TempString, &TempListItem->Name) == 0) {
1935 *Type = TempListItem->Type;
1936 FreePool(TempString);
1937 return (TRUE);
1938 }
1939 FreePool(TempString);
1940 }
1941 } else if (StringNoCaseCompare(&Name, &TempListItem->Name) == 0) {
1942 *Type = TempListItem->Type;
1943 return (TRUE);
1944 }
1945 }
1946
1947 return (FALSE);
1948 }
1949 /**
1950 Checks the string for indicators of "flag" status. this is a leading '/', '-', or '+'
1951
1952 @param[in] Name pointer to Name of parameter found
1953 @param[in] AlwaysAllowNumbers TRUE to allow numbers, FALSE to not.
1954 @param[in] TimeNumbers TRUE to allow numbers with ":", FALSE otherwise.
1955
1956 @retval TRUE the Parameter is a flag.
1957 @retval FALSE the Parameter not a flag.
1958 **/
1959 BOOLEAN
1960 EFIAPI
1961 InternalIsFlag (
1962 IN CONST CHAR16 *Name,
1963 IN CONST BOOLEAN AlwaysAllowNumbers,
1964 IN CONST BOOLEAN TimeNumbers
1965 )
1966 {
1967 //
1968 // ASSERT that Name isn't NULL
1969 //
1970 ASSERT(Name != NULL);
1971
1972 //
1973 // If we accept numbers then dont return TRUE. (they will be values)
1974 //
1975 if (((Name[0] == L'-' || Name[0] == L'+') && InternalShellIsHexOrDecimalNumber(Name+1, FALSE, FALSE, TimeNumbers)) && AlwaysAllowNumbers) {
1976 return (FALSE);
1977 }
1978
1979 //
1980 // If the Name has a /, +, or - as the first character return TRUE
1981 //
1982 if ((Name[0] == L'/') ||
1983 (Name[0] == L'-') ||
1984 (Name[0] == L'+')
1985 ) {
1986 return (TRUE);
1987 }
1988 return (FALSE);
1989 }
1990
1991 /**
1992 Checks the command line arguments passed against the list of valid ones.
1993
1994 If no initialization is required, then return RETURN_SUCCESS.
1995
1996 @param[in] CheckList pointer to list of parameters to check
1997 @param[out] CheckPackage pointer to pointer to list checked values
1998 @param[out] ProblemParam optional pointer to pointer to unicode string for
1999 the paramater that caused failure. If used then the
2000 caller is responsible for freeing the memory.
2001 @param[in] AutoPageBreak will automatically set PageBreakEnabled for "b" parameter
2002 @param[in] Argv pointer to array of parameters
2003 @param[in] Argc Count of parameters in Argv
2004 @param[in] AlwaysAllowNumbers TRUE to allow numbers always, FALSE otherwise.
2005
2006 @retval EFI_SUCCESS The operation completed sucessfully.
2007 @retval EFI_OUT_OF_RESOURCES A memory allocation failed
2008 @retval EFI_INVALID_PARAMETER A parameter was invalid
2009 @retval EFI_VOLUME_CORRUPTED the command line was corrupt. an argument was
2010 duplicated. the duplicated command line argument
2011 was returned in ProblemParam if provided.
2012 @retval EFI_NOT_FOUND a argument required a value that was missing.
2013 the invalid command line argument was returned in
2014 ProblemParam if provided.
2015 **/
2016 EFI_STATUS
2017 EFIAPI
2018 InternalCommandLineParse (
2019 IN CONST SHELL_PARAM_ITEM *CheckList,
2020 OUT LIST_ENTRY **CheckPackage,
2021 OUT CHAR16 **ProblemParam OPTIONAL,
2022 IN BOOLEAN AutoPageBreak,
2023 IN CONST CHAR16 **Argv,
2024 IN UINTN Argc,
2025 IN BOOLEAN AlwaysAllowNumbers
2026 )
2027 {
2028 UINTN LoopCounter;
2029 SHELL_PARAM_TYPE CurrentItemType;
2030 SHELL_PARAM_PACKAGE *CurrentItemPackage;
2031 UINTN GetItemValue;
2032 UINTN ValueSize;
2033 UINTN Count;
2034 CONST CHAR16 *TempPointer;
2035 UINTN CurrentValueSize;
2036 CHAR16 *NewValue;
2037
2038 CurrentItemPackage = NULL;
2039 GetItemValue = 0;
2040 ValueSize = 0;
2041 Count = 0;
2042
2043 //
2044 // If there is only 1 item we dont need to do anything
2045 //
2046 if (Argc < 1) {
2047 *CheckPackage = NULL;
2048 return (EFI_SUCCESS);
2049 }
2050
2051 //
2052 // ASSERTs
2053 //
2054 ASSERT(CheckList != NULL);
2055 ASSERT(Argv != NULL);
2056
2057 //
2058 // initialize the linked list
2059 //
2060 *CheckPackage = (LIST_ENTRY*)AllocateZeroPool(sizeof(LIST_ENTRY));
2061 if (*CheckPackage == NULL) {
2062 return (EFI_OUT_OF_RESOURCES);
2063 }
2064
2065 InitializeListHead(*CheckPackage);
2066
2067 //
2068 // loop through each of the arguments
2069 //
2070 for (LoopCounter = 0 ; LoopCounter < Argc ; ++LoopCounter) {
2071 if (Argv[LoopCounter] == NULL) {
2072 //
2073 // do nothing for NULL argv
2074 //
2075 } else if (InternalIsOnCheckList(Argv[LoopCounter], CheckList, &CurrentItemType)) {
2076 //
2077 // We might have leftover if last parameter didnt have optional value
2078 //
2079 if (GetItemValue != 0) {
2080 GetItemValue = 0;
2081 InsertHeadList(*CheckPackage, &CurrentItemPackage->Link);
2082 }
2083 //
2084 // this is a flag
2085 //
2086 CurrentItemPackage = AllocateZeroPool(sizeof(SHELL_PARAM_PACKAGE));
2087 if (CurrentItemPackage == NULL) {
2088 ShellCommandLineFreeVarList(*CheckPackage);
2089 *CheckPackage = NULL;
2090 return (EFI_OUT_OF_RESOURCES);
2091 }
2092 CurrentItemPackage->Name = AllocateCopyPool(StrSize(Argv[LoopCounter]), Argv[LoopCounter]);
2093 if (CurrentItemPackage->Name == NULL) {
2094 ShellCommandLineFreeVarList(*CheckPackage);
2095 *CheckPackage = NULL;
2096 return (EFI_OUT_OF_RESOURCES);
2097 }
2098 CurrentItemPackage->Type = CurrentItemType;
2099 CurrentItemPackage->OriginalPosition = (UINTN)(-1);
2100 CurrentItemPackage->Value = NULL;
2101
2102 //
2103 // Does this flag require a value
2104 //
2105 switch (CurrentItemPackage->Type) {
2106 //
2107 // possibly trigger the next loop(s) to populate the value of this item
2108 //
2109 case TypeValue:
2110 case TypeTimeValue:
2111 GetItemValue = 1;
2112 ValueSize = 0;
2113 break;
2114 case TypeDoubleValue:
2115 GetItemValue = 2;
2116 ValueSize = 0;
2117 break;
2118 case TypeMaxValue:
2119 GetItemValue = (UINTN)(-1);
2120 ValueSize = 0;
2121 break;
2122 default:
2123 //
2124 // this item has no value expected; we are done
2125 //
2126 InsertHeadList(*CheckPackage, &CurrentItemPackage->Link);
2127 ASSERT(GetItemValue == 0);
2128 break;
2129 }
2130 } else if (GetItemValue != 0 && CurrentItemPackage != NULL && !InternalIsFlag(Argv[LoopCounter], AlwaysAllowNumbers, (BOOLEAN)(CurrentItemPackage->Type == TypeTimeValue))) {
2131 //
2132 // get the item VALUE for a previous flag
2133 //
2134 CurrentValueSize = ValueSize + StrSize(Argv[LoopCounter]) + sizeof(CHAR16);
2135 NewValue = ReallocatePool(ValueSize, CurrentValueSize, CurrentItemPackage->Value);
2136 if (NewValue == NULL) {
2137 SHELL_FREE_NON_NULL (CurrentItemPackage->Value);
2138 SHELL_FREE_NON_NULL (CurrentItemPackage);
2139 ShellCommandLineFreeVarList (*CheckPackage);
2140 *CheckPackage = NULL;
2141 return EFI_OUT_OF_RESOURCES;
2142 }
2143 CurrentItemPackage->Value = NewValue;
2144 if (ValueSize == 0) {
2145 StrCpyS( CurrentItemPackage->Value,
2146 CurrentValueSize/sizeof(CHAR16),
2147 Argv[LoopCounter]
2148 );
2149 } else {
2150 StrCatS( CurrentItemPackage->Value,
2151 CurrentValueSize/sizeof(CHAR16),
2152 L" "
2153 );
2154 StrCatS( CurrentItemPackage->Value,
2155 CurrentValueSize/sizeof(CHAR16),
2156 Argv[LoopCounter]
2157 );
2158 }
2159 ValueSize += StrSize(Argv[LoopCounter]) + sizeof(CHAR16);
2160
2161 GetItemValue--;
2162 if (GetItemValue == 0) {
2163 InsertHeadList(*CheckPackage, &CurrentItemPackage->Link);
2164 }
2165 } else if (!InternalIsFlag(Argv[LoopCounter], AlwaysAllowNumbers, FALSE)){
2166 //
2167 // add this one as a non-flag
2168 //
2169
2170 TempPointer = Argv[LoopCounter];
2171 if ((*TempPointer == L'^' && *(TempPointer+1) == L'-')
2172 || (*TempPointer == L'^' && *(TempPointer+1) == L'/')
2173 || (*TempPointer == L'^' && *(TempPointer+1) == L'+')
2174 ){
2175 TempPointer++;
2176 }
2177 CurrentItemPackage = AllocateZeroPool(sizeof(SHELL_PARAM_PACKAGE));
2178 if (CurrentItemPackage == NULL) {
2179 ShellCommandLineFreeVarList(*CheckPackage);
2180 *CheckPackage = NULL;
2181 return (EFI_OUT_OF_RESOURCES);
2182 }
2183 CurrentItemPackage->Name = NULL;
2184 CurrentItemPackage->Type = TypePosition;
2185 CurrentItemPackage->Value = AllocateCopyPool(StrSize(TempPointer), TempPointer);
2186 if (CurrentItemPackage->Value == NULL) {
2187 ShellCommandLineFreeVarList(*CheckPackage);
2188 *CheckPackage = NULL;
2189 return (EFI_OUT_OF_RESOURCES);
2190 }
2191 CurrentItemPackage->OriginalPosition = Count++;
2192 InsertHeadList(*CheckPackage, &CurrentItemPackage->Link);
2193 } else {
2194 //
2195 // this was a non-recognised flag... error!
2196 //
2197 if (ProblemParam != NULL) {
2198 *ProblemParam = AllocateCopyPool(StrSize(Argv[LoopCounter]), Argv[LoopCounter]);
2199 }
2200 ShellCommandLineFreeVarList(*CheckPackage);
2201 *CheckPackage = NULL;
2202 return (EFI_VOLUME_CORRUPTED);
2203 }
2204 }
2205 if (GetItemValue != 0) {
2206 GetItemValue = 0;
2207 InsertHeadList(*CheckPackage, &CurrentItemPackage->Link);
2208 }
2209 //
2210 // support for AutoPageBreak
2211 //
2212 if (AutoPageBreak && ShellCommandLineGetFlag(*CheckPackage, L"-b")) {
2213 ShellSetPageBreakMode(TRUE);
2214 }
2215 return (EFI_SUCCESS);
2216 }
2217
2218 /**
2219 Checks the command line arguments passed against the list of valid ones.
2220 Optionally removes NULL values first.
2221
2222 If no initialization is required, then return RETURN_SUCCESS.
2223
2224 @param[in] CheckList The pointer to list of parameters to check.
2225 @param[out] CheckPackage The package of checked values.
2226 @param[out] ProblemParam Optional pointer to pointer to unicode string for
2227 the paramater that caused failure.
2228 @param[in] AutoPageBreak Will automatically set PageBreakEnabled.
2229 @param[in] AlwaysAllowNumbers Will never fail for number based flags.
2230
2231 @retval EFI_SUCCESS The operation completed sucessfully.
2232 @retval EFI_OUT_OF_RESOURCES A memory allocation failed.
2233 @retval EFI_INVALID_PARAMETER A parameter was invalid.
2234 @retval EFI_VOLUME_CORRUPTED The command line was corrupt.
2235 @retval EFI_DEVICE_ERROR The commands contained 2 opposing arguments. One
2236 of the command line arguments was returned in
2237 ProblemParam if provided.
2238 @retval EFI_NOT_FOUND A argument required a value that was missing.
2239 The invalid command line argument was returned in
2240 ProblemParam if provided.
2241 **/
2242 EFI_STATUS
2243 EFIAPI
2244 ShellCommandLineParseEx (
2245 IN CONST SHELL_PARAM_ITEM *CheckList,
2246 OUT LIST_ENTRY **CheckPackage,
2247 OUT CHAR16 **ProblemParam OPTIONAL,
2248 IN BOOLEAN AutoPageBreak,
2249 IN BOOLEAN AlwaysAllowNumbers
2250 )
2251 {
2252 //
2253 // ASSERT that CheckList and CheckPackage aren't NULL
2254 //
2255 ASSERT(CheckList != NULL);
2256 ASSERT(CheckPackage != NULL);
2257
2258 //
2259 // Check for UEFI Shell 2.0 protocols
2260 //
2261 if (gEfiShellParametersProtocol != NULL) {
2262 return (InternalCommandLineParse(CheckList,
2263 CheckPackage,
2264 ProblemParam,
2265 AutoPageBreak,
2266 (CONST CHAR16**) gEfiShellParametersProtocol->Argv,
2267 gEfiShellParametersProtocol->Argc,
2268 AlwaysAllowNumbers));
2269 }
2270
2271 //
2272 // ASSERT That EFI Shell is not required
2273 //
2274 ASSERT (mEfiShellInterface != NULL);
2275 return (InternalCommandLineParse(CheckList,
2276 CheckPackage,
2277 ProblemParam,
2278 AutoPageBreak,
2279 (CONST CHAR16**) mEfiShellInterface->Argv,
2280 mEfiShellInterface->Argc,
2281 AlwaysAllowNumbers));
2282 }
2283
2284 /**
2285 Frees shell variable list that was returned from ShellCommandLineParse.
2286
2287 This function will free all the memory that was used for the CheckPackage
2288 list of postprocessed shell arguments.
2289
2290 this function has no return value.
2291
2292 if CheckPackage is NULL, then return
2293
2294 @param CheckPackage the list to de-allocate
2295 **/
2296 VOID
2297 EFIAPI
2298 ShellCommandLineFreeVarList (
2299 IN LIST_ENTRY *CheckPackage
2300 )
2301 {
2302 LIST_ENTRY *Node;
2303
2304 //
2305 // check for CheckPackage == NULL
2306 //
2307 if (CheckPackage == NULL) {
2308 return;
2309 }
2310
2311 //
2312 // for each node in the list
2313 //
2314 for ( Node = GetFirstNode(CheckPackage)
2315 ; !IsListEmpty(CheckPackage)
2316 ; Node = GetFirstNode(CheckPackage)
2317 ){
2318 //
2319 // Remove it from the list
2320 //
2321 RemoveEntryList(Node);
2322
2323 //
2324 // if it has a name free the name
2325 //
2326 if (((SHELL_PARAM_PACKAGE*)Node)->Name != NULL) {
2327 FreePool(((SHELL_PARAM_PACKAGE*)Node)->Name);
2328 }
2329
2330 //
2331 // if it has a value free the value
2332 //
2333 if (((SHELL_PARAM_PACKAGE*)Node)->Value != NULL) {
2334 FreePool(((SHELL_PARAM_PACKAGE*)Node)->Value);
2335 }
2336
2337 //
2338 // free the node structure
2339 //
2340 FreePool((SHELL_PARAM_PACKAGE*)Node);
2341 }
2342 //
2343 // free the list head node
2344 //
2345 FreePool(CheckPackage);
2346 }
2347 /**
2348 Checks for presence of a flag parameter
2349
2350 flag arguments are in the form of "-<Key>" or "/<Key>", but do not have a value following the key
2351
2352 if CheckPackage is NULL then return FALSE.
2353 if KeyString is NULL then ASSERT()
2354
2355 @param CheckPackage The package of parsed command line arguments
2356 @param KeyString the Key of the command line argument to check for
2357
2358 @retval TRUE the flag is on the command line
2359 @retval FALSE the flag is not on the command line
2360 **/
2361 BOOLEAN
2362 EFIAPI
2363 ShellCommandLineGetFlag (
2364 IN CONST LIST_ENTRY * CONST CheckPackage,
2365 IN CONST CHAR16 * CONST KeyString
2366 )
2367 {
2368 LIST_ENTRY *Node;
2369 CHAR16 *TempString;
2370
2371 //
2372 // return FALSE for no package or KeyString is NULL
2373 //
2374 if (CheckPackage == NULL || KeyString == NULL) {
2375 return (FALSE);
2376 }
2377
2378 //
2379 // enumerate through the list of parametrs
2380 //
2381 for ( Node = GetFirstNode(CheckPackage)
2382 ; !IsNull (CheckPackage, Node)
2383 ; Node = GetNextNode(CheckPackage, Node)
2384 ){
2385 //
2386 // If the Name matches, return TRUE (and there may be NULL name)
2387 //
2388 if (((SHELL_PARAM_PACKAGE*)Node)->Name != NULL) {
2389 //
2390 // If Type is TypeStart then only compare the begining of the strings
2391 //
2392 if (((SHELL_PARAM_PACKAGE*)Node)->Type == TypeStart) {
2393 if (StrnCmp(KeyString, ((SHELL_PARAM_PACKAGE*)Node)->Name, StrLen(KeyString)) == 0) {
2394 return (TRUE);
2395 }
2396 TempString = NULL;
2397 TempString = StrnCatGrow(&TempString, NULL, KeyString, StrLen(((SHELL_PARAM_PACKAGE*)Node)->Name));
2398 if (TempString != NULL) {
2399 if (StringNoCaseCompare(&KeyString, &((SHELL_PARAM_PACKAGE*)Node)->Name) == 0) {
2400 FreePool(TempString);
2401 return (TRUE);
2402 }
2403 FreePool(TempString);
2404 }
2405 } else if (StringNoCaseCompare(&KeyString, &((SHELL_PARAM_PACKAGE*)Node)->Name) == 0) {
2406 return (TRUE);
2407 }
2408 }
2409 }
2410 return (FALSE);
2411 }
2412 /**
2413 Returns value from command line argument.
2414
2415 Value parameters are in the form of "-<Key> value" or "/<Key> value".
2416
2417 If CheckPackage is NULL, then return NULL.
2418
2419 @param[in] CheckPackage The package of parsed command line arguments.
2420 @param[in] KeyString The Key of the command line argument to check for.
2421
2422 @retval NULL The flag is not on the command line.
2423 @retval !=NULL The pointer to unicode string of the value.
2424 **/
2425 CONST CHAR16*
2426 EFIAPI
2427 ShellCommandLineGetValue (
2428 IN CONST LIST_ENTRY *CheckPackage,
2429 IN CHAR16 *KeyString
2430 )
2431 {
2432 LIST_ENTRY *Node;
2433 CHAR16 *TempString;
2434
2435 //
2436 // return NULL for no package or KeyString is NULL
2437 //
2438 if (CheckPackage == NULL || KeyString == NULL) {
2439 return (NULL);
2440 }
2441
2442 //
2443 // enumerate through the list of parametrs
2444 //
2445 for ( Node = GetFirstNode(CheckPackage)
2446 ; !IsNull (CheckPackage, Node)
2447 ; Node = GetNextNode(CheckPackage, Node)
2448 ){
2449 //
2450 // If the Name matches, return TRUE (and there may be NULL name)
2451 //
2452 if (((SHELL_PARAM_PACKAGE*)Node)->Name != NULL) {
2453 //
2454 // If Type is TypeStart then only compare the begining of the strings
2455 //
2456 if (((SHELL_PARAM_PACKAGE*)Node)->Type == TypeStart) {
2457 if (StrnCmp(KeyString, ((SHELL_PARAM_PACKAGE*)Node)->Name, StrLen(KeyString)) == 0) {
2458 return (((SHELL_PARAM_PACKAGE*)Node)->Name + StrLen(KeyString));
2459 }
2460 TempString = NULL;
2461 TempString = StrnCatGrow(&TempString, NULL, KeyString, StrLen(((SHELL_PARAM_PACKAGE*)Node)->Name));
2462 if (TempString != NULL) {
2463 if (StringNoCaseCompare(&KeyString, &((SHELL_PARAM_PACKAGE*)Node)->Name) == 0) {
2464 FreePool(TempString);
2465 return (((SHELL_PARAM_PACKAGE*)Node)->Name + StrLen(KeyString));
2466 }
2467 FreePool(TempString);
2468 }
2469 } else if (StringNoCaseCompare(&KeyString, &((SHELL_PARAM_PACKAGE*)Node)->Name) == 0) {
2470 return (((SHELL_PARAM_PACKAGE*)Node)->Value);
2471 }
2472 }
2473 }
2474 return (NULL);
2475 }
2476
2477 /**
2478 Returns raw value from command line argument.
2479
2480 Raw value parameters are in the form of "value" in a specific position in the list.
2481
2482 If CheckPackage is NULL, then return NULL.
2483
2484 @param[in] CheckPackage The package of parsed command line arguments.
2485 @param[in] Position The position of the value.
2486
2487 @retval NULL The flag is not on the command line.
2488 @retval !=NULL The pointer to unicode string of the value.
2489 **/
2490 CONST CHAR16*
2491 EFIAPI
2492 ShellCommandLineGetRawValue (
2493 IN CONST LIST_ENTRY * CONST CheckPackage,
2494 IN UINTN Position
2495 )
2496 {
2497 LIST_ENTRY *Node;
2498
2499 //
2500 // check for CheckPackage == NULL
2501 //
2502 if (CheckPackage == NULL) {
2503 return (NULL);
2504 }
2505
2506 //
2507 // enumerate through the list of parametrs
2508 //
2509 for ( Node = GetFirstNode(CheckPackage)
2510 ; !IsNull (CheckPackage, Node)
2511 ; Node = GetNextNode(CheckPackage, Node)
2512 ){
2513 //
2514 // If the position matches, return the value
2515 //
2516 if (((SHELL_PARAM_PACKAGE*)Node)->OriginalPosition == Position) {
2517 return (((SHELL_PARAM_PACKAGE*)Node)->Value);
2518 }
2519 }
2520 return (NULL);
2521 }
2522
2523 /**
2524 returns the number of command line value parameters that were parsed.
2525
2526 this will not include flags.
2527
2528 @param[in] CheckPackage The package of parsed command line arguments.
2529
2530 @retval (UINTN)-1 No parsing has ocurred
2531 @return other The number of value parameters found
2532 **/
2533 UINTN
2534 EFIAPI
2535 ShellCommandLineGetCount(
2536 IN CONST LIST_ENTRY *CheckPackage
2537 )
2538 {
2539 LIST_ENTRY *Node1;
2540 UINTN Count;
2541
2542 if (CheckPackage == NULL) {
2543 return (0);
2544 }
2545 for ( Node1 = GetFirstNode(CheckPackage), Count = 0
2546 ; !IsNull (CheckPackage, Node1)
2547 ; Node1 = GetNextNode(CheckPackage, Node1)
2548 ){
2549 if (((SHELL_PARAM_PACKAGE*)Node1)->Name == NULL) {
2550 Count++;
2551 }
2552 }
2553 return (Count);
2554 }
2555
2556 /**
2557 Determines if a parameter is duplicated.
2558
2559 If Param is not NULL then it will point to a callee allocated string buffer
2560 with the parameter value if a duplicate is found.
2561
2562 If CheckPackage is NULL, then ASSERT.
2563
2564 @param[in] CheckPackage The package of parsed command line arguments.
2565 @param[out] Param Upon finding one, a pointer to the duplicated parameter.
2566
2567 @retval EFI_SUCCESS No parameters were duplicated.
2568 @retval EFI_DEVICE_ERROR A duplicate was found.
2569 **/
2570 EFI_STATUS
2571 EFIAPI
2572 ShellCommandLineCheckDuplicate (
2573 IN CONST LIST_ENTRY *CheckPackage,
2574 OUT CHAR16 **Param
2575 )
2576 {
2577 LIST_ENTRY *Node1;
2578 LIST_ENTRY *Node2;
2579
2580 ASSERT(CheckPackage != NULL);
2581
2582 for ( Node1 = GetFirstNode(CheckPackage)
2583 ; !IsNull (CheckPackage, Node1)
2584 ; Node1 = GetNextNode(CheckPackage, Node1)
2585 ){
2586 for ( Node2 = GetNextNode(CheckPackage, Node1)
2587 ; !IsNull (CheckPackage, Node2)
2588 ; Node2 = GetNextNode(CheckPackage, Node2)
2589 ){
2590 if ((((SHELL_PARAM_PACKAGE*)Node1)->Name != NULL) && (((SHELL_PARAM_PACKAGE*)Node2)->Name != NULL) && StrCmp(((SHELL_PARAM_PACKAGE*)Node1)->Name, ((SHELL_PARAM_PACKAGE*)Node2)->Name) == 0) {
2591 if (Param != NULL) {
2592 *Param = NULL;
2593 *Param = StrnCatGrow(Param, NULL, ((SHELL_PARAM_PACKAGE*)Node1)->Name, 0);
2594 }
2595 return (EFI_DEVICE_ERROR);
2596 }
2597 }
2598 }
2599 return (EFI_SUCCESS);
2600 }
2601
2602 /**
2603 This is a find and replace function. Upon successful return the NewString is a copy of
2604 SourceString with each instance of FindTarget replaced with ReplaceWith.
2605
2606 If SourceString and NewString overlap the behavior is undefined.
2607
2608 If the string would grow bigger than NewSize it will halt and return error.
2609
2610 @param[in] SourceString The string with source buffer.
2611 @param[in, out] NewString The string with resultant buffer.
2612 @param[in] NewSize The size in bytes of NewString.
2613 @param[in] FindTarget The string to look for.
2614 @param[in] ReplaceWith The string to replace FindTarget with.
2615 @param[in] SkipPreCarrot If TRUE will skip a FindTarget that has a '^'
2616 immediately before it.
2617 @param[in] ParameterReplacing If TRUE will add "" around items with spaces.
2618
2619 @retval EFI_INVALID_PARAMETER SourceString was NULL.
2620 @retval EFI_INVALID_PARAMETER NewString was NULL.
2621 @retval EFI_INVALID_PARAMETER FindTarget was NULL.
2622 @retval EFI_INVALID_PARAMETER ReplaceWith was NULL.
2623 @retval EFI_INVALID_PARAMETER FindTarget had length < 1.
2624 @retval EFI_INVALID_PARAMETER SourceString had length < 1.
2625 @retval EFI_BUFFER_TOO_SMALL NewSize was less than the minimum size to hold
2626 the new string (truncation occurred).
2627 @retval EFI_SUCCESS The string was successfully copied with replacement.
2628 **/
2629 EFI_STATUS
2630 EFIAPI
2631 ShellCopySearchAndReplace(
2632 IN CHAR16 CONST *SourceString,
2633 IN OUT CHAR16 *NewString,
2634 IN UINTN NewSize,
2635 IN CONST CHAR16 *FindTarget,
2636 IN CONST CHAR16 *ReplaceWith,
2637 IN CONST BOOLEAN SkipPreCarrot,
2638 IN CONST BOOLEAN ParameterReplacing
2639 )
2640 {
2641 UINTN Size;
2642 CHAR16 *Replace;
2643
2644 if ( (SourceString == NULL)
2645 || (NewString == NULL)
2646 || (FindTarget == NULL)
2647 || (ReplaceWith == NULL)
2648 || (StrLen(FindTarget) < 1)
2649 || (StrLen(SourceString) < 1)
2650 ){
2651 return (EFI_INVALID_PARAMETER);
2652 }
2653 Replace = NULL;
2654 if (StrStr(ReplaceWith, L" ") == NULL || !ParameterReplacing) {
2655 Replace = StrnCatGrow(&Replace, NULL, ReplaceWith, 0);
2656 } else {
2657 Replace = AllocateZeroPool(StrSize(ReplaceWith) + 2*sizeof(CHAR16));
2658 if (Replace != NULL) {
2659 UnicodeSPrint(Replace, StrSize(ReplaceWith) + 2*sizeof(CHAR16), L"\"%s\"", ReplaceWith);
2660 }
2661 }
2662 if (Replace == NULL) {
2663 return (EFI_OUT_OF_RESOURCES);
2664 }
2665 NewString = ZeroMem(NewString, NewSize);
2666 while (*SourceString != CHAR_NULL) {
2667 //
2668 // if we find the FindTarget and either Skip == FALSE or Skip and we
2669 // dont have a carrot do a replace...
2670 //
2671 if (StrnCmp(SourceString, FindTarget, StrLen(FindTarget)) == 0
2672 && ((SkipPreCarrot && *(SourceString-1) != L'^') || !SkipPreCarrot)
2673 ){
2674 SourceString += StrLen(FindTarget);
2675 Size = StrSize(NewString);
2676 if ((Size + (StrLen(Replace)*sizeof(CHAR16))) > NewSize) {
2677 FreePool(Replace);
2678 return (EFI_BUFFER_TOO_SMALL);
2679 }
2680 StrCatS(NewString, NewSize/sizeof(CHAR16), Replace);
2681 } else {
2682 Size = StrSize(NewString);
2683 if (Size + sizeof(CHAR16) > NewSize) {
2684 FreePool(Replace);
2685 return (EFI_BUFFER_TOO_SMALL);
2686 }
2687 StrnCatS(NewString, NewSize/sizeof(CHAR16), SourceString, 1);
2688 SourceString++;
2689 }
2690 }
2691 FreePool(Replace);
2692 return (EFI_SUCCESS);
2693 }
2694
2695 /**
2696 Internal worker function to output a string.
2697
2698 This function will output a string to the correct StdOut.
2699
2700 @param[in] String The string to print out.
2701
2702 @retval EFI_SUCCESS The operation was sucessful.
2703 @retval !EFI_SUCCESS The operation failed.
2704 **/
2705 EFI_STATUS
2706 EFIAPI
2707 InternalPrintTo (
2708 IN CONST CHAR16 *String
2709 )
2710 {
2711 UINTN Size;
2712 Size = StrSize(String) - sizeof(CHAR16);
2713 if (Size == 0) {
2714 return (EFI_SUCCESS);
2715 }
2716 if (gEfiShellParametersProtocol != NULL) {
2717 return (gEfiShellProtocol->WriteFile(gEfiShellParametersProtocol->StdOut, &Size, (VOID*)String));
2718 }
2719 if (mEfiShellInterface != NULL) {
2720 if (mEfiShellInterface->RedirArgc == 0) {
2721 //
2722 // Divide in half for old shell. Must be string length not size.
2723 //
2724 Size /=2; // Divide in half only when no redirection.
2725 }
2726 return (mEfiShellInterface->StdOut->Write(mEfiShellInterface->StdOut, &Size, (VOID*)String));
2727 }
2728 ASSERT(FALSE);
2729 return (EFI_UNSUPPORTED);
2730 }
2731
2732 /**
2733 Print at a specific location on the screen.
2734
2735 This function will move the cursor to a given screen location and print the specified string
2736
2737 If -1 is specified for either the Row or Col the current screen location for BOTH
2738 will be used.
2739
2740 if either Row or Col is out of range for the current console, then ASSERT
2741 if Format is NULL, then ASSERT
2742
2743 In addition to the standard %-based flags as supported by UefiLib Print() this supports
2744 the following additional flags:
2745 %N - Set output attribute to normal
2746 %H - Set output attribute to highlight
2747 %E - Set output attribute to error
2748 %B - Set output attribute to blue color
2749 %V - Set output attribute to green color
2750
2751 Note: The background color is controlled by the shell command cls.
2752
2753 @param[in] Col the column to print at
2754 @param[in] Row the row to print at
2755 @param[in] Format the format string
2756 @param[in] Marker the marker for the variable argument list
2757
2758 @return EFI_SUCCESS The operation was successful.
2759 @return EFI_DEVICE_ERROR The console device reported an error.
2760 **/
2761 EFI_STATUS
2762 EFIAPI
2763 InternalShellPrintWorker(
2764 IN INT32 Col OPTIONAL,
2765 IN INT32 Row OPTIONAL,
2766 IN CONST CHAR16 *Format,
2767 IN VA_LIST Marker
2768 )
2769 {
2770 EFI_STATUS Status;
2771 CHAR16 *ResumeLocation;
2772 CHAR16 *FormatWalker;
2773 UINTN OriginalAttribute;
2774 CHAR16 *mPostReplaceFormat;
2775 CHAR16 *mPostReplaceFormat2;
2776
2777 mPostReplaceFormat = AllocateZeroPool (PcdGet16 (PcdShellPrintBufferSize));
2778 mPostReplaceFormat2 = AllocateZeroPool (PcdGet16 (PcdShellPrintBufferSize));
2779
2780 if (mPostReplaceFormat == NULL || mPostReplaceFormat2 == NULL) {
2781 SHELL_FREE_NON_NULL(mPostReplaceFormat);
2782 SHELL_FREE_NON_NULL(mPostReplaceFormat2);
2783 return (EFI_OUT_OF_RESOURCES);
2784 }
2785
2786 Status = EFI_SUCCESS;
2787 OriginalAttribute = gST->ConOut->Mode->Attribute;
2788
2789 //
2790 // Back and forth each time fixing up 1 of our flags...
2791 //
2792 Status = ShellCopySearchAndReplace(Format, mPostReplaceFormat, PcdGet16 (PcdShellPrintBufferSize), L"%N", L"%%N", FALSE, FALSE);
2793 ASSERT_EFI_ERROR(Status);
2794 Status = ShellCopySearchAndReplace(mPostReplaceFormat, mPostReplaceFormat2, PcdGet16 (PcdShellPrintBufferSize), L"%E", L"%%E", FALSE, FALSE);
2795 ASSERT_EFI_ERROR(Status);
2796 Status = ShellCopySearchAndReplace(mPostReplaceFormat2, mPostReplaceFormat, PcdGet16 (PcdShellPrintBufferSize), L"%H", L"%%H", FALSE, FALSE);
2797 ASSERT_EFI_ERROR(Status);
2798 Status = ShellCopySearchAndReplace(mPostReplaceFormat, mPostReplaceFormat2, PcdGet16 (PcdShellPrintBufferSize), L"%B", L"%%B", FALSE, FALSE);
2799 ASSERT_EFI_ERROR(Status);
2800 Status = ShellCopySearchAndReplace(mPostReplaceFormat2, mPostReplaceFormat, PcdGet16 (PcdShellPrintBufferSize), L"%V", L"%%V", FALSE, FALSE);
2801 ASSERT_EFI_ERROR(Status);
2802
2803 //
2804 // Use the last buffer from replacing to print from...
2805 //
2806 UnicodeVSPrint (mPostReplaceFormat2, PcdGet16 (PcdShellPrintBufferSize), mPostReplaceFormat, Marker);
2807
2808 if (Col != -1 && Row != -1) {
2809 Status = gST->ConOut->SetCursorPosition(gST->ConOut, Col, Row);
2810 }
2811
2812 FormatWalker = mPostReplaceFormat2;
2813 while (*FormatWalker != CHAR_NULL) {
2814 //
2815 // Find the next attribute change request
2816 //
2817 ResumeLocation = StrStr(FormatWalker, L"%");
2818 if (ResumeLocation != NULL) {
2819 *ResumeLocation = CHAR_NULL;
2820 }
2821 //
2822 // print the current FormatWalker string
2823 //
2824 if (StrLen(FormatWalker)>0) {
2825 Status = InternalPrintTo(FormatWalker);
2826 if (EFI_ERROR(Status)) {
2827 break;
2828 }
2829 }
2830
2831 //
2832 // update the attribute
2833 //
2834 if (ResumeLocation != NULL) {
2835 if (*(ResumeLocation-1) == L'^') {
2836 //
2837 // Move cursor back 1 position to overwrite the ^
2838 //
2839 gST->ConOut->SetCursorPosition(gST->ConOut, gST->ConOut->Mode->CursorColumn - 1, gST->ConOut->Mode->CursorRow);
2840
2841 //
2842 // Print a simple '%' symbol
2843 //
2844 Status = InternalPrintTo(L"%");
2845 ResumeLocation = ResumeLocation - 1;
2846 } else {
2847 switch (*(ResumeLocation+1)) {
2848 case (L'N'):
2849 gST->ConOut->SetAttribute(gST->ConOut, OriginalAttribute);
2850 break;
2851 case (L'E'):
2852 gST->ConOut->SetAttribute(gST->ConOut, EFI_TEXT_ATTR(EFI_YELLOW, ((OriginalAttribute&(BIT4|BIT5|BIT6))>>4)));
2853 break;
2854 case (L'H'):
2855 gST->ConOut->SetAttribute(gST->ConOut, EFI_TEXT_ATTR(EFI_WHITE, ((OriginalAttribute&(BIT4|BIT5|BIT6))>>4)));
2856 break;
2857 case (L'B'):
2858 gST->ConOut->SetAttribute(gST->ConOut, EFI_TEXT_ATTR(EFI_BLUE, ((OriginalAttribute&(BIT4|BIT5|BIT6))>>4)));
2859 break;
2860 case (L'V'):
2861 gST->ConOut->SetAttribute(gST->ConOut, EFI_TEXT_ATTR(EFI_GREEN, ((OriginalAttribute&(BIT4|BIT5|BIT6))>>4)));
2862 break;
2863 default:
2864 //
2865 // Print a simple '%' symbol
2866 //
2867 Status = InternalPrintTo(L"%");
2868 if (EFI_ERROR(Status)) {
2869 break;
2870 }
2871 ResumeLocation = ResumeLocation - 1;
2872 break;
2873 }
2874 }
2875 } else {
2876 //
2877 // reset to normal now...
2878 //
2879 break;
2880 }
2881
2882 //
2883 // update FormatWalker to Resume + 2 (skip the % and the indicator)
2884 //
2885 FormatWalker = ResumeLocation + 2;
2886 }
2887
2888 gST->ConOut->SetAttribute(gST->ConOut, OriginalAttribute);
2889
2890 SHELL_FREE_NON_NULL(mPostReplaceFormat);
2891 SHELL_FREE_NON_NULL(mPostReplaceFormat2);
2892 return (Status);
2893 }
2894
2895 /**
2896 Print at a specific location on the screen.
2897
2898 This function will move the cursor to a given screen location and print the specified string.
2899
2900 If -1 is specified for either the Row or Col the current screen location for BOTH
2901 will be used.
2902
2903 If either Row or Col is out of range for the current console, then ASSERT.
2904 If Format is NULL, then ASSERT.
2905
2906 In addition to the standard %-based flags as supported by UefiLib Print() this supports
2907 the following additional flags:
2908 %N - Set output attribute to normal
2909 %H - Set output attribute to highlight
2910 %E - Set output attribute to error
2911 %B - Set output attribute to blue color
2912 %V - Set output attribute to green color
2913
2914 Note: The background color is controlled by the shell command cls.
2915
2916 @param[in] Col the column to print at
2917 @param[in] Row the row to print at
2918 @param[in] Format the format string
2919 @param[in] ... The variable argument list.
2920
2921 @return EFI_SUCCESS The printing was successful.
2922 @return EFI_DEVICE_ERROR The console device reported an error.
2923 **/
2924 EFI_STATUS
2925 EFIAPI
2926 ShellPrintEx(
2927 IN INT32 Col OPTIONAL,
2928 IN INT32 Row OPTIONAL,
2929 IN CONST CHAR16 *Format,
2930 ...
2931 )
2932 {
2933 VA_LIST Marker;
2934 EFI_STATUS RetVal;
2935 if (Format == NULL) {
2936 return (EFI_INVALID_PARAMETER);
2937 }
2938 VA_START (Marker, Format);
2939 RetVal = InternalShellPrintWorker(Col, Row, Format, Marker);
2940 VA_END(Marker);
2941 return(RetVal);
2942 }
2943
2944 /**
2945 Print at a specific location on the screen.
2946
2947 This function will move the cursor to a given screen location and print the specified string.
2948
2949 If -1 is specified for either the Row or Col the current screen location for BOTH
2950 will be used.
2951
2952 If either Row or Col is out of range for the current console, then ASSERT.
2953 If Format is NULL, then ASSERT.
2954
2955 In addition to the standard %-based flags as supported by UefiLib Print() this supports
2956 the following additional flags:
2957 %N - Set output attribute to normal.
2958 %H - Set output attribute to highlight.
2959 %E - Set output attribute to error.
2960 %B - Set output attribute to blue color.
2961 %V - Set output attribute to green color.
2962
2963 Note: The background color is controlled by the shell command cls.
2964
2965 @param[in] Col The column to print at.
2966 @param[in] Row The row to print at.
2967 @param[in] Language The language of the string to retrieve. If this parameter
2968 is NULL, then the current platform language is used.
2969 @param[in] HiiFormatStringId The format string Id for getting from Hii.
2970 @param[in] HiiFormatHandle The format string Handle for getting from Hii.
2971 @param[in] ... The variable argument list.
2972
2973 @return EFI_SUCCESS The printing was successful.
2974 @return EFI_DEVICE_ERROR The console device reported an error.
2975 **/
2976 EFI_STATUS
2977 EFIAPI
2978 ShellPrintHiiEx(
2979 IN INT32 Col OPTIONAL,
2980 IN INT32 Row OPTIONAL,
2981 IN CONST CHAR8 *Language OPTIONAL,
2982 IN CONST EFI_STRING_ID HiiFormatStringId,
2983 IN CONST EFI_HANDLE HiiFormatHandle,
2984 ...
2985 )
2986 {
2987 VA_LIST Marker;
2988 CHAR16 *HiiFormatString;
2989 EFI_STATUS RetVal;
2990
2991 RetVal = EFI_DEVICE_ERROR;
2992
2993 VA_START (Marker, HiiFormatHandle);
2994 HiiFormatString = HiiGetString(HiiFormatHandle, HiiFormatStringId, Language);
2995 if (HiiFormatString != NULL) {
2996 RetVal = InternalShellPrintWorker (Col, Row, HiiFormatString, Marker);
2997 SHELL_FREE_NON_NULL (HiiFormatString);
2998 }
2999 VA_END(Marker);
3000
3001 return (RetVal);
3002 }
3003
3004 /**
3005 Function to determine if a given filename represents a file or a directory.
3006
3007 @param[in] DirName Path to directory to test.
3008
3009 @retval EFI_SUCCESS The Path represents a directory
3010 @retval EFI_NOT_FOUND The Path does not represent a directory
3011 @retval EFI_OUT_OF_RESOURCES A memory allocation failed.
3012 @return The path failed to open
3013 **/
3014 EFI_STATUS
3015 EFIAPI
3016 ShellIsDirectory(
3017 IN CONST CHAR16 *DirName
3018 )
3019 {
3020 EFI_STATUS Status;
3021 SHELL_FILE_HANDLE Handle;
3022 CHAR16 *TempLocation;
3023 CHAR16 *TempLocation2;
3024
3025 ASSERT(DirName != NULL);
3026
3027 Handle = NULL;
3028 TempLocation = NULL;
3029
3030 Status = ShellOpenFileByName(DirName, &Handle, EFI_FILE_MODE_READ, 0);
3031 if (EFI_ERROR(Status)) {
3032 //
3033 // try good logic first.
3034 //
3035 if (gEfiShellProtocol != NULL) {
3036 TempLocation = StrnCatGrow(&TempLocation, NULL, DirName, 0);
3037 if (TempLocation == NULL) {
3038 ShellCloseFile(&Handle);
3039 return (EFI_OUT_OF_RESOURCES);
3040 }
3041 TempLocation2 = StrStr(TempLocation, L":");
3042 if (TempLocation2 != NULL && StrLen(StrStr(TempLocation, L":")) == 2) {
3043 *(TempLocation2+1) = CHAR_NULL;
3044 }
3045 if (gEfiShellProtocol->GetDevicePathFromMap(TempLocation) != NULL) {
3046 FreePool(TempLocation);
3047 return (EFI_SUCCESS);
3048 }
3049 FreePool(TempLocation);
3050 } else {
3051 //
3052 // probably a map name?!?!!?
3053 //
3054 TempLocation = StrStr(DirName, L"\\");
3055 if (TempLocation != NULL && *(TempLocation+1) == CHAR_NULL) {
3056 return (EFI_SUCCESS);
3057 }
3058 }
3059 return (Status);
3060 }
3061
3062 if (FileHandleIsDirectory(Handle) == EFI_SUCCESS) {
3063 ShellCloseFile(&Handle);
3064 return (EFI_SUCCESS);
3065 }
3066 ShellCloseFile(&Handle);
3067 return (EFI_NOT_FOUND);
3068 }
3069
3070 /**
3071 Function to determine if a given filename represents a file.
3072
3073 @param[in] Name Path to file to test.
3074
3075 @retval EFI_SUCCESS The Path represents a file.
3076 @retval EFI_NOT_FOUND The Path does not represent a file.
3077 @retval other The path failed to open.
3078 **/
3079 EFI_STATUS
3080 EFIAPI
3081 ShellIsFile(
3082 IN CONST CHAR16 *Name
3083 )
3084 {
3085 EFI_STATUS Status;
3086 SHELL_FILE_HANDLE Handle;
3087
3088 ASSERT(Name != NULL);
3089
3090 Handle = NULL;
3091
3092 Status = ShellOpenFileByName(Name, &Handle, EFI_FILE_MODE_READ, 0);
3093 if (EFI_ERROR(Status)) {
3094 return (Status);
3095 }
3096
3097 if (FileHandleIsDirectory(Handle) != EFI_SUCCESS) {
3098 ShellCloseFile(&Handle);
3099 return (EFI_SUCCESS);
3100 }
3101 ShellCloseFile(&Handle);
3102 return (EFI_NOT_FOUND);
3103 }
3104
3105 /**
3106 Function to determine if a given filename represents a file.
3107
3108 This will search the CWD and then the Path.
3109
3110 If Name is NULL, then ASSERT.
3111
3112 @param[in] Name Path to file to test.
3113
3114 @retval EFI_SUCCESS The Path represents a file.
3115 @retval EFI_NOT_FOUND The Path does not represent a file.
3116 @retval other The path failed to open.
3117 **/
3118 EFI_STATUS
3119 EFIAPI
3120 ShellIsFileInPath(
3121 IN CONST CHAR16 *Name
3122 )
3123 {
3124 CHAR16 *NewName;
3125 EFI_STATUS Status;
3126
3127 if (!EFI_ERROR(ShellIsFile(Name))) {
3128 return (EFI_SUCCESS);
3129 }
3130
3131 NewName = ShellFindFilePath(Name);
3132 if (NewName == NULL) {
3133 return (EFI_NOT_FOUND);
3134 }
3135 Status = ShellIsFile(NewName);
3136 FreePool(NewName);
3137 return (Status);
3138 }
3139
3140 /**
3141 Function return the number converted from a hex representation of a number.
3142
3143 Note: this function cannot be used when (UINTN)(-1), (0xFFFFFFFF) may be a valid
3144 result. Use ShellConvertStringToUint64 instead.
3145
3146 @param[in] String String representation of a number.
3147
3148 @return The unsigned integer result of the conversion.
3149 @retval (UINTN)(-1) An error occured.
3150 **/
3151 UINTN
3152 EFIAPI
3153 ShellHexStrToUintn(
3154 IN CONST CHAR16 *String
3155 )
3156 {
3157 UINT64 RetVal;
3158
3159 if (!EFI_ERROR(ShellConvertStringToUint64(String, &RetVal, TRUE, TRUE))) {
3160 return ((UINTN)RetVal);
3161 }
3162
3163 return ((UINTN)(-1));
3164 }
3165
3166 /**
3167 Function to determine whether a string is decimal or hex representation of a number
3168 and return the number converted from the string. Spaces are always skipped.
3169
3170 @param[in] String String representation of a number
3171
3172 @return the number
3173 @retval (UINTN)(-1) An error ocurred.
3174 **/
3175 UINTN
3176 EFIAPI
3177 ShellStrToUintn(
3178 IN CONST CHAR16 *String
3179 )
3180 {
3181 UINT64 RetVal;
3182 BOOLEAN Hex;
3183
3184 Hex = FALSE;
3185
3186 if (!InternalShellIsHexOrDecimalNumber(String, Hex, TRUE, FALSE)) {
3187 Hex = TRUE;
3188 }
3189
3190 if (!EFI_ERROR(ShellConvertStringToUint64(String, &RetVal, Hex, TRUE))) {
3191 return ((UINTN)RetVal);
3192 }
3193 return ((UINTN)(-1));
3194 }
3195
3196 /**
3197 Safely append with automatic string resizing given length of Destination and
3198 desired length of copy from Source.
3199
3200 append the first D characters of Source to the end of Destination, where D is
3201 the lesser of Count and the StrLen() of Source. If appending those D characters
3202 will fit within Destination (whose Size is given as CurrentSize) and
3203 still leave room for a NULL terminator, then those characters are appended,
3204 starting at the original terminating NULL of Destination, and a new terminating
3205 NULL is appended.
3206
3207 If appending D characters onto Destination will result in a overflow of the size
3208 given in CurrentSize the string will be grown such that the copy can be performed
3209 and CurrentSize will be updated to the new size.
3210
3211 If Source is NULL, there is nothing to append, just return the current buffer in
3212 Destination.
3213
3214 if Destination is NULL, then ASSERT()
3215 if Destination's current length (including NULL terminator) is already more then
3216 CurrentSize, then ASSERT()
3217
3218 @param[in, out] Destination The String to append onto
3219 @param[in, out] CurrentSize on call the number of bytes in Destination. On
3220 return possibly the new size (still in bytes). if NULL
3221 then allocate whatever is needed.
3222 @param[in] Source The String to append from
3223 @param[in] Count Maximum number of characters to append. if 0 then
3224 all are appended.
3225
3226 @return Destination return the resultant string.
3227 **/
3228 CHAR16*
3229 EFIAPI
3230 StrnCatGrow (
3231 IN OUT CHAR16 **Destination,
3232 IN OUT UINTN *CurrentSize,
3233 IN CONST CHAR16 *Source,
3234 IN UINTN Count
3235 )
3236 {
3237 UINTN DestinationStartSize;
3238 UINTN NewSize;
3239
3240 //
3241 // ASSERTs
3242 //
3243 ASSERT(Destination != NULL);
3244
3245 //
3246 // If there's nothing to do then just return Destination
3247 //
3248 if (Source == NULL) {
3249 return (*Destination);
3250 }
3251
3252 //
3253 // allow for un-initialized pointers, based on size being 0
3254 //
3255 if (CurrentSize != NULL && *CurrentSize == 0) {
3256 *Destination = NULL;
3257 }
3258
3259 //
3260 // allow for NULL pointers address as Destination
3261 //
3262 if (*Destination != NULL) {
3263 ASSERT(CurrentSize != 0);
3264 DestinationStartSize = StrSize(*Destination);
3265 ASSERT(DestinationStartSize <= *CurrentSize);
3266 } else {
3267 DestinationStartSize = 0;
3268 // ASSERT(*CurrentSize == 0);
3269 }
3270
3271 //
3272 // Append all of Source?
3273 //
3274 if (Count == 0) {
3275 Count = StrLen(Source);
3276 }
3277
3278 //
3279 // Test and grow if required
3280 //
3281 if (CurrentSize != NULL) {
3282 NewSize = *CurrentSize;
3283 if (NewSize < DestinationStartSize + (Count * sizeof(CHAR16))) {
3284 while (NewSize < (DestinationStartSize + (Count*sizeof(CHAR16)))) {
3285 NewSize += 2 * Count * sizeof(CHAR16);
3286 }
3287 *Destination = ReallocatePool(*CurrentSize, NewSize, *Destination);
3288 *CurrentSize = NewSize;
3289 }
3290 } else {
3291 NewSize = (Count+1)*sizeof(CHAR16);
3292 *Destination = AllocateZeroPool(NewSize);
3293 }
3294
3295 //
3296 // Now use standard StrnCat on a big enough buffer
3297 //
3298 if (*Destination == NULL) {
3299 return (NULL);
3300 }
3301
3302 StrnCatS(*Destination, NewSize/sizeof(CHAR16), Source, Count);
3303 return *Destination;
3304 }
3305
3306 /**
3307 Prompt the user and return the resultant answer to the requestor.
3308
3309 This function will display the requested question on the shell prompt and then
3310 wait for an appropriate answer to be input from the console.
3311
3312 if the SHELL_PROMPT_REQUEST_TYPE is SHELL_PROMPT_REQUEST_TYPE_YESNO, ShellPromptResponseTypeQuitContinue
3313 or SHELL_PROMPT_REQUEST_TYPE_YESNOCANCEL then *Response is of type SHELL_PROMPT_RESPONSE.
3314
3315 if the SHELL_PROMPT_REQUEST_TYPE is ShellPromptResponseTypeFreeform then *Response is of type
3316 CHAR16*.
3317
3318 In either case *Response must be callee freed if Response was not NULL;
3319
3320 @param Type What type of question is asked. This is used to filter the input
3321 to prevent invalid answers to question.
3322 @param Prompt Pointer to string prompt to use to request input.
3323 @param Response Pointer to Response which will be populated upon return.
3324
3325 @retval EFI_SUCCESS The operation was sucessful.
3326 @retval EFI_UNSUPPORTED The operation is not supported as requested.
3327 @retval EFI_INVALID_PARAMETER A parameter was invalid.
3328 @return other The operation failed.
3329 **/
3330 EFI_STATUS
3331 EFIAPI
3332 ShellPromptForResponse (
3333 IN SHELL_PROMPT_REQUEST_TYPE Type,
3334 IN CHAR16 *Prompt OPTIONAL,
3335 IN OUT VOID **Response OPTIONAL
3336 )
3337 {
3338 EFI_STATUS Status;
3339 EFI_INPUT_KEY Key;
3340 UINTN EventIndex;
3341 SHELL_PROMPT_RESPONSE *Resp;
3342 UINTN Size;
3343 CHAR16 *Buffer;
3344
3345 Status = EFI_UNSUPPORTED;
3346 Resp = NULL;
3347 Buffer = NULL;
3348 Size = 0;
3349 if (Type != ShellPromptResponseTypeFreeform) {
3350 Resp = (SHELL_PROMPT_RESPONSE*)AllocateZeroPool(sizeof(SHELL_PROMPT_RESPONSE));
3351 if (Resp == NULL) {
3352 return (EFI_OUT_OF_RESOURCES);
3353 }
3354 }
3355
3356 switch(Type) {
3357 case ShellPromptResponseTypeQuitContinue:
3358 if (Prompt != NULL) {
3359 ShellPrintEx(-1, -1, L"%s", Prompt);
3360 }
3361 //
3362 // wait for valid response
3363 //
3364 gBS->WaitForEvent (1, &gST->ConIn->WaitForKey, &EventIndex);
3365 Status = gST->ConIn->ReadKeyStroke (gST->ConIn, &Key);
3366 if (EFI_ERROR(Status)) {
3367 break;
3368 }
3369 ShellPrintEx(-1, -1, L"%c", Key.UnicodeChar);
3370 if (Key.UnicodeChar == L'Q' || Key.UnicodeChar ==L'q') {
3371 *Resp = ShellPromptResponseQuit;
3372 } else {
3373 *Resp = ShellPromptResponseContinue;
3374 }
3375 break;
3376 case ShellPromptResponseTypeYesNoCancel:
3377 if (Prompt != NULL) {
3378 ShellPrintEx(-1, -1, L"%s", Prompt);
3379 }
3380 //
3381 // wait for valid response
3382 //
3383 *Resp = ShellPromptResponseMax;
3384 while (*Resp == ShellPromptResponseMax) {
3385 if (ShellGetExecutionBreakFlag()) {
3386 Status = EFI_ABORTED;
3387 break;
3388 }
3389 gBS->WaitForEvent (1, &gST->ConIn->WaitForKey, &EventIndex);
3390 Status = gST->ConIn->ReadKeyStroke (gST->ConIn, &Key);
3391 if (EFI_ERROR(Status)) {
3392 break;
3393 }
3394 ShellPrintEx(-1, -1, L"%c", Key.UnicodeChar);
3395 switch (Key.UnicodeChar) {
3396 case L'Y':
3397 case L'y':
3398 *Resp = ShellPromptResponseYes;
3399 break;
3400 case L'N':
3401 case L'n':
3402 *Resp = ShellPromptResponseNo;
3403 break;
3404 case L'C':
3405 case L'c':
3406 *Resp = ShellPromptResponseCancel;
3407 break;
3408 }
3409 }
3410 break; case ShellPromptResponseTypeYesNoAllCancel:
3411 if (Prompt != NULL) {
3412 ShellPrintEx(-1, -1, L"%s", Prompt);
3413 }
3414 //
3415 // wait for valid response
3416 //
3417 *Resp = ShellPromptResponseMax;
3418 while (*Resp == ShellPromptResponseMax) {
3419 if (ShellGetExecutionBreakFlag()) {
3420 Status = EFI_ABORTED;
3421 break;
3422 }
3423 gBS->WaitForEvent (1, &gST->ConIn->WaitForKey, &EventIndex);
3424 Status = gST->ConIn->ReadKeyStroke (gST->ConIn, &Key);
3425 if (EFI_ERROR(Status)) {
3426 break;
3427 }
3428 ShellPrintEx(-1, -1, L"%c", Key.UnicodeChar);
3429 switch (Key.UnicodeChar) {
3430 case L'Y':
3431 case L'y':
3432 *Resp = ShellPromptResponseYes;
3433 break;
3434 case L'N':
3435 case L'n':
3436 *Resp = ShellPromptResponseNo;
3437 break;
3438 case L'A':
3439 case L'a':
3440 *Resp = ShellPromptResponseAll;
3441 break;
3442 case L'C':
3443 case L'c':
3444 *Resp = ShellPromptResponseCancel;
3445 break;
3446 }
3447 }
3448 break;
3449 case ShellPromptResponseTypeEnterContinue:
3450 case ShellPromptResponseTypeAnyKeyContinue:
3451 if (Prompt != NULL) {
3452 ShellPrintEx(-1, -1, L"%s", Prompt);
3453 }
3454 //
3455 // wait for valid response
3456 //
3457 *Resp = ShellPromptResponseMax;
3458 while (*Resp == ShellPromptResponseMax) {
3459 if (ShellGetExecutionBreakFlag()) {
3460 Status = EFI_ABORTED;
3461 break;
3462 }
3463 gBS->WaitForEvent (1, &gST->ConIn->WaitForKey, &EventIndex);
3464 if (Type == ShellPromptResponseTypeEnterContinue) {
3465 Status = gST->ConIn->ReadKeyStroke (gST->ConIn, &Key);
3466 if (EFI_ERROR(Status)) {
3467 break;
3468 }
3469 ShellPrintEx(-1, -1, L"%c", Key.UnicodeChar);
3470 if (Key.UnicodeChar == CHAR_CARRIAGE_RETURN) {
3471 *Resp = ShellPromptResponseContinue;
3472 break;
3473 }
3474 }
3475 if (Type == ShellPromptResponseTypeAnyKeyContinue) {
3476 Status = gST->ConIn->ReadKeyStroke (gST->ConIn, &Key);
3477 ASSERT_EFI_ERROR(Status);
3478 *Resp = ShellPromptResponseContinue;
3479 break;
3480 }
3481 }
3482 break;
3483 case ShellPromptResponseTypeYesNo:
3484 if (Prompt != NULL) {
3485 ShellPrintEx(-1, -1, L"%s", Prompt);
3486 }
3487 //
3488 // wait for valid response
3489 //
3490 *Resp = ShellPromptResponseMax;
3491 while (*Resp == ShellPromptResponseMax) {
3492 if (ShellGetExecutionBreakFlag()) {
3493 Status = EFI_ABORTED;
3494 break;
3495 }
3496 gBS->WaitForEvent (1, &gST->ConIn->WaitForKey, &EventIndex);
3497 Status = gST->ConIn->ReadKeyStroke (gST->ConIn, &Key);
3498 if (EFI_ERROR(Status)) {
3499 break;
3500 }
3501 ShellPrintEx(-1, -1, L"%c", Key.UnicodeChar);
3502 switch (Key.UnicodeChar) {
3503 case L'Y':
3504 case L'y':
3505 *Resp = ShellPromptResponseYes;
3506 break;
3507 case L'N':
3508 case L'n':
3509 *Resp = ShellPromptResponseNo;
3510 break;
3511 }
3512 }
3513 break;
3514 case ShellPromptResponseTypeFreeform:
3515 if (Prompt != NULL) {
3516 ShellPrintEx(-1, -1, L"%s", Prompt);
3517 }
3518 while(1) {
3519 if (ShellGetExecutionBreakFlag()) {
3520 Status = EFI_ABORTED;
3521 break;
3522 }
3523 gBS->WaitForEvent (1, &gST->ConIn->WaitForKey, &EventIndex);
3524 Status = gST->ConIn->ReadKeyStroke (gST->ConIn, &Key);
3525 if (EFI_ERROR(Status)) {
3526 break;
3527 }
3528 ShellPrintEx(-1, -1, L"%c", Key.UnicodeChar);
3529 if (Key.UnicodeChar == CHAR_CARRIAGE_RETURN) {
3530 break;
3531 }
3532 ASSERT((Buffer == NULL && Size == 0) || (Buffer != NULL));
3533 StrnCatGrow(&Buffer, &Size, &Key.UnicodeChar, 1);
3534 }
3535 break;
3536 //
3537 // This is the location to add new prompt types.
3538 // If your new type loops remember to add ExecutionBreak support.
3539 //
3540 default:
3541 ASSERT(FALSE);
3542 }
3543
3544 if (Response != NULL) {
3545 if (Resp != NULL) {
3546 *Response = Resp;
3547 } else if (Buffer != NULL) {
3548 *Response = Buffer;
3549 }
3550 } else {
3551 if (Resp != NULL) {
3552 FreePool(Resp);
3553 }
3554 if (Buffer != NULL) {
3555 FreePool(Buffer);
3556 }
3557 }
3558
3559 ShellPrintEx(-1, -1, L"\r\n");
3560 return (Status);
3561 }
3562
3563 /**
3564 Prompt the user and return the resultant answer to the requestor.
3565
3566 This function is the same as ShellPromptForResponse, except that the prompt is
3567 automatically pulled from HII.
3568
3569 @param Type What type of question is asked. This is used to filter the input
3570 to prevent invalid answers to question.
3571 @param[in] HiiFormatStringId The format string Id for getting from Hii.
3572 @param[in] HiiFormatHandle The format string Handle for getting from Hii.
3573 @param Response Pointer to Response which will be populated upon return.
3574
3575 @retval EFI_SUCCESS the operation was sucessful.
3576 @return other the operation failed.
3577
3578 @sa ShellPromptForResponse
3579 **/
3580 EFI_STATUS
3581 EFIAPI
3582 ShellPromptForResponseHii (
3583 IN SHELL_PROMPT_REQUEST_TYPE Type,
3584 IN CONST EFI_STRING_ID HiiFormatStringId,
3585 IN CONST EFI_HANDLE HiiFormatHandle,
3586 IN OUT VOID **Response
3587 )
3588 {
3589 CHAR16 *Prompt;
3590 EFI_STATUS Status;
3591
3592 Prompt = HiiGetString(HiiFormatHandle, HiiFormatStringId, NULL);
3593 Status = ShellPromptForResponse(Type, Prompt, Response);
3594 FreePool(Prompt);
3595 return (Status);
3596 }
3597
3598 /**
3599 Function to determin if an entire string is a valid number.
3600
3601 If Hex it must be preceeded with a 0x or has ForceHex, set TRUE.
3602
3603 @param[in] String The string to evaluate.
3604 @param[in] ForceHex TRUE - always assume hex.
3605 @param[in] StopAtSpace TRUE to halt upon finding a space, FALSE to keep going.
3606 @param[in] TimeNumbers TRUE to allow numbers with ":", FALSE otherwise.
3607
3608 @retval TRUE It is all numeric (dec/hex) characters.
3609 @retval FALSE There is a non-numeric character.
3610 **/
3611 BOOLEAN
3612 EFIAPI
3613 InternalShellIsHexOrDecimalNumber (
3614 IN CONST CHAR16 *String,
3615 IN CONST BOOLEAN ForceHex,
3616 IN CONST BOOLEAN StopAtSpace,
3617 IN CONST BOOLEAN TimeNumbers
3618 )
3619 {
3620 BOOLEAN Hex;
3621
3622 //
3623 // chop off a single negative sign
3624 //
3625 if (String != NULL && *String == L'-') {
3626 String++;
3627 }
3628
3629 if (String == NULL) {
3630 return (FALSE);
3631 }
3632
3633 //
3634 // chop leading zeroes
3635 //
3636 while(String != NULL && *String == L'0'){
3637 String++;
3638 }
3639 //
3640 // allow '0x' or '0X', but not 'x' or 'X'
3641 //
3642 if (String != NULL && (*String == L'x' || *String == L'X')) {
3643 if (*(String-1) != L'0') {
3644 //
3645 // we got an x without a preceeding 0
3646 //
3647 return (FALSE);
3648 }
3649 String++;
3650 Hex = TRUE;
3651 } else if (ForceHex) {
3652 Hex = TRUE;
3653 } else {
3654 Hex = FALSE;
3655 }
3656
3657 //
3658 // loop through the remaining characters and use the lib function
3659 //
3660 for ( ; String != NULL && *String != CHAR_NULL && !(StopAtSpace && *String == L' ') ; String++){
3661 if (TimeNumbers && (String[0] == L':')) {
3662 continue;
3663 }
3664 if (Hex) {
3665 if (!ShellIsHexaDecimalDigitCharacter(*String)) {
3666 return (FALSE);
3667 }
3668 } else {
3669 if (!ShellIsDecimalDigitCharacter(*String)) {
3670 return (FALSE);
3671 }
3672 }
3673 }
3674
3675 return (TRUE);
3676 }
3677
3678 /**
3679 Function to determine if a given filename exists.
3680
3681 @param[in] Name Path to test.
3682
3683 @retval EFI_SUCCESS The Path represents a file.
3684 @retval EFI_NOT_FOUND The Path does not represent a file.
3685 @retval other The path failed to open.
3686 **/
3687 EFI_STATUS
3688 EFIAPI
3689 ShellFileExists(
3690 IN CONST CHAR16 *Name
3691 )
3692 {
3693 EFI_STATUS Status;
3694 EFI_SHELL_FILE_INFO *List;
3695
3696 ASSERT(Name != NULL);
3697
3698 List = NULL;
3699 Status = ShellOpenFileMetaArg((CHAR16*)Name, EFI_FILE_MODE_READ, &List);
3700 if (EFI_ERROR(Status)) {
3701 return (Status);
3702 }
3703
3704 ShellCloseFileMetaArg(&List);
3705
3706 return (EFI_SUCCESS);
3707 }
3708
3709 /**
3710 Convert a Unicode character to upper case only if
3711 it maps to a valid small-case ASCII character.
3712
3713 This internal function only deal with Unicode character
3714 which maps to a valid small-case ASCII character, i.e.
3715 L'a' to L'z'. For other Unicode character, the input character
3716 is returned directly.
3717
3718 @param Char The character to convert.
3719
3720 @retval LowerCharacter If the Char is with range L'a' to L'z'.
3721 @retval Unchanged Otherwise.
3722
3723 **/
3724 CHAR16
3725 EFIAPI
3726 InternalShellCharToUpper (
3727 IN CHAR16 Char
3728 )
3729 {
3730 if (Char >= L'a' && Char <= L'z') {
3731 return (CHAR16) (Char - (L'a' - L'A'));
3732 }
3733
3734 return Char;
3735 }
3736
3737 /**
3738 Convert a Unicode character to numerical value.
3739
3740 This internal function only deal with Unicode character
3741 which maps to a valid hexadecimal ASII character, i.e.
3742 L'0' to L'9', L'a' to L'f' or L'A' to L'F'. For other
3743 Unicode character, the value returned does not make sense.
3744
3745 @param Char The character to convert.
3746
3747 @return The numerical value converted.
3748
3749 **/
3750 UINTN
3751 EFIAPI
3752 InternalShellHexCharToUintn (
3753 IN CHAR16 Char
3754 )
3755 {
3756 if (ShellIsDecimalDigitCharacter (Char)) {
3757 return Char - L'0';
3758 }
3759
3760 return (UINTN) (10 + InternalShellCharToUpper (Char) - L'A');
3761 }
3762
3763 /**
3764 Convert a Null-terminated Unicode hexadecimal string to a value of type UINT64.
3765
3766 This function returns a value of type UINT64 by interpreting the contents
3767 of the Unicode string specified by String as a hexadecimal number.
3768 The format of the input Unicode string String is:
3769
3770 [spaces][zeros][x][hexadecimal digits].
3771
3772 The valid hexadecimal digit character is in the range [0-9], [a-f] and [A-F].
3773 The prefix "0x" is optional. Both "x" and "X" is allowed in "0x" prefix.
3774 If "x" appears in the input string, it must be prefixed with at least one 0.
3775 The function will ignore the pad space, which includes spaces or tab characters,
3776 before [zeros], [x] or [hexadecimal digit]. The running zero before [x] or
3777 [hexadecimal digit] will be ignored. Then, the decoding starts after [x] or the
3778 first valid hexadecimal digit. Then, the function stops at the first character that is
3779 a not a valid hexadecimal character or NULL, whichever one comes first.
3780
3781 If String has only pad spaces, then zero is returned.
3782 If String has no leading pad spaces, leading zeros or valid hexadecimal digits,
3783 then zero is returned.
3784
3785 @param[in] String A pointer to a Null-terminated Unicode string.
3786 @param[out] Value Upon a successful return the value of the conversion.
3787 @param[in] StopAtSpace FALSE to skip spaces.
3788
3789 @retval EFI_SUCCESS The conversion was successful.
3790 @retval EFI_INVALID_PARAMETER A parameter was NULL or invalid.
3791 @retval EFI_DEVICE_ERROR An overflow occured.
3792 **/
3793 EFI_STATUS
3794 EFIAPI
3795 InternalShellStrHexToUint64 (
3796 IN CONST CHAR16 *String,
3797 OUT UINT64 *Value,
3798 IN CONST BOOLEAN StopAtSpace
3799 )
3800 {
3801 UINT64 Result;
3802
3803 if (String == NULL || StrSize(String) == 0 || Value == NULL) {
3804 return (EFI_INVALID_PARAMETER);
3805 }
3806
3807 //
3808 // Ignore the pad spaces (space or tab)
3809 //
3810 while ((*String == L' ') || (*String == L'\t')) {
3811 String++;
3812 }
3813
3814 //
3815 // Ignore leading Zeros after the spaces
3816 //
3817 while (*String == L'0') {
3818 String++;
3819 }
3820
3821 if (InternalShellCharToUpper (*String) == L'X') {
3822 if (*(String - 1) != L'0') {
3823 return 0;
3824 }
3825 //
3826 // Skip the 'X'
3827 //
3828 String++;
3829 }
3830
3831 Result = 0;
3832
3833 //
3834 // there is a space where there should't be
3835 //
3836 if (*String == L' ') {
3837 return (EFI_INVALID_PARAMETER);
3838 }
3839
3840 while (ShellIsHexaDecimalDigitCharacter (*String)) {
3841 //
3842 // If the Hex Number represented by String overflows according
3843 // to the range defined by UINT64, then return EFI_DEVICE_ERROR.
3844 //
3845 if (!(Result <= (RShiftU64((((UINT64) ~0) - InternalShellHexCharToUintn (*String)), 4)))) {
3846 // if (!(Result <= ((((UINT64) ~0) - InternalShellHexCharToUintn (*String)) >> 4))) {
3847 return (EFI_DEVICE_ERROR);
3848 }
3849
3850 Result = (LShiftU64(Result, 4));
3851 Result += InternalShellHexCharToUintn (*String);
3852 String++;
3853
3854 //
3855 // stop at spaces if requested
3856 //
3857 if (StopAtSpace && *String == L' ') {
3858 break;
3859 }
3860 }
3861
3862 *Value = Result;
3863 return (EFI_SUCCESS);
3864 }
3865
3866 /**
3867 Convert a Null-terminated Unicode decimal string to a value of
3868 type UINT64.
3869
3870 This function returns a value of type UINT64 by interpreting the contents
3871 of the Unicode string specified by String as a decimal number. The format
3872 of the input Unicode string String is:
3873
3874 [spaces] [decimal digits].
3875
3876 The valid decimal digit character is in the range [0-9]. The
3877 function will ignore the pad space, which includes spaces or
3878 tab characters, before [decimal digits]. The running zero in the
3879 beginning of [decimal digits] will be ignored. Then, the function
3880 stops at the first character that is a not a valid decimal character
3881 or a Null-terminator, whichever one comes first.
3882
3883 If String has only pad spaces, then 0 is returned.
3884 If String has no pad spaces or valid decimal digits,
3885 then 0 is returned.
3886
3887 @param[in] String A pointer to a Null-terminated Unicode string.
3888 @param[out] Value Upon a successful return the value of the conversion.
3889 @param[in] StopAtSpace FALSE to skip spaces.
3890
3891 @retval EFI_SUCCESS The conversion was successful.
3892 @retval EFI_INVALID_PARAMETER A parameter was NULL or invalid.
3893 @retval EFI_DEVICE_ERROR An overflow occured.
3894 **/
3895 EFI_STATUS
3896 EFIAPI
3897 InternalShellStrDecimalToUint64 (
3898 IN CONST CHAR16 *String,
3899 OUT UINT64 *Value,
3900 IN CONST BOOLEAN StopAtSpace
3901 )
3902 {
3903 UINT64 Result;
3904
3905 if (String == NULL || StrSize (String) == 0 || Value == NULL) {
3906 return (EFI_INVALID_PARAMETER);
3907 }
3908
3909 //
3910 // Ignore the pad spaces (space or tab)
3911 //
3912 while ((*String == L' ') || (*String == L'\t')) {
3913 String++;
3914 }
3915
3916 //
3917 // Ignore leading Zeros after the spaces
3918 //
3919 while (*String == L'0') {
3920 String++;
3921 }
3922
3923 Result = 0;
3924
3925 //
3926 // Stop upon space if requested
3927 // (if the whole value was 0)
3928 //
3929 if (StopAtSpace && *String == L' ') {
3930 *Value = Result;
3931 return (EFI_SUCCESS);
3932 }
3933
3934 while (ShellIsDecimalDigitCharacter (*String)) {
3935 //
3936 // If the number represented by String overflows according
3937 // to the range defined by UINT64, then return EFI_DEVICE_ERROR.
3938 //
3939
3940 if (!(Result <= (DivU64x32((((UINT64) ~0) - (*String - L'0')),10)))) {
3941 return (EFI_DEVICE_ERROR);
3942 }
3943
3944 Result = MultU64x32(Result, 10) + (*String - L'0');
3945 String++;
3946
3947 //
3948 // Stop at spaces if requested
3949 //
3950 if (StopAtSpace && *String == L' ') {
3951 break;
3952 }
3953 }
3954
3955 *Value = Result;
3956
3957 return (EFI_SUCCESS);
3958 }
3959
3960 /**
3961 Function to verify and convert a string to its numerical value.
3962
3963 If Hex it must be preceeded with a 0x, 0X, or has ForceHex set TRUE.
3964
3965 @param[in] String The string to evaluate.
3966 @param[out] Value Upon a successful return the value of the conversion.
3967 @param[in] ForceHex TRUE - always assume hex.
3968 @param[in] StopAtSpace FALSE to skip spaces.
3969
3970 @retval EFI_SUCCESS The conversion was successful.
3971 @retval EFI_INVALID_PARAMETER String contained an invalid character.
3972 @retval EFI_NOT_FOUND String was a number, but Value was NULL.
3973 **/
3974 EFI_STATUS
3975 EFIAPI
3976 ShellConvertStringToUint64(
3977 IN CONST CHAR16 *String,
3978 OUT UINT64 *Value,
3979 IN CONST BOOLEAN ForceHex,
3980 IN CONST BOOLEAN StopAtSpace
3981 )
3982 {
3983 UINT64 RetVal;
3984 CONST CHAR16 *Walker;
3985 EFI_STATUS Status;
3986 BOOLEAN Hex;
3987
3988 Hex = ForceHex;
3989
3990 if (!InternalShellIsHexOrDecimalNumber(String, Hex, StopAtSpace, FALSE)) {
3991 if (!Hex) {
3992 Hex = TRUE;
3993 if (!InternalShellIsHexOrDecimalNumber(String, Hex, StopAtSpace, FALSE)) {
3994 return (EFI_INVALID_PARAMETER);
3995 }
3996 } else {
3997 return (EFI_INVALID_PARAMETER);
3998 }
3999 }
4000
4001 //
4002 // Chop off leading spaces
4003 //
4004 for (Walker = String; Walker != NULL && *Walker != CHAR_NULL && *Walker == L' '; Walker++);
4005
4006 //
4007 // make sure we have something left that is numeric.
4008 //
4009 if (Walker == NULL || *Walker == CHAR_NULL || !InternalShellIsHexOrDecimalNumber(Walker, Hex, StopAtSpace, FALSE)) {
4010 return (EFI_INVALID_PARAMETER);
4011 }
4012
4013 //
4014 // do the conversion.
4015 //
4016 if (Hex || StrnCmp(Walker, L"0x", 2) == 0 || StrnCmp(Walker, L"0X", 2) == 0){
4017 Status = InternalShellStrHexToUint64(Walker, &RetVal, StopAtSpace);
4018 } else {
4019 Status = InternalShellStrDecimalToUint64(Walker, &RetVal, StopAtSpace);
4020 }
4021
4022 if (Value == NULL && !EFI_ERROR(Status)) {
4023 return (EFI_NOT_FOUND);
4024 }
4025
4026 if (Value != NULL) {
4027 *Value = RetVal;
4028 }
4029
4030 return (Status);
4031 }
4032
4033 /**
4034 Function to determin if an entire string is a valid number.
4035
4036 If Hex it must be preceeded with a 0x or has ForceHex, set TRUE.
4037
4038 @param[in] String The string to evaluate.
4039 @param[in] ForceHex TRUE - always assume hex.
4040 @param[in] StopAtSpace TRUE to halt upon finding a space, FALSE to keep going.
4041
4042 @retval TRUE It is all numeric (dec/hex) characters.
4043 @retval FALSE There is a non-numeric character.
4044 **/
4045 BOOLEAN
4046 EFIAPI
4047 ShellIsHexOrDecimalNumber (
4048 IN CONST CHAR16 *String,
4049 IN CONST BOOLEAN ForceHex,
4050 IN CONST BOOLEAN StopAtSpace
4051 )
4052 {
4053 if (ShellConvertStringToUint64(String, NULL, ForceHex, StopAtSpace) == EFI_NOT_FOUND) {
4054 return (TRUE);
4055 }
4056 return (FALSE);
4057 }
4058
4059 /**
4060 Function to read a single line from a SHELL_FILE_HANDLE. The \n is not included in the returned
4061 buffer. The returned buffer must be callee freed.
4062
4063 If the position upon start is 0, then the Ascii Boolean will be set. This should be
4064 maintained and not changed for all operations with the same file.
4065
4066 @param[in] Handle SHELL_FILE_HANDLE to read from.
4067 @param[in, out] Ascii Boolean value for indicating whether the file is
4068 Ascii (TRUE) or UCS2 (FALSE).
4069
4070 @return The line of text from the file.
4071 @retval NULL There was not enough memory available.
4072
4073 @sa ShellFileHandleReadLine
4074 **/
4075 CHAR16*
4076 EFIAPI
4077 ShellFileHandleReturnLine(
4078 IN SHELL_FILE_HANDLE Handle,
4079 IN OUT BOOLEAN *Ascii
4080 )
4081 {
4082 CHAR16 *RetVal;
4083 UINTN Size;
4084 EFI_STATUS Status;
4085
4086 Size = 0;
4087 RetVal = NULL;
4088
4089 Status = ShellFileHandleReadLine(Handle, RetVal, &Size, FALSE, Ascii);
4090 if (Status == EFI_BUFFER_TOO_SMALL) {
4091 RetVal = AllocateZeroPool(Size);
4092 if (RetVal == NULL) {
4093 return (NULL);
4094 }
4095 Status = ShellFileHandleReadLine(Handle, RetVal, &Size, FALSE, Ascii);
4096
4097 }
4098 if (Status == EFI_END_OF_FILE && RetVal != NULL && *RetVal != CHAR_NULL) {
4099 Status = EFI_SUCCESS;
4100 }
4101 if (EFI_ERROR(Status) && (RetVal != NULL)) {
4102 FreePool(RetVal);
4103 RetVal = NULL;
4104 }
4105 return (RetVal);
4106 }
4107
4108 /**
4109 Function to read a single line (up to but not including the \n) from a SHELL_FILE_HANDLE.
4110
4111 If the position upon start is 0, then the Ascii Boolean will be set. This should be
4112 maintained and not changed for all operations with the same file.
4113
4114 NOTE: LINES THAT ARE RETURNED BY THIS FUNCTION ARE UCS2, EVEN IF THE FILE BEING READ
4115 IS IN ASCII FORMAT.
4116
4117 @param[in] Handle SHELL_FILE_HANDLE to read from.
4118 @param[in, out] Buffer The pointer to buffer to read into. If this function
4119 returns EFI_SUCCESS, then on output Buffer will
4120 contain a UCS2 string, even if the file being
4121 read is ASCII.
4122 @param[in, out] Size On input, pointer to number of bytes in Buffer.
4123 On output, unchanged unless Buffer is too small
4124 to contain the next line of the file. In that
4125 case Size is set to the number of bytes needed
4126 to hold the next line of the file (as a UCS2
4127 string, even if it is an ASCII file).
4128 @param[in] Truncate If the buffer is large enough, this has no effect.
4129 If the buffer is is too small and Truncate is TRUE,
4130 the line will be truncated.
4131 If the buffer is is too small and Truncate is FALSE,
4132 then no read will occur.
4133
4134 @param[in, out] Ascii Boolean value for indicating whether the file is
4135 Ascii (TRUE) or UCS2 (FALSE).
4136
4137 @retval EFI_SUCCESS The operation was successful. The line is stored in
4138 Buffer.
4139 @retval EFI_END_OF_FILE There are no more lines in the file.
4140 @retval EFI_INVALID_PARAMETER Handle was NULL.
4141 @retval EFI_INVALID_PARAMETER Size was NULL.
4142 @retval EFI_BUFFER_TOO_SMALL Size was not large enough to store the line.
4143 Size was updated to the minimum space required.
4144 **/
4145 EFI_STATUS
4146 EFIAPI
4147 ShellFileHandleReadLine(
4148 IN SHELL_FILE_HANDLE Handle,
4149 IN OUT CHAR16 *Buffer,
4150 IN OUT UINTN *Size,
4151 IN BOOLEAN Truncate,
4152 IN OUT BOOLEAN *Ascii
4153 )
4154 {
4155 EFI_STATUS Status;
4156 CHAR16 CharBuffer;
4157 UINTN CharSize;
4158 UINTN CountSoFar;
4159 UINT64 OriginalFilePosition;
4160
4161
4162 if (Handle == NULL
4163 ||Size == NULL
4164 ){
4165 return (EFI_INVALID_PARAMETER);
4166 }
4167 if (Buffer == NULL) {
4168 ASSERT(*Size == 0);
4169 } else {
4170 *Buffer = CHAR_NULL;
4171 }
4172 gEfiShellProtocol->GetFilePosition(Handle, &OriginalFilePosition);
4173 if (OriginalFilePosition == 0) {
4174 CharSize = sizeof(CHAR16);
4175 Status = gEfiShellProtocol->ReadFile(Handle, &CharSize, &CharBuffer);
4176 ASSERT_EFI_ERROR(Status);
4177 if (CharBuffer == gUnicodeFileTag) {
4178 *Ascii = FALSE;
4179 } else {
4180 *Ascii = TRUE;
4181 gEfiShellProtocol->SetFilePosition(Handle, OriginalFilePosition);
4182 }
4183 }
4184
4185 if (*Ascii) {
4186 CharSize = sizeof(CHAR8);
4187 } else {
4188 CharSize = sizeof(CHAR16);
4189 }
4190 for (CountSoFar = 0;;CountSoFar++){
4191 CharBuffer = 0;
4192 Status = gEfiShellProtocol->ReadFile(Handle, &CharSize, &CharBuffer);
4193 if ( EFI_ERROR(Status)
4194 || CharSize == 0
4195 || (CharBuffer == L'\n' && !(*Ascii))
4196 || (CharBuffer == '\n' && *Ascii)
4197 ){
4198 if (CharSize == 0) {
4199 Status = EFI_END_OF_FILE;
4200 }
4201 break;
4202 }
4203 //
4204 // if we have space save it...
4205 //
4206 if ((CountSoFar+1)*sizeof(CHAR16) < *Size){
4207 ASSERT(Buffer != NULL);
4208 ((CHAR16*)Buffer)[CountSoFar] = CharBuffer;
4209 ((CHAR16*)Buffer)[CountSoFar+1] = CHAR_NULL;
4210 }
4211 }
4212
4213 //
4214 // if we ran out of space tell when...
4215 //
4216 if ((CountSoFar+1)*sizeof(CHAR16) > *Size){
4217 *Size = (CountSoFar+1)*sizeof(CHAR16);
4218 if (!Truncate) {
4219 gEfiShellProtocol->SetFilePosition(Handle, OriginalFilePosition);
4220 } else {
4221 DEBUG((DEBUG_WARN, "The line was truncated in ShellFileHandleReadLine"));
4222 }
4223 return (EFI_BUFFER_TOO_SMALL);
4224 }
4225 while(Buffer[StrLen(Buffer)-1] == L'\r') {
4226 Buffer[StrLen(Buffer)-1] = CHAR_NULL;
4227 }
4228
4229 return (Status);
4230 }
4231
4232 /**
4233 Function to print help file / man page content in the spec from the UEFI Shell protocol GetHelpText function.
4234
4235 @param[in] CommandToGetHelpOn Pointer to a string containing the command name of help file to be printed.
4236 @param[in] SectionToGetHelpOn Pointer to the section specifier(s).
4237 @param[in] PrintCommandText If TRUE, prints the command followed by the help content, otherwise prints
4238 the help content only.
4239 @retval EFI_DEVICE_ERROR The help data format was incorrect.
4240 @retval EFI_NOT_FOUND The help data could not be found.
4241 @retval EFI_SUCCESS The operation was successful.
4242 **/
4243 EFI_STATUS
4244 EFIAPI
4245 ShellPrintHelp (
4246 IN CONST CHAR16 *CommandToGetHelpOn,
4247 IN CONST CHAR16 *SectionToGetHelpOn,
4248 IN BOOLEAN PrintCommandText
4249 )
4250 {
4251 EFI_STATUS Status;
4252 CHAR16 *OutText;
4253
4254 OutText = NULL;
4255
4256 //
4257 // Get the string to print based
4258 //
4259 Status = gEfiShellProtocol->GetHelpText (CommandToGetHelpOn, SectionToGetHelpOn, &OutText);
4260
4261 //
4262 // make sure we got a valid string
4263 //
4264 if (EFI_ERROR(Status)){
4265 return Status;
4266 }
4267 if (OutText == NULL || StrLen(OutText) == 0) {
4268 return EFI_NOT_FOUND;
4269 }
4270
4271 //
4272 // Chop off trailing stuff we dont need
4273 //
4274 while (OutText[StrLen(OutText)-1] == L'\r' || OutText[StrLen(OutText)-1] == L'\n' || OutText[StrLen(OutText)-1] == L' ') {
4275 OutText[StrLen(OutText)-1] = CHAR_NULL;
4276 }
4277
4278 //
4279 // Print this out to the console
4280 //
4281 if (PrintCommandText) {
4282 ShellPrintEx(-1, -1, L"%H%-14s%N- %s\r\n", CommandToGetHelpOn, OutText);
4283 } else {
4284 ShellPrintEx(-1, -1, L"%N%s\r\n", OutText);
4285 }
4286
4287 SHELL_FREE_NON_NULL(OutText);
4288
4289 return EFI_SUCCESS;
4290 }
4291
4292 /**
4293 Function to delete a file by name
4294
4295 @param[in] FileName Pointer to file name to delete.
4296
4297 @retval EFI_SUCCESS the file was deleted sucessfully
4298 @retval EFI_WARN_DELETE_FAILURE the handle was closed, but the file was not
4299 deleted
4300 @retval EFI_INVALID_PARAMETER One of the parameters has an invalid value.
4301 @retval EFI_NOT_FOUND The specified file could not be found on the
4302 device or the file system could not be found
4303 on the device.
4304 @retval EFI_NO_MEDIA The device has no medium.
4305 @retval EFI_MEDIA_CHANGED The device has a different medium in it or the
4306 medium is no longer supported.
4307 @retval EFI_DEVICE_ERROR The device reported an error.
4308 @retval EFI_VOLUME_CORRUPTED The file system structures are corrupted.
4309 @retval EFI_WRITE_PROTECTED The file or medium is write protected.
4310 @retval EFI_ACCESS_DENIED The file was opened read only.
4311 @retval EFI_OUT_OF_RESOURCES Not enough resources were available to open the
4312 file.
4313 @retval other The file failed to open
4314 **/
4315 EFI_STATUS
4316 EFIAPI
4317 ShellDeleteFileByName(
4318 IN CONST CHAR16 *FileName
4319 )
4320 {
4321 EFI_STATUS Status;
4322 SHELL_FILE_HANDLE FileHandle;
4323
4324 Status = ShellFileExists(FileName);
4325
4326 if (Status == EFI_SUCCESS){
4327 Status = ShellOpenFileByName(FileName, &FileHandle, EFI_FILE_MODE_READ | EFI_FILE_MODE_WRITE | EFI_FILE_MODE_CREATE, 0x0);
4328 if (Status == EFI_SUCCESS){
4329 Status = ShellDeleteFile(&FileHandle);
4330 }
4331 }
4332
4333 return(Status);
4334
4335 }
4336
4337 /**
4338 Cleans off all the quotes in the string.
4339
4340 @param[in] OriginalString pointer to the string to be cleaned.
4341 @param[out] CleanString The new string with all quotes removed.
4342 Memory allocated in the function and free
4343 by caller.
4344
4345 @retval EFI_SUCCESS The operation was successful.
4346 **/
4347 EFI_STATUS
4348 EFIAPI
4349 InternalShellStripQuotes (
4350 IN CONST CHAR16 *OriginalString,
4351 OUT CHAR16 **CleanString
4352 )
4353 {
4354 CHAR16 *Walker;
4355
4356 if (OriginalString == NULL || CleanString == NULL) {
4357 return EFI_INVALID_PARAMETER;
4358 }
4359
4360 *CleanString = AllocateCopyPool (StrSize (OriginalString), OriginalString);
4361 if (*CleanString == NULL) {
4362 return EFI_OUT_OF_RESOURCES;
4363 }
4364
4365 for (Walker = *CleanString; Walker != NULL && *Walker != CHAR_NULL ; Walker++) {
4366 if (*Walker == L'\"') {
4367 CopyMem(Walker, Walker+1, StrSize(Walker) - sizeof(Walker[0]));
4368 }
4369 }
4370
4371 return EFI_SUCCESS;
4372 }
4373