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