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