1 /** @file
2   Member functions of EFI_SHELL_PROTOCOL and functions for creation,
3   manipulation, and initialization of EFI_SHELL_PROTOCOL.
4 
5   (C) Copyright 2014 Hewlett-Packard Development Company, L.P.<BR>
6   (C) Copyright 2016 Hewlett Packard Enterprise Development LP<BR>
7   Copyright (c) 2009 - 2018, Intel Corporation. All rights reserved.<BR>
8   SPDX-License-Identifier: BSD-2-Clause-Patent
9 
10 **/
11 
12 #include "Shell.h"
13 
14 #define INIT_NAME_BUFFER_SIZE  128
15 
16 /**
17   Close an open file handle.
18 
19   This function closes a specified file handle. All "dirty" cached file data is
20   flushed to the device, and the file is closed. In all cases the handle is
21   closed.
22 
23   @param[in] FileHandle           The file handle to close.
24 
25   @retval EFI_SUCCESS             The file handle was closed successfully.
26 **/
27 EFI_STATUS
28 EFIAPI
EfiShellClose(IN SHELL_FILE_HANDLE FileHandle)29 EfiShellClose (
30   IN SHELL_FILE_HANDLE            FileHandle
31   )
32 {
33   ShellFileHandleRemove(FileHandle);
34   return (FileHandleClose(ConvertShellHandleToEfiFileProtocol(FileHandle)));
35 }
36 
37 /**
38   Internal worker to determine whether there is a BlockIo somewhere
39   upon the device path specified.
40 
41   @param[in] DevicePath    The device path to test.
42 
43   @retval TRUE      gEfiBlockIoProtocolGuid was installed on a handle with this device path
44   @retval FALSE     gEfiBlockIoProtocolGuid was not found.
45 **/
46 BOOLEAN
InternalShellProtocolIsBlockIoPresent(IN CONST EFI_DEVICE_PATH_PROTOCOL * DevicePath)47 InternalShellProtocolIsBlockIoPresent(
48   IN CONST EFI_DEVICE_PATH_PROTOCOL *DevicePath
49   )
50 {
51   EFI_DEVICE_PATH_PROTOCOL  *DevicePathCopy;
52   EFI_STATUS                Status;
53   EFI_HANDLE                Handle;
54 
55   Handle = NULL;
56 
57   DevicePathCopy = (EFI_DEVICE_PATH_PROTOCOL*)DevicePath;
58   Status = gBS->LocateDevicePath(&gEfiBlockIoProtocolGuid, &DevicePathCopy, &Handle);
59 
60   if ((Handle != NULL) && (!EFI_ERROR(Status))) {
61     return (TRUE);
62   }
63   return (FALSE);
64 }
65 
66 /**
67   Internal worker to determine whether there is a file system somewhere
68   upon the device path specified.
69 
70   @param[in] DevicePath    The device path to test.
71 
72   @retval TRUE      gEfiSimpleFileSystemProtocolGuid was installed on a handle with this device path
73   @retval FALSE     gEfiSimpleFileSystemProtocolGuid was not found.
74 **/
75 BOOLEAN
InternalShellProtocolIsSimpleFileSystemPresent(IN CONST EFI_DEVICE_PATH_PROTOCOL * DevicePath)76 InternalShellProtocolIsSimpleFileSystemPresent(
77   IN CONST EFI_DEVICE_PATH_PROTOCOL *DevicePath
78   )
79 {
80   EFI_DEVICE_PATH_PROTOCOL  *DevicePathCopy;
81   EFI_STATUS                Status;
82   EFI_HANDLE                Handle;
83 
84   Handle = NULL;
85 
86   DevicePathCopy = (EFI_DEVICE_PATH_PROTOCOL*)DevicePath;
87   Status = gBS->LocateDevicePath(&gEfiSimpleFileSystemProtocolGuid, &DevicePathCopy, &Handle);
88 
89   if ((Handle != NULL) && (!EFI_ERROR(Status))) {
90     return (TRUE);
91   }
92   return (FALSE);
93 }
94 
95 
96 /**
97   This function creates a mapping for a device path.
98 
99   If both DeviecPath and Mapping are NULL, this will reset the mapping to default values.
100 
101   @param DevicePath             Points to the device path. If this is NULL and Mapping points to a valid mapping,
102                                 then the mapping will be deleted.
103   @param Mapping                Points to the NULL-terminated mapping for the device path.  Must end with a ':'
104 
105   @retval EFI_SUCCESS           Mapping created or deleted successfully.
106   @retval EFI_NO_MAPPING        There is no handle that corresponds exactly to DevicePath. See the
107                                 boot service function LocateDevicePath().
108   @retval EFI_ACCESS_DENIED     The mapping is a built-in alias.
109   @retval EFI_INVALID_PARAMETER Mapping was NULL
110   @retval EFI_INVALID_PARAMETER Mapping did not end with a ':'
111   @retval EFI_INVALID_PARAMETER DevicePath was not pointing at a device that had a SIMPLE_FILE_SYSTEM_PROTOCOL installed.
112   @retval EFI_NOT_FOUND         There was no mapping found to delete
113   @retval EFI_OUT_OF_RESOURCES  Memory allocation failed
114 **/
115 EFI_STATUS
116 EFIAPI
EfiShellSetMap(IN CONST EFI_DEVICE_PATH_PROTOCOL * DevicePath OPTIONAL,IN CONST CHAR16 * Mapping)117 EfiShellSetMap(
118   IN CONST EFI_DEVICE_PATH_PROTOCOL *DevicePath OPTIONAL,
119   IN CONST CHAR16 *Mapping
120   )
121 {
122   EFI_STATUS      Status;
123   SHELL_MAP_LIST  *MapListNode;
124 
125   if (Mapping == NULL){
126     return (EFI_INVALID_PARAMETER);
127   }
128 
129   if (Mapping[StrLen(Mapping)-1] != ':') {
130     return (EFI_INVALID_PARAMETER);
131   }
132 
133   //
134   // Delete the mapping
135   //
136   if (DevicePath == NULL) {
137     if (IsListEmpty(&gShellMapList.Link)) {
138       return (EFI_NOT_FOUND);
139     }
140     for ( MapListNode = (SHELL_MAP_LIST *)GetFirstNode(&gShellMapList.Link)
141         ; !IsNull(&gShellMapList.Link, &MapListNode->Link)
142         ; MapListNode = (SHELL_MAP_LIST *)GetNextNode(&gShellMapList.Link, &MapListNode->Link)
143        ){
144           if (StringNoCaseCompare(&MapListNode->MapName, &Mapping) == 0) {
145             RemoveEntryList(&MapListNode->Link);
146             SHELL_FREE_NON_NULL(MapListNode->DevicePath);
147             SHELL_FREE_NON_NULL(MapListNode->MapName);
148             SHELL_FREE_NON_NULL(MapListNode->CurrentDirectoryPath);
149             FreePool(MapListNode);
150             return (EFI_SUCCESS);
151           }
152     } // for loop
153 
154     //
155     // We didnt find one to delete
156     //
157     return (EFI_NOT_FOUND);
158   }
159 
160   //
161   // make sure this is a valid to add device path
162   //
163   ///@todo add BlockIo to this test...
164   if (!InternalShellProtocolIsSimpleFileSystemPresent(DevicePath)
165     && !InternalShellProtocolIsBlockIoPresent(DevicePath)) {
166     return (EFI_INVALID_PARAMETER);
167   }
168 
169   //
170   // First make sure there is no old mapping
171   //
172   Status = EfiShellSetMap(NULL, Mapping);
173   if ((Status != EFI_SUCCESS) && (Status != EFI_NOT_FOUND)) {
174     return (Status);
175   }
176 
177   //
178   // now add the new one.
179   //
180   Status = ShellCommandAddMapItemAndUpdatePath(Mapping, DevicePath, 0, FALSE);
181 
182   return(Status);
183 }
184 
185 /**
186   Gets the device path from the mapping.
187 
188   This function gets the device path associated with a mapping.
189 
190   @param Mapping                A pointer to the mapping
191 
192   @retval !=NULL                Pointer to the device path that corresponds to the
193                                 device mapping. The returned pointer does not need
194                                 to be freed.
195   @retval NULL                  There is no device path associated with the
196                                 specified mapping.
197 **/
198 CONST EFI_DEVICE_PATH_PROTOCOL *
199 EFIAPI
EfiShellGetDevicePathFromMap(IN CONST CHAR16 * Mapping)200 EfiShellGetDevicePathFromMap(
201   IN CONST CHAR16 *Mapping
202   )
203 {
204   SHELL_MAP_LIST  *MapListItem;
205   CHAR16          *NewName;
206   UINTN           Size;
207 
208   NewName = NULL;
209   Size    = 0;
210 
211   StrnCatGrow(&NewName, &Size, Mapping, 0);
212   if (Mapping[StrLen(Mapping)-1] != L':') {
213     StrnCatGrow(&NewName, &Size, L":", 0);
214   }
215 
216   MapListItem = ShellCommandFindMapItem(NewName);
217 
218   FreePool(NewName);
219 
220   if (MapListItem != NULL) {
221     return (MapListItem->DevicePath);
222   }
223   return(NULL);
224 }
225 
226 /**
227   Gets the mapping(s) that most closely matches the device path.
228 
229   This function gets the mapping which corresponds to the device path *DevicePath. If
230   there is no exact match, then the mapping which most closely matches *DevicePath
231   is returned, and *DevicePath is updated to point to the remaining portion of the
232   device path. If there is an exact match, the mapping is returned and *DevicePath
233   points to the end-of-device-path node.
234 
235   If there are multiple map names they will be semi-colon seperated in the
236   NULL-terminated string.
237 
238   @param DevicePath             On entry, points to a device path pointer. On
239                                 exit, updates the pointer to point to the
240                                 portion of the device path after the mapping.
241 
242   @retval NULL                  No mapping was found.
243   @return !=NULL                Pointer to NULL-terminated mapping. The buffer
244                                 is callee allocated and should be freed by the caller.
245 **/
246 CONST CHAR16 *
247 EFIAPI
EfiShellGetMapFromDevicePath(IN OUT EFI_DEVICE_PATH_PROTOCOL ** DevicePath)248 EfiShellGetMapFromDevicePath(
249   IN OUT EFI_DEVICE_PATH_PROTOCOL **DevicePath
250   )
251 {
252   SHELL_MAP_LIST              *Node;
253   CHAR16                      *PathForReturn;
254   UINTN                       PathSize;
255 //  EFI_HANDLE                  PathHandle;
256 //  EFI_HANDLE                  MapHandle;
257 //  EFI_STATUS                  Status;
258 //  EFI_DEVICE_PATH_PROTOCOL    *DevicePathCopy;
259 //  EFI_DEVICE_PATH_PROTOCOL    *MapPathCopy;
260 
261   if (DevicePath == NULL || *DevicePath == NULL) {
262     return (NULL);
263   }
264 
265   PathForReturn = NULL;
266   PathSize      = 0;
267 
268   for ( Node = (SHELL_MAP_LIST *)GetFirstNode(&gShellMapList.Link)
269       ; !IsNull(&gShellMapList.Link, &Node->Link)
270       ; Node = (SHELL_MAP_LIST *)GetNextNode(&gShellMapList.Link, &Node->Link)
271      ){
272     //
273     // check for exact match
274     //
275     if (DevicePathCompare(DevicePath, &Node->DevicePath) == 0) {
276       ASSERT((PathForReturn == NULL && PathSize == 0) || (PathForReturn != NULL));
277       if (PathSize != 0) {
278         PathForReturn = StrnCatGrow(&PathForReturn, &PathSize, L";", 0);
279       }
280       PathForReturn = StrnCatGrow(&PathForReturn, &PathSize, Node->MapName, 0);
281     }
282   }
283   if (PathForReturn != NULL) {
284     while (!IsDevicePathEndType (*DevicePath)) {
285       *DevicePath = NextDevicePathNode (*DevicePath);
286     }
287     SetDevicePathEndNode (*DevicePath);
288   }
289 /*
290   ///@todo finish code for inexact matches.
291   if (PathForReturn == NULL) {
292     PathSize = 0;
293 
294     DevicePathCopy = DuplicateDevicePath(*DevicePath);
295     ASSERT(DevicePathCopy != NULL);
296     Status = gBS->LocateDevicePath(&gEfiSimpleFileSystemProtocolGuid, &DevicePathCopy, &PathHandle);
297     ASSERT_EFI_ERROR(Status);
298     //
299     //  check each of the device paths we have to get the root of the path for consist mappings
300     //
301     for ( Node = (SHELL_MAP_LIST *)GetFirstNode(&gShellMapList.Link)
302         ; !IsNull(&gShellMapList.Link, &Node->Link)
303         ; Node = (SHELL_MAP_LIST *)GetNextNode(&gShellMapList.Link, &Node->Link)
304        ){
305       if ((Node->Flags & SHELL_MAP_FLAGS_CONSIST) == 0) {
306         continue;
307       }
308       MapPathCopy = DuplicateDevicePath(Node->DevicePath);
309       ASSERT(MapPathCopy != NULL);
310       Status = gBS->LocateDevicePath(&gEfiSimpleFileSystemProtocolGuid, &MapPathCopy, &MapHandle);
311       if (MapHandle == PathHandle) {
312 
313         *DevicePath = DevicePathCopy;
314 
315         MapPathCopy = NULL;
316         DevicePathCopy = NULL;
317         PathForReturn = StrnCatGrow(&PathForReturn, &PathSize, Node->MapName, 0);
318         PathForReturn = StrnCatGrow(&PathForReturn, &PathSize, L";", 0);
319         break;
320       }
321     }
322     //
323     // now add on the non-consistent mappings
324     //
325     for ( Node = (SHELL_MAP_LIST *)GetFirstNode(&gShellMapList.Link)
326         ; !IsNull(&gShellMapList.Link, &Node->Link)
327         ; Node = (SHELL_MAP_LIST *)GetNextNode(&gShellMapList.Link, &Node->Link)
328        ){
329       if ((Node->Flags & SHELL_MAP_FLAGS_CONSIST) != 0) {
330         continue;
331       }
332       MapPathCopy = Node->DevicePath;
333       ASSERT(MapPathCopy != NULL);
334       Status = gBS->LocateDevicePath(&gEfiSimpleFileSystemProtocolGuid, &MapPathCopy, &MapHandle);
335       if (MapHandle == PathHandle) {
336         PathForReturn = StrnCatGrow(&PathForReturn, &PathSize, Node->MapName, 0);
337         PathForReturn = StrnCatGrow(&PathForReturn, &PathSize, L";", 0);
338         break;
339       }
340     }
341   }
342 */
343 
344   return (AddBufferToFreeList(PathForReturn));
345 }
346 
347 /**
348   Converts a device path to a file system-style path.
349 
350   This function converts a device path to a file system path by replacing part, or all, of
351   the device path with the file-system mapping. If there are more than one application
352   file system mappings, the one that most closely matches Path will be used.
353 
354   @param Path                   The pointer to the device path
355 
356   @retval NULL                  the device path could not be found.
357   @return all                   The pointer of the NULL-terminated file path. The path
358                                 is callee-allocated and should be freed by the caller.
359 **/
360 CHAR16 *
361 EFIAPI
EfiShellGetFilePathFromDevicePath(IN CONST EFI_DEVICE_PATH_PROTOCOL * Path)362 EfiShellGetFilePathFromDevicePath(
363   IN CONST EFI_DEVICE_PATH_PROTOCOL *Path
364   )
365 {
366   EFI_DEVICE_PATH_PROTOCOL  *DevicePathCopy;
367   EFI_DEVICE_PATH_PROTOCOL        *MapPathCopy;
368   SHELL_MAP_LIST                  *MapListItem;
369   CHAR16                          *PathForReturn;
370   UINTN                           PathSize;
371   EFI_HANDLE                      PathHandle;
372   EFI_HANDLE                      MapHandle;
373   EFI_STATUS                      Status;
374   FILEPATH_DEVICE_PATH            *FilePath;
375   FILEPATH_DEVICE_PATH            *AlignedNode;
376 
377   PathForReturn = NULL;
378   PathSize = 0;
379 
380   DevicePathCopy = (EFI_DEVICE_PATH_PROTOCOL*)Path;
381   ASSERT(DevicePathCopy != NULL);
382   if (DevicePathCopy == NULL) {
383     return (NULL);
384   }
385   ///@todo BlockIo?
386   Status = gBS->LocateDevicePath(&gEfiSimpleFileSystemProtocolGuid, &DevicePathCopy, &PathHandle);
387 
388   if (EFI_ERROR(Status)) {
389     return (NULL);
390   }
391   //
392   //  check each of the device paths we have to get the root of the path
393   //
394   for ( MapListItem = (SHELL_MAP_LIST *)GetFirstNode(&gShellMapList.Link)
395       ; !IsNull(&gShellMapList.Link, &MapListItem->Link)
396       ; MapListItem = (SHELL_MAP_LIST *)GetNextNode(&gShellMapList.Link, &MapListItem->Link)
397      ){
398     MapPathCopy = (EFI_DEVICE_PATH_PROTOCOL*)MapListItem->DevicePath;
399     ASSERT(MapPathCopy != NULL);
400     ///@todo BlockIo?
401     Status = gBS->LocateDevicePath(&gEfiSimpleFileSystemProtocolGuid, &MapPathCopy, &MapHandle);
402     if (MapHandle == PathHandle) {
403       ASSERT((PathForReturn == NULL && PathSize == 0) || (PathForReturn != NULL));
404       PathForReturn = StrnCatGrow(&PathForReturn, &PathSize, MapListItem->MapName, 0);
405       //
406       // go through all the remaining nodes in the device path
407       //
408       for ( FilePath = (FILEPATH_DEVICE_PATH*)DevicePathCopy
409           ; !IsDevicePathEnd (&FilePath->Header)
410           ; FilePath = (FILEPATH_DEVICE_PATH*)NextDevicePathNode (&FilePath->Header)
411          ){
412         //
413         // If any node is not a file path node, then the conversion can not be completed
414         //
415         if ((DevicePathType(&FilePath->Header) != MEDIA_DEVICE_PATH) ||
416             (DevicePathSubType(&FilePath->Header) != MEDIA_FILEPATH_DP)) {
417           FreePool(PathForReturn);
418           return NULL;
419         }
420 
421         //
422         // append the path part onto the filepath.
423         //
424         ASSERT((PathForReturn == NULL && PathSize == 0) || (PathForReturn != NULL));
425 
426         AlignedNode = AllocateCopyPool (DevicePathNodeLength(FilePath), FilePath);
427         if (AlignedNode == NULL) {
428           FreePool (PathForReturn);
429           return NULL;
430         }
431 
432         // File Path Device Path Nodes 'can optionally add a "\" separator to
433         //  the beginning and/or the end of the Path Name string.'
434         // (UEFI Spec 2.4 section 9.3.6.4).
435         // If necessary, add a "\", but otherwise don't
436         // (This is specified in the above section, and also implied by the
437         //  UEFI Shell spec section 3.7)
438         if ((PathSize != 0)                        &&
439             (PathForReturn != NULL)                &&
440             (PathForReturn[PathSize / sizeof (CHAR16) - 1] != L'\\') &&
441             (AlignedNode->PathName[0]    != L'\\')) {
442           PathForReturn = StrnCatGrow (&PathForReturn, &PathSize, L"\\", 1);
443         }
444 
445         PathForReturn = StrnCatGrow(&PathForReturn, &PathSize, AlignedNode->PathName, 0);
446         FreePool(AlignedNode);
447       } // for loop of remaining nodes
448     }
449     if (PathForReturn != NULL) {
450       break;
451     }
452   } // for loop of paths to check
453   return(PathForReturn);
454 }
455 
456 /**
457   Converts a file system style name to a device path.
458 
459   This function converts a file system style name to a device path, by replacing any
460   mapping references to the associated device path.
461 
462   @param[in] Path               The pointer to the path.
463 
464   @return                       The pointer of the file path. The file path is callee
465                                 allocated and should be freed by the caller.
466   @retval NULL                  The path could not be found.
467   @retval NULL                  There was not enough available memory.
468 **/
469 EFI_DEVICE_PATH_PROTOCOL *
470 EFIAPI
EfiShellGetDevicePathFromFilePath(IN CONST CHAR16 * Path)471 EfiShellGetDevicePathFromFilePath(
472   IN CONST CHAR16 *Path
473   )
474 {
475   CHAR16                          *MapName;
476   CHAR16                          *NewPath;
477   CONST CHAR16                    *Cwd;
478   UINTN                           Size;
479   CONST EFI_DEVICE_PATH_PROTOCOL  *DevicePath;
480   EFI_DEVICE_PATH_PROTOCOL        *DevicePathCopy;
481   EFI_DEVICE_PATH_PROTOCOL        *DevicePathCopyForFree;
482   EFI_DEVICE_PATH_PROTOCOL        *DevicePathForReturn;
483   EFI_HANDLE                      Handle;
484   EFI_STATUS                      Status;
485 
486   if (Path == NULL) {
487     return (NULL);
488   }
489 
490   MapName = NULL;
491   NewPath = NULL;
492 
493   if (StrStr(Path, L":") == NULL) {
494     Cwd = EfiShellGetCurDir(NULL);
495     if (Cwd == NULL) {
496       return (NULL);
497     }
498     Size = StrSize(Cwd) + StrSize(Path);
499     NewPath = AllocateZeroPool(Size);
500     if (NewPath == NULL) {
501       return (NULL);
502     }
503     StrCpyS(NewPath, Size/sizeof(CHAR16), Cwd);
504     StrCatS(NewPath, Size/sizeof(CHAR16), L"\\");
505     if (*Path == L'\\') {
506       Path++;
507       while (PathRemoveLastItem(NewPath)) ;
508     }
509     StrCatS(NewPath, Size/sizeof(CHAR16), Path);
510     DevicePathForReturn = EfiShellGetDevicePathFromFilePath(NewPath);
511     FreePool(NewPath);
512     return (DevicePathForReturn);
513   }
514 
515   Size = 0;
516   //
517   // find the part before (but including) the : for the map name
518   //
519   ASSERT((MapName == NULL && Size == 0) || (MapName != NULL));
520   MapName = StrnCatGrow(&MapName, &Size, Path, (StrStr(Path, L":")-Path+1));
521   if (MapName == NULL || MapName[StrLen(MapName)-1] != L':') {
522     return (NULL);
523   }
524 
525   //
526   // look up the device path in the map
527   //
528   DevicePath = EfiShellGetDevicePathFromMap(MapName);
529   if (DevicePath == NULL) {
530     //
531     // Must have been a bad Mapname
532     //
533     return (NULL);
534   }
535 
536   //
537   // make a copy for LocateDevicePath to modify (also save a pointer to call FreePool with)
538   //
539   DevicePathCopyForFree = DevicePathCopy = DuplicateDevicePath(DevicePath);
540   if (DevicePathCopy == NULL) {
541     FreePool(MapName);
542     return (NULL);
543   }
544 
545   //
546   // get the handle
547   //
548   ///@todo BlockIo?
549   Status = gBS->LocateDevicePath(&gEfiSimpleFileSystemProtocolGuid, &DevicePathCopy, &Handle);
550   if (EFI_ERROR(Status)) {
551     if (DevicePathCopyForFree != NULL) {
552       FreePool(DevicePathCopyForFree);
553     }
554     FreePool(MapName);
555     return (NULL);
556   }
557 
558   //
559   // build the full device path
560   //
561   if ((*(Path+StrLen(MapName)) != CHAR_NULL) &&
562       (*(Path+StrLen(MapName)+1) == CHAR_NULL)) {
563     DevicePathForReturn = FileDevicePath(Handle, L"\\");
564   } else {
565     DevicePathForReturn = FileDevicePath(Handle, Path+StrLen(MapName));
566   }
567 
568   FreePool(MapName);
569   if (DevicePathCopyForFree != NULL) {
570     FreePool(DevicePathCopyForFree);
571   }
572 
573   return (DevicePathForReturn);
574 }
575 
576 /**
577   Gets the name of the device specified by the device handle.
578 
579   This function gets the user-readable name of the device specified by the device
580   handle. If no user-readable name could be generated, then *BestDeviceName will be
581   NULL and EFI_NOT_FOUND will be returned.
582 
583   If EFI_DEVICE_NAME_USE_COMPONENT_NAME is set, then the function will return the
584   device's name using the EFI_COMPONENT_NAME2_PROTOCOL, if present on
585   DeviceHandle.
586 
587   If EFI_DEVICE_NAME_USE_DEVICE_PATH is set, then the function will return the
588   device's name using the EFI_DEVICE_PATH_PROTOCOL, if present on DeviceHandle.
589   If both EFI_DEVICE_NAME_USE_COMPONENT_NAME and
590   EFI_DEVICE_NAME_USE_DEVICE_PATH are set, then
591   EFI_DEVICE_NAME_USE_COMPONENT_NAME will have higher priority.
592 
593   @param DeviceHandle           The handle of the device.
594   @param Flags                  Determines the possible sources of component names.
595                                 Valid bits are:
596                                   EFI_DEVICE_NAME_USE_COMPONENT_NAME
597                                   EFI_DEVICE_NAME_USE_DEVICE_PATH
598   @param Language               A pointer to the language specified for the device
599                                 name, in the same format as described in the UEFI
600                                 specification, Appendix M
601   @param BestDeviceName         On return, points to the callee-allocated NULL-
602                                 terminated name of the device. If no device name
603                                 could be found, points to NULL. The name must be
604                                 freed by the caller...
605 
606   @retval EFI_SUCCESS           Get the name successfully.
607   @retval EFI_NOT_FOUND         Fail to get the device name.
608   @retval EFI_INVALID_PARAMETER Flags did not have a valid bit set.
609   @retval EFI_INVALID_PARAMETER BestDeviceName was NULL
610   @retval EFI_INVALID_PARAMETER DeviceHandle was NULL
611 **/
612 EFI_STATUS
613 EFIAPI
EfiShellGetDeviceName(IN EFI_HANDLE DeviceHandle,IN EFI_SHELL_DEVICE_NAME_FLAGS Flags,IN CHAR8 * Language,OUT CHAR16 ** BestDeviceName)614 EfiShellGetDeviceName(
615   IN EFI_HANDLE DeviceHandle,
616   IN EFI_SHELL_DEVICE_NAME_FLAGS Flags,
617   IN CHAR8 *Language,
618   OUT CHAR16 **BestDeviceName
619   )
620 {
621   EFI_STATUS                        Status;
622   EFI_COMPONENT_NAME2_PROTOCOL      *CompName2;
623   EFI_DEVICE_PATH_PROTOCOL          *DevicePath;
624   EFI_HANDLE                        *HandleList;
625   UINTN                             HandleCount;
626   UINTN                             LoopVar;
627   CHAR16                            *DeviceNameToReturn;
628   CHAR8                             *Lang;
629   UINTN                             ParentControllerCount;
630   EFI_HANDLE                        *ParentControllerBuffer;
631   UINTN                             ParentDriverCount;
632   EFI_HANDLE                        *ParentDriverBuffer;
633 
634   if (BestDeviceName == NULL ||
635       DeviceHandle   == NULL
636      ){
637     return (EFI_INVALID_PARAMETER);
638   }
639 
640   //
641   // make sure one of the 2 supported bits is on
642   //
643   if (((Flags & EFI_DEVICE_NAME_USE_COMPONENT_NAME) == 0) &&
644       ((Flags & EFI_DEVICE_NAME_USE_DEVICE_PATH) == 0)) {
645     return (EFI_INVALID_PARAMETER);
646   }
647 
648   DeviceNameToReturn  = NULL;
649   *BestDeviceName     = NULL;
650   HandleList          = NULL;
651   HandleCount         = 0;
652   Lang                = NULL;
653 
654   if ((Flags & EFI_DEVICE_NAME_USE_COMPONENT_NAME) != 0) {
655     Status = ParseHandleDatabaseByRelationship(
656       NULL,
657       DeviceHandle,
658       HR_DRIVER_BINDING_HANDLE|HR_DEVICE_DRIVER,
659       &HandleCount,
660       &HandleList);
661     for (LoopVar = 0; LoopVar < HandleCount ; LoopVar++){
662       //
663       // Go through those handles until we get one that passes for GetComponentName
664       //
665       Status = gBS->OpenProtocol(
666         HandleList[LoopVar],
667         &gEfiComponentName2ProtocolGuid,
668         (VOID**)&CompName2,
669         gImageHandle,
670         NULL,
671         EFI_OPEN_PROTOCOL_GET_PROTOCOL);
672       if (EFI_ERROR(Status)) {
673         Status = gBS->OpenProtocol(
674           HandleList[LoopVar],
675           &gEfiComponentNameProtocolGuid,
676           (VOID**)&CompName2,
677           gImageHandle,
678           NULL,
679           EFI_OPEN_PROTOCOL_GET_PROTOCOL);
680       }
681 
682       if (EFI_ERROR(Status)) {
683         continue;
684       }
685       Lang = GetBestLanguageForDriver(CompName2->SupportedLanguages, Language, FALSE);
686       Status = CompName2->GetControllerName(CompName2, DeviceHandle, NULL, Lang, &DeviceNameToReturn);
687       FreePool(Lang);
688       Lang = NULL;
689       if (!EFI_ERROR(Status) && DeviceNameToReturn != NULL) {
690         break;
691       }
692     }
693     if (HandleList != NULL) {
694       FreePool(HandleList);
695     }
696 
697     //
698     // Now check the parent controller using this as the child.
699     //
700     if (DeviceNameToReturn == NULL){
701       PARSE_HANDLE_DATABASE_PARENTS(DeviceHandle, &ParentControllerCount, &ParentControllerBuffer);
702       for (LoopVar = 0 ; LoopVar < ParentControllerCount ; LoopVar++) {
703         PARSE_HANDLE_DATABASE_UEFI_DRIVERS(ParentControllerBuffer[LoopVar], &ParentDriverCount, &ParentDriverBuffer);
704         for (HandleCount = 0 ; HandleCount < ParentDriverCount ; HandleCount++) {
705           //
706           // try using that driver's component name with controller and our driver as the child.
707           //
708           Status = gBS->OpenProtocol(
709             ParentDriverBuffer[HandleCount],
710             &gEfiComponentName2ProtocolGuid,
711             (VOID**)&CompName2,
712             gImageHandle,
713             NULL,
714             EFI_OPEN_PROTOCOL_GET_PROTOCOL);
715           if (EFI_ERROR(Status)) {
716             Status = gBS->OpenProtocol(
717               ParentDriverBuffer[HandleCount],
718               &gEfiComponentNameProtocolGuid,
719               (VOID**)&CompName2,
720               gImageHandle,
721               NULL,
722               EFI_OPEN_PROTOCOL_GET_PROTOCOL);
723           }
724 
725           if (EFI_ERROR(Status)) {
726             continue;
727           }
728           Lang = GetBestLanguageForDriver(CompName2->SupportedLanguages, Language, FALSE);
729           Status = CompName2->GetControllerName(CompName2, ParentControllerBuffer[LoopVar], DeviceHandle, Lang, &DeviceNameToReturn);
730           FreePool(Lang);
731           Lang = NULL;
732           if (!EFI_ERROR(Status) && DeviceNameToReturn != NULL) {
733             break;
734           }
735 
736 
737 
738         }
739         SHELL_FREE_NON_NULL(ParentDriverBuffer);
740         if (!EFI_ERROR(Status) && DeviceNameToReturn != NULL) {
741           break;
742         }
743       }
744       SHELL_FREE_NON_NULL(ParentControllerBuffer);
745     }
746     //
747     // dont return on fail since we will try device path if that bit is on
748     //
749     if (DeviceNameToReturn != NULL){
750       ASSERT(BestDeviceName != NULL);
751       StrnCatGrow(BestDeviceName, NULL, DeviceNameToReturn, 0);
752       return (EFI_SUCCESS);
753     }
754   }
755   if ((Flags & EFI_DEVICE_NAME_USE_DEVICE_PATH) != 0) {
756     Status = gBS->OpenProtocol(
757       DeviceHandle,
758       &gEfiDevicePathProtocolGuid,
759       (VOID**)&DevicePath,
760       gImageHandle,
761       NULL,
762       EFI_OPEN_PROTOCOL_GET_PROTOCOL);
763     if (!EFI_ERROR(Status)) {
764       //
765       // use device path to text on the device path
766       //
767       *BestDeviceName = ConvertDevicePathToText(DevicePath, TRUE, TRUE);
768       return (EFI_SUCCESS);
769     }
770   }
771   //
772   // none of the selected bits worked.
773   //
774   return (EFI_NOT_FOUND);
775 }
776 
777 /**
778   Opens the root directory of a device on a handle
779 
780   This function opens the root directory of a device and returns a file handle to it.
781 
782   @param DeviceHandle           The handle of the device that contains the volume.
783   @param FileHandle             On exit, points to the file handle corresponding to the root directory on the
784                                 device.
785 
786   @retval EFI_SUCCESS           Root opened successfully.
787   @retval EFI_NOT_FOUND         EFI_SIMPLE_FILE_SYSTEM could not be found or the root directory
788                                 could not be opened.
789   @retval EFI_VOLUME_CORRUPTED  The data structures in the volume were corrupted.
790   @retval EFI_DEVICE_ERROR      The device had an error.
791   @retval Others                Error status returned from EFI_SIMPLE_FILE_SYSTEM_PROTOCOL->OpenVolume().
792 **/
793 EFI_STATUS
794 EFIAPI
EfiShellOpenRootByHandle(IN EFI_HANDLE DeviceHandle,OUT SHELL_FILE_HANDLE * FileHandle)795 EfiShellOpenRootByHandle(
796   IN EFI_HANDLE DeviceHandle,
797   OUT SHELL_FILE_HANDLE *FileHandle
798   )
799 {
800   EFI_STATUS                      Status;
801   EFI_SIMPLE_FILE_SYSTEM_PROTOCOL *SimpleFileSystem;
802   EFI_FILE_PROTOCOL               *RealFileHandle;
803   EFI_DEVICE_PATH_PROTOCOL        *DevPath;
804 
805   //
806   // get the simple file system interface
807   //
808   Status = gBS->OpenProtocol(DeviceHandle,
809                              &gEfiSimpleFileSystemProtocolGuid,
810                              (VOID**)&SimpleFileSystem,
811                              gImageHandle,
812                              NULL,
813                              EFI_OPEN_PROTOCOL_GET_PROTOCOL);
814   if (EFI_ERROR(Status)) {
815     return (EFI_NOT_FOUND);
816   }
817 
818   Status = gBS->OpenProtocol(DeviceHandle,
819                              &gEfiDevicePathProtocolGuid,
820                              (VOID**)&DevPath,
821                              gImageHandle,
822                              NULL,
823                              EFI_OPEN_PROTOCOL_GET_PROTOCOL);
824   if (EFI_ERROR(Status)) {
825     return (EFI_NOT_FOUND);
826   }
827   //
828   // Open the root volume now...
829   //
830   Status = SimpleFileSystem->OpenVolume(SimpleFileSystem, &RealFileHandle);
831   if (EFI_ERROR(Status)) {
832     return Status;
833   }
834 
835   *FileHandle = ConvertEfiFileProtocolToShellHandle(RealFileHandle, EfiShellGetMapFromDevicePath(&DevPath));
836   return (EFI_SUCCESS);
837 }
838 
839 /**
840   Opens the root directory of a device.
841 
842   This function opens the root directory of a device and returns a file handle to it.
843 
844   @param DevicePath             Points to the device path corresponding to the device where the
845                                 EFI_SIMPLE_FILE_SYSTEM_PROTOCOL is installed.
846   @param FileHandle             On exit, points to the file handle corresponding to the root directory on the
847                                 device.
848 
849   @retval EFI_SUCCESS           Root opened successfully.
850   @retval EFI_NOT_FOUND         EFI_SIMPLE_FILE_SYSTEM could not be found or the root directory
851                                 could not be opened.
852   @retval EFI_VOLUME_CORRUPTED  The data structures in the volume were corrupted.
853   @retval EFI_DEVICE_ERROR      The device had an error
854   @retval EFI_INVALID_PARAMETER FileHandle is NULL.
855 **/
856 EFI_STATUS
857 EFIAPI
EfiShellOpenRoot(IN EFI_DEVICE_PATH_PROTOCOL * DevicePath,OUT SHELL_FILE_HANDLE * FileHandle)858 EfiShellOpenRoot(
859   IN EFI_DEVICE_PATH_PROTOCOL *DevicePath,
860   OUT SHELL_FILE_HANDLE *FileHandle
861   )
862 {
863   EFI_STATUS Status;
864   EFI_HANDLE Handle;
865 
866   if (FileHandle == NULL) {
867     return (EFI_INVALID_PARAMETER);
868   }
869 
870   //
871   // find the handle of the device with that device handle and the file system
872   //
873   ///@todo BlockIo?
874   Status = gBS->LocateDevicePath(&gEfiSimpleFileSystemProtocolGuid,
875                                  &DevicePath,
876                                  &Handle);
877   if (EFI_ERROR(Status)) {
878     return (EFI_NOT_FOUND);
879   }
880 
881   return (EfiShellOpenRootByHandle(Handle, FileHandle));
882 }
883 
884 /**
885   Returns whether any script files are currently being processed.
886 
887   @retval TRUE                 There is at least one script file active.
888   @retval FALSE                No script files are active now.
889 
890 **/
891 BOOLEAN
892 EFIAPI
EfiShellBatchIsActive(VOID)893 EfiShellBatchIsActive (
894   VOID
895   )
896 {
897   if (ShellCommandGetCurrentScriptFile() == NULL) {
898     return (FALSE);
899   }
900   return (TRUE);
901 }
902 
903 /**
904   Worker function to open a file based on a device path.  this will open the root
905   of the volume and then traverse down to the file itself.
906 
907   @param DevicePath               Device Path of the file.
908   @param FileHandle               Pointer to the file upon a successful return.
909   @param OpenMode                 mode to open file in.
910   @param Attributes               the File Attributes to use when creating a new file.
911 
912   @retval EFI_SUCCESS             the file is open and FileHandle is valid
913   @retval EFI_UNSUPPORTED         the device path cotained non-path elements
914   @retval other                   an error ocurred.
915 **/
916 EFI_STATUS
InternalOpenFileDevicePath(IN OUT EFI_DEVICE_PATH_PROTOCOL * DevicePath,OUT SHELL_FILE_HANDLE * FileHandle,IN UINT64 OpenMode,IN UINT64 Attributes OPTIONAL)917 InternalOpenFileDevicePath(
918   IN OUT EFI_DEVICE_PATH_PROTOCOL *DevicePath,
919   OUT SHELL_FILE_HANDLE           *FileHandle,
920   IN UINT64                       OpenMode,
921   IN UINT64                       Attributes OPTIONAL
922   )
923 {
924   EFI_STATUS                      Status;
925   FILEPATH_DEVICE_PATH            *FilePathNode;
926   EFI_HANDLE                      Handle;
927   SHELL_FILE_HANDLE               ShellHandle;
928   EFI_FILE_PROTOCOL               *Handle1;
929   EFI_FILE_PROTOCOL               *Handle2;
930   FILEPATH_DEVICE_PATH            *AlignedNode;
931 
932   if (FileHandle == NULL) {
933     return (EFI_INVALID_PARAMETER);
934   }
935   *FileHandle   = NULL;
936   Handle1       = NULL;
937   Handle2       = NULL;
938   Handle        = NULL;
939   ShellHandle   = NULL;
940   FilePathNode  = NULL;
941   AlignedNode   = NULL;
942 
943   Status = EfiShellOpenRoot(DevicePath, &ShellHandle);
944 
945   if (!EFI_ERROR(Status)) {
946     Handle1 = ConvertShellHandleToEfiFileProtocol(ShellHandle);
947     if (Handle1 != NULL) {
948       //
949       // chop off the begining part before the file system part...
950       //
951       ///@todo BlockIo?
952       Status = gBS->LocateDevicePath(&gEfiSimpleFileSystemProtocolGuid,
953                                      &DevicePath,
954                                      &Handle);
955         if (!EFI_ERROR(Status)) {
956         //
957         // To access as a file system, the file path should only
958         // contain file path components.  Follow the file path nodes
959         // and find the target file
960         //
961         for ( FilePathNode = (FILEPATH_DEVICE_PATH *)DevicePath
962             ; !IsDevicePathEnd (&FilePathNode->Header)
963             ; FilePathNode = (FILEPATH_DEVICE_PATH *) NextDevicePathNode (&FilePathNode->Header)
964            ){
965           SHELL_FREE_NON_NULL(AlignedNode);
966           AlignedNode = AllocateCopyPool (DevicePathNodeLength(FilePathNode), FilePathNode);
967           //
968           // For file system access each node should be a file path component
969           //
970           if (DevicePathType (&FilePathNode->Header) != MEDIA_DEVICE_PATH ||
971               DevicePathSubType (&FilePathNode->Header) != MEDIA_FILEPATH_DP
972              ) {
973             Status = EFI_UNSUPPORTED;
974             break;
975           }
976 
977           //
978           // Open this file path node
979           //
980           Handle2 = Handle1;
981           Handle1 = NULL;
982 
983           //
984           // if this is the last node in the DevicePath always create (if that was requested).
985           //
986           if (IsDevicePathEnd ((NextDevicePathNode (&FilePathNode->Header)))) {
987             Status = Handle2->Open (
988                                   Handle2,
989                                   &Handle1,
990                                   AlignedNode->PathName,
991                                   OpenMode,
992                                   Attributes
993                                  );
994           } else {
995 
996             //
997             //  This is not the last node and we dont want to 'create' existing
998             //  directory entries...
999             //
1000 
1001             //
1002             // open without letting it create
1003             // prevents error on existing files/directories
1004             //
1005             Status = Handle2->Open (
1006                                   Handle2,
1007                                   &Handle1,
1008                                   AlignedNode->PathName,
1009                                   OpenMode &~EFI_FILE_MODE_CREATE,
1010                                   Attributes
1011                                  );
1012             //
1013             // if above failed now open and create the 'item'
1014             // if OpenMode EFI_FILE_MODE_CREATE bit was on (but disabled above)
1015             //
1016             if ((EFI_ERROR (Status)) && ((OpenMode & EFI_FILE_MODE_CREATE) != 0)) {
1017               Status = Handle2->Open (
1018                                     Handle2,
1019                                     &Handle1,
1020                                     AlignedNode->PathName,
1021                                     OpenMode,
1022                                     Attributes
1023                                    );
1024             }
1025           }
1026           //
1027           // Close the last node
1028           //
1029           ShellInfoObject.NewEfiShellProtocol->CloseFile (Handle2);
1030 
1031           //
1032           // If there's been an error, stop
1033           //
1034           if (EFI_ERROR (Status)) {
1035             break;
1036           }
1037         } // for loop
1038       }
1039     }
1040   }
1041   SHELL_FREE_NON_NULL(AlignedNode);
1042   if (EFI_ERROR(Status)) {
1043     if (Handle1 != NULL) {
1044       ShellInfoObject.NewEfiShellProtocol->CloseFile(Handle1);
1045     }
1046   } else {
1047     *FileHandle = ConvertEfiFileProtocolToShellHandle(Handle1, ShellFileHandleGetPath(ShellHandle));
1048   }
1049   return (Status);
1050 }
1051 
1052 /**
1053   Creates a file or directory by name.
1054 
1055   This function creates an empty new file or directory with the specified attributes and
1056   returns the new file's handle. If the file already exists and is read-only, then
1057   EFI_INVALID_PARAMETER will be returned.
1058 
1059   If the file already existed, it is truncated and its attributes updated. If the file is
1060   created successfully, the FileHandle is the file's handle, else, the FileHandle is NULL.
1061 
1062   If the file name begins with >v, then the file handle which is returned refers to the
1063   shell environment variable with the specified name. If the shell environment variable
1064   already exists and is non-volatile then EFI_INVALID_PARAMETER is returned.
1065 
1066   @param FileName           Pointer to NULL-terminated file path
1067   @param FileAttribs        The new file's attrbiutes.  the different attributes are
1068                             described in EFI_FILE_PROTOCOL.Open().
1069   @param FileHandle         On return, points to the created file handle or directory's handle
1070 
1071   @retval EFI_SUCCESS       The file was opened.  FileHandle points to the new file's handle.
1072   @retval EFI_INVALID_PARAMETER One of the parameters has an invalid value.
1073   @retval EFI_UNSUPPORTED   could not open the file path
1074   @retval EFI_NOT_FOUND     the specified file could not be found on the devide, or could not
1075                             file the file system on the device.
1076   @retval EFI_NO_MEDIA      the device has no medium.
1077   @retval EFI_MEDIA_CHANGED The device has a different medium in it or the medium is no
1078                             longer supported.
1079   @retval EFI_DEVICE_ERROR The device reported an error or can't get the file path according
1080                             the DirName.
1081   @retval EFI_VOLUME_CORRUPTED The file system structures are corrupted.
1082   @retval EFI_WRITE_PROTECTED An attempt was made to create a file, or open a file for write
1083                             when the media is write-protected.
1084   @retval EFI_ACCESS_DENIED The service denied access to the file.
1085   @retval EFI_OUT_OF_RESOURCES Not enough resources were available to open the file.
1086   @retval EFI_VOLUME_FULL   The volume is full.
1087 **/
1088 EFI_STATUS
1089 EFIAPI
EfiShellCreateFile(IN CONST CHAR16 * FileName,IN UINT64 FileAttribs,OUT SHELL_FILE_HANDLE * FileHandle)1090 EfiShellCreateFile(
1091   IN CONST CHAR16       *FileName,
1092   IN UINT64             FileAttribs,
1093   OUT SHELL_FILE_HANDLE *FileHandle
1094   )
1095 {
1096   EFI_DEVICE_PATH_PROTOCOL  *DevicePath;
1097   EFI_STATUS                Status;
1098   BOOLEAN                   Volatile;
1099 
1100   //
1101   // Is this for an environment variable
1102   // do we start with >v
1103   //
1104   if (StrStr(FileName, L">v") == FileName) {
1105     Status = IsVolatileEnv (FileName + 2, &Volatile);
1106     if (EFI_ERROR (Status)) {
1107       return Status;
1108     }
1109     if (!Volatile) {
1110       return (EFI_INVALID_PARAMETER);
1111     }
1112     *FileHandle = CreateFileInterfaceEnv(FileName+2);
1113     return (EFI_SUCCESS);
1114   }
1115 
1116   //
1117   // We are opening a regular file.
1118   //
1119   DevicePath = EfiShellGetDevicePathFromFilePath(FileName);
1120   if (DevicePath == NULL) {
1121     return (EFI_NOT_FOUND);
1122   }
1123 
1124   Status = InternalOpenFileDevicePath(DevicePath, FileHandle, EFI_FILE_MODE_READ|EFI_FILE_MODE_WRITE|EFI_FILE_MODE_CREATE, FileAttribs);
1125   FreePool(DevicePath);
1126 
1127   return(Status);
1128 }
1129 
1130 /**
1131   Register a GUID and a localized human readable name for it.
1132 
1133   If Guid is not assigned a name, then assign GuidName to Guid.  This list of GUID
1134   names must be used whenever a shell command outputs GUID information.
1135 
1136   This function is only available when the major and minor versions in the
1137   EfiShellProtocol are greater than or equal to 2 and 1, respectively.
1138 
1139   @param[in] Guid       A pointer to the GUID being registered.
1140   @param[in] GuidName   A pointer to the localized name for the GUID being registered.
1141 
1142   @retval EFI_SUCCESS             The operation was successful.
1143   @retval EFI_INVALID_PARAMETER   Guid was NULL.
1144   @retval EFI_INVALID_PARAMETER   GuidName was NULL.
1145   @retval EFI_ACCESS_DENIED       Guid already is assigned a name.
1146 **/
1147 EFI_STATUS
1148 EFIAPI
EfiShellRegisterGuidName(IN CONST EFI_GUID * Guid,IN CONST CHAR16 * GuidName)1149 EfiShellRegisterGuidName(
1150   IN CONST EFI_GUID *Guid,
1151   IN CONST CHAR16   *GuidName
1152   )
1153 {
1154   return (AddNewGuidNameMapping(Guid, GuidName, NULL));
1155 }
1156 
1157 /**
1158   Opens a file or a directory by file name.
1159 
1160   This function opens the specified file in the specified OpenMode and returns a file
1161   handle.
1162   If the file name begins with >v, then the file handle which is returned refers to the
1163   shell environment variable with the specified name. If the shell environment variable
1164   exists, is non-volatile and the OpenMode indicates EFI_FILE_MODE_WRITE, then
1165   EFI_INVALID_PARAMETER is returned.
1166 
1167   If the file name is >i, then the file handle which is returned refers to the standard
1168   input. If the OpenMode indicates EFI_FILE_MODE_WRITE, then EFI_INVALID_PARAMETER
1169   is returned.
1170 
1171   If the file name is >o, then the file handle which is returned refers to the standard
1172   output. If the OpenMode indicates EFI_FILE_MODE_READ, then EFI_INVALID_PARAMETER
1173   is returned.
1174 
1175   If the file name is >e, then the file handle which is returned refers to the standard
1176   error. If the OpenMode indicates EFI_FILE_MODE_READ, then EFI_INVALID_PARAMETER
1177   is returned.
1178 
1179   If the file name is NUL, then the file handle that is returned refers to the standard NUL
1180   file. If the OpenMode indicates EFI_FILE_MODE_READ, then EFI_INVALID_PARAMETER is
1181   returned.
1182 
1183   If return EFI_SUCCESS, the FileHandle is the opened file's handle, else, the
1184   FileHandle is NULL.
1185 
1186   @param FileName               Points to the NULL-terminated UCS-2 encoded file name.
1187   @param FileHandle             On return, points to the file handle.
1188   @param OpenMode               File open mode. Either EFI_FILE_MODE_READ or
1189                                 EFI_FILE_MODE_WRITE from section 12.4 of the UEFI
1190                                 Specification.
1191   @retval EFI_SUCCESS           The file was opened. FileHandle has the opened file's handle.
1192   @retval EFI_INVALID_PARAMETER One of the parameters has an invalid value. FileHandle is NULL.
1193   @retval EFI_UNSUPPORTED       Could not open the file path. FileHandle is NULL.
1194   @retval EFI_NOT_FOUND         The specified file could not be found on the device or the file
1195                                 system could not be found on the device. FileHandle is NULL.
1196   @retval EFI_NO_MEDIA          The device has no medium. FileHandle is NULL.
1197   @retval EFI_MEDIA_CHANGED     The device has a different medium in it or the medium is no
1198                                 longer supported. FileHandle is NULL.
1199   @retval EFI_DEVICE_ERROR      The device reported an error or can't get the file path according
1200                                 the FileName. FileHandle is NULL.
1201   @retval EFI_VOLUME_CORRUPTED  The file system structures are corrupted. FileHandle is NULL.
1202   @retval EFI_WRITE_PROTECTED   An attempt was made to create a file, or open a file for write
1203                                 when the media is write-protected. FileHandle is NULL.
1204   @retval EFI_ACCESS_DENIED     The service denied access to the file. FileHandle is NULL.
1205   @retval EFI_OUT_OF_RESOURCES  Not enough resources were available to open the file. FileHandle
1206                                 is NULL.
1207   @retval EFI_VOLUME_FULL       The volume is full. FileHandle is NULL.
1208 **/
1209 EFI_STATUS
1210 EFIAPI
EfiShellOpenFileByName(IN CONST CHAR16 * FileName,OUT SHELL_FILE_HANDLE * FileHandle,IN UINT64 OpenMode)1211 EfiShellOpenFileByName(
1212   IN CONST CHAR16       *FileName,
1213   OUT SHELL_FILE_HANDLE *FileHandle,
1214   IN UINT64             OpenMode
1215   )
1216 {
1217   EFI_DEVICE_PATH_PROTOCOL        *DevicePath;
1218   EFI_STATUS                      Status;
1219   BOOLEAN                         Volatile;
1220 
1221   *FileHandle = NULL;
1222 
1223   //
1224   // Is this for StdIn
1225   //
1226   if (StrCmp(FileName, L">i") == 0) {
1227     //
1228     // make sure not writing to StdIn
1229     //
1230     if ((OpenMode & EFI_FILE_MODE_WRITE) != 0) {
1231       return (EFI_INVALID_PARAMETER);
1232     }
1233     *FileHandle = ShellInfoObject.NewShellParametersProtocol->StdIn;
1234     ASSERT(*FileHandle != NULL);
1235     return (EFI_SUCCESS);
1236   }
1237 
1238   //
1239   // Is this for StdOut
1240   //
1241   if (StrCmp(FileName, L">o") == 0) {
1242     //
1243     // make sure not writing to StdIn
1244     //
1245     if ((OpenMode & EFI_FILE_MODE_READ) != 0) {
1246       return (EFI_INVALID_PARAMETER);
1247     }
1248     *FileHandle = &FileInterfaceStdOut;
1249     return (EFI_SUCCESS);
1250   }
1251 
1252   //
1253   // Is this for NUL / NULL file
1254   //
1255   if ((gUnicodeCollation->StriColl (gUnicodeCollation, (CHAR16*)FileName, L"NUL") == 0) ||
1256       (gUnicodeCollation->StriColl (gUnicodeCollation, (CHAR16*)FileName, L"NULL") == 0)) {
1257     *FileHandle = &FileInterfaceNulFile;
1258     return (EFI_SUCCESS);
1259   }
1260 
1261   //
1262   // Is this for StdErr
1263   //
1264   if (StrCmp(FileName, L">e") == 0) {
1265     //
1266     // make sure not writing to StdIn
1267     //
1268     if ((OpenMode & EFI_FILE_MODE_READ) != 0) {
1269       return (EFI_INVALID_PARAMETER);
1270     }
1271     *FileHandle = &FileInterfaceStdErr;
1272     return (EFI_SUCCESS);
1273   }
1274 
1275   //
1276   // Is this for an environment variable
1277   // do we start with >v
1278   //
1279   if (StrStr(FileName, L">v") == FileName) {
1280     Status = IsVolatileEnv (FileName + 2, &Volatile);
1281     if (EFI_ERROR (Status)) {
1282       return Status;
1283     }
1284     if (!Volatile &&
1285         ((OpenMode & EFI_FILE_MODE_WRITE) != 0)) {
1286       return (EFI_INVALID_PARAMETER);
1287     }
1288     *FileHandle = CreateFileInterfaceEnv(FileName+2);
1289     return (EFI_SUCCESS);
1290   }
1291 
1292   //
1293   // We are opening a regular file.
1294   //
1295   DevicePath = EfiShellGetDevicePathFromFilePath(FileName);
1296 
1297   if (DevicePath == NULL) {
1298     return (EFI_NOT_FOUND);
1299   }
1300 
1301   //
1302   // Copy the device path, open the file, then free the memory
1303   //
1304   Status = InternalOpenFileDevicePath(DevicePath, FileHandle, OpenMode, 0); // 0 = no specific file attributes
1305   FreePool(DevicePath);
1306 
1307   return(Status);
1308 }
1309 
1310 /**
1311   Deletes the file specified by the file name.
1312 
1313   This function deletes a file.
1314 
1315   @param FileName                 Points to the NULL-terminated file name.
1316 
1317   @retval EFI_SUCCESS             The file was closed and deleted, and the handle was closed.
1318   @retval EFI_WARN_DELETE_FAILURE The handle was closed but the file was not deleted.
1319   @sa EfiShellCreateFile
1320 **/
1321 EFI_STATUS
1322 EFIAPI
EfiShellDeleteFileByName(IN CONST CHAR16 * FileName)1323 EfiShellDeleteFileByName(
1324   IN CONST CHAR16 *FileName
1325   )
1326 {
1327   SHELL_FILE_HANDLE FileHandle;
1328   EFI_STATUS        Status;
1329 
1330   FileHandle = NULL;
1331 
1332   //
1333   // get a handle to the file
1334   //
1335   Status = EfiShellCreateFile(FileName,
1336                               0,
1337                               &FileHandle);
1338   if (EFI_ERROR(Status)) {
1339     return (Status);
1340   }
1341   //
1342   // now delete the file
1343   //
1344   ShellFileHandleRemove(FileHandle);
1345   return (ShellInfoObject.NewEfiShellProtocol->DeleteFile(FileHandle));
1346 }
1347 
1348 /**
1349   Disables the page break output mode.
1350 **/
1351 VOID
1352 EFIAPI
EfiShellDisablePageBreak(VOID)1353 EfiShellDisablePageBreak (
1354   VOID
1355   )
1356 {
1357   ShellInfoObject.PageBreakEnabled = FALSE;
1358 }
1359 
1360 /**
1361   Enables the page break output mode.
1362 **/
1363 VOID
1364 EFIAPI
EfiShellEnablePageBreak(VOID)1365 EfiShellEnablePageBreak (
1366   VOID
1367   )
1368 {
1369   ShellInfoObject.PageBreakEnabled = TRUE;
1370 }
1371 
1372 /**
1373   internal worker function to load and run an image via device path.
1374 
1375   @param ParentImageHandle      A handle of the image that is executing the specified
1376                                 command line.
1377   @param DevicePath             device path of the file to execute
1378   @param CommandLine            Points to the NULL-terminated UCS-2 encoded string
1379                                 containing the command line. If NULL then the command-
1380                                 line will be empty.
1381   @param Environment            Points to a NULL-terminated array of environment
1382                                 variables with the format 'x=y', where x is the
1383                                 environment variable name and y is the value. If this
1384                                 is NULL, then the current shell environment is used.
1385 
1386   @param[out] StartImageStatus  Returned status from gBS->StartImage.
1387 
1388   @retval EFI_SUCCESS       The command executed successfully. The  status code
1389                             returned by the command is pointed to by StatusCode.
1390   @retval EFI_INVALID_PARAMETER The parameters are invalid.
1391   @retval EFI_OUT_OF_RESOURCES Out of resources.
1392   @retval EFI_UNSUPPORTED   Nested shell invocations are not allowed.
1393 **/
1394 EFI_STATUS
InternalShellExecuteDevicePath(IN CONST EFI_HANDLE * ParentImageHandle,IN CONST EFI_DEVICE_PATH_PROTOCOL * DevicePath,IN CONST CHAR16 * CommandLine OPTIONAL,IN CONST CHAR16 ** Environment OPTIONAL,OUT EFI_STATUS * StartImageStatus OPTIONAL)1395 InternalShellExecuteDevicePath(
1396   IN CONST EFI_HANDLE               *ParentImageHandle,
1397   IN CONST EFI_DEVICE_PATH_PROTOCOL *DevicePath,
1398   IN CONST CHAR16                   *CommandLine OPTIONAL,
1399   IN CONST CHAR16                   **Environment OPTIONAL,
1400   OUT EFI_STATUS                    *StartImageStatus OPTIONAL
1401   )
1402 {
1403   EFI_STATUS                    Status;
1404   EFI_STATUS                    StartStatus;
1405   EFI_STATUS                    CleanupStatus;
1406   EFI_HANDLE                    NewHandle;
1407   EFI_LOADED_IMAGE_PROTOCOL     *LoadedImage;
1408   LIST_ENTRY                    OrigEnvs;
1409   EFI_SHELL_PARAMETERS_PROTOCOL ShellParamsProtocol;
1410   CHAR16                        *ImagePath;
1411   UINTN                         Index;
1412   CHAR16                        *Walker;
1413   CHAR16                        *NewCmdLine;
1414 
1415   if (ParentImageHandle == NULL) {
1416     return (EFI_INVALID_PARAMETER);
1417   }
1418 
1419   InitializeListHead(&OrigEnvs);
1420   ZeroMem(&ShellParamsProtocol, sizeof(EFI_SHELL_PARAMETERS_PROTOCOL));
1421 
1422   NewHandle = NULL;
1423 
1424   NewCmdLine = AllocateCopyPool (StrSize (CommandLine), CommandLine);
1425   if (NewCmdLine == NULL) {
1426     return EFI_OUT_OF_RESOURCES;
1427   }
1428 
1429   for (Walker = NewCmdLine; Walker != NULL && *Walker != CHAR_NULL ; Walker++) {
1430     if (*Walker == L'^' && *(Walker+1) == L'#') {
1431       CopyMem(Walker, Walker+1, StrSize(Walker) - sizeof(Walker[0]));
1432     }
1433   }
1434 
1435   //
1436   // Load the image with:
1437   // FALSE - not from boot manager and NULL, 0 being not already in memory
1438   //
1439   Status = gBS->LoadImage(
1440     FALSE,
1441     *ParentImageHandle,
1442     (EFI_DEVICE_PATH_PROTOCOL*)DevicePath,
1443     NULL,
1444     0,
1445     &NewHandle);
1446 
1447   if (EFI_ERROR(Status)) {
1448     if (NewHandle != NULL) {
1449       gBS->UnloadImage(NewHandle);
1450     }
1451     FreePool (NewCmdLine);
1452     return (Status);
1453   }
1454   Status = gBS->OpenProtocol(
1455     NewHandle,
1456     &gEfiLoadedImageProtocolGuid,
1457     (VOID**)&LoadedImage,
1458     gImageHandle,
1459     NULL,
1460     EFI_OPEN_PROTOCOL_GET_PROTOCOL);
1461 
1462   if (!EFI_ERROR(Status)) {
1463     //
1464     // If the image is not an app abort it.
1465     //
1466     if (LoadedImage->ImageCodeType != EfiLoaderCode){
1467       ShellPrintHiiEx(
1468         -1,
1469         -1,
1470         NULL,
1471         STRING_TOKEN (STR_SHELL_IMAGE_NOT_APP),
1472         ShellInfoObject.HiiHandle
1473       );
1474       goto UnloadImage;
1475     }
1476 
1477     ASSERT(LoadedImage->LoadOptionsSize == 0);
1478     if (NewCmdLine != NULL) {
1479       LoadedImage->LoadOptionsSize  = (UINT32)StrSize(NewCmdLine);
1480       LoadedImage->LoadOptions      = (VOID*)NewCmdLine;
1481     }
1482 
1483     //
1484     // Save our current environment settings for later restoration if necessary
1485     //
1486     if (Environment != NULL) {
1487       Status = GetEnvironmentVariableList(&OrigEnvs);
1488       if (!EFI_ERROR(Status)) {
1489         Status = SetEnvironmentVariables(Environment);
1490       }
1491     }
1492 
1493     //
1494     // Initialize and install a shell parameters protocol on the image.
1495     //
1496     ShellParamsProtocol.StdIn   = ShellInfoObject.NewShellParametersProtocol->StdIn;
1497     ShellParamsProtocol.StdOut  = ShellInfoObject.NewShellParametersProtocol->StdOut;
1498     ShellParamsProtocol.StdErr  = ShellInfoObject.NewShellParametersProtocol->StdErr;
1499     Status = UpdateArgcArgv(&ShellParamsProtocol, NewCmdLine, Efi_Application, NULL, NULL);
1500     ASSERT_EFI_ERROR(Status);
1501     //
1502     // Replace Argv[0] with the full path of the binary we're executing:
1503     // If the command line was "foo", the binary might be called "foo.efi".
1504     // "The first entry in [Argv] is always the full file path of the
1505     //  executable" - UEFI Shell Spec section 2.3
1506     //
1507     ImagePath = EfiShellGetFilePathFromDevicePath (DevicePath);
1508     // The image we're executing isn't necessarily in a filesystem - it might
1509     // be memory mapped. In this case EfiShellGetFilePathFromDevicePath will
1510     // return NULL, and we'll leave Argv[0] as UpdateArgcArgv set it.
1511     if (ImagePath != NULL) {
1512       if (ShellParamsProtocol.Argv == NULL) {
1513         // Command line was empty or null.
1514         // (UpdateArgcArgv sets Argv to NULL when CommandLine is "" or NULL)
1515         ShellParamsProtocol.Argv = AllocatePool (sizeof (CHAR16 *));
1516         if (ShellParamsProtocol.Argv == NULL) {
1517           Status = EFI_OUT_OF_RESOURCES;
1518           goto UnloadImage;
1519         }
1520         ShellParamsProtocol.Argc = 1;
1521       } else {
1522         // Free the string UpdateArgcArgv put in Argv[0];
1523         FreePool (ShellParamsProtocol.Argv[0]);
1524       }
1525       ShellParamsProtocol.Argv[0] = ImagePath;
1526     }
1527 
1528     Status = gBS->InstallProtocolInterface(&NewHandle, &gEfiShellParametersProtocolGuid, EFI_NATIVE_INTERFACE, &ShellParamsProtocol);
1529     ASSERT_EFI_ERROR(Status);
1530 
1531     ///@todo initialize and install ShellInterface protocol on the new image for compatibility if - PcdGetBool(PcdShellSupportOldProtocols)
1532 
1533     //
1534     // now start the image and if the caller wanted the return code pass it to them...
1535     //
1536     if (!EFI_ERROR(Status)) {
1537       StartStatus      = gBS->StartImage(
1538                           NewHandle,
1539                           0,
1540                           NULL
1541                           );
1542       if (StartImageStatus != NULL) {
1543         *StartImageStatus = StartStatus;
1544       }
1545 
1546       CleanupStatus = gBS->UninstallProtocolInterface(
1547                             NewHandle,
1548                             &gEfiShellParametersProtocolGuid,
1549                             &ShellParamsProtocol
1550                             );
1551       ASSERT_EFI_ERROR(CleanupStatus);
1552 
1553       goto FreeAlloc;
1554     }
1555 
1556 UnloadImage:
1557     // Unload image - We should only get here if we didn't call StartImage
1558     gBS->UnloadImage (NewHandle);
1559 
1560 FreeAlloc:
1561     // Free Argv (Allocated in UpdateArgcArgv)
1562     if (ShellParamsProtocol.Argv != NULL) {
1563       for (Index = 0; Index < ShellParamsProtocol.Argc; Index++) {
1564         if (ShellParamsProtocol.Argv[Index] != NULL) {
1565           FreePool (ShellParamsProtocol.Argv[Index]);
1566         }
1567       }
1568       FreePool (ShellParamsProtocol.Argv);
1569     }
1570   }
1571 
1572   // Restore environment variables
1573   if (!IsListEmpty(&OrigEnvs)) {
1574     CleanupStatus = SetEnvironmentVariableList(&OrigEnvs);
1575     ASSERT_EFI_ERROR (CleanupStatus);
1576   }
1577 
1578   FreePool (NewCmdLine);
1579 
1580   return(Status);
1581 }
1582 
1583 /**
1584   internal worker function to load and run an image in the current shell.
1585 
1586   @param CommandLine            Points to the NULL-terminated UCS-2 encoded string
1587                                 containing the command line. If NULL then the command-
1588                                 line will be empty.
1589   @param Environment            Points to a NULL-terminated array of environment
1590                                 variables with the format 'x=y', where x is the
1591                                 environment variable name and y is the value. If this
1592                                 is NULL, then the current shell environment is used.
1593 
1594   @param[out] StartImageStatus  Returned status from the command line.
1595 
1596   @retval EFI_SUCCESS       The command executed successfully. The  status code
1597                             returned by the command is pointed to by StatusCode.
1598   @retval EFI_INVALID_PARAMETER The parameters are invalid.
1599   @retval EFI_OUT_OF_RESOURCES Out of resources.
1600   @retval EFI_UNSUPPORTED   Nested shell invocations are not allowed.
1601 **/
1602 EFI_STATUS
InternalShellExecute(IN CONST CHAR16 * CommandLine OPTIONAL,IN CONST CHAR16 ** Environment OPTIONAL,OUT EFI_STATUS * StartImageStatus OPTIONAL)1603 InternalShellExecute(
1604   IN CONST CHAR16                   *CommandLine OPTIONAL,
1605   IN CONST CHAR16                   **Environment OPTIONAL,
1606   OUT EFI_STATUS                    *StartImageStatus OPTIONAL
1607   )
1608 {
1609   EFI_STATUS                    Status;
1610   EFI_STATUS                    CleanupStatus;
1611   LIST_ENTRY                    OrigEnvs;
1612 
1613   InitializeListHead(&OrigEnvs);
1614 
1615   //
1616   // Save our current environment settings for later restoration if necessary
1617   //
1618   if (Environment != NULL) {
1619     Status = GetEnvironmentVariableList(&OrigEnvs);
1620     if (!EFI_ERROR(Status)) {
1621       Status = SetEnvironmentVariables(Environment);
1622     } else {
1623       return Status;
1624     }
1625   }
1626 
1627   Status = RunShellCommand(CommandLine, StartImageStatus);
1628 
1629   // Restore environment variables
1630   if (!IsListEmpty(&OrigEnvs)) {
1631     CleanupStatus = SetEnvironmentVariableList(&OrigEnvs);
1632     ASSERT_EFI_ERROR (CleanupStatus);
1633   }
1634 
1635   return(Status);
1636 }
1637 
1638 /**
1639   Determine if the UEFI Shell is currently running with nesting enabled or disabled.
1640 
1641   @retval FALSE   nesting is required
1642   @retval other   nesting is enabled
1643 **/
1644 STATIC
1645 BOOLEAN
NestingEnabled(VOID)1646 NestingEnabled(
1647   VOID
1648 )
1649 {
1650   EFI_STATUS  Status;
1651   CHAR16      *Temp;
1652   CHAR16      *Temp2;
1653   UINTN       TempSize;
1654   BOOLEAN     RetVal;
1655 
1656   RetVal = TRUE;
1657   Temp   = NULL;
1658   Temp2  = NULL;
1659 
1660   if (ShellInfoObject.ShellInitSettings.BitUnion.Bits.NoNest) {
1661     TempSize = 0;
1662     Temp     = NULL;
1663     Status = SHELL_GET_ENVIRONMENT_VARIABLE(mNoNestingEnvVarName, &TempSize, Temp);
1664     if (Status == EFI_BUFFER_TOO_SMALL) {
1665       Temp = AllocateZeroPool(TempSize + sizeof(CHAR16));
1666       if (Temp != NULL) {
1667         Status = SHELL_GET_ENVIRONMENT_VARIABLE(mNoNestingEnvVarName, &TempSize, Temp);
1668       }
1669     }
1670     Temp2 = StrnCatGrow(&Temp2, NULL, mNoNestingTrue, 0);
1671     if (Temp != NULL && Temp2 != NULL && StringNoCaseCompare(&Temp, &Temp2) == 0) {
1672       //
1673       // Use the no nesting method.
1674       //
1675       RetVal = FALSE;
1676     }
1677   }
1678 
1679   SHELL_FREE_NON_NULL(Temp);
1680   SHELL_FREE_NON_NULL(Temp2);
1681   return (RetVal);
1682 }
1683 
1684 /**
1685   Execute the command line.
1686 
1687   This function creates a nested instance of the shell and executes the specified
1688   command (CommandLine) with the specified environment (Environment). Upon return,
1689   the status code returned by the specified command is placed in StatusCode.
1690 
1691   If Environment is NULL, then the current environment is used and all changes made
1692   by the commands executed will be reflected in the current environment. If the
1693   Environment is non-NULL, then the changes made will be discarded.
1694 
1695   The CommandLine is executed from the current working directory on the current
1696   device.
1697 
1698   @param ParentImageHandle  A handle of the image that is executing the specified
1699                             command line.
1700   @param CommandLine        Points to the NULL-terminated UCS-2 encoded string
1701                             containing the command line. If NULL then the command-
1702                             line will be empty.
1703   @param Environment        Points to a NULL-terminated array of environment
1704                             variables with the format 'x=y', where x is the
1705                             environment variable name and y is the value. If this
1706                             is NULL, then the current shell environment is used.
1707   @param StatusCode         Points to the status code returned by the CommandLine.
1708 
1709   @retval EFI_SUCCESS       The command executed successfully. The  status code
1710                             returned by the command is pointed to by StatusCode.
1711   @retval EFI_INVALID_PARAMETER The parameters are invalid.
1712   @retval EFI_OUT_OF_RESOURCES Out of resources.
1713   @retval EFI_UNSUPPORTED   Nested shell invocations are not allowed.
1714   @retval EFI_UNSUPPORTED   The support level required for this function is not present.
1715 
1716   @sa InternalShellExecuteDevicePath
1717 **/
1718 EFI_STATUS
1719 EFIAPI
EfiShellExecute(IN EFI_HANDLE * ParentImageHandle,IN CHAR16 * CommandLine OPTIONAL,IN CHAR16 ** Environment OPTIONAL,OUT EFI_STATUS * StatusCode OPTIONAL)1720 EfiShellExecute(
1721   IN EFI_HANDLE *ParentImageHandle,
1722   IN CHAR16 *CommandLine OPTIONAL,
1723   IN CHAR16 **Environment OPTIONAL,
1724   OUT EFI_STATUS *StatusCode OPTIONAL
1725   )
1726 {
1727   EFI_STATUS                Status;
1728   CHAR16                    *Temp;
1729   EFI_DEVICE_PATH_PROTOCOL  *DevPath;
1730   UINTN                     Size;
1731 
1732   if ((PcdGet8(PcdShellSupportLevel) < 1)) {
1733     return (EFI_UNSUPPORTED);
1734   }
1735 
1736   if (NestingEnabled()) {
1737     DevPath = AppendDevicePath (ShellInfoObject.ImageDevPath, ShellInfoObject.FileDevPath);
1738 
1739     DEBUG_CODE_BEGIN();
1740     Temp = ConvertDevicePathToText(ShellInfoObject.FileDevPath, TRUE, TRUE);
1741     FreePool(Temp);
1742     Temp = ConvertDevicePathToText(ShellInfoObject.ImageDevPath, TRUE, TRUE);
1743     FreePool(Temp);
1744     Temp = ConvertDevicePathToText(DevPath, TRUE, TRUE);
1745     FreePool(Temp);
1746     DEBUG_CODE_END();
1747 
1748     Temp = NULL;
1749     Size = 0;
1750     ASSERT((Temp == NULL && Size == 0) || (Temp != NULL));
1751     StrnCatGrow(&Temp, &Size, L"Shell.efi -exit ", 0);
1752     StrnCatGrow(&Temp, &Size, CommandLine, 0);
1753 
1754     Status = InternalShellExecuteDevicePath(
1755       ParentImageHandle,
1756       DevPath,
1757       Temp,
1758       (CONST CHAR16**)Environment,
1759       StatusCode);
1760 
1761     //
1762     // de-allocate and return
1763     //
1764     FreePool(DevPath);
1765     FreePool(Temp);
1766   } else {
1767     Status = InternalShellExecute(
1768       (CONST CHAR16*)CommandLine,
1769       (CONST CHAR16**)Environment,
1770       StatusCode);
1771   }
1772 
1773   return(Status);
1774 }
1775 
1776 /**
1777   Utility cleanup function for EFI_SHELL_FILE_INFO objects.
1778 
1779   1) frees all pointers (non-NULL)
1780   2) Closes the SHELL_FILE_HANDLE
1781 
1782   @param FileListNode     pointer to the list node to free
1783 **/
1784 VOID
InternalFreeShellFileInfoNode(IN EFI_SHELL_FILE_INFO * FileListNode)1785 InternalFreeShellFileInfoNode(
1786   IN EFI_SHELL_FILE_INFO *FileListNode
1787   )
1788 {
1789   if (FileListNode->Info != NULL) {
1790     FreePool((VOID*)FileListNode->Info);
1791   }
1792   if (FileListNode->FileName != NULL) {
1793     FreePool((VOID*)FileListNode->FileName);
1794   }
1795   if (FileListNode->FullName != NULL) {
1796     FreePool((VOID*)FileListNode->FullName);
1797   }
1798   if (FileListNode->Handle != NULL) {
1799     ShellInfoObject.NewEfiShellProtocol->CloseFile(FileListNode->Handle);
1800   }
1801   FreePool(FileListNode);
1802 }
1803 /**
1804   Frees the file list.
1805 
1806   This function cleans up the file list and any related data structures. It has no
1807   impact on the files themselves.
1808 
1809   @param FileList               The file list to free. Type EFI_SHELL_FILE_INFO is
1810                                 defined in OpenFileList()
1811 
1812   @retval EFI_SUCCESS           Free the file list successfully.
1813   @retval EFI_INVALID_PARAMETER FileList was NULL or *FileList was NULL;
1814 **/
1815 EFI_STATUS
1816 EFIAPI
EfiShellFreeFileList(IN EFI_SHELL_FILE_INFO ** FileList)1817 EfiShellFreeFileList(
1818   IN EFI_SHELL_FILE_INFO **FileList
1819   )
1820 {
1821   EFI_SHELL_FILE_INFO *ShellFileListItem;
1822 
1823   if (FileList == NULL || *FileList == NULL) {
1824     return (EFI_INVALID_PARAMETER);
1825   }
1826 
1827   for ( ShellFileListItem = (EFI_SHELL_FILE_INFO*)GetFirstNode(&(*FileList)->Link)
1828       ; !IsListEmpty(&(*FileList)->Link)
1829       ; ShellFileListItem = (EFI_SHELL_FILE_INFO*)GetFirstNode(&(*FileList)->Link)
1830      ){
1831     RemoveEntryList(&ShellFileListItem->Link);
1832     InternalFreeShellFileInfoNode(ShellFileListItem);
1833   }
1834   InternalFreeShellFileInfoNode(*FileList);
1835   *FileList = NULL;
1836   return(EFI_SUCCESS);
1837 }
1838 
1839 /**
1840   Deletes the duplicate file names files in the given file list.
1841 
1842   This function deletes the reduplicate files in the given file list.
1843 
1844   @param FileList               A pointer to the first entry in the file list.
1845 
1846   @retval EFI_SUCCESS           Always success.
1847   @retval EFI_INVALID_PARAMETER FileList was NULL or *FileList was NULL;
1848 **/
1849 EFI_STATUS
1850 EFIAPI
EfiShellRemoveDupInFileList(IN EFI_SHELL_FILE_INFO ** FileList)1851 EfiShellRemoveDupInFileList(
1852   IN EFI_SHELL_FILE_INFO **FileList
1853   )
1854 {
1855   EFI_SHELL_FILE_INFO *ShellFileListItem;
1856   EFI_SHELL_FILE_INFO *ShellFileListItem2;
1857   EFI_SHELL_FILE_INFO *TempNode;
1858 
1859   if (FileList == NULL || *FileList == NULL) {
1860     return (EFI_INVALID_PARAMETER);
1861   }
1862   for ( ShellFileListItem = (EFI_SHELL_FILE_INFO*)GetFirstNode(&(*FileList)->Link)
1863       ; !IsNull(&(*FileList)->Link, &ShellFileListItem->Link)
1864       ; ShellFileListItem = (EFI_SHELL_FILE_INFO*)GetNextNode(&(*FileList)->Link, &ShellFileListItem->Link)
1865      ){
1866     for ( ShellFileListItem2 = (EFI_SHELL_FILE_INFO*)GetNextNode(&(*FileList)->Link, &ShellFileListItem->Link)
1867         ; !IsNull(&(*FileList)->Link, &ShellFileListItem2->Link)
1868         ; ShellFileListItem2 = (EFI_SHELL_FILE_INFO*)GetNextNode(&(*FileList)->Link, &ShellFileListItem2->Link)
1869        ){
1870       if (gUnicodeCollation->StriColl(
1871             gUnicodeCollation,
1872             (CHAR16*)ShellFileListItem->FullName,
1873             (CHAR16*)ShellFileListItem2->FullName) == 0
1874          ){
1875         TempNode = (EFI_SHELL_FILE_INFO *)GetPreviousNode(
1876                                             &(*FileList)->Link,
1877                                             &ShellFileListItem2->Link
1878                                             );
1879         RemoveEntryList(&ShellFileListItem2->Link);
1880         InternalFreeShellFileInfoNode(ShellFileListItem2);
1881         // Set ShellFileListItem2 to PreviousNode so we don't access Freed
1882         // memory in GetNextNode in the loop expression above.
1883         ShellFileListItem2 = TempNode;
1884       }
1885     }
1886   }
1887   return (EFI_SUCCESS);
1888 }
1889 
1890 //
1891 // This is the same structure as the external version, but it has no CONST qualifiers.
1892 //
1893 typedef struct {
1894   LIST_ENTRY        Link;       ///< Linked list members.
1895   EFI_STATUS        Status;     ///< Status of opening the file.  Valid only if Handle != NULL.
1896         CHAR16      *FullName;  ///< Fully qualified filename.
1897         CHAR16      *FileName;  ///< name of this file.
1898   SHELL_FILE_HANDLE Handle;     ///< Handle for interacting with the opened file or NULL if closed.
1899   EFI_FILE_INFO     *Info;      ///< Pointer to the FileInfo struct for this file or NULL.
1900 } EFI_SHELL_FILE_INFO_NO_CONST;
1901 
1902 /**
1903   Allocates and duplicates a EFI_SHELL_FILE_INFO node.
1904 
1905   @param[in] Node     The node to copy from.
1906   @param[in] Save     TRUE to set Node->Handle to NULL, FALSE otherwise.
1907 
1908   @retval NULL        a memory allocation error ocurred
1909   @return != NULL     a pointer to the new node
1910 **/
1911 EFI_SHELL_FILE_INFO*
InternalDuplicateShellFileInfo(IN EFI_SHELL_FILE_INFO * Node,IN BOOLEAN Save)1912 InternalDuplicateShellFileInfo(
1913   IN       EFI_SHELL_FILE_INFO *Node,
1914   IN BOOLEAN                   Save
1915   )
1916 {
1917   EFI_SHELL_FILE_INFO_NO_CONST *NewNode;
1918 
1919   //
1920   // try to confirm that the objects are in sync
1921   //
1922   ASSERT(sizeof(EFI_SHELL_FILE_INFO_NO_CONST) == sizeof(EFI_SHELL_FILE_INFO));
1923 
1924   NewNode = AllocateZeroPool(sizeof(EFI_SHELL_FILE_INFO));
1925   if (NewNode == NULL) {
1926     return (NULL);
1927   }
1928   NewNode->FullName = AllocateCopyPool(StrSize(Node->FullName), Node->FullName);
1929   NewNode->FileName = AllocateCopyPool(StrSize(Node->FileName), Node->FileName);
1930   NewNode->Info     = AllocateCopyPool((UINTN)Node->Info->Size, Node->Info);
1931   if ( NewNode->FullName == NULL
1932     || NewNode->FileName == NULL
1933     || NewNode->Info == NULL
1934   ){
1935     SHELL_FREE_NON_NULL(NewNode->FullName);
1936     SHELL_FREE_NON_NULL(NewNode->FileName);
1937     SHELL_FREE_NON_NULL(NewNode->Info);
1938     SHELL_FREE_NON_NULL(NewNode);
1939     return(NULL);
1940   }
1941   NewNode->Status = Node->Status;
1942   NewNode->Handle = Node->Handle;
1943   if (!Save) {
1944     Node->Handle = NULL;
1945   }
1946 
1947   return((EFI_SHELL_FILE_INFO*)NewNode);
1948 }
1949 
1950 /**
1951   Allocates and populates a EFI_SHELL_FILE_INFO structure.  if any memory operation
1952   failed it will return NULL.
1953 
1954   @param[in] BasePath         the Path to prepend onto filename for FullPath
1955   @param[in] Status           Status member initial value.
1956   @param[in] FileName         FileName member initial value.
1957   @param[in] Handle           Handle member initial value.
1958   @param[in] Info             Info struct to copy.
1959 
1960   @retval NULL                An error ocurred.
1961   @return                     a pointer to the newly allocated structure.
1962 **/
1963 EFI_SHELL_FILE_INFO *
CreateAndPopulateShellFileInfo(IN CONST CHAR16 * BasePath,IN CONST EFI_STATUS Status,IN CONST CHAR16 * FileName,IN CONST SHELL_FILE_HANDLE Handle,IN CONST EFI_FILE_INFO * Info)1964 CreateAndPopulateShellFileInfo(
1965   IN CONST CHAR16 *BasePath,
1966   IN CONST EFI_STATUS Status,
1967   IN CONST CHAR16 *FileName,
1968   IN CONST SHELL_FILE_HANDLE Handle,
1969   IN CONST EFI_FILE_INFO *Info
1970   )
1971 {
1972   EFI_SHELL_FILE_INFO *ShellFileListItem;
1973   CHAR16              *TempString;
1974   UINTN               Size;
1975 
1976   TempString = NULL;
1977   Size = 0;
1978 
1979   ShellFileListItem = AllocateZeroPool(sizeof(EFI_SHELL_FILE_INFO));
1980   if (ShellFileListItem == NULL) {
1981     return (NULL);
1982   }
1983   if (Info != NULL && Info->Size != 0) {
1984     ShellFileListItem->Info = AllocateZeroPool((UINTN)Info->Size);
1985     if (ShellFileListItem->Info == NULL) {
1986       FreePool(ShellFileListItem);
1987       return (NULL);
1988     }
1989     CopyMem(ShellFileListItem->Info, Info, (UINTN)Info->Size);
1990   } else {
1991     ShellFileListItem->Info = NULL;
1992   }
1993   if (FileName != NULL) {
1994     ASSERT(TempString == NULL);
1995     ShellFileListItem->FileName = StrnCatGrow(&TempString, 0, FileName, 0);
1996     if (ShellFileListItem->FileName == NULL) {
1997       FreePool(ShellFileListItem->Info);
1998       FreePool(ShellFileListItem);
1999       return (NULL);
2000     }
2001   } else {
2002     ShellFileListItem->FileName = NULL;
2003   }
2004   Size = 0;
2005   TempString = NULL;
2006   if (BasePath != NULL) {
2007     ASSERT((TempString == NULL && Size == 0) || (TempString != NULL));
2008     TempString = StrnCatGrow(&TempString, &Size, BasePath, 0);
2009     if (TempString == NULL) {
2010       FreePool((VOID*)ShellFileListItem->FileName);
2011       SHELL_FREE_NON_NULL(ShellFileListItem->Info);
2012       FreePool(ShellFileListItem);
2013       return (NULL);
2014     }
2015   }
2016   if (ShellFileListItem->FileName != NULL) {
2017     ASSERT((TempString == NULL && Size == 0) || (TempString != NULL));
2018     TempString = StrnCatGrow(&TempString, &Size, ShellFileListItem->FileName, 0);
2019     if (TempString == NULL) {
2020       FreePool((VOID*)ShellFileListItem->FileName);
2021       FreePool(ShellFileListItem->Info);
2022       FreePool(ShellFileListItem);
2023       return (NULL);
2024     }
2025   }
2026 
2027   TempString = PathCleanUpDirectories(TempString);
2028 
2029   ShellFileListItem->FullName = TempString;
2030   ShellFileListItem->Status   = Status;
2031   ShellFileListItem->Handle   = Handle;
2032 
2033   return (ShellFileListItem);
2034 }
2035 
2036 /**
2037   Find all files in a specified directory.
2038 
2039   @param FileDirHandle          Handle of the directory to search.
2040   @param FileList               On return, points to the list of files in the directory
2041                                 or NULL if there are no files in the directory.
2042 
2043   @retval EFI_SUCCESS           File information was returned successfully.
2044   @retval EFI_VOLUME_CORRUPTED  The file system structures have been corrupted.
2045   @retval EFI_DEVICE_ERROR      The device reported an error.
2046   @retval EFI_NO_MEDIA          The device media is not present.
2047   @retval EFI_INVALID_PARAMETER The FileDirHandle was not a directory.
2048   @return                       An error from FileHandleGetFileName().
2049 **/
2050 EFI_STATUS
2051 EFIAPI
EfiShellFindFilesInDir(IN SHELL_FILE_HANDLE FileDirHandle,OUT EFI_SHELL_FILE_INFO ** FileList)2052 EfiShellFindFilesInDir(
2053   IN SHELL_FILE_HANDLE FileDirHandle,
2054   OUT EFI_SHELL_FILE_INFO **FileList
2055   )
2056 {
2057   EFI_SHELL_FILE_INFO       *ShellFileList;
2058   EFI_SHELL_FILE_INFO       *ShellFileListItem;
2059   EFI_FILE_INFO             *FileInfo;
2060   EFI_STATUS                Status;
2061   BOOLEAN                   NoFile;
2062   CHAR16                    *TempString;
2063   CHAR16                    *BasePath;
2064   UINTN                     Size;
2065   CHAR16                    *TempSpot;
2066 
2067   BasePath = NULL;
2068   Status = FileHandleGetFileName(FileDirHandle, &BasePath);
2069   if (EFI_ERROR(Status)) {
2070     return (Status);
2071   }
2072 
2073   if (ShellFileHandleGetPath(FileDirHandle) != NULL) {
2074     TempString        = NULL;
2075     Size              = 0;
2076     TempString        = StrnCatGrow(&TempString, &Size, ShellFileHandleGetPath(FileDirHandle), 0);
2077     if (TempString == NULL) {
2078       SHELL_FREE_NON_NULL(BasePath);
2079       return (EFI_OUT_OF_RESOURCES);
2080     }
2081     TempSpot          = StrStr(TempString, L";");
2082 
2083     if (TempSpot != NULL) {
2084       *TempSpot = CHAR_NULL;
2085     }
2086 
2087     TempString        = StrnCatGrow(&TempString, &Size, BasePath, 0);
2088     if (TempString == NULL) {
2089       SHELL_FREE_NON_NULL(BasePath);
2090       return (EFI_OUT_OF_RESOURCES);
2091     }
2092     SHELL_FREE_NON_NULL(BasePath);
2093     BasePath          = TempString;
2094   }
2095 
2096   NoFile            = FALSE;
2097   ShellFileList     = NULL;
2098   ShellFileListItem = NULL;
2099   FileInfo          = NULL;
2100   Status            = EFI_SUCCESS;
2101 
2102 
2103   for ( Status = FileHandleFindFirstFile(FileDirHandle, &FileInfo)
2104       ; !EFI_ERROR(Status) && !NoFile
2105       ; Status = FileHandleFindNextFile(FileDirHandle, FileInfo, &NoFile)
2106      ){
2107     if (ShellFileList == NULL) {
2108       ShellFileList = (EFI_SHELL_FILE_INFO*)AllocateZeroPool(sizeof(EFI_SHELL_FILE_INFO));
2109       if (ShellFileList == NULL) {
2110         SHELL_FREE_NON_NULL (BasePath);
2111         return EFI_OUT_OF_RESOURCES;
2112       }
2113       InitializeListHead(&ShellFileList->Link);
2114     }
2115     //
2116     // allocate a new EFI_SHELL_FILE_INFO and populate it...
2117     //
2118     ShellFileListItem = CreateAndPopulateShellFileInfo(
2119       BasePath,
2120       EFI_SUCCESS,  // success since we didnt fail to open it...
2121       FileInfo->FileName,
2122       NULL,         // no handle since not open
2123       FileInfo);
2124     if (ShellFileListItem == NULL) {
2125       Status = EFI_OUT_OF_RESOURCES;
2126       //
2127       // Free resources outside the loop.
2128       //
2129       break;
2130     }
2131     InsertTailList(&ShellFileList->Link, &ShellFileListItem->Link);
2132   }
2133   if (EFI_ERROR(Status)) {
2134     EfiShellFreeFileList(&ShellFileList);
2135     *FileList = NULL;
2136   } else {
2137     *FileList = ShellFileList;
2138   }
2139   SHELL_FREE_NON_NULL(BasePath);
2140   return(Status);
2141 }
2142 
2143 /**
2144   Get the GUID value from a human readable name.
2145 
2146   If GuidName is a known GUID name, then update Guid to have the correct value for
2147   that GUID.
2148 
2149   This function is only available when the major and minor versions in the
2150   EfiShellProtocol are greater than or equal to 2 and 1, respectively.
2151 
2152   @param[in]  GuidName   A pointer to the localized name for the GUID being queried.
2153   @param[out] Guid       A pointer to the GUID structure to be filled in.
2154 
2155   @retval EFI_SUCCESS             The operation was successful.
2156   @retval EFI_INVALID_PARAMETER   Guid was NULL.
2157   @retval EFI_INVALID_PARAMETER   GuidName was NULL.
2158   @retval EFI_NOT_FOUND           GuidName is not a known GUID Name.
2159 **/
2160 EFI_STATUS
2161 EFIAPI
EfiShellGetGuidFromName(IN CONST CHAR16 * GuidName,OUT EFI_GUID * Guid)2162 EfiShellGetGuidFromName(
2163   IN  CONST CHAR16   *GuidName,
2164   OUT       EFI_GUID *Guid
2165   )
2166 {
2167   EFI_GUID    *NewGuid;
2168   EFI_STATUS  Status;
2169 
2170   if (Guid == NULL || GuidName == NULL) {
2171     return (EFI_INVALID_PARAMETER);
2172   }
2173 
2174   Status = GetGuidFromStringName(GuidName, NULL, &NewGuid);
2175 
2176   if (!EFI_ERROR(Status)) {
2177     CopyGuid(Guid, NewGuid);
2178   }
2179 
2180   return (Status);
2181 }
2182 
2183 /**
2184   Get the human readable name for a GUID from the value.
2185 
2186   If Guid is assigned a name, then update *GuidName to point to the name. The callee
2187   should not modify the value.
2188 
2189   This function is only available when the major and minor versions in the
2190   EfiShellProtocol are greater than or equal to 2 and 1, respectively.
2191 
2192   @param[in]  Guid       A pointer to the GUID being queried.
2193   @param[out] GuidName   A pointer to a pointer the localized to name for the GUID being requested
2194 
2195   @retval EFI_SUCCESS             The operation was successful.
2196   @retval EFI_INVALID_PARAMETER   Guid was NULL.
2197   @retval EFI_INVALID_PARAMETER   GuidName was NULL.
2198   @retval EFI_NOT_FOUND           Guid is not assigned a name.
2199 **/
2200 EFI_STATUS
2201 EFIAPI
EfiShellGetGuidName(IN CONST EFI_GUID * Guid,OUT CONST CHAR16 ** GuidName)2202 EfiShellGetGuidName(
2203   IN  CONST EFI_GUID *Guid,
2204   OUT CONST CHAR16   **GuidName
2205   )
2206 {
2207   CHAR16   *Name;
2208 
2209   if (Guid == NULL || GuidName == NULL) {
2210     return (EFI_INVALID_PARAMETER);
2211   }
2212 
2213   Name = GetStringNameFromGuid(Guid, NULL);
2214   if (Name == NULL || StrLen(Name) == 0) {
2215     SHELL_FREE_NON_NULL(Name);
2216     return (EFI_NOT_FOUND);
2217   }
2218 
2219   *GuidName = AddBufferToFreeList(Name);
2220 
2221   return (EFI_SUCCESS);
2222 }
2223 
2224 
2225 
2226 /**
2227   If FileHandle is a directory then the function reads from FileHandle and reads in
2228   each of the FileInfo structures.  If one of them matches the Pattern's first
2229   "level" then it opens that handle and calls itself on that handle.
2230 
2231   If FileHandle is a file and matches all of the remaining Pattern (which would be
2232   on its last node), then add a EFI_SHELL_FILE_INFO object for this file to fileList.
2233 
2234   Upon a EFI_SUCCESS return fromt he function any the caller is responsible to call
2235   FreeFileList with FileList.
2236 
2237   @param[in] FilePattern         The FilePattern to check against.
2238   @param[in] UnicodeCollation    The pointer to EFI_UNICODE_COLLATION_PROTOCOL structure
2239   @param[in] FileHandle          The FileHandle to start with
2240   @param[in, out] FileList       pointer to pointer to list of found files.
2241   @param[in] ParentNode          The node for the parent. Same file as identified by HANDLE.
2242   @param[in] MapName             The file system name this file is on.
2243 
2244   @retval EFI_SUCCESS           all files were found and the FileList contains a list.
2245   @retval EFI_NOT_FOUND         no files were found
2246   @retval EFI_OUT_OF_RESOURCES  a memory allocation failed
2247 **/
2248 EFI_STATUS
ShellSearchHandle(IN CONST CHAR16 * FilePattern,IN EFI_UNICODE_COLLATION_PROTOCOL * UnicodeCollation,IN SHELL_FILE_HANDLE FileHandle,IN OUT EFI_SHELL_FILE_INFO ** FileList,IN CONST EFI_SHELL_FILE_INFO * ParentNode OPTIONAL,IN CONST CHAR16 * MapName)2249 ShellSearchHandle(
2250   IN     CONST CHAR16                         *FilePattern,
2251   IN           EFI_UNICODE_COLLATION_PROTOCOL *UnicodeCollation,
2252   IN           SHELL_FILE_HANDLE              FileHandle,
2253   IN OUT       EFI_SHELL_FILE_INFO            **FileList,
2254   IN     CONST EFI_SHELL_FILE_INFO            *ParentNode OPTIONAL,
2255   IN     CONST CHAR16                         *MapName
2256   )
2257 {
2258   EFI_STATUS          Status;
2259   CONST CHAR16        *NextFilePatternStart;
2260   CHAR16              *CurrentFilePattern;
2261   EFI_SHELL_FILE_INFO *ShellInfo;
2262   EFI_SHELL_FILE_INFO *ShellInfoNode;
2263   EFI_SHELL_FILE_INFO *NewShellNode;
2264   EFI_FILE_INFO       *FileInfo;
2265   BOOLEAN             Directory;
2266   CHAR16              *NewFullName;
2267   UINTN               Size;
2268 
2269   if ( FilePattern      == NULL
2270     || UnicodeCollation == NULL
2271     || FileList         == NULL
2272    ){
2273     return (EFI_INVALID_PARAMETER);
2274   }
2275   ShellInfo = NULL;
2276   CurrentFilePattern = NULL;
2277 
2278   if (*FilePattern == L'\\') {
2279     FilePattern++;
2280   }
2281 
2282   for( NextFilePatternStart = FilePattern
2283      ; *NextFilePatternStart != CHAR_NULL && *NextFilePatternStart != L'\\'
2284      ; NextFilePatternStart++);
2285 
2286   CurrentFilePattern = AllocateZeroPool((NextFilePatternStart-FilePattern+1)*sizeof(CHAR16));
2287   if (CurrentFilePattern == NULL) {
2288     return EFI_OUT_OF_RESOURCES;
2289   }
2290 
2291   StrnCpyS(CurrentFilePattern, NextFilePatternStart-FilePattern+1, FilePattern, NextFilePatternStart-FilePattern);
2292 
2293   if (CurrentFilePattern[0]   == CHAR_NULL
2294     &&NextFilePatternStart[0] == CHAR_NULL
2295     ){
2296     //
2297     // we want the parent or root node (if no parent)
2298     //
2299     if (ParentNode == NULL) {
2300       //
2301       // We want the root node.  create the node.
2302       //
2303       FileInfo = FileHandleGetInfo(FileHandle);
2304       NewShellNode = CreateAndPopulateShellFileInfo(
2305         MapName,
2306         EFI_SUCCESS,
2307         L"\\",
2308         FileHandle,
2309         FileInfo
2310         );
2311       SHELL_FREE_NON_NULL(FileInfo);
2312     } else {
2313       //
2314       // Add the current parameter FileHandle to the list, then end...
2315       //
2316       NewShellNode = InternalDuplicateShellFileInfo((EFI_SHELL_FILE_INFO*)ParentNode, TRUE);
2317     }
2318     if (NewShellNode == NULL) {
2319       Status = EFI_OUT_OF_RESOURCES;
2320     } else {
2321       NewShellNode->Handle = NULL;
2322       if (*FileList == NULL) {
2323         *FileList = AllocateZeroPool(sizeof(EFI_SHELL_FILE_INFO));
2324         InitializeListHead(&((*FileList)->Link));
2325       }
2326 
2327       //
2328       // Add to the returning to use list
2329       //
2330       InsertTailList(&(*FileList)->Link, &NewShellNode->Link);
2331 
2332       Status = EFI_SUCCESS;
2333     }
2334   } else {
2335     Status = EfiShellFindFilesInDir(FileHandle, &ShellInfo);
2336 
2337     if (!EFI_ERROR(Status)){
2338       if (StrStr(NextFilePatternStart, L"\\") != NULL){
2339         Directory = TRUE;
2340       } else {
2341         Directory = FALSE;
2342       }
2343       for ( ShellInfoNode = (EFI_SHELL_FILE_INFO*)GetFirstNode(&ShellInfo->Link)
2344           ; !IsNull (&ShellInfo->Link, &ShellInfoNode->Link)
2345           ; ShellInfoNode = (EFI_SHELL_FILE_INFO*)GetNextNode(&ShellInfo->Link, &ShellInfoNode->Link)
2346          ){
2347         if (UnicodeCollation->MetaiMatch(UnicodeCollation, (CHAR16*)ShellInfoNode->FileName, CurrentFilePattern)){
2348           if (ShellInfoNode->FullName != NULL && StrStr(ShellInfoNode->FullName, L":") == NULL) {
2349             Size = StrSize (ShellInfoNode->FullName) + StrSize (MapName);
2350             NewFullName = AllocateZeroPool(Size);
2351             if (NewFullName == NULL) {
2352               Status = EFI_OUT_OF_RESOURCES;
2353             } else {
2354               StrCpyS(NewFullName, Size / sizeof(CHAR16), MapName);
2355               StrCatS(NewFullName, Size / sizeof(CHAR16), ShellInfoNode->FullName);
2356               FreePool ((VOID *) ShellInfoNode->FullName);
2357               ShellInfoNode->FullName = NewFullName;
2358             }
2359           }
2360           if (Directory && !EFI_ERROR(Status) && ShellInfoNode->FullName != NULL && ShellInfoNode->FileName != NULL){
2361             //
2362             // should be a directory
2363             //
2364 
2365             //
2366             // don't open the . and .. directories
2367             //
2368             if ( (StrCmp(ShellInfoNode->FileName, L".") != 0)
2369               && (StrCmp(ShellInfoNode->FileName, L"..") != 0)
2370              ){
2371               //
2372               //
2373               //
2374               if (EFI_ERROR(Status)) {
2375                 break;
2376               }
2377               //
2378               // Open the directory since we need that handle in the next recursion.
2379               //
2380               ShellInfoNode->Status = EfiShellOpenFileByName (ShellInfoNode->FullName, &ShellInfoNode->Handle, EFI_FILE_MODE_READ);
2381 
2382               //
2383               // recurse with the next part of the pattern
2384               //
2385               Status = ShellSearchHandle(NextFilePatternStart, UnicodeCollation, ShellInfoNode->Handle, FileList, ShellInfoNode, MapName);
2386               EfiShellClose(ShellInfoNode->Handle);
2387               ShellInfoNode->Handle = NULL;
2388             }
2389           } else if (!EFI_ERROR(Status)) {
2390             //
2391             // should be a file
2392             //
2393 
2394             //
2395             // copy the information we need into a new Node
2396             //
2397             NewShellNode = InternalDuplicateShellFileInfo(ShellInfoNode, FALSE);
2398             if (NewShellNode == NULL) {
2399               Status = EFI_OUT_OF_RESOURCES;
2400             }
2401             if (*FileList == NULL) {
2402               *FileList = AllocateZeroPool(sizeof(EFI_SHELL_FILE_INFO));
2403               InitializeListHead(&((*FileList)->Link));
2404             }
2405 
2406             //
2407             // Add to the returning to use list
2408             //
2409             InsertTailList(&(*FileList)->Link, &NewShellNode->Link);
2410           }
2411         }
2412         if (EFI_ERROR(Status)) {
2413           break;
2414         }
2415       }
2416       if (EFI_ERROR(Status)) {
2417         EfiShellFreeFileList(&ShellInfo);
2418       } else {
2419         Status = EfiShellFreeFileList(&ShellInfo);
2420       }
2421     }
2422   }
2423 
2424   if (*FileList == NULL || (*FileList != NULL && IsListEmpty(&(*FileList)->Link))) {
2425     Status = EFI_NOT_FOUND;
2426   }
2427 
2428   FreePool(CurrentFilePattern);
2429   return (Status);
2430 }
2431 
2432 /**
2433   Find files that match a specified pattern.
2434 
2435   This function searches for all files and directories that match the specified
2436   FilePattern. The FilePattern can contain wild-card characters. The resulting file
2437   information is placed in the file list FileList.
2438 
2439   Wildcards are processed
2440   according to the rules specified in UEFI Shell 2.0 spec section 3.7.1.
2441 
2442   The files in the file list are not opened. The OpenMode field is set to 0 and the FileInfo
2443   field is set to NULL.
2444 
2445   if *FileList is not NULL then it must be a pre-existing and properly initialized list.
2446 
2447   @param FilePattern      Points to a NULL-terminated shell file path, including wildcards.
2448   @param FileList         On return, points to the start of a file list containing the names
2449                           of all matching files or else points to NULL if no matching files
2450                           were found.  only on a EFI_SUCCESS return will; this be non-NULL.
2451 
2452   @retval EFI_SUCCESS           Files found.  FileList is a valid list.
2453   @retval EFI_NOT_FOUND         No files found.
2454   @retval EFI_NO_MEDIA          The device has no media
2455   @retval EFI_DEVICE_ERROR      The device reported an error
2456   @retval EFI_VOLUME_CORRUPTED  The file system structures are corrupted
2457 **/
2458 EFI_STATUS
2459 EFIAPI
EfiShellFindFiles(IN CONST CHAR16 * FilePattern,OUT EFI_SHELL_FILE_INFO ** FileList)2460 EfiShellFindFiles(
2461   IN CONST CHAR16 *FilePattern,
2462   OUT EFI_SHELL_FILE_INFO **FileList
2463   )
2464 {
2465   EFI_STATUS                      Status;
2466   CHAR16                          *PatternCopy;
2467   CHAR16                          *PatternCurrentLocation;
2468   EFI_DEVICE_PATH_PROTOCOL        *RootDevicePath;
2469   SHELL_FILE_HANDLE               RootFileHandle;
2470   CHAR16                          *MapName;
2471   UINTN                           Count;
2472 
2473   if ( FilePattern      == NULL
2474     || FileList         == NULL
2475     || StrStr(FilePattern, L":") == NULL
2476    ){
2477     return (EFI_INVALID_PARAMETER);
2478   }
2479   Status = EFI_SUCCESS;
2480   RootDevicePath = NULL;
2481   RootFileHandle = NULL;
2482   MapName        = NULL;
2483   PatternCopy = AllocateCopyPool(StrSize(FilePattern), FilePattern);
2484   if (PatternCopy == NULL) {
2485     return (EFI_OUT_OF_RESOURCES);
2486   }
2487 
2488   PatternCopy = PathCleanUpDirectories(PatternCopy);
2489 
2490   Count = StrStr(PatternCopy, L":") - PatternCopy + 1;
2491   ASSERT (Count <= StrLen (PatternCopy));
2492 
2493   ASSERT(MapName == NULL);
2494   MapName = StrnCatGrow(&MapName, NULL, PatternCopy, Count);
2495   if (MapName == NULL) {
2496     Status = EFI_OUT_OF_RESOURCES;
2497   } else {
2498     RootDevicePath = EfiShellGetDevicePathFromFilePath(PatternCopy);
2499     if (RootDevicePath == NULL) {
2500       Status = EFI_INVALID_PARAMETER;
2501     } else {
2502       Status = EfiShellOpenRoot(RootDevicePath, &RootFileHandle);
2503       if (!EFI_ERROR(Status)) {
2504         for ( PatternCurrentLocation = PatternCopy
2505             ; *PatternCurrentLocation != ':'
2506             ; PatternCurrentLocation++);
2507         PatternCurrentLocation++;
2508         Status = ShellSearchHandle(PatternCurrentLocation, gUnicodeCollation, RootFileHandle, FileList, NULL, MapName);
2509         EfiShellClose(RootFileHandle);
2510       }
2511       FreePool(RootDevicePath);
2512     }
2513   }
2514 
2515   SHELL_FREE_NON_NULL(PatternCopy);
2516   SHELL_FREE_NON_NULL(MapName);
2517 
2518   return(Status);
2519 }
2520 
2521 /**
2522   Opens the files that match the path specified.
2523 
2524   This function opens all of the files specified by Path. Wildcards are processed
2525   according to the rules specified in UEFI Shell 2.0 spec section 3.7.1. Each
2526   matching file has an EFI_SHELL_FILE_INFO structure created in a linked list.
2527 
2528   @param Path                   A pointer to the path string.
2529   @param OpenMode               Specifies the mode used to open each file, EFI_FILE_MODE_READ or
2530                                 EFI_FILE_MODE_WRITE.
2531   @param FileList               Points to the start of a list of files opened.
2532 
2533   @retval EFI_SUCCESS           Create the file list successfully.
2534   @return Others                Can't create the file list.
2535 **/
2536 EFI_STATUS
2537 EFIAPI
EfiShellOpenFileList(IN CHAR16 * Path,IN UINT64 OpenMode,IN OUT EFI_SHELL_FILE_INFO ** FileList)2538 EfiShellOpenFileList(
2539   IN CHAR16 *Path,
2540   IN UINT64 OpenMode,
2541   IN OUT EFI_SHELL_FILE_INFO **FileList
2542   )
2543 {
2544   EFI_STATUS Status;
2545   EFI_SHELL_FILE_INFO *ShellFileListItem;
2546   CHAR16              *Path2;
2547   UINTN               Path2Size;
2548   CONST CHAR16        *CurDir;
2549   BOOLEAN             Found;
2550 
2551   PathCleanUpDirectories(Path);
2552 
2553   Path2Size     = 0;
2554   Path2         = NULL;
2555 
2556   if (FileList == NULL || *FileList == NULL) {
2557     return (EFI_INVALID_PARAMETER);
2558   }
2559 
2560   if (*Path == L'.' && *(Path+1) == L'\\') {
2561     Path+=2;
2562   }
2563 
2564   //
2565   // convert a local path to an absolute path
2566   //
2567   if (StrStr(Path, L":") == NULL) {
2568     CurDir = EfiShellGetCurDir(NULL);
2569     ASSERT((Path2 == NULL && Path2Size == 0) || (Path2 != NULL));
2570     StrnCatGrow(&Path2, &Path2Size, CurDir, 0);
2571     StrnCatGrow(&Path2, &Path2Size, L"\\", 0);
2572     if (*Path == L'\\') {
2573       Path++;
2574       while (PathRemoveLastItem(Path2)) ;
2575     }
2576     ASSERT((Path2 == NULL && Path2Size == 0) || (Path2 != NULL));
2577     StrnCatGrow(&Path2, &Path2Size, Path, 0);
2578   } else {
2579     ASSERT(Path2 == NULL);
2580     StrnCatGrow(&Path2, NULL, Path, 0);
2581   }
2582 
2583   PathCleanUpDirectories (Path2);
2584 
2585   //
2586   // do the search
2587   //
2588   Status = EfiShellFindFiles(Path2, FileList);
2589 
2590   FreePool(Path2);
2591 
2592   if (EFI_ERROR(Status)) {
2593     return (Status);
2594   }
2595 
2596   Found = FALSE;
2597   //
2598   // We had no errors so open all the files (that are not already opened...)
2599   //
2600   for ( ShellFileListItem = (EFI_SHELL_FILE_INFO*)GetFirstNode(&(*FileList)->Link)
2601       ; !IsNull(&(*FileList)->Link, &ShellFileListItem->Link)
2602       ; ShellFileListItem = (EFI_SHELL_FILE_INFO*)GetNextNode(&(*FileList)->Link, &ShellFileListItem->Link)
2603      ){
2604     if (ShellFileListItem->Status == 0 && ShellFileListItem->Handle == NULL) {
2605       ShellFileListItem->Status = EfiShellOpenFileByName (ShellFileListItem->FullName, &ShellFileListItem->Handle, OpenMode);
2606       Found = TRUE;
2607     }
2608   }
2609 
2610   if (!Found) {
2611     return (EFI_NOT_FOUND);
2612   }
2613   return(EFI_SUCCESS);
2614 }
2615 
2616 /**
2617   Gets the environment variable and Attributes, or list of environment variables.  Can be
2618   used instead of GetEnv().
2619 
2620   This function returns the current value of the specified environment variable and
2621   the Attributes. If no variable name was specified, then all of the known
2622   variables will be returned.
2623 
2624   @param[in] Name               A pointer to the environment variable name. If Name is NULL,
2625                                 then the function will return all of the defined shell
2626                                 environment variables. In the case where multiple environment
2627                                 variables are being returned, each variable will be terminated
2628                                 by a NULL, and the list will be terminated by a double NULL.
2629   @param[out] Attributes        If not NULL, a pointer to the returned attributes bitmask for
2630                                 the environment variable. In the case where Name is NULL, and
2631                                 multiple environment variables are being returned, Attributes
2632                                 is undefined.
2633 
2634   @retval NULL                  The environment variable doesn't exist.
2635   @return                       A non-NULL value points to the variable's value. The returned
2636                                 pointer does not need to be freed by the caller.
2637 **/
2638 CONST CHAR16 *
2639 EFIAPI
EfiShellGetEnvEx(IN CONST CHAR16 * Name,OUT UINT32 * Attributes OPTIONAL)2640 EfiShellGetEnvEx(
2641   IN  CONST CHAR16 *Name,
2642   OUT       UINT32 *Attributes OPTIONAL
2643   )
2644 {
2645   EFI_STATUS  Status;
2646   VOID        *Buffer;
2647   UINTN       Size;
2648   ENV_VAR_LIST *Node;
2649   CHAR16      *CurrentWriteLocation;
2650 
2651   Size = 0;
2652   Buffer = NULL;
2653 
2654   if (Name == NULL) {
2655 
2656     //
2657     // Build the semi-colon delimited list. (2 passes)
2658     //
2659     for ( Node = (ENV_VAR_LIST*)GetFirstNode(&gShellEnvVarList.Link)
2660       ; !IsNull(&gShellEnvVarList.Link, &Node->Link)
2661       ; Node = (ENV_VAR_LIST*)GetNextNode(&gShellEnvVarList.Link, &Node->Link)
2662      ){
2663       ASSERT(Node->Key != NULL);
2664       Size += StrSize(Node->Key);
2665     }
2666 
2667     Size += 2*sizeof(CHAR16);
2668 
2669     Buffer = AllocateZeroPool(Size);
2670     if (Buffer == NULL) {
2671       return (NULL);
2672     }
2673     CurrentWriteLocation = (CHAR16*)Buffer;
2674 
2675     for ( Node = (ENV_VAR_LIST*)GetFirstNode(&gShellEnvVarList.Link)
2676       ; !IsNull(&gShellEnvVarList.Link, &Node->Link)
2677       ; Node = (ENV_VAR_LIST*)GetNextNode(&gShellEnvVarList.Link, &Node->Link)
2678      ){
2679       ASSERT(Node->Key != NULL);
2680       StrCpyS( CurrentWriteLocation,
2681                 (Size)/sizeof(CHAR16) - (CurrentWriteLocation - ((CHAR16*)Buffer)),
2682                 Node->Key
2683                 );
2684       CurrentWriteLocation += StrLen(CurrentWriteLocation) + 1;
2685     }
2686 
2687   } else {
2688     //
2689     // We are doing a specific environment variable
2690     //
2691     Status = ShellFindEnvVarInList(Name, (CHAR16**)&Buffer, &Size, Attributes);
2692 
2693     if (EFI_ERROR(Status)){
2694       //
2695       // get the size we need for this EnvVariable
2696       //
2697       Status = SHELL_GET_ENVIRONMENT_VARIABLE_AND_ATTRIBUTES(Name, Attributes, &Size, Buffer);
2698       if (Status == EFI_BUFFER_TOO_SMALL) {
2699         //
2700         // Allocate the space and recall the get function
2701         //
2702         Buffer = AllocateZeroPool(Size);
2703         Status = SHELL_GET_ENVIRONMENT_VARIABLE_AND_ATTRIBUTES(Name, Attributes, &Size, Buffer);
2704       }
2705       //
2706       // we didnt get it (might not exist)
2707       // free the memory if we allocated any and return NULL
2708       //
2709       if (EFI_ERROR(Status)) {
2710         if (Buffer != NULL) {
2711           FreePool(Buffer);
2712         }
2713         return (NULL);
2714       } else {
2715         //
2716         // If we did not find the environment variable in the gShellEnvVarList
2717         // but get it from UEFI variable storage successfully then we need update
2718         // the gShellEnvVarList.
2719         //
2720         ShellFreeEnvVarList ();
2721         Status = ShellInitEnvVarList ();
2722         ASSERT (Status == EFI_SUCCESS);
2723       }
2724     }
2725   }
2726 
2727   //
2728   // return the buffer
2729   //
2730   return (AddBufferToFreeList(Buffer));
2731 }
2732 
2733 /**
2734   Gets either a single or list of environment variables.
2735 
2736   If name is not NULL then this function returns the current value of the specified
2737   environment variable.
2738 
2739   If Name is NULL, then a list of all environment variable names is returned.  Each is a
2740   NULL terminated string with a double NULL terminating the list.
2741 
2742   @param Name                   A pointer to the environment variable name.  If
2743                                 Name is NULL, then the function will return all
2744                                 of the defined shell environment variables.  In
2745                                 the case where multiple environment variables are
2746                                 being returned, each variable will be terminated by
2747                                 a NULL, and the list will be terminated by a double
2748                                 NULL.
2749 
2750   @retval !=NULL                A pointer to the returned string.
2751                                 The returned pointer does not need to be freed by the caller.
2752 
2753   @retval NULL                  The environment variable doesn't exist or there are
2754                                 no environment variables.
2755 **/
2756 CONST CHAR16 *
2757 EFIAPI
EfiShellGetEnv(IN CONST CHAR16 * Name)2758 EfiShellGetEnv(
2759   IN CONST CHAR16 *Name
2760   )
2761 {
2762   return (EfiShellGetEnvEx(Name, NULL));
2763 }
2764 
2765 /**
2766   Internal variable setting function.  Allows for setting of the read only variables.
2767 
2768   @param Name                   Points to the NULL-terminated environment variable name.
2769   @param Value                  Points to the NULL-terminated environment variable value. If the value is an
2770                                 empty string then the environment variable is deleted.
2771   @param Volatile               Indicates whether the variable is non-volatile (FALSE) or volatile (TRUE).
2772 
2773   @retval EFI_SUCCESS           The environment variable was successfully updated.
2774 **/
2775 EFI_STATUS
InternalEfiShellSetEnv(IN CONST CHAR16 * Name,IN CONST CHAR16 * Value,IN BOOLEAN Volatile)2776 InternalEfiShellSetEnv(
2777   IN CONST CHAR16 *Name,
2778   IN CONST CHAR16 *Value,
2779   IN BOOLEAN Volatile
2780   )
2781 {
2782   EFI_STATUS      Status;
2783 
2784   if (Value == NULL || StrLen(Value) == 0) {
2785     Status = SHELL_DELETE_ENVIRONMENT_VARIABLE(Name);
2786     if (!EFI_ERROR(Status)) {
2787       ShellRemvoeEnvVarFromList(Name);
2788     }
2789   } else {
2790     SHELL_DELETE_ENVIRONMENT_VARIABLE(Name);
2791     Status = ShellAddEnvVarToList(
2792                Name, Value, StrSize(Value),
2793                EFI_VARIABLE_BOOTSERVICE_ACCESS | (Volatile ? 0 : EFI_VARIABLE_NON_VOLATILE)
2794                );
2795     if (!EFI_ERROR (Status)) {
2796       Status = Volatile
2797              ? SHELL_SET_ENVIRONMENT_VARIABLE_V (Name, StrSize (Value) - sizeof (CHAR16), Value)
2798              : SHELL_SET_ENVIRONMENT_VARIABLE_NV (Name, StrSize (Value) - sizeof (CHAR16), Value);
2799       if (EFI_ERROR (Status)) {
2800         ShellRemvoeEnvVarFromList(Name);
2801       }
2802     }
2803   }
2804   return Status;
2805 }
2806 
2807 /**
2808   Sets the environment variable.
2809 
2810   This function changes the current value of the specified environment variable. If the
2811   environment variable exists and the Value is an empty string, then the environment
2812   variable is deleted. If the environment variable exists and the Value is not an empty
2813   string, then the value of the environment variable is changed. If the environment
2814   variable does not exist and the Value is an empty string, there is no action. If the
2815   environment variable does not exist and the Value is a non-empty string, then the
2816   environment variable is created and assigned the specified value.
2817 
2818   For a description of volatile and non-volatile environment variables, see UEFI Shell
2819   2.0 specification section 3.6.1.
2820 
2821   @param Name                   Points to the NULL-terminated environment variable name.
2822   @param Value                  Points to the NULL-terminated environment variable value. If the value is an
2823                                 empty string then the environment variable is deleted.
2824   @param Volatile               Indicates whether the variable is non-volatile (FALSE) or volatile (TRUE).
2825 
2826   @retval EFI_SUCCESS           The environment variable was successfully updated.
2827 **/
2828 EFI_STATUS
2829 EFIAPI
EfiShellSetEnv(IN CONST CHAR16 * Name,IN CONST CHAR16 * Value,IN BOOLEAN Volatile)2830 EfiShellSetEnv(
2831   IN CONST CHAR16 *Name,
2832   IN CONST CHAR16 *Value,
2833   IN BOOLEAN Volatile
2834   )
2835 {
2836   if (Name == NULL || *Name == CHAR_NULL) {
2837     return (EFI_INVALID_PARAMETER);
2838   }
2839   //
2840   // Make sure we dont 'set' a predefined read only variable
2841   //
2842   if ((StrCmp (Name, L"cwd") == 0) ||
2843       (StrCmp (Name, L"lasterror") == 0) ||
2844       (StrCmp (Name, L"profiles") == 0) ||
2845       (StrCmp (Name, L"uefishellsupport") == 0) ||
2846       (StrCmp (Name, L"uefishellversion") == 0) ||
2847       (StrCmp (Name, L"uefiversion") == 0) ||
2848       (!ShellInfoObject.ShellInitSettings.BitUnion.Bits.NoNest &&
2849        StrCmp (Name, mNoNestingEnvVarName) == 0)
2850      ) {
2851     return (EFI_INVALID_PARAMETER);
2852   }
2853   return (InternalEfiShellSetEnv(Name, Value, Volatile));
2854 }
2855 
2856 /**
2857   Returns the current directory on the specified device.
2858 
2859   If FileSystemMapping is NULL, it returns the current working directory. If the
2860   FileSystemMapping is not NULL, it returns the current directory associated with the
2861   FileSystemMapping. In both cases, the returned name includes the file system
2862   mapping (i.e. fs0:\current-dir).
2863 
2864   Note that the current directory string should exclude the tailing backslash character.
2865 
2866   @param FileSystemMapping      A pointer to the file system mapping. If NULL,
2867                                 then the current working directory is returned.
2868 
2869   @retval !=NULL                The current directory.
2870   @retval NULL                  Current directory does not exist.
2871 **/
2872 CONST CHAR16 *
2873 EFIAPI
EfiShellGetCurDir(IN CONST CHAR16 * FileSystemMapping OPTIONAL)2874 EfiShellGetCurDir(
2875   IN CONST CHAR16 *FileSystemMapping OPTIONAL
2876   )
2877 {
2878   CHAR16  *PathToReturn;
2879   UINTN   Size;
2880   SHELL_MAP_LIST *MapListItem;
2881   if (!IsListEmpty(&gShellMapList.Link)) {
2882     //
2883     // if parameter is NULL, use current
2884     //
2885     if (FileSystemMapping == NULL) {
2886       return (EfiShellGetEnv(L"cwd"));
2887     } else {
2888       Size = 0;
2889       PathToReturn = NULL;
2890       MapListItem = ShellCommandFindMapItem(FileSystemMapping);
2891       if (MapListItem != NULL) {
2892         ASSERT((PathToReturn == NULL && Size == 0) || (PathToReturn != NULL));
2893         PathToReturn = StrnCatGrow(&PathToReturn, &Size, MapListItem->MapName, 0);
2894         PathToReturn = StrnCatGrow(&PathToReturn, &Size, MapListItem->CurrentDirectoryPath, 0);
2895       }
2896     }
2897     return (AddBufferToFreeList(PathToReturn));
2898   } else {
2899     return (NULL);
2900   }
2901 }
2902 
2903 /**
2904   Changes the current directory on the specified device.
2905 
2906   If the FileSystem is NULL, and the directory Dir does not contain a file system's
2907   mapped name, this function changes the current working directory.
2908 
2909   If the FileSystem is NULL and the directory Dir contains a mapped name, then the
2910   current file system and the current directory on that file system are changed.
2911 
2912   If FileSystem is NULL, and Dir is not NULL, then this changes the current working file
2913   system.
2914 
2915   If FileSystem is not NULL and Dir is not NULL, then this function changes the current
2916   directory on the specified file system.
2917 
2918   If the current working directory or the current working file system is changed then the
2919   %cwd% environment variable will be updated
2920 
2921   Note that the current directory string should exclude the tailing backslash character.
2922 
2923   @param FileSystem             A pointer to the file system's mapped name. If NULL, then the current working
2924                                 directory is changed.
2925   @param Dir                    Points to the NULL-terminated directory on the device specified by FileSystem.
2926 
2927   @retval EFI_SUCCESS           The operation was sucessful
2928   @retval EFI_NOT_FOUND         The file system could not be found
2929 **/
2930 EFI_STATUS
2931 EFIAPI
EfiShellSetCurDir(IN CONST CHAR16 * FileSystem OPTIONAL,IN CONST CHAR16 * Dir)2932 EfiShellSetCurDir(
2933   IN CONST CHAR16 *FileSystem OPTIONAL,
2934   IN CONST CHAR16 *Dir
2935   )
2936 {
2937   CHAR16          *MapName;
2938   SHELL_MAP_LIST  *MapListItem;
2939   UINTN           Size;
2940   EFI_STATUS      Status;
2941   CHAR16          *TempString;
2942   CHAR16          *DirectoryName;
2943   UINTN           TempLen;
2944 
2945   Size          = 0;
2946   MapName       = NULL;
2947   MapListItem   = NULL;
2948   TempString    = NULL;
2949   DirectoryName = NULL;
2950 
2951   if ((FileSystem == NULL && Dir == NULL) || Dir == NULL) {
2952     return (EFI_INVALID_PARAMETER);
2953   }
2954 
2955   if (IsListEmpty(&gShellMapList.Link)){
2956     return (EFI_NOT_FOUND);
2957   }
2958 
2959   DirectoryName = StrnCatGrow(&DirectoryName, NULL, Dir, 0);
2960   ASSERT(DirectoryName != NULL);
2961 
2962   PathCleanUpDirectories(DirectoryName);
2963 
2964   if (FileSystem == NULL) {
2965     //
2966     // determine the file system mapping to use
2967     //
2968     if (StrStr(DirectoryName, L":") != NULL) {
2969       ASSERT(MapName == NULL);
2970       MapName = StrnCatGrow(&MapName, NULL, DirectoryName, (StrStr(DirectoryName, L":")-DirectoryName+1));
2971     }
2972     //
2973     // find the file system mapping's entry in the list
2974     // or use current
2975     //
2976     if (MapName != NULL) {
2977       MapListItem = ShellCommandFindMapItem(MapName);
2978 
2979       //
2980       // make that the current file system mapping
2981       //
2982       if (MapListItem != NULL) {
2983         gShellCurMapping = MapListItem;
2984       }
2985     } else {
2986       MapListItem = gShellCurMapping;
2987     }
2988 
2989     if (MapListItem == NULL) {
2990       FreePool (DirectoryName);
2991       SHELL_FREE_NON_NULL(MapName);
2992       return (EFI_NOT_FOUND);
2993     }
2994 
2995     //
2996     // now update the MapListItem's current directory
2997     //
2998     if (MapListItem->CurrentDirectoryPath != NULL && DirectoryName[StrLen(DirectoryName) - 1] != L':') {
2999       FreePool(MapListItem->CurrentDirectoryPath);
3000       MapListItem->CurrentDirectoryPath = NULL;
3001     }
3002     if (MapName != NULL) {
3003       TempLen = StrLen(MapName);
3004       if (TempLen != StrLen(DirectoryName)) {
3005         ASSERT((MapListItem->CurrentDirectoryPath == NULL && Size == 0) || (MapListItem->CurrentDirectoryPath != NULL));
3006         MapListItem->CurrentDirectoryPath = StrnCatGrow(&MapListItem->CurrentDirectoryPath, &Size, DirectoryName+StrLen(MapName), 0);
3007       }
3008       FreePool (MapName);
3009     } else {
3010       ASSERT((MapListItem->CurrentDirectoryPath == NULL && Size == 0) || (MapListItem->CurrentDirectoryPath != NULL));
3011       MapListItem->CurrentDirectoryPath = StrnCatGrow(&MapListItem->CurrentDirectoryPath, &Size, DirectoryName, 0);
3012     }
3013     if ((MapListItem->CurrentDirectoryPath != NULL && MapListItem->CurrentDirectoryPath[StrLen(MapListItem->CurrentDirectoryPath)-1] == L'\\') || (MapListItem->CurrentDirectoryPath == NULL)) {
3014       ASSERT((MapListItem->CurrentDirectoryPath == NULL && Size == 0) || (MapListItem->CurrentDirectoryPath != NULL));
3015       if (MapListItem->CurrentDirectoryPath != NULL) {
3016         MapListItem->CurrentDirectoryPath[StrLen(MapListItem->CurrentDirectoryPath)-1] = CHAR_NULL;
3017     }
3018     }
3019   } else {
3020     //
3021     // cant have a mapping in the directory...
3022     //
3023     if (StrStr(DirectoryName, L":") != NULL) {
3024       FreePool (DirectoryName);
3025       return (EFI_INVALID_PARAMETER);
3026     }
3027     //
3028     // FileSystem != NULL
3029     //
3030     MapListItem = ShellCommandFindMapItem(FileSystem);
3031     if (MapListItem == NULL) {
3032       FreePool (DirectoryName);
3033       return (EFI_INVALID_PARAMETER);
3034     }
3035 //    gShellCurMapping = MapListItem;
3036     if (DirectoryName != NULL) {
3037       //
3038       // change current dir on that file system
3039       //
3040 
3041       if (MapListItem->CurrentDirectoryPath != NULL) {
3042         FreePool(MapListItem->CurrentDirectoryPath);
3043         DEBUG_CODE(MapListItem->CurrentDirectoryPath = NULL;);
3044       }
3045 //      ASSERT((MapListItem->CurrentDirectoryPath == NULL && Size == 0) || (MapListItem->CurrentDirectoryPath != NULL));
3046 //      MapListItem->CurrentDirectoryPath = StrnCatGrow(&MapListItem->CurrentDirectoryPath, &Size, FileSystem, 0);
3047       ASSERT((MapListItem->CurrentDirectoryPath == NULL && Size == 0) || (MapListItem->CurrentDirectoryPath != NULL));
3048       MapListItem->CurrentDirectoryPath = StrnCatGrow(&MapListItem->CurrentDirectoryPath, &Size, L"\\", 0);
3049       ASSERT((MapListItem->CurrentDirectoryPath == NULL && Size == 0) || (MapListItem->CurrentDirectoryPath != NULL));
3050       MapListItem->CurrentDirectoryPath = StrnCatGrow(&MapListItem->CurrentDirectoryPath, &Size, DirectoryName, 0);
3051       if (MapListItem->CurrentDirectoryPath != NULL && MapListItem->CurrentDirectoryPath[StrLen(MapListItem->CurrentDirectoryPath)-1] == L'\\') {
3052         ASSERT((MapListItem->CurrentDirectoryPath == NULL && Size == 0) || (MapListItem->CurrentDirectoryPath != NULL));
3053         MapListItem->CurrentDirectoryPath[StrLen(MapListItem->CurrentDirectoryPath)-1] = CHAR_NULL;
3054       }
3055     }
3056   }
3057   FreePool (DirectoryName);
3058   //
3059   // if updated the current directory then update the environment variable
3060   //
3061   if (MapListItem == gShellCurMapping) {
3062     Size = 0;
3063     ASSERT((TempString == NULL && Size == 0) || (TempString != NULL));
3064     StrnCatGrow(&TempString, &Size, MapListItem->MapName, 0);
3065     ASSERT((TempString == NULL && Size == 0) || (TempString != NULL));
3066     StrnCatGrow(&TempString, &Size, MapListItem->CurrentDirectoryPath, 0);
3067     Status =  InternalEfiShellSetEnv(L"cwd", TempString, TRUE);
3068     FreePool(TempString);
3069     return (Status);
3070   }
3071   return(EFI_SUCCESS);
3072 }
3073 
3074 /**
3075   Return help information about a specific command.
3076 
3077   This function returns the help information for the specified command. The help text
3078   can be internal to the shell or can be from a UEFI Shell manual page.
3079 
3080   If Sections is specified, then each section name listed will be compared in a casesensitive
3081   manner, to the section names described in Appendix B. If the section exists,
3082   it will be appended to the returned help text. If the section does not exist, no
3083   information will be returned. If Sections is NULL, then all help text information
3084   available will be returned.
3085 
3086   @param Command                Points to the NULL-terminated UEFI Shell command name.
3087   @param Sections               Points to the NULL-terminated comma-delimited
3088                                 section names to return. If NULL, then all
3089                                 sections will be returned.
3090   @param HelpText               On return, points to a callee-allocated buffer
3091                                 containing all specified help text.
3092 
3093   @retval EFI_SUCCESS           The help text was returned.
3094   @retval EFI_OUT_OF_RESOURCES  The necessary buffer could not be allocated to hold the
3095                                 returned help text.
3096   @retval EFI_INVALID_PARAMETER HelpText is NULL
3097   @retval EFI_NOT_FOUND         There is no help text available for Command.
3098 **/
3099 EFI_STATUS
3100 EFIAPI
EfiShellGetHelpText(IN CONST CHAR16 * Command,IN CONST CHAR16 * Sections OPTIONAL,OUT CHAR16 ** HelpText)3101 EfiShellGetHelpText(
3102   IN CONST CHAR16 *Command,
3103   IN CONST CHAR16 *Sections OPTIONAL,
3104   OUT CHAR16 **HelpText
3105   )
3106 {
3107   CONST CHAR16  *ManFileName;
3108   CHAR16        *FixCommand;
3109   EFI_STATUS    Status;
3110 
3111   ASSERT(HelpText != NULL);
3112   FixCommand = NULL;
3113 
3114   ManFileName = ShellCommandGetManFileNameHandler(Command);
3115 
3116   if (ManFileName != NULL) {
3117     return (ProcessManFile(ManFileName, Command, Sections, NULL, HelpText));
3118   } else {
3119     if ((StrLen(Command)> 4)
3120     && (Command[StrLen(Command)-1] == L'i' || Command[StrLen(Command)-1] == L'I')
3121     && (Command[StrLen(Command)-2] == L'f' || Command[StrLen(Command)-2] == L'F')
3122     && (Command[StrLen(Command)-3] == L'e' || Command[StrLen(Command)-3] == L'E')
3123     && (Command[StrLen(Command)-4] == L'.')
3124     ) {
3125       FixCommand = AllocateZeroPool(StrSize(Command) - 4 * sizeof (CHAR16));
3126       if (FixCommand == NULL) {
3127         return EFI_OUT_OF_RESOURCES;
3128       }
3129 
3130       StrnCpyS( FixCommand,
3131                 (StrSize(Command) - 4 * sizeof (CHAR16))/sizeof(CHAR16),
3132                 Command,
3133                 StrLen(Command)-4
3134                 );
3135       Status = ProcessManFile(FixCommand, FixCommand, Sections, NULL, HelpText);
3136       FreePool(FixCommand);
3137       return Status;
3138     } else {
3139       return (ProcessManFile(Command, Command, Sections, NULL, HelpText));
3140     }
3141   }
3142 }
3143 
3144 /**
3145   Gets the enable status of the page break output mode.
3146 
3147   User can use this function to determine current page break mode.
3148 
3149   @retval TRUE                  The page break output mode is enabled.
3150   @retval FALSE                 The page break output mode is disabled.
3151 **/
3152 BOOLEAN
3153 EFIAPI
EfiShellGetPageBreak(VOID)3154 EfiShellGetPageBreak(
3155   VOID
3156   )
3157 {
3158   return(ShellInfoObject.PageBreakEnabled);
3159 }
3160 
3161 /**
3162   Judges whether the active shell is the root shell.
3163 
3164   This function makes the user to know that whether the active Shell is the root shell.
3165 
3166   @retval TRUE                  The active Shell is the root Shell.
3167   @retval FALSE                 The active Shell is NOT the root Shell.
3168 **/
3169 BOOLEAN
3170 EFIAPI
EfiShellIsRootShell(VOID)3171 EfiShellIsRootShell(
3172   VOID
3173   )
3174 {
3175   return(ShellInfoObject.RootShellInstance);
3176 }
3177 
3178 /**
3179   function to return a semi-colon delimeted list of all alias' in the current shell
3180 
3181   up to caller to free the memory.
3182 
3183   @retval NULL    No alias' were found
3184   @retval NULL    An error ocurred getting alias'
3185   @return !NULL   a list of all alias'
3186 **/
3187 CHAR16 *
InternalEfiShellGetListAlias(VOID)3188 InternalEfiShellGetListAlias(
3189   VOID
3190   )
3191 {
3192 
3193   EFI_STATUS        Status;
3194   EFI_GUID          Guid;
3195   CHAR16            *VariableName;
3196   UINTN             NameSize;
3197   UINTN             NameBufferSize;
3198   CHAR16            *RetVal;
3199   UINTN             RetSize;
3200 
3201   NameBufferSize = INIT_NAME_BUFFER_SIZE;
3202   VariableName  = AllocateZeroPool(NameBufferSize);
3203   RetSize       = 0;
3204   RetVal        = NULL;
3205 
3206   if (VariableName == NULL) {
3207     return (NULL);
3208   }
3209 
3210   VariableName[0] = CHAR_NULL;
3211 
3212   while (TRUE) {
3213     NameSize = NameBufferSize;
3214     Status = gRT->GetNextVariableName(&NameSize, VariableName, &Guid);
3215     if (Status == EFI_NOT_FOUND){
3216       break;
3217     } else if (Status == EFI_BUFFER_TOO_SMALL) {
3218       NameBufferSize = NameSize > NameBufferSize * 2 ? NameSize : NameBufferSize * 2;
3219       SHELL_FREE_NON_NULL(VariableName);
3220       VariableName = AllocateZeroPool(NameBufferSize);
3221       if (VariableName == NULL) {
3222         Status = EFI_OUT_OF_RESOURCES;
3223         SHELL_FREE_NON_NULL(RetVal);
3224         RetVal = NULL;
3225         break;
3226       }
3227 
3228       NameSize = NameBufferSize;
3229       Status = gRT->GetNextVariableName(&NameSize, VariableName, &Guid);
3230     }
3231 
3232     if (EFI_ERROR (Status)) {
3233       SHELL_FREE_NON_NULL(RetVal);
3234       RetVal = NULL;
3235       break;
3236     }
3237 
3238     if (CompareGuid(&Guid, &gShellAliasGuid)){
3239       ASSERT((RetVal == NULL && RetSize == 0) || (RetVal != NULL));
3240       RetVal = StrnCatGrow(&RetVal, &RetSize, VariableName, 0);
3241       RetVal = StrnCatGrow(&RetVal, &RetSize, L";", 0);
3242     } // compare guid
3243   } // while
3244   SHELL_FREE_NON_NULL(VariableName);
3245 
3246   return (RetVal);
3247 }
3248 
3249 /**
3250   Convert a null-terminated unicode string, in-place, to all lowercase.
3251   Then return it.
3252 
3253   @param  Str    The null-terminated string to be converted to all lowercase.
3254 
3255   @return        The null-terminated string converted into all lowercase.
3256 **/
3257 CHAR16 *
ToLower(CHAR16 * Str)3258 ToLower (
3259   CHAR16 *Str
3260   )
3261 {
3262   UINTN Index;
3263 
3264   for (Index = 0; Str[Index] != L'\0'; Index++) {
3265     if (Str[Index] >= L'A' && Str[Index] <= L'Z') {
3266       Str[Index] -= (CHAR16)(L'A' - L'a');
3267     }
3268   }
3269   return Str;
3270 }
3271 
3272 /**
3273   This function returns the command associated with a alias or a list of all
3274   alias'.
3275 
3276   @param[in] Alias              Points to the NULL-terminated shell alias.
3277                                 If this parameter is NULL, then all
3278                                 aliases will be returned in ReturnedData.
3279   @param[out] Volatile          upon return of a single command if TRUE indicates
3280                                 this is stored in a volatile fashion.  FALSE otherwise.
3281 
3282   @return                        If Alias is not NULL, it will return a pointer to
3283                                 the NULL-terminated command for that alias.
3284                                 If Alias is NULL, ReturnedData points to a ';'
3285                                 delimited list of alias (e.g.
3286                                 ReturnedData = "dir;del;copy;mfp") that is NULL-terminated.
3287   @retval NULL                  an error ocurred
3288   @retval NULL                  Alias was not a valid Alias
3289 **/
3290 CONST CHAR16 *
3291 EFIAPI
EfiShellGetAlias(IN CONST CHAR16 * Alias,OUT BOOLEAN * Volatile OPTIONAL)3292 EfiShellGetAlias(
3293   IN  CONST CHAR16 *Alias,
3294   OUT BOOLEAN      *Volatile OPTIONAL
3295   )
3296 {
3297   CHAR16      *RetVal;
3298   UINTN       RetSize;
3299   UINT32      Attribs;
3300   EFI_STATUS  Status;
3301   CHAR16      *AliasLower;
3302   CHAR16      *AliasVal;
3303 
3304   // Convert to lowercase to make aliases case-insensitive
3305   if (Alias != NULL) {
3306     AliasLower = AllocateCopyPool (StrSize (Alias), Alias);
3307     if (AliasLower == NULL) {
3308       return NULL;
3309     }
3310     ToLower (AliasLower);
3311 
3312     if (Volatile == NULL) {
3313       GetVariable2 (AliasLower, &gShellAliasGuid, (VOID **)&AliasVal, NULL);
3314       FreePool(AliasLower);
3315       return (AddBufferToFreeList(AliasVal));
3316     }
3317     RetSize = 0;
3318     RetVal = NULL;
3319     Status = gRT->GetVariable(AliasLower, &gShellAliasGuid, &Attribs, &RetSize, RetVal);
3320     if (Status == EFI_BUFFER_TOO_SMALL) {
3321       RetVal = AllocateZeroPool(RetSize);
3322       Status = gRT->GetVariable(AliasLower, &gShellAliasGuid, &Attribs, &RetSize, RetVal);
3323     }
3324     if (EFI_ERROR(Status)) {
3325       if (RetVal != NULL) {
3326         FreePool(RetVal);
3327       }
3328       FreePool(AliasLower);
3329       return (NULL);
3330     }
3331     if ((EFI_VARIABLE_NON_VOLATILE & Attribs) == EFI_VARIABLE_NON_VOLATILE) {
3332       *Volatile = FALSE;
3333     } else {
3334       *Volatile = TRUE;
3335     }
3336 
3337     FreePool (AliasLower);
3338     return (AddBufferToFreeList(RetVal));
3339   }
3340   return (AddBufferToFreeList(InternalEfiShellGetListAlias()));
3341 }
3342 
3343 /**
3344   Changes a shell command alias.
3345 
3346   This function creates an alias for a shell command or if Alias is NULL it will delete an existing alias.
3347 
3348   this function does not check for built in alias'.
3349 
3350   @param[in] Command            Points to the NULL-terminated shell command or existing alias.
3351   @param[in] Alias              Points to the NULL-terminated alias for the shell command. If this is NULL, and
3352                                 Command refers to an alias, that alias will be deleted.
3353   @param[in] Volatile           if TRUE the Alias being set will be stored in a volatile fashion.  if FALSE the
3354                                 Alias being set will be stored in a non-volatile fashion.
3355 
3356   @retval EFI_SUCCESS           Alias created or deleted successfully.
3357   @retval EFI_NOT_FOUND         the Alias intended to be deleted was not found
3358 **/
3359 EFI_STATUS
InternalSetAlias(IN CONST CHAR16 * Command,IN CONST CHAR16 * Alias,IN BOOLEAN Volatile)3360 InternalSetAlias(
3361   IN CONST CHAR16 *Command,
3362   IN CONST CHAR16 *Alias,
3363   IN BOOLEAN Volatile
3364   )
3365 {
3366   EFI_STATUS  Status;
3367   CHAR16      *AliasLower;
3368   BOOLEAN     DeleteAlias;
3369 
3370   DeleteAlias = FALSE;
3371   if (Alias == NULL) {
3372     //
3373     // We must be trying to remove one if Alias is NULL
3374     // remove an alias (but passed in COMMAND parameter)
3375     //
3376     Alias       = Command;
3377     DeleteAlias = TRUE;
3378   }
3379   ASSERT (Alias != NULL);
3380 
3381   //
3382   // Convert to lowercase to make aliases case-insensitive
3383   //
3384   AliasLower = AllocateCopyPool (StrSize (Alias), Alias);
3385   if (AliasLower == NULL) {
3386     return EFI_OUT_OF_RESOURCES;
3387   }
3388   ToLower (AliasLower);
3389 
3390   if (DeleteAlias) {
3391     Status = gRT->SetVariable (AliasLower, &gShellAliasGuid, 0, 0, NULL);
3392   } else {
3393     Status = gRT->SetVariable (
3394                     AliasLower, &gShellAliasGuid,
3395                     EFI_VARIABLE_BOOTSERVICE_ACCESS | (Volatile ? 0 : EFI_VARIABLE_NON_VOLATILE),
3396                     StrSize (Command), (VOID *) Command
3397                     );
3398   }
3399 
3400   FreePool (AliasLower);
3401 
3402   return Status;
3403 }
3404 
3405 /**
3406   Changes a shell command alias.
3407 
3408   This function creates an alias for a shell command or if Alias is NULL it will delete an existing alias.
3409 
3410 
3411   @param[in] Command            Points to the NULL-terminated shell command or existing alias.
3412   @param[in] Alias              Points to the NULL-terminated alias for the shell command. If this is NULL, and
3413                                 Command refers to an alias, that alias will be deleted.
3414   @param[in] Replace            If TRUE and the alias already exists, then the existing alias will be replaced. If
3415                                 FALSE and the alias already exists, then the existing alias is unchanged and
3416                                 EFI_ACCESS_DENIED is returned.
3417   @param[in] Volatile           if TRUE the Alias being set will be stored in a volatile fashion.  if FALSE the
3418                                 Alias being set will be stored in a non-volatile fashion.
3419 
3420   @retval EFI_SUCCESS           Alias created or deleted successfully.
3421   @retval EFI_NOT_FOUND         the Alias intended to be deleted was not found
3422   @retval EFI_ACCESS_DENIED     The alias is a built-in alias or already existed and Replace was set to
3423                                 FALSE.
3424   @retval EFI_INVALID_PARAMETER Command is null or the empty string.
3425 **/
3426 EFI_STATUS
3427 EFIAPI
EfiShellSetAlias(IN CONST CHAR16 * Command,IN CONST CHAR16 * Alias,IN BOOLEAN Replace,IN BOOLEAN Volatile)3428 EfiShellSetAlias(
3429   IN CONST CHAR16 *Command,
3430   IN CONST CHAR16 *Alias,
3431   IN BOOLEAN Replace,
3432   IN BOOLEAN Volatile
3433   )
3434 {
3435   if (ShellCommandIsOnAliasList(Alias==NULL?Command:Alias)) {
3436     //
3437     // cant set over a built in alias
3438     //
3439     return (EFI_ACCESS_DENIED);
3440   } else if (Command == NULL || *Command == CHAR_NULL || StrLen(Command) == 0) {
3441     //
3442     // Command is null or empty
3443     //
3444     return (EFI_INVALID_PARAMETER);
3445   } else if (EfiShellGetAlias(Command, NULL) != NULL && !Replace) {
3446     //
3447     // Alias already exists, Replace not set
3448     //
3449     return (EFI_ACCESS_DENIED);
3450   } else {
3451     return (InternalSetAlias(Command, Alias, Volatile));
3452   }
3453 }
3454 
3455 // Pure FILE_HANDLE operations are passed to FileHandleLib
3456 // these functions are indicated by the *
3457 EFI_SHELL_PROTOCOL         mShellProtocol = {
3458   EfiShellExecute,
3459   EfiShellGetEnv,
3460   EfiShellSetEnv,
3461   EfiShellGetAlias,
3462   EfiShellSetAlias,
3463   EfiShellGetHelpText,
3464   EfiShellGetDevicePathFromMap,
3465   EfiShellGetMapFromDevicePath,
3466   EfiShellGetDevicePathFromFilePath,
3467   EfiShellGetFilePathFromDevicePath,
3468   EfiShellSetMap,
3469   EfiShellGetCurDir,
3470   EfiShellSetCurDir,
3471   EfiShellOpenFileList,
3472   EfiShellFreeFileList,
3473   EfiShellRemoveDupInFileList,
3474   EfiShellBatchIsActive,
3475   EfiShellIsRootShell,
3476   EfiShellEnablePageBreak,
3477   EfiShellDisablePageBreak,
3478   EfiShellGetPageBreak,
3479   EfiShellGetDeviceName,
3480   (EFI_SHELL_GET_FILE_INFO)FileHandleGetInfo,         //*
3481   (EFI_SHELL_SET_FILE_INFO)FileHandleSetInfo,         //*
3482   EfiShellOpenFileByName,
3483   EfiShellClose,
3484   EfiShellCreateFile,
3485   (EFI_SHELL_READ_FILE)FileHandleRead,                //*
3486   (EFI_SHELL_WRITE_FILE)FileHandleWrite,              //*
3487   (EFI_SHELL_DELETE_FILE)FileHandleDelete,            //*
3488   EfiShellDeleteFileByName,
3489   (EFI_SHELL_GET_FILE_POSITION)FileHandleGetPosition, //*
3490   (EFI_SHELL_SET_FILE_POSITION)FileHandleSetPosition, //*
3491   (EFI_SHELL_FLUSH_FILE)FileHandleFlush,              //*
3492   EfiShellFindFiles,
3493   EfiShellFindFilesInDir,
3494   (EFI_SHELL_GET_FILE_SIZE)FileHandleGetSize,         //*
3495   EfiShellOpenRoot,
3496   EfiShellOpenRootByHandle,
3497   NULL,
3498   SHELL_MAJOR_VERSION,
3499   SHELL_MINOR_VERSION,
3500 
3501   // New for UEFI Shell 2.1
3502   EfiShellRegisterGuidName,
3503   EfiShellGetGuidName,
3504   EfiShellGetGuidFromName,
3505   EfiShellGetEnvEx
3506 };
3507 
3508 /**
3509   Function to create and install on the current handle.
3510 
3511   Will overwrite any existing ShellProtocols in the system to be sure that
3512   the current shell is in control.
3513 
3514   This must be removed via calling CleanUpShellProtocol().
3515 
3516   @param[in, out] NewShell   The pointer to the pointer to the structure
3517   to install.
3518 
3519   @retval EFI_SUCCESS     The operation was successful.
3520   @return                 An error from LocateHandle, CreateEvent, or other core function.
3521 **/
3522 EFI_STATUS
CreatePopulateInstallShellProtocol(IN OUT EFI_SHELL_PROTOCOL ** NewShell)3523 CreatePopulateInstallShellProtocol (
3524   IN OUT EFI_SHELL_PROTOCOL  **NewShell
3525   )
3526 {
3527   EFI_STATUS                  Status;
3528   UINTN                       BufferSize;
3529   EFI_HANDLE                  *Buffer;
3530   UINTN                       HandleCounter;
3531   SHELL_PROTOCOL_HANDLE_LIST  *OldProtocolNode;
3532   EFI_SHELL_PROTOCOL          *OldShell;
3533 
3534   if (NewShell == NULL) {
3535     return (EFI_INVALID_PARAMETER);
3536   }
3537 
3538   BufferSize = 0;
3539   Buffer = NULL;
3540   OldProtocolNode = NULL;
3541   InitializeListHead(&ShellInfoObject.OldShellList.Link);
3542 
3543   //
3544   // Initialize EfiShellProtocol object...
3545   //
3546   Status = gBS->CreateEvent(0,
3547                             0,
3548                             NULL,
3549                             NULL,
3550                             &mShellProtocol.ExecutionBreak);
3551   if (EFI_ERROR(Status)) {
3552     return (Status);
3553   }
3554 
3555   //
3556   // Get the size of the buffer we need.
3557   //
3558   Status = gBS->LocateHandle(ByProtocol,
3559                              &gEfiShellProtocolGuid,
3560                              NULL,
3561                              &BufferSize,
3562                              Buffer);
3563   if (Status == EFI_BUFFER_TOO_SMALL) {
3564     //
3565     // Allocate and recall with buffer of correct size
3566     //
3567     Buffer = AllocateZeroPool(BufferSize);
3568     if (Buffer == NULL) {
3569       return (EFI_OUT_OF_RESOURCES);
3570     }
3571     Status = gBS->LocateHandle(ByProtocol,
3572                                &gEfiShellProtocolGuid,
3573                                NULL,
3574                                &BufferSize,
3575                                Buffer);
3576     if (EFI_ERROR(Status)) {
3577       FreePool(Buffer);
3578       return (Status);
3579     }
3580     //
3581     // now overwrite each of them, but save the info to restore when we end.
3582     //
3583     for (HandleCounter = 0 ; HandleCounter < (BufferSize/sizeof(EFI_HANDLE)) ; HandleCounter++) {
3584       Status = gBS->OpenProtocol(Buffer[HandleCounter],
3585                                 &gEfiShellProtocolGuid,
3586                                 (VOID **) &OldShell,
3587                                 gImageHandle,
3588                                 NULL,
3589                                 EFI_OPEN_PROTOCOL_GET_PROTOCOL
3590                                );
3591       if (!EFI_ERROR(Status)) {
3592         OldProtocolNode = AllocateZeroPool(sizeof(SHELL_PROTOCOL_HANDLE_LIST));
3593         if (OldProtocolNode == NULL) {
3594           if (!IsListEmpty (&ShellInfoObject.OldShellList.Link)) {
3595             CleanUpShellProtocol (&mShellProtocol);
3596           }
3597           Status = EFI_OUT_OF_RESOURCES;
3598           break;
3599         }
3600         //
3601         // reinstall over the old one...
3602         //
3603         OldProtocolNode->Handle    = Buffer[HandleCounter];
3604         OldProtocolNode->Interface = OldShell;
3605         Status = gBS->ReinstallProtocolInterface(
3606                             OldProtocolNode->Handle,
3607                             &gEfiShellProtocolGuid,
3608                             OldProtocolNode->Interface,
3609                             (VOID*)(&mShellProtocol));
3610         if (!EFI_ERROR(Status)) {
3611           //
3612           // we reinstalled sucessfully.  log this so we can reverse it later.
3613           //
3614 
3615           //
3616           // add to the list for subsequent...
3617           //
3618           InsertTailList(&ShellInfoObject.OldShellList.Link, &OldProtocolNode->Link);
3619         }
3620       }
3621     }
3622     FreePool(Buffer);
3623   } else if (Status == EFI_NOT_FOUND) {
3624     ASSERT(IsListEmpty(&ShellInfoObject.OldShellList.Link));
3625     //
3626     // no one else published yet.  just publish it ourselves.
3627     //
3628     Status = gBS->InstallProtocolInterface (
3629                       &gImageHandle,
3630                       &gEfiShellProtocolGuid,
3631                       EFI_NATIVE_INTERFACE,
3632                       (VOID*)(&mShellProtocol));
3633   }
3634 
3635   if (PcdGetBool(PcdShellSupportOldProtocols)){
3636     ///@todo support ShellEnvironment2
3637     ///@todo do we need to support ShellEnvironment (not ShellEnvironment2) also?
3638   }
3639 
3640   if (!EFI_ERROR(Status)) {
3641     *NewShell = &mShellProtocol;
3642   }
3643   return (Status);
3644 }
3645 
3646 /**
3647   Opposite of CreatePopulateInstallShellProtocol.
3648 
3649   Free all memory and restore the system to the state it was in before calling
3650   CreatePopulateInstallShellProtocol.
3651 
3652   @param[in, out] NewShell   The pointer to the new shell protocol structure.
3653 
3654   @retval EFI_SUCCESS       The operation was successful.
3655 **/
3656 EFI_STATUS
CleanUpShellProtocol(IN OUT EFI_SHELL_PROTOCOL * NewShell)3657 CleanUpShellProtocol (
3658   IN OUT EFI_SHELL_PROTOCOL  *NewShell
3659   )
3660 {
3661   SHELL_PROTOCOL_HANDLE_LIST        *Node2;
3662 
3663   //
3664   // if we need to restore old protocols...
3665   //
3666   if (!IsListEmpty(&ShellInfoObject.OldShellList.Link)) {
3667     for (Node2 = (SHELL_PROTOCOL_HANDLE_LIST *) GetFirstNode (&ShellInfoObject.OldShellList.Link)
3668          ; !IsListEmpty (&ShellInfoObject.OldShellList.Link)
3669          ; Node2 = (SHELL_PROTOCOL_HANDLE_LIST *) GetFirstNode (&ShellInfoObject.OldShellList.Link)
3670          ) {
3671       RemoveEntryList (&Node2->Link);
3672       gBS->ReinstallProtocolInterface (Node2->Handle, &gEfiShellProtocolGuid, NewShell, Node2->Interface);
3673       FreePool (Node2);
3674     }
3675   } else {
3676     //
3677     // no need to restore
3678     //
3679     gBS->UninstallProtocolInterface (gImageHandle, &gEfiShellProtocolGuid, NewShell);
3680   }
3681   return EFI_SUCCESS;
3682 }
3683 
3684 /**
3685   Cleanup the shell environment.
3686 
3687   @param[in, out] NewShell   The pointer to the new shell protocol structure.
3688 
3689   @retval EFI_SUCCESS       The operation was successful.
3690 **/
3691 EFI_STATUS
CleanUpShellEnvironment(IN OUT EFI_SHELL_PROTOCOL * NewShell)3692 CleanUpShellEnvironment (
3693   IN OUT EFI_SHELL_PROTOCOL  *NewShell
3694   )
3695 {
3696   EFI_STATUS                        Status;
3697   EFI_SIMPLE_TEXT_INPUT_EX_PROTOCOL *SimpleEx;
3698 
3699   CleanUpShellProtocol (NewShell);
3700 
3701   Status = gBS->CloseEvent(NewShell->ExecutionBreak);
3702   NewShell->ExecutionBreak = NULL;
3703 
3704   Status = gBS->OpenProtocol(
3705     gST->ConsoleInHandle,
3706     &gEfiSimpleTextInputExProtocolGuid,
3707     (VOID**)&SimpleEx,
3708     gImageHandle,
3709     NULL,
3710     EFI_OPEN_PROTOCOL_GET_PROTOCOL);
3711 
3712   if (!EFI_ERROR (Status)) {
3713     Status = SimpleEx->UnregisterKeyNotify(SimpleEx, ShellInfoObject.CtrlCNotifyHandle1);
3714     Status = SimpleEx->UnregisterKeyNotify(SimpleEx, ShellInfoObject.CtrlCNotifyHandle2);
3715     Status = SimpleEx->UnregisterKeyNotify(SimpleEx, ShellInfoObject.CtrlCNotifyHandle3);
3716     Status = SimpleEx->UnregisterKeyNotify(SimpleEx, ShellInfoObject.CtrlCNotifyHandle4);
3717     Status = SimpleEx->UnregisterKeyNotify(SimpleEx, ShellInfoObject.CtrlSNotifyHandle1);
3718     Status = SimpleEx->UnregisterKeyNotify(SimpleEx, ShellInfoObject.CtrlSNotifyHandle2);
3719     Status = SimpleEx->UnregisterKeyNotify(SimpleEx, ShellInfoObject.CtrlSNotifyHandle3);
3720     Status = SimpleEx->UnregisterKeyNotify(SimpleEx, ShellInfoObject.CtrlSNotifyHandle4);
3721   }
3722   return (Status);
3723 }
3724 
3725 /**
3726   Notification function for keystrokes.
3727 
3728   @param[in] KeyData    The key that was pressed.
3729 
3730   @retval EFI_SUCCESS   The operation was successful.
3731 **/
3732 EFI_STATUS
3733 EFIAPI
NotificationFunction(IN EFI_KEY_DATA * KeyData)3734 NotificationFunction(
3735   IN EFI_KEY_DATA *KeyData
3736   )
3737 {
3738   if ( ((KeyData->Key.UnicodeChar == L'c') &&
3739         (KeyData->KeyState.KeyShiftState == (EFI_SHIFT_STATE_VALID|EFI_LEFT_CONTROL_PRESSED) || KeyData->KeyState.KeyShiftState  == (EFI_SHIFT_STATE_VALID|EFI_RIGHT_CONTROL_PRESSED))) ||
3740       (KeyData->Key.UnicodeChar == 3)
3741       ){
3742     if (ShellInfoObject.NewEfiShellProtocol->ExecutionBreak == NULL) {
3743       return (EFI_UNSUPPORTED);
3744     }
3745     return (gBS->SignalEvent(ShellInfoObject.NewEfiShellProtocol->ExecutionBreak));
3746   } else if  ((KeyData->Key.UnicodeChar == L's') &&
3747               (KeyData->KeyState.KeyShiftState  == (EFI_SHIFT_STATE_VALID|EFI_LEFT_CONTROL_PRESSED) || KeyData->KeyState.KeyShiftState  == (EFI_SHIFT_STATE_VALID|EFI_RIGHT_CONTROL_PRESSED))
3748               ){
3749     ShellInfoObject.HaltOutput = TRUE;
3750   }
3751   return (EFI_SUCCESS);
3752 }
3753 
3754 /**
3755   Function to start monitoring for CTRL-C using SimpleTextInputEx.  This
3756   feature's enabled state was not known when the shell initially launched.
3757 
3758   @retval EFI_SUCCESS           The feature is enabled.
3759   @retval EFI_OUT_OF_RESOURCES  There is not enough mnemory available.
3760 **/
3761 EFI_STATUS
InernalEfiShellStartMonitor(VOID)3762 InernalEfiShellStartMonitor(
3763   VOID
3764   )
3765 {
3766   EFI_SIMPLE_TEXT_INPUT_EX_PROTOCOL *SimpleEx;
3767   EFI_KEY_DATA                      KeyData;
3768   EFI_STATUS                        Status;
3769 
3770   Status = gBS->OpenProtocol(
3771     gST->ConsoleInHandle,
3772     &gEfiSimpleTextInputExProtocolGuid,
3773     (VOID**)&SimpleEx,
3774     gImageHandle,
3775     NULL,
3776     EFI_OPEN_PROTOCOL_GET_PROTOCOL);
3777   if (EFI_ERROR(Status)) {
3778     ShellPrintHiiEx(
3779       -1,
3780       -1,
3781       NULL,
3782       STRING_TOKEN (STR_SHELL_NO_IN_EX),
3783       ShellInfoObject.HiiHandle);
3784     return (EFI_SUCCESS);
3785   }
3786 
3787   if (ShellInfoObject.NewEfiShellProtocol->ExecutionBreak == NULL) {
3788     return (EFI_UNSUPPORTED);
3789   }
3790 
3791   KeyData.KeyState.KeyToggleState = 0;
3792   KeyData.Key.ScanCode            = 0;
3793   KeyData.KeyState.KeyShiftState  = EFI_SHIFT_STATE_VALID|EFI_LEFT_CONTROL_PRESSED;
3794   KeyData.Key.UnicodeChar         = L'c';
3795 
3796   Status = SimpleEx->RegisterKeyNotify(
3797     SimpleEx,
3798     &KeyData,
3799     NotificationFunction,
3800     &ShellInfoObject.CtrlCNotifyHandle1);
3801 
3802   KeyData.KeyState.KeyShiftState  = EFI_SHIFT_STATE_VALID|EFI_RIGHT_CONTROL_PRESSED;
3803   if (!EFI_ERROR(Status)) {
3804     Status = SimpleEx->RegisterKeyNotify(
3805       SimpleEx,
3806       &KeyData,
3807       NotificationFunction,
3808       &ShellInfoObject.CtrlCNotifyHandle2);
3809   }
3810   KeyData.KeyState.KeyShiftState  = EFI_SHIFT_STATE_VALID|EFI_LEFT_CONTROL_PRESSED;
3811   KeyData.Key.UnicodeChar         = 3;
3812   if (!EFI_ERROR(Status)) {
3813     Status = SimpleEx->RegisterKeyNotify(
3814       SimpleEx,
3815       &KeyData,
3816       NotificationFunction,
3817       &ShellInfoObject.CtrlCNotifyHandle3);
3818   }
3819   KeyData.KeyState.KeyShiftState  = EFI_SHIFT_STATE_VALID|EFI_RIGHT_CONTROL_PRESSED;
3820   if (!EFI_ERROR(Status)) {
3821     Status = SimpleEx->RegisterKeyNotify(
3822       SimpleEx,
3823       &KeyData,
3824       NotificationFunction,
3825       &ShellInfoObject.CtrlCNotifyHandle4);
3826   }
3827   return (Status);
3828 }
3829 
3830