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