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