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