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