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