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