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