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