VirtualBox

source: vbox/trunk/src/VBox/Devices/EFI/Firmware/ShellPkg/Library/UefiShellLib/UefiShellLib.c@ 105681

Last change on this file since 105681 was 105670, checked in by vboxsync, 5 months ago

Devices/EFI/FirmwareNew: Merge edk2-stable-202405 and make it build on aarch64, bugref:4643

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

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette