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