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