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