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