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