• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /** @file
2   Provides interface to shell internal functions for shell commands.
3 
4   Copyright (c) 2009 - 2016, Intel Corporation. All rights reserved.<BR>
5   (C) Copyright 2013-2015 Hewlett-Packard Development Company, L.P.<BR>
6   (C) Copyright 2016 Hewlett Packard Enterprise Development LP<BR>
7 
8   This program and the accompanying materials
9   are licensed and made available under the terms and conditions of the BSD License
10   which accompanies this distribution.  The full text of the license may be found at
11   http://opensource.org/licenses/bsd-license.php
12 
13   THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
14   WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
15 
16 **/
17 
18 #include "UefiShellCommandLib.h"
19 
20 // STATIC local variables
21 STATIC SHELL_COMMAND_INTERNAL_LIST_ENTRY  mCommandList;
22 STATIC SCRIPT_FILE_LIST                   mScriptList;
23 STATIC ALIAS_LIST                         mAliasList;
24 STATIC BOOLEAN                            mEchoState;
25 STATIC BOOLEAN                            mExitRequested;
26 STATIC UINT64                             mExitCode;
27 STATIC BOOLEAN                            mExitScript;
28 STATIC CHAR16                             *mProfileList;
29 STATIC UINTN                              mProfileListSize;
30 STATIC UINTN                              mFsMaxCount = 0;
31 STATIC UINTN                              mBlkMaxCount = 0;
32 STATIC BUFFER_LIST                        mFileHandleList;
33 
34 STATIC CONST CHAR8 Hex[] = {
35   '0',
36   '1',
37   '2',
38   '3',
39   '4',
40   '5',
41   '6',
42   '7',
43   '8',
44   '9',
45   'A',
46   'B',
47   'C',
48   'D',
49   'E',
50   'F'
51 };
52 
53 // global variables required by library class.
54 EFI_UNICODE_COLLATION_PROTOCOL    *gUnicodeCollation            = NULL;
55 SHELL_MAP_LIST                    gShellMapList;
56 SHELL_MAP_LIST                    *gShellCurDir                 = NULL;
57 
58 CONST CHAR16* SupportLevel[] = {
59   L"Minimal",
60   L"Scripting",
61   L"Basic",
62   L"Interactive"
63 };
64 
65 /**
66   Function to make sure that the global protocol pointers are valid.
67   must be called after constructor before accessing the pointers.
68 **/
69 EFI_STATUS
70 EFIAPI
CommandInit(VOID)71 CommandInit(
72   VOID
73   )
74 {
75   EFI_STATUS Status;
76   if (gUnicodeCollation == NULL) {
77     Status = gBS->LocateProtocol(&gEfiUnicodeCollation2ProtocolGuid, NULL, (VOID**)&gUnicodeCollation);
78     if (EFI_ERROR(Status)) {
79       return (EFI_DEVICE_ERROR);
80     }
81   }
82   return (EFI_SUCCESS);
83 }
84 
85 /**
86   Constructor for the Shell Command library.
87 
88   Initialize the library and determine if the underlying is a UEFI Shell 2.0 or an EFI shell.
89 
90   @param ImageHandle    the image handle of the process
91   @param SystemTable    the EFI System Table pointer
92 
93   @retval EFI_SUCCESS   the initialization was complete sucessfully
94 **/
95 RETURN_STATUS
96 EFIAPI
ShellCommandLibConstructor(IN EFI_HANDLE ImageHandle,IN EFI_SYSTEM_TABLE * SystemTable)97 ShellCommandLibConstructor (
98   IN EFI_HANDLE        ImageHandle,
99   IN EFI_SYSTEM_TABLE  *SystemTable
100   )
101 {
102   EFI_STATUS        Status;
103   InitializeListHead(&gShellMapList.Link);
104   InitializeListHead(&mCommandList.Link);
105   InitializeListHead(&mAliasList.Link);
106   InitializeListHead(&mScriptList.Link);
107   InitializeListHead(&mFileHandleList.Link);
108   mEchoState = TRUE;
109 
110   mExitRequested    = FALSE;
111   mExitScript       = FALSE;
112   mProfileListSize  = 0;
113   mProfileList      = NULL;
114 
115   if (gUnicodeCollation == NULL) {
116     Status = gBS->LocateProtocol(&gEfiUnicodeCollation2ProtocolGuid, NULL, (VOID**)&gUnicodeCollation);
117     if (EFI_ERROR(Status)) {
118       return (EFI_DEVICE_ERROR);
119     }
120   }
121 
122   return (RETURN_SUCCESS);
123 }
124 
125 /**
126   Frees list of file handles.
127 
128   @param[in] List     The list to free.
129 **/
130 VOID
FreeFileHandleList(IN BUFFER_LIST * List)131 FreeFileHandleList (
132   IN BUFFER_LIST *List
133   )
134 {
135   BUFFER_LIST               *BufferListEntry;
136 
137   if (List == NULL){
138     return;
139   }
140   //
141   // enumerate through the buffer list and free all memory
142   //
143   for ( BufferListEntry = ( BUFFER_LIST *)GetFirstNode(&List->Link)
144       ; !IsListEmpty (&List->Link)
145       ; BufferListEntry = (BUFFER_LIST *)GetFirstNode(&List->Link)
146      ){
147     RemoveEntryList(&BufferListEntry->Link);
148     ASSERT(BufferListEntry->Buffer != NULL);
149     SHELL_FREE_NON_NULL(((SHELL_COMMAND_FILE_HANDLE*)(BufferListEntry->Buffer))->Path);
150     SHELL_FREE_NON_NULL(BufferListEntry->Buffer);
151     SHELL_FREE_NON_NULL(BufferListEntry);
152   }
153 }
154 
155 /**
156   Destructor for the library.  free any resources.
157 
158   @param ImageHandle    the image handle of the process
159   @param SystemTable    the EFI System Table pointer
160 
161   @retval RETURN_SUCCESS this function always returns success
162 **/
163 RETURN_STATUS
164 EFIAPI
ShellCommandLibDestructor(IN EFI_HANDLE ImageHandle,IN EFI_SYSTEM_TABLE * SystemTable)165 ShellCommandLibDestructor (
166   IN EFI_HANDLE        ImageHandle,
167   IN EFI_SYSTEM_TABLE  *SystemTable
168   )
169 {
170   SHELL_COMMAND_INTERNAL_LIST_ENTRY *Node;
171   ALIAS_LIST                        *Node2;
172   SCRIPT_FILE_LIST                  *Node3;
173   SHELL_MAP_LIST                    *MapNode;
174   //
175   // enumerate throught the list and free all the memory
176   //
177   while (!IsListEmpty (&mCommandList.Link)) {
178     Node = (SHELL_COMMAND_INTERNAL_LIST_ENTRY *)GetFirstNode(&mCommandList.Link);
179     RemoveEntryList(&Node->Link);
180     SHELL_FREE_NON_NULL(Node->CommandString);
181     FreePool(Node);
182     DEBUG_CODE(Node = NULL;);
183   }
184 
185   //
186   // enumerate through the alias list and free all memory
187   //
188   while (!IsListEmpty (&mAliasList.Link)) {
189     Node2 = (ALIAS_LIST *)GetFirstNode(&mAliasList.Link);
190     RemoveEntryList(&Node2->Link);
191     SHELL_FREE_NON_NULL(Node2->CommandString);
192     SHELL_FREE_NON_NULL(Node2->Alias);
193     SHELL_FREE_NON_NULL(Node2);
194     DEBUG_CODE(Node2 = NULL;);
195   }
196 
197   //
198   // enumerate throught the list and free all the memory
199   //
200   while (!IsListEmpty (&mScriptList.Link)) {
201     Node3 = (SCRIPT_FILE_LIST *)GetFirstNode(&mScriptList.Link);
202     RemoveEntryList(&Node3->Link);
203     DeleteScriptFileStruct(Node3->Data);
204     FreePool(Node3);
205   }
206 
207   //
208   // enumerate throught the mappings list and free all the memory
209   //
210   if (!IsListEmpty(&gShellMapList.Link)) {
211     for (MapNode = (SHELL_MAP_LIST *)GetFirstNode(&gShellMapList.Link)
212          ; !IsListEmpty (&gShellMapList.Link)
213          ; MapNode = (SHELL_MAP_LIST *)GetFirstNode(&gShellMapList.Link)
214         ){
215       ASSERT(MapNode != NULL);
216       RemoveEntryList(&MapNode->Link);
217       SHELL_FREE_NON_NULL(MapNode->DevicePath);
218       SHELL_FREE_NON_NULL(MapNode->MapName);
219       SHELL_FREE_NON_NULL(MapNode->CurrentDirectoryPath);
220       FreePool(MapNode);
221     }
222   }
223   if (!IsListEmpty(&mFileHandleList.Link)){
224     FreeFileHandleList(&mFileHandleList);
225   }
226 
227   if (mProfileList != NULL) {
228     FreePool(mProfileList);
229   }
230 
231   gUnicodeCollation            = NULL;
232   gShellCurDir                 = NULL;
233 
234   return (RETURN_SUCCESS);
235 }
236 
237 /**
238   Find a dynamic command protocol instance given a command name string.
239 
240   @param CommandString  the command name string
241 
242   @return instance      the command protocol instance, if dynamic command instance found
243   @retval NULL          no dynamic command protocol instance found for name
244 **/
245 CONST EFI_SHELL_DYNAMIC_COMMAND_PROTOCOL *
ShellCommandFindDynamicCommand(IN CONST CHAR16 * CommandString)246 ShellCommandFindDynamicCommand (
247   IN CONST CHAR16 *CommandString
248   )
249 {
250   EFI_STATUS                          Status;
251   EFI_HANDLE                          *CommandHandleList;
252   EFI_HANDLE                          *NextCommand;
253   EFI_SHELL_DYNAMIC_COMMAND_PROTOCOL  *DynamicCommand;
254 
255   CommandHandleList = GetHandleListByProtocol(&gEfiShellDynamicCommandProtocolGuid);
256   if (CommandHandleList == NULL) {
257     //
258     // not found or out of resources
259     //
260     return NULL;
261   }
262 
263   for (NextCommand = CommandHandleList; *NextCommand != NULL; NextCommand++) {
264     Status = gBS->HandleProtocol(
265       *NextCommand,
266       &gEfiShellDynamicCommandProtocolGuid,
267       (VOID **)&DynamicCommand
268       );
269 
270     if (EFI_ERROR(Status)) {
271       continue;
272     }
273 
274     if (gUnicodeCollation->StriColl(
275           gUnicodeCollation,
276           (CHAR16*)CommandString,
277           (CHAR16*)DynamicCommand->CommandName) == 0
278           ){
279         FreePool(CommandHandleList);
280         return (DynamicCommand);
281     }
282   }
283 
284   FreePool(CommandHandleList);
285   return (NULL);
286 }
287 
288 /**
289   Checks if a command exists as a dynamic command protocol instance
290 
291   @param[in] CommandString        The command string to check for on the list.
292 **/
293 BOOLEAN
ShellCommandDynamicCommandExists(IN CONST CHAR16 * CommandString)294 ShellCommandDynamicCommandExists (
295   IN CONST CHAR16 *CommandString
296   )
297 {
298   return (BOOLEAN) ((ShellCommandFindDynamicCommand(CommandString) != NULL));
299 }
300 
301 /**
302   Checks if a command is already on the internal command list.
303 
304   @param[in] CommandString        The command string to check for on the list.
305 **/
306 BOOLEAN
ShellCommandIsCommandOnInternalList(IN CONST CHAR16 * CommandString)307 ShellCommandIsCommandOnInternalList(
308   IN CONST  CHAR16 *CommandString
309   )
310 {
311   SHELL_COMMAND_INTERNAL_LIST_ENTRY *Node;
312 
313   //
314   // assert for NULL parameter
315   //
316   ASSERT(CommandString != NULL);
317 
318   //
319   // check for the command
320   //
321   for ( Node = (SHELL_COMMAND_INTERNAL_LIST_ENTRY *)GetFirstNode(&mCommandList.Link)
322       ; !IsNull(&mCommandList.Link, &Node->Link)
323       ; Node = (SHELL_COMMAND_INTERNAL_LIST_ENTRY *)GetNextNode(&mCommandList.Link, &Node->Link)
324      ){
325     ASSERT(Node->CommandString != NULL);
326     if (gUnicodeCollation->StriColl(
327           gUnicodeCollation,
328           (CHAR16*)CommandString,
329           Node->CommandString) == 0
330        ){
331       return (TRUE);
332     }
333   }
334   return (FALSE);
335 }
336 
337 /**
338   Checks if a command exists, either internally or through the dynamic command protocol.
339 
340   @param[in] CommandString        The command string to check for on the list.
341 **/
342 BOOLEAN
343 EFIAPI
ShellCommandIsCommandOnList(IN CONST CHAR16 * CommandString)344 ShellCommandIsCommandOnList(
345   IN CONST  CHAR16                      *CommandString
346   )
347 {
348   if (ShellCommandIsCommandOnInternalList(CommandString)) {
349     return TRUE;
350   }
351 
352   return ShellCommandDynamicCommandExists(CommandString);
353 }
354 
355 /**
356  Get the help text for a dynamic command.
357 
358   @param[in] CommandString        The command name.
359 
360   @retval NULL  No help text was found.
361   @return       String of help text. Caller required to free.
362 **/
363 CHAR16*
ShellCommandGetDynamicCommandHelp(IN CONST CHAR16 * CommandString)364 ShellCommandGetDynamicCommandHelp(
365   IN CONST  CHAR16                      *CommandString
366   )
367 {
368   EFI_SHELL_DYNAMIC_COMMAND_PROTOCOL  *DynamicCommand;
369 
370   DynamicCommand = (EFI_SHELL_DYNAMIC_COMMAND_PROTOCOL  *)ShellCommandFindDynamicCommand(CommandString);
371   if (DynamicCommand == NULL) {
372     return (NULL);
373   }
374 
375   //
376   // TODO: how to get proper language?
377   //
378   return DynamicCommand->GetHelp(DynamicCommand, "en");
379 }
380 
381 /**
382   Get the help text for an internal command.
383 
384   @param[in] CommandString        The command name.
385 
386   @retval NULL  No help text was found.
387   @return       String of help text. Caller reuiqred to free.
388 **/
389 CHAR16*
ShellCommandGetInternalCommandHelp(IN CONST CHAR16 * CommandString)390 ShellCommandGetInternalCommandHelp(
391   IN CONST  CHAR16                      *CommandString
392   )
393 {
394   SHELL_COMMAND_INTERNAL_LIST_ENTRY *Node;
395 
396   //
397   // assert for NULL parameter
398   //
399   ASSERT(CommandString != NULL);
400 
401   //
402   // check for the command
403   //
404   for ( Node = (SHELL_COMMAND_INTERNAL_LIST_ENTRY *)GetFirstNode(&mCommandList.Link)
405       ; !IsNull(&mCommandList.Link, &Node->Link)
406       ; Node = (SHELL_COMMAND_INTERNAL_LIST_ENTRY *)GetNextNode(&mCommandList.Link, &Node->Link)
407      ){
408     ASSERT(Node->CommandString != NULL);
409     if (gUnicodeCollation->StriColl(
410           gUnicodeCollation,
411           (CHAR16*)CommandString,
412           Node->CommandString) == 0
413        ){
414       return (HiiGetString(Node->HiiHandle, Node->ManFormatHelp, NULL));
415     }
416   }
417   return (NULL);
418 }
419 
420 /**
421   Get the help text for a command.
422 
423   @param[in] CommandString        The command name.
424 
425   @retval NULL  No help text was found.
426   @return       String of help text.Caller reuiqred to free.
427 **/
428 CHAR16*
429 EFIAPI
ShellCommandGetCommandHelp(IN CONST CHAR16 * CommandString)430 ShellCommandGetCommandHelp (
431   IN CONST  CHAR16                      *CommandString
432   )
433 {
434   CHAR16      *HelpStr;
435   HelpStr = ShellCommandGetInternalCommandHelp(CommandString);
436 
437   if (HelpStr == NULL) {
438     HelpStr = ShellCommandGetDynamicCommandHelp(CommandString);
439   }
440 
441   return HelpStr;
442 }
443 
444 
445 /**
446   Registers handlers of type SHELL_RUN_COMMAND and
447   SHELL_GET_MAN_FILENAME for each shell command.
448 
449   If the ShellSupportLevel is greater than the value of the
450   PcdShellSupportLevel then return RETURN_UNSUPPORTED.
451 
452   Registers the handlers specified by GetHelpInfoHandler and CommandHandler
453   with the command specified by CommandString. If the command named by
454   CommandString has already been registered, then return
455   RETURN_ALREADY_STARTED.
456 
457   If there are not enough resources available to register the handlers then
458   RETURN_OUT_OF_RESOURCES is returned.
459 
460   If CommandString is NULL, then ASSERT().
461   If GetHelpInfoHandler is NULL, then ASSERT().
462   If CommandHandler is NULL, then ASSERT().
463   If ProfileName is NULL, then ASSERT().
464 
465   @param[in]  CommandString         Pointer to the command name.  This is the
466                                     name to look for on the command line in
467                                     the shell.
468   @param[in]  CommandHandler        Pointer to a function that runs the
469                                     specified command.
470   @param[in]  GetManFileName        Pointer to a function that provides man
471                                     filename.
472   @param[in]  ShellMinSupportLevel  minimum Shell Support Level which has this
473                                     function.
474   @param[in]  ProfileName           profile name to require for support of this
475                                     function.
476   @param[in]  CanAffectLE           indicates whether this command's return value
477                                     can change the LASTERROR environment variable.
478   @param[in]  HiiHandle             Handle of this command's HII entry.
479   @param[in]  ManFormatHelp         HII locator for the help text.
480 
481   @retval  RETURN_SUCCESS           The handlers were registered.
482   @retval  RETURN_OUT_OF_RESOURCES  There are not enough resources available to
483                                     register the shell command.
484   @retval RETURN_UNSUPPORTED        the ShellMinSupportLevel was higher than the
485                                     currently allowed support level.
486   @retval RETURN_ALREADY_STARTED    The CommandString represents a command that
487                                     is already registered.  Only 1 handler set for
488                                     a given command is allowed.
489   @sa SHELL_GET_MAN_FILENAME
490   @sa SHELL_RUN_COMMAND
491 **/
492 RETURN_STATUS
493 EFIAPI
ShellCommandRegisterCommandName(IN CONST CHAR16 * CommandString,IN SHELL_RUN_COMMAND CommandHandler,IN SHELL_GET_MAN_FILENAME GetManFileName,IN UINT32 ShellMinSupportLevel,IN CONST CHAR16 * ProfileName,IN CONST BOOLEAN CanAffectLE,IN CONST EFI_HANDLE HiiHandle,IN CONST EFI_STRING_ID ManFormatHelp)494 ShellCommandRegisterCommandName (
495   IN CONST  CHAR16                      *CommandString,
496   IN        SHELL_RUN_COMMAND           CommandHandler,
497   IN        SHELL_GET_MAN_FILENAME      GetManFileName,
498   IN        UINT32                      ShellMinSupportLevel,
499   IN CONST  CHAR16                      *ProfileName,
500   IN CONST  BOOLEAN                     CanAffectLE,
501   IN CONST  EFI_HANDLE                  HiiHandle,
502   IN CONST  EFI_STRING_ID               ManFormatHelp
503   )
504 {
505   SHELL_COMMAND_INTERNAL_LIST_ENTRY *Node;
506   SHELL_COMMAND_INTERNAL_LIST_ENTRY *Command;
507   SHELL_COMMAND_INTERNAL_LIST_ENTRY *PrevCommand;
508   INTN LexicalMatchValue;
509 
510   //
511   // Initialize local variables.
512   //
513   Command = NULL;
514   PrevCommand = NULL;
515   LexicalMatchValue = 0;
516 
517   //
518   // ASSERTs for NULL parameters
519   //
520   ASSERT(CommandString  != NULL);
521   ASSERT(GetManFileName != NULL);
522   ASSERT(CommandHandler != NULL);
523   ASSERT(ProfileName    != NULL);
524 
525   //
526   // check for shell support level
527   //
528   if (PcdGet8(PcdShellSupportLevel) < ShellMinSupportLevel) {
529     return (RETURN_UNSUPPORTED);
530   }
531 
532   //
533   // check for already on the list
534   //
535   if (ShellCommandIsCommandOnList(CommandString)) {
536     return (RETURN_ALREADY_STARTED);
537   }
538 
539   //
540   // allocate memory for new struct
541   //
542   Node = AllocateZeroPool(sizeof(SHELL_COMMAND_INTERNAL_LIST_ENTRY));
543   if (Node == NULL) {
544     return RETURN_OUT_OF_RESOURCES;
545   }
546   Node->CommandString = AllocateCopyPool(StrSize(CommandString), CommandString);
547   if (Node->CommandString == NULL) {
548     FreePool (Node);
549     return RETURN_OUT_OF_RESOURCES;
550   }
551 
552   Node->GetManFileName  = GetManFileName;
553   Node->CommandHandler  = CommandHandler;
554   Node->LastError       = CanAffectLE;
555   Node->HiiHandle       = HiiHandle;
556   Node->ManFormatHelp   = ManFormatHelp;
557 
558   if ( StrLen(ProfileName)>0
559     && ((mProfileList != NULL
560     && StrStr(mProfileList, ProfileName) == NULL) || mProfileList == NULL)
561    ){
562     ASSERT((mProfileList == NULL && mProfileListSize == 0) || (mProfileList != NULL));
563     if (mProfileList == NULL) {
564       //
565       // If this is the first make a leading ';'
566       //
567       StrnCatGrow(&mProfileList, &mProfileListSize, L";", 0);
568     }
569     StrnCatGrow(&mProfileList, &mProfileListSize, ProfileName, 0);
570     StrnCatGrow(&mProfileList, &mProfileListSize, L";", 0);
571   }
572 
573   //
574   // Insert a new entry on top of the list
575   //
576   InsertHeadList (&mCommandList.Link, &Node->Link);
577 
578   //
579   // Move a new registered command to its sorted ordered location in the list
580   //
581   for (Command = (SHELL_COMMAND_INTERNAL_LIST_ENTRY *)GetFirstNode (&mCommandList.Link),
582         PrevCommand = (SHELL_COMMAND_INTERNAL_LIST_ENTRY *)GetFirstNode (&mCommandList.Link)
583         ; !IsNull (&mCommandList.Link, &Command->Link)
584         ; Command = (SHELL_COMMAND_INTERNAL_LIST_ENTRY *)GetNextNode (&mCommandList.Link, &Command->Link)) {
585 
586     //
587     // Get Lexical Comparison Value between PrevCommand and Command list entry
588     //
589     LexicalMatchValue = gUnicodeCollation->StriColl (
590                                              gUnicodeCollation,
591                                              PrevCommand->CommandString,
592                                              Command->CommandString
593                                              );
594 
595     //
596     // Swap PrevCommand and Command list entry if PrevCommand list entry
597     // is alphabetically greater than Command list entry
598     //
599     if (LexicalMatchValue > 0){
600       Command = (SHELL_COMMAND_INTERNAL_LIST_ENTRY *) SwapListEntries (&PrevCommand->Link, &Command->Link);
601     } else if (LexicalMatchValue < 0) {
602       //
603       // PrevCommand entry is lexically lower than Command entry
604       //
605       break;
606     }
607   }
608 
609   return (RETURN_SUCCESS);
610 }
611 
612 /**
613   Function to get the current Profile string.
614 
615   @retval NULL  There are no installed profiles.
616   @return       A semi-colon delimited list of profiles.
617 **/
618 CONST CHAR16 *
619 EFIAPI
ShellCommandGetProfileList(VOID)620 ShellCommandGetProfileList (
621   VOID
622   )
623 {
624   return (mProfileList);
625 }
626 
627 /**
628   Checks if a command string has been registered for CommandString and if so it runs
629   the previously registered handler for that command with the command line.
630 
631   If CommandString is NULL, then ASSERT().
632 
633   If Sections is specified, then each section name listed will be compared in a casesensitive
634   manner, to the section names described in Appendix B UEFI Shell 2.0 spec. If the section exists,
635   it will be appended to the returned help text. If the section does not exist, no
636   information will be returned. If Sections is NULL, then all help text information
637   available will be returned.
638 
639   @param[in]  CommandString          Pointer to the command name.  This is the name
640                                      found on the command line in the shell.
641   @param[in, out] RetVal             Pointer to the return vaule from the command handler.
642 
643   @param[in, out]  CanAffectLE       indicates whether this command's return value
644                                      needs to be placed into LASTERROR environment variable.
645 
646   @retval RETURN_SUCCESS            The handler was run.
647   @retval RETURN_NOT_FOUND          The CommandString did not match a registered
648                                     command name.
649   @sa SHELL_RUN_COMMAND
650 **/
651 RETURN_STATUS
652 EFIAPI
ShellCommandRunCommandHandler(IN CONST CHAR16 * CommandString,IN OUT SHELL_STATUS * RetVal,IN OUT BOOLEAN * CanAffectLE OPTIONAL)653 ShellCommandRunCommandHandler (
654   IN CONST CHAR16               *CommandString,
655   IN OUT SHELL_STATUS           *RetVal,
656   IN OUT BOOLEAN                *CanAffectLE OPTIONAL
657   )
658 {
659   SHELL_COMMAND_INTERNAL_LIST_ENTRY   *Node;
660   EFI_SHELL_DYNAMIC_COMMAND_PROTOCOL  *DynamicCommand;
661 
662   //
663   // assert for NULL parameters
664   //
665   ASSERT(CommandString != NULL);
666 
667   //
668   // check for the command
669   //
670   for ( Node = (SHELL_COMMAND_INTERNAL_LIST_ENTRY *)GetFirstNode(&mCommandList.Link)
671       ; !IsNull(&mCommandList.Link, &Node->Link)
672       ; Node = (SHELL_COMMAND_INTERNAL_LIST_ENTRY *)GetNextNode(&mCommandList.Link, &Node->Link)
673      ){
674     ASSERT(Node->CommandString != NULL);
675     if (gUnicodeCollation->StriColl(
676           gUnicodeCollation,
677           (CHAR16*)CommandString,
678           Node->CommandString) == 0
679       ){
680       if (CanAffectLE != NULL) {
681         *CanAffectLE = Node->LastError;
682       }
683       if (RetVal != NULL) {
684         *RetVal = Node->CommandHandler(NULL, gST);
685       } else {
686         Node->CommandHandler(NULL, gST);
687       }
688       return (RETURN_SUCCESS);
689     }
690   }
691 
692   //
693   // An internal command was not found, try to find a dynamic command
694   //
695   DynamicCommand = (EFI_SHELL_DYNAMIC_COMMAND_PROTOCOL  *)ShellCommandFindDynamicCommand(CommandString);
696   if (DynamicCommand != NULL) {
697     if (RetVal != NULL) {
698       *RetVal = DynamicCommand->Handler(DynamicCommand, gST, gEfiShellParametersProtocol, gEfiShellProtocol);
699     } else {
700       DynamicCommand->Handler(DynamicCommand, gST, gEfiShellParametersProtocol, gEfiShellProtocol);
701     }
702     return (RETURN_SUCCESS);
703   }
704 
705   return (RETURN_NOT_FOUND);
706 }
707 
708 /**
709   Checks if a command string has been registered for CommandString and if so it
710   returns the MAN filename specified for that command.
711 
712   If CommandString is NULL, then ASSERT().
713 
714   @param[in]  CommandString         Pointer to the command name.  This is the name
715                                     found on the command line in the shell.\
716 
717   @retval NULL                      the commandString was not a registered command.
718   @return other                     the name of the MAN file.
719   @sa SHELL_GET_MAN_FILENAME
720 **/
721 CONST CHAR16*
722 EFIAPI
ShellCommandGetManFileNameHandler(IN CONST CHAR16 * CommandString)723 ShellCommandGetManFileNameHandler (
724   IN CONST CHAR16               *CommandString
725   )
726 {
727   SHELL_COMMAND_INTERNAL_LIST_ENTRY *Node;
728 
729   //
730   // assert for NULL parameters
731   //
732   ASSERT(CommandString != NULL);
733 
734   //
735   // check for the command
736   //
737   for ( Node = (SHELL_COMMAND_INTERNAL_LIST_ENTRY *)GetFirstNode(&mCommandList.Link)
738       ; !IsNull(&mCommandList.Link, &Node->Link)
739       ; Node = (SHELL_COMMAND_INTERNAL_LIST_ENTRY *)GetNextNode(&mCommandList.Link, &Node->Link)
740      ){
741     ASSERT(Node->CommandString != NULL);
742     if (gUnicodeCollation->StriColl(
743           gUnicodeCollation,
744           (CHAR16*)CommandString,
745           Node->CommandString) == 0
746        ){
747       return (Node->GetManFileName());
748     }
749   }
750   return (NULL);
751 }
752 
753 /**
754   Get the list of all available shell internal commands.  This is a linked list
755   (via LIST_ENTRY structure).  enumerate through it using the BaseLib linked
756   list functions.  do not modify the values.
757 
758   @param[in] Sort       TRUE to alphabetically sort the values first.  FALSE otherwise.
759 
760   @return a Linked list of all available shell commands.
761 **/
762 CONST COMMAND_LIST*
763 EFIAPI
ShellCommandGetCommandList(IN CONST BOOLEAN Sort)764 ShellCommandGetCommandList (
765   IN CONST BOOLEAN Sort
766   )
767 {
768 //  if (!Sort) {
769 //    return ((COMMAND_LIST*)(&mCommandList));
770 //  }
771   return ((COMMAND_LIST*)(&mCommandList));
772 }
773 
774 /**
775   Registers aliases to be set as part of the initialization of the shell application.
776 
777   If Command is NULL, then ASSERT().
778   If Alias is NULL, then ASSERT().
779 
780   @param[in]  Command               Pointer to the Command
781   @param[in]  Alias                 Pointer to Alias
782 
783   @retval  RETURN_SUCCESS           The handlers were registered.
784   @retval  RETURN_OUT_OF_RESOURCES  There are not enough resources available to
785                                     register the shell command.
786 **/
787 RETURN_STATUS
788 EFIAPI
ShellCommandRegisterAlias(IN CONST CHAR16 * Command,IN CONST CHAR16 * Alias)789 ShellCommandRegisterAlias (
790   IN CONST CHAR16                       *Command,
791   IN CONST CHAR16                       *Alias
792   )
793 {
794   ALIAS_LIST *Node;
795   ALIAS_LIST *CommandAlias;
796   ALIAS_LIST *PrevCommandAlias;
797   INTN       LexicalMatchValue;
798 
799   //
800   // Asserts for NULL
801   //
802   ASSERT(Command != NULL);
803   ASSERT(Alias   != NULL);
804 
805   //
806   // allocate memory for new struct
807   //
808   Node = AllocateZeroPool(sizeof(ALIAS_LIST));
809   if (Node == NULL) {
810     return RETURN_OUT_OF_RESOURCES;
811   }
812   Node->CommandString = AllocateCopyPool(StrSize(Command), Command);
813   if (Node->CommandString == NULL) {
814     FreePool (Node);
815     return RETURN_OUT_OF_RESOURCES;
816   }
817   Node->Alias = AllocateCopyPool(StrSize(Alias), Alias);
818   if (Node->Alias == NULL) {
819     FreePool (Node->CommandString);
820     FreePool (Node);
821     return RETURN_OUT_OF_RESOURCES;
822   }
823 
824   InsertHeadList (&mAliasList.Link, &Node->Link);
825 
826   //
827   // Move a new pre-defined registered alias to its sorted ordered location in the list
828   //
829   for ( CommandAlias = (ALIAS_LIST *)GetFirstNode (&mAliasList.Link),
830          PrevCommandAlias = (ALIAS_LIST *)GetFirstNode (&mAliasList.Link)
831        ; !IsNull (&mAliasList.Link, &CommandAlias->Link)
832        ; CommandAlias = (ALIAS_LIST *) GetNextNode (&mAliasList.Link, &CommandAlias->Link) ) {
833     //
834     // Get Lexical comparison value between PrevCommandAlias and CommandAlias List Entry
835     //
836     LexicalMatchValue = gUnicodeCollation->StriColl (
837                                              gUnicodeCollation,
838                                              PrevCommandAlias->Alias,
839                                              CommandAlias->Alias
840                                              );
841 
842     //
843     // Swap PrevCommandAlias and CommandAlias list entry if PrevCommandAlias list entry
844     // is alphabetically greater than CommandAlias list entry
845     //
846     if (LexicalMatchValue > 0) {
847       CommandAlias = (ALIAS_LIST *) SwapListEntries (&PrevCommandAlias->Link, &CommandAlias->Link);
848     } else if (LexicalMatchValue < 0) {
849       //
850       // PrevCommandAlias entry is lexically lower than CommandAlias entry
851       //
852       break;
853     }
854   }
855 
856   return (RETURN_SUCCESS);
857 }
858 
859 /**
860   Get the list of all shell alias commands.  This is a linked list
861   (via LIST_ENTRY structure).  enumerate through it using the BaseLib linked
862   list functions.  do not modify the values.
863 
864   @return a Linked list of all requested shell alias'.
865 **/
866 CONST ALIAS_LIST*
867 EFIAPI
ShellCommandGetInitAliasList(VOID)868 ShellCommandGetInitAliasList (
869   VOID
870   )
871 {
872     return (&mAliasList);
873 }
874 
875 /**
876   Determine if a given alias is on the list of built in alias'.
877 
878   @param[in] Alias              The alias to test for
879 
880   @retval TRUE                  The alias is a built in alias
881   @retval FALSE                 The alias is not a built in alias
882 **/
883 BOOLEAN
884 EFIAPI
ShellCommandIsOnAliasList(IN CONST CHAR16 * Alias)885 ShellCommandIsOnAliasList(
886   IN CONST CHAR16 *Alias
887   )
888 {
889   ALIAS_LIST *Node;
890 
891   //
892   // assert for NULL parameter
893   //
894   ASSERT(Alias != NULL);
895 
896   //
897   // check for the Alias
898   //
899   for ( Node = (ALIAS_LIST *)GetFirstNode(&mAliasList.Link)
900       ; !IsNull(&mAliasList.Link, &Node->Link)
901       ; Node = (ALIAS_LIST *)GetNextNode(&mAliasList.Link, &Node->Link)
902      ){
903     ASSERT(Node->CommandString != NULL);
904     ASSERT(Node->Alias != NULL);
905     if (gUnicodeCollation->StriColl(
906           gUnicodeCollation,
907           (CHAR16*)Alias,
908           Node->CommandString) == 0
909        ){
910       return (TRUE);
911     }
912     if (gUnicodeCollation->StriColl(
913           gUnicodeCollation,
914           (CHAR16*)Alias,
915           Node->Alias) == 0
916        ){
917       return (TRUE);
918     }
919   }
920   return (FALSE);
921 }
922 
923 /**
924   Function to determine current state of ECHO.  Echo determines if lines from scripts
925   and ECHO commands are enabled.
926 
927   @retval TRUE    Echo is currently enabled
928   @retval FALSE   Echo is currently disabled
929 **/
930 BOOLEAN
931 EFIAPI
ShellCommandGetEchoState(VOID)932 ShellCommandGetEchoState(
933   VOID
934   )
935 {
936   return (mEchoState);
937 }
938 
939 /**
940   Function to set current state of ECHO.  Echo determines if lines from scripts
941   and ECHO commands are enabled.
942 
943   If State is TRUE, Echo will be enabled.
944   If State is FALSE, Echo will be disabled.
945 
946   @param[in] State      How to set echo.
947 **/
948 VOID
949 EFIAPI
ShellCommandSetEchoState(IN BOOLEAN State)950 ShellCommandSetEchoState(
951   IN BOOLEAN State
952   )
953 {
954   mEchoState = State;
955 }
956 
957 /**
958   Indicate that the current shell or script should exit.
959 
960   @param[in] ScriptOnly   TRUE if exiting a script; FALSE otherwise.
961   @param[in] ErrorCode    The 64 bit error code to return.
962 **/
963 VOID
964 EFIAPI
ShellCommandRegisterExit(IN BOOLEAN ScriptOnly,IN CONST UINT64 ErrorCode)965 ShellCommandRegisterExit (
966   IN BOOLEAN      ScriptOnly,
967   IN CONST UINT64 ErrorCode
968   )
969 {
970   mExitRequested = (BOOLEAN)(!mExitRequested);
971   if (mExitRequested) {
972     mExitScript    = ScriptOnly;
973   } else {
974     mExitScript    = FALSE;
975   }
976   mExitCode = ErrorCode;
977 }
978 
979 /**
980   Retrieve the Exit indicator.
981 
982   @retval TRUE      Exit was indicated.
983   @retval FALSE     Exis was not indicated.
984 **/
985 BOOLEAN
986 EFIAPI
ShellCommandGetExit(VOID)987 ShellCommandGetExit (
988   VOID
989   )
990 {
991   return (mExitRequested);
992 }
993 
994 /**
995   Retrieve the Exit code.
996 
997   If ShellCommandGetExit returns FALSE than the return from this is undefined.
998 
999   @return the value passed into RegisterExit.
1000 **/
1001 UINT64
1002 EFIAPI
ShellCommandGetExitCode(VOID)1003 ShellCommandGetExitCode (
1004   VOID
1005   )
1006 {
1007   return (mExitCode);
1008 }
1009 /**
1010   Retrieve the Exit script indicator.
1011 
1012   If ShellCommandGetExit returns FALSE than the return from this is undefined.
1013 
1014   @retval TRUE      ScriptOnly was indicated.
1015   @retval FALSE     ScriptOnly was not indicated.
1016 **/
1017 BOOLEAN
1018 EFIAPI
ShellCommandGetScriptExit(VOID)1019 ShellCommandGetScriptExit (
1020   VOID
1021   )
1022 {
1023   return (mExitScript);
1024 }
1025 
1026 /**
1027   Function to cleanup all memory from a SCRIPT_FILE structure.
1028 
1029   @param[in] Script     The pointer to the structure to cleanup.
1030 **/
1031 VOID
1032 EFIAPI
DeleteScriptFileStruct(IN SCRIPT_FILE * Script)1033 DeleteScriptFileStruct (
1034   IN SCRIPT_FILE *Script
1035   )
1036 {
1037   UINT8       LoopVar;
1038 
1039   if (Script == NULL) {
1040     return;
1041   }
1042 
1043   for (LoopVar = 0 ; LoopVar < Script->Argc ; LoopVar++) {
1044     SHELL_FREE_NON_NULL(Script->Argv[LoopVar]);
1045   }
1046   if (Script->Argv != NULL) {
1047     SHELL_FREE_NON_NULL(Script->Argv);
1048   }
1049   Script->CurrentCommand = NULL;
1050   while (!IsListEmpty (&Script->CommandList)) {
1051     Script->CurrentCommand = (SCRIPT_COMMAND_LIST *)GetFirstNode(&Script->CommandList);
1052     if (Script->CurrentCommand != NULL) {
1053       RemoveEntryList(&Script->CurrentCommand->Link);
1054       if (Script->CurrentCommand->Cl != NULL) {
1055         SHELL_FREE_NON_NULL(Script->CurrentCommand->Cl);
1056       }
1057       if (Script->CurrentCommand->Data != NULL) {
1058         SHELL_FREE_NON_NULL(Script->CurrentCommand->Data);
1059       }
1060       SHELL_FREE_NON_NULL(Script->CurrentCommand);
1061     }
1062   }
1063   SHELL_FREE_NON_NULL(Script->ScriptName);
1064   SHELL_FREE_NON_NULL(Script);
1065 }
1066 
1067 /**
1068   Function to return a pointer to the currently running script file object.
1069 
1070   @retval NULL        A script file is not currently running.
1071   @return             A pointer to the current script file object.
1072 **/
1073 SCRIPT_FILE*
1074 EFIAPI
ShellCommandGetCurrentScriptFile(VOID)1075 ShellCommandGetCurrentScriptFile (
1076   VOID
1077   )
1078 {
1079   SCRIPT_FILE_LIST *List;
1080   if (IsListEmpty (&mScriptList.Link)) {
1081     return (NULL);
1082   }
1083   List = ((SCRIPT_FILE_LIST*)GetFirstNode(&mScriptList.Link));
1084   return (List->Data);
1085 }
1086 
1087 /**
1088   Function to set a new script as the currently running one.
1089 
1090   This function will correctly stack and unstack nested scripts.
1091 
1092   @param[in] Script   Pointer to new script information structure.  if NULL
1093                       will remove and de-allocate the top-most Script structure.
1094 
1095   @return             A pointer to the current running script file after this
1096                       change.  NULL if removing the final script.
1097 **/
1098 SCRIPT_FILE*
1099 EFIAPI
ShellCommandSetNewScript(IN SCRIPT_FILE * Script OPTIONAL)1100 ShellCommandSetNewScript (
1101   IN SCRIPT_FILE *Script OPTIONAL
1102   )
1103 {
1104   SCRIPT_FILE_LIST *Node;
1105   if (Script == NULL) {
1106     if (IsListEmpty (&mScriptList.Link)) {
1107       return (NULL);
1108     }
1109     Node = (SCRIPT_FILE_LIST *)GetFirstNode(&mScriptList.Link);
1110     RemoveEntryList(&Node->Link);
1111     DeleteScriptFileStruct(Node->Data);
1112     FreePool(Node);
1113   } else {
1114     Node = AllocateZeroPool(sizeof(SCRIPT_FILE_LIST));
1115     if (Node == NULL) {
1116       return (NULL);
1117     }
1118     Node->Data = Script;
1119     InsertHeadList(&mScriptList.Link, &Node->Link);
1120   }
1121   return (ShellCommandGetCurrentScriptFile());
1122 }
1123 
1124 /**
1125   Function to generate the next default mapping name.
1126 
1127   If the return value is not NULL then it must be callee freed.
1128 
1129   @param Type                   What kind of mapping name to make.
1130 
1131   @retval NULL                  a memory allocation failed.
1132   @return a new map name string
1133 **/
1134 CHAR16*
1135 EFIAPI
ShellCommandCreateNewMappingName(IN CONST SHELL_MAPPING_TYPE Type)1136 ShellCommandCreateNewMappingName(
1137   IN CONST SHELL_MAPPING_TYPE Type
1138   )
1139 {
1140   CHAR16  *String;
1141   ASSERT(Type < MappingTypeMax);
1142 
1143   String = NULL;
1144 
1145   String = AllocateZeroPool(PcdGet8(PcdShellMapNameLength) * sizeof(String[0]));
1146   UnicodeSPrint(
1147     String,
1148     PcdGet8(PcdShellMapNameLength) * sizeof(String[0]),
1149     Type == MappingTypeFileSystem?L"FS%d:":L"BLK%d:",
1150     Type == MappingTypeFileSystem?mFsMaxCount++:mBlkMaxCount++);
1151 
1152   return (String);
1153 }
1154 
1155 /**
1156   Function to add a map node to the list of map items and update the "path" environment variable (optionally).
1157 
1158   If Path is TRUE (during initialization only), the path environment variable will also be updated to include
1159   default paths on the new map name...
1160 
1161   Path should be FALSE when this function is called from the protocol SetMap function.
1162 
1163   @param[in] Name               The human readable mapped name.
1164   @param[in] DevicePath         The Device Path for this map.
1165   @param[in] Flags              The Flags attribute for this map item.
1166   @param[in] Path               TRUE to update path, FALSE to skip this step (should only be TRUE during initialization).
1167 
1168   @retval EFI_SUCCESS           The addition was sucessful.
1169   @retval EFI_OUT_OF_RESOURCES  A memory allocation failed.
1170   @retval EFI_INVALID_PARAMETER A parameter was invalid.
1171 **/
1172 EFI_STATUS
1173 EFIAPI
ShellCommandAddMapItemAndUpdatePath(IN CONST CHAR16 * Name,IN CONST EFI_DEVICE_PATH_PROTOCOL * DevicePath,IN CONST UINT64 Flags,IN CONST BOOLEAN Path)1174 ShellCommandAddMapItemAndUpdatePath(
1175   IN CONST CHAR16                   *Name,
1176   IN CONST EFI_DEVICE_PATH_PROTOCOL *DevicePath,
1177   IN CONST UINT64                   Flags,
1178   IN CONST BOOLEAN                  Path
1179   )
1180 {
1181   EFI_STATUS      Status;
1182   SHELL_MAP_LIST  *MapListNode;
1183   CONST CHAR16    *OriginalPath;
1184   CHAR16          *NewPath;
1185   UINTN           NewPathSize;
1186 
1187   NewPathSize = 0;
1188   NewPath = NULL;
1189   OriginalPath = NULL;
1190   Status = EFI_SUCCESS;
1191 
1192   MapListNode = AllocateZeroPool(sizeof(SHELL_MAP_LIST));
1193   if (MapListNode == NULL) {
1194     Status = EFI_OUT_OF_RESOURCES;
1195   } else {
1196     MapListNode->Flags = Flags;
1197     MapListNode->MapName = AllocateCopyPool(StrSize(Name), Name);
1198     MapListNode->DevicePath = DuplicateDevicePath(DevicePath);
1199     if ((MapListNode->MapName == NULL) || (MapListNode->DevicePath == NULL)){
1200       Status = EFI_OUT_OF_RESOURCES;
1201     } else {
1202       InsertTailList(&gShellMapList.Link, &MapListNode->Link);
1203     }
1204   }
1205   if (EFI_ERROR(Status)) {
1206     if (MapListNode != NULL) {
1207       if (MapListNode->DevicePath != NULL) {
1208         FreePool(MapListNode->DevicePath);
1209       }
1210       if (MapListNode->MapName != NULL) {
1211         FreePool(MapListNode->MapName);
1212       }
1213       FreePool(MapListNode);
1214     }
1215   } else if (Path) {
1216     //
1217     // Since there was no error and Path was TRUE
1218     // Now add the correct path for that mapping
1219     //
1220     OriginalPath = gEfiShellProtocol->GetEnv(L"path");
1221     ASSERT((NewPath == NULL && NewPathSize == 0) || (NewPath != NULL));
1222     if (OriginalPath != NULL) {
1223       StrnCatGrow(&NewPath, &NewPathSize, OriginalPath, 0);
1224       StrnCatGrow(&NewPath, &NewPathSize, L";", 0);
1225     }
1226     StrnCatGrow(&NewPath, &NewPathSize, Name, 0);
1227     StrnCatGrow(&NewPath, &NewPathSize, L"\\efi\\tools\\;", 0);
1228     StrnCatGrow(&NewPath, &NewPathSize, Name, 0);
1229     StrnCatGrow(&NewPath, &NewPathSize, L"\\efi\\boot\\;", 0);
1230     StrnCatGrow(&NewPath, &NewPathSize, Name, 0);
1231     StrnCatGrow(&NewPath, &NewPathSize, L"\\", 0);
1232 
1233     Status = gEfiShellProtocol->SetEnv(L"path", NewPath, TRUE);
1234     ASSERT_EFI_ERROR(Status);
1235     FreePool(NewPath);
1236   }
1237   return (Status);
1238 }
1239 
1240 /**
1241   Creates the default map names for each device path in the system with
1242   a protocol depending on the Type.
1243 
1244   Creates the consistent map names for each device path in the system with
1245   a protocol depending on the Type.
1246 
1247   Note: This will reset all mappings in the system("map -r").
1248 
1249   Also sets up the default path environment variable if Type is FileSystem.
1250 
1251   @retval EFI_SUCCESS           All map names were created sucessfully.
1252   @retval EFI_NOT_FOUND         No protocols were found in the system.
1253   @return                       Error returned from gBS->LocateHandle().
1254 
1255   @sa LocateHandle
1256 **/
1257 EFI_STATUS
1258 EFIAPI
ShellCommandCreateInitialMappingsAndPaths(VOID)1259 ShellCommandCreateInitialMappingsAndPaths(
1260   VOID
1261   )
1262 {
1263   EFI_STATUS                Status;
1264   EFI_HANDLE                *HandleList;
1265   UINTN                     Count;
1266   EFI_DEVICE_PATH_PROTOCOL  **DevicePathList;
1267   CHAR16                    *NewDefaultName;
1268   CHAR16                    *NewConsistName;
1269   EFI_DEVICE_PATH_PROTOCOL  **ConsistMappingTable;
1270   SHELL_MAP_LIST            *MapListNode;
1271 
1272   HandleList  = NULL;
1273 
1274   //
1275   // Reset the static members back to zero
1276   //
1277   mFsMaxCount = 0;
1278   mBlkMaxCount = 0;
1279 
1280   gEfiShellProtocol->SetEnv(L"path", L"", TRUE);
1281 
1282   //
1283   // First empty out the existing list.
1284   //
1285   if (!IsListEmpty(&gShellMapList.Link)) {
1286     for ( MapListNode = (SHELL_MAP_LIST *)GetFirstNode(&gShellMapList.Link)
1287         ; !IsListEmpty(&gShellMapList.Link)
1288         ; MapListNode = (SHELL_MAP_LIST *)GetFirstNode(&gShellMapList.Link)
1289        ){
1290           RemoveEntryList(&MapListNode->Link);
1291           SHELL_FREE_NON_NULL(MapListNode->DevicePath);
1292           SHELL_FREE_NON_NULL(MapListNode->MapName);
1293           SHELL_FREE_NON_NULL(MapListNode->CurrentDirectoryPath);
1294           FreePool(MapListNode);
1295     } // for loop
1296   }
1297 
1298   //
1299   // Find each handle with Simple File System
1300   //
1301   HandleList = GetHandleListByProtocol(&gEfiSimpleFileSystemProtocolGuid);
1302   if (HandleList != NULL) {
1303     //
1304     // Do a count of the handles
1305     //
1306     for (Count = 0 ; HandleList[Count] != NULL ; Count++);
1307 
1308     //
1309     // Get all Device Paths
1310     //
1311     DevicePathList = AllocateZeroPool(sizeof(EFI_DEVICE_PATH_PROTOCOL*) * Count);
1312     if (DevicePathList == NULL) {
1313       SHELL_FREE_NON_NULL (HandleList);
1314       return EFI_OUT_OF_RESOURCES;
1315     }
1316 
1317     for (Count = 0 ; HandleList[Count] != NULL ; Count++) {
1318       DevicePathList[Count] = DevicePathFromHandle(HandleList[Count]);
1319     }
1320 
1321     //
1322     // Sort all DevicePaths
1323     //
1324     PerformQuickSort(DevicePathList, Count, sizeof(EFI_DEVICE_PATH_PROTOCOL*), DevicePathCompare);
1325 
1326     ShellCommandConsistMappingInitialize(&ConsistMappingTable);
1327     //
1328     // Assign new Mappings to all...
1329     //
1330     for (Count = 0 ; HandleList[Count] != NULL ; Count++) {
1331       //
1332       // Get default name first
1333       //
1334       NewDefaultName = ShellCommandCreateNewMappingName(MappingTypeFileSystem);
1335       ASSERT(NewDefaultName != NULL);
1336       Status = ShellCommandAddMapItemAndUpdatePath(NewDefaultName, DevicePathList[Count], 0, TRUE);
1337       ASSERT_EFI_ERROR(Status);
1338       FreePool(NewDefaultName);
1339 
1340       //
1341       // Now do consistent name
1342       //
1343       NewConsistName = ShellCommandConsistMappingGenMappingName(DevicePathList[Count], ConsistMappingTable);
1344       if (NewConsistName != NULL) {
1345         Status = ShellCommandAddMapItemAndUpdatePath(NewConsistName, DevicePathList[Count], 0, FALSE);
1346         ASSERT_EFI_ERROR(Status);
1347         FreePool(NewConsistName);
1348       }
1349     }
1350 
1351     ShellCommandConsistMappingUnInitialize(ConsistMappingTable);
1352 
1353     SHELL_FREE_NON_NULL(HandleList);
1354     SHELL_FREE_NON_NULL(DevicePathList);
1355 
1356     HandleList = NULL;
1357   } else {
1358     Count = (UINTN)-1;
1359   }
1360 
1361   //
1362   // Find each handle with Block Io
1363   //
1364   HandleList = GetHandleListByProtocol(&gEfiBlockIoProtocolGuid);
1365   if (HandleList != NULL) {
1366     for (Count = 0 ; HandleList[Count] != NULL ; Count++);
1367 
1368     //
1369     // Get all Device Paths
1370     //
1371     DevicePathList = AllocateZeroPool(sizeof(EFI_DEVICE_PATH_PROTOCOL*) * Count);
1372     if (DevicePathList == NULL) {
1373       SHELL_FREE_NON_NULL (HandleList);
1374       return EFI_OUT_OF_RESOURCES;
1375     }
1376 
1377     for (Count = 0 ; HandleList[Count] != NULL ; Count++) {
1378       DevicePathList[Count] = DevicePathFromHandle(HandleList[Count]);
1379     }
1380 
1381     //
1382     // Sort all DevicePaths
1383     //
1384     PerformQuickSort(DevicePathList, Count, sizeof(EFI_DEVICE_PATH_PROTOCOL*), DevicePathCompare);
1385 
1386     //
1387     // Assign new Mappings to all...
1388     //
1389     for (Count = 0 ; HandleList[Count] != NULL ; Count++) {
1390       //
1391       // Get default name first
1392       //
1393       NewDefaultName = ShellCommandCreateNewMappingName(MappingTypeBlockIo);
1394       ASSERT(NewDefaultName != NULL);
1395       Status = ShellCommandAddMapItemAndUpdatePath(NewDefaultName, DevicePathList[Count], 0, FALSE);
1396       ASSERT_EFI_ERROR(Status);
1397       FreePool(NewDefaultName);
1398     }
1399 
1400     SHELL_FREE_NON_NULL(HandleList);
1401     SHELL_FREE_NON_NULL(DevicePathList);
1402   } else if (Count == (UINTN)-1) {
1403     return (EFI_NOT_FOUND);
1404   }
1405 
1406   return (EFI_SUCCESS);
1407 }
1408 
1409 /**
1410   Add mappings for any devices without one.  Do not change any existing maps.
1411 
1412   @retval EFI_SUCCESS   The operation was successful.
1413 **/
1414 EFI_STATUS
1415 EFIAPI
ShellCommandUpdateMapping(VOID)1416 ShellCommandUpdateMapping (
1417   VOID
1418   )
1419 {
1420   EFI_STATUS                Status;
1421   EFI_HANDLE                *HandleList;
1422   UINTN                     Count;
1423   EFI_DEVICE_PATH_PROTOCOL  **DevicePathList;
1424   CHAR16                    *NewDefaultName;
1425   CHAR16                    *NewConsistName;
1426   EFI_DEVICE_PATH_PROTOCOL  **ConsistMappingTable;
1427 
1428   HandleList  = NULL;
1429   Status      = EFI_SUCCESS;
1430 
1431   //
1432   // remove mappings that represent removed devices.
1433   //
1434 
1435   //
1436   // Find each handle with Simple File System
1437   //
1438   HandleList = GetHandleListByProtocol(&gEfiSimpleFileSystemProtocolGuid);
1439   if (HandleList != NULL) {
1440     //
1441     // Do a count of the handles
1442     //
1443     for (Count = 0 ; HandleList[Count] != NULL ; Count++);
1444 
1445     //
1446     // Get all Device Paths
1447     //
1448     DevicePathList = AllocateZeroPool(sizeof(EFI_DEVICE_PATH_PROTOCOL*) * Count);
1449     if (DevicePathList == NULL) {
1450       return (EFI_OUT_OF_RESOURCES);
1451     }
1452 
1453     for (Count = 0 ; HandleList[Count] != NULL ; Count++) {
1454       DevicePathList[Count] = DevicePathFromHandle(HandleList[Count]);
1455     }
1456 
1457     //
1458     // Sort all DevicePaths
1459     //
1460     PerformQuickSort(DevicePathList, Count, sizeof(EFI_DEVICE_PATH_PROTOCOL*), DevicePathCompare);
1461 
1462     ShellCommandConsistMappingInitialize(&ConsistMappingTable);
1463 
1464     //
1465     // Assign new Mappings to remainders
1466     //
1467     for (Count = 0 ; !EFI_ERROR(Status) && HandleList[Count] != NULL && !EFI_ERROR(Status); Count++) {
1468       //
1469       // Skip ones that already have
1470       //
1471       if (gEfiShellProtocol->GetMapFromDevicePath(&DevicePathList[Count]) != NULL) {
1472         continue;
1473       }
1474       //
1475       // Get default name
1476       //
1477       NewDefaultName = ShellCommandCreateNewMappingName(MappingTypeFileSystem);
1478       if (NewDefaultName == NULL) {
1479         Status = EFI_OUT_OF_RESOURCES;
1480         break;
1481       }
1482 
1483       //
1484       // Call shell protocol SetMap function now...
1485       //
1486       Status = gEfiShellProtocol->SetMap(DevicePathList[Count], NewDefaultName);
1487 
1488       if (!EFI_ERROR(Status)) {
1489         //
1490         // Now do consistent name
1491         //
1492         NewConsistName = ShellCommandConsistMappingGenMappingName(DevicePathList[Count], ConsistMappingTable);
1493         if (NewConsistName != NULL) {
1494           Status = gEfiShellProtocol->SetMap(DevicePathList[Count], NewConsistName);
1495           FreePool(NewConsistName);
1496         }
1497       }
1498 
1499       FreePool(NewDefaultName);
1500     }
1501     ShellCommandConsistMappingUnInitialize(ConsistMappingTable);
1502     SHELL_FREE_NON_NULL(HandleList);
1503     SHELL_FREE_NON_NULL(DevicePathList);
1504 
1505     HandleList = NULL;
1506   } else {
1507     Count = (UINTN)-1;
1508   }
1509   //
1510   // Do it all over again for gEfiBlockIoProtocolGuid
1511   //
1512 
1513   return (Status);
1514 }
1515 
1516 /**
1517   Converts a SHELL_FILE_HANDLE to an EFI_FILE_PROTOCOL*.
1518 
1519   @param[in] Handle     The SHELL_FILE_HANDLE to convert.
1520 
1521   @return a EFI_FILE_PROTOCOL* representing the same file.
1522 **/
1523 EFI_FILE_PROTOCOL*
1524 EFIAPI
ConvertShellHandleToEfiFileProtocol(IN CONST SHELL_FILE_HANDLE Handle)1525 ConvertShellHandleToEfiFileProtocol(
1526   IN CONST SHELL_FILE_HANDLE Handle
1527   )
1528 {
1529   return ((EFI_FILE_PROTOCOL*)(Handle));
1530 }
1531 
1532 /**
1533   Converts a EFI_FILE_PROTOCOL* to an SHELL_FILE_HANDLE.
1534 
1535   @param[in] Handle     The pointer to EFI_FILE_PROTOCOL to convert.
1536   @param[in] Path       The path to the file for verification.
1537 
1538   @return               A SHELL_FILE_HANDLE representing the same file.
1539   @retval NULL          There was not enough memory.
1540 **/
1541 SHELL_FILE_HANDLE
1542 EFIAPI
ConvertEfiFileProtocolToShellHandle(IN CONST EFI_FILE_PROTOCOL * Handle,IN CONST CHAR16 * Path)1543 ConvertEfiFileProtocolToShellHandle(
1544   IN CONST EFI_FILE_PROTOCOL *Handle,
1545   IN CONST CHAR16            *Path
1546   )
1547 {
1548   SHELL_COMMAND_FILE_HANDLE *Buffer;
1549   BUFFER_LIST               *NewNode;
1550 
1551   if (Path != NULL) {
1552     Buffer              = AllocateZeroPool(sizeof(SHELL_COMMAND_FILE_HANDLE));
1553     if (Buffer == NULL) {
1554       return (NULL);
1555     }
1556     NewNode             = AllocateZeroPool(sizeof(BUFFER_LIST));
1557     if (NewNode == NULL) {
1558       SHELL_FREE_NON_NULL(Buffer);
1559       return (NULL);
1560     }
1561     Buffer->FileHandle  = (EFI_FILE_PROTOCOL*)Handle;
1562     Buffer->Path        = StrnCatGrow(&Buffer->Path, NULL, Path, 0);
1563     if (Buffer->Path == NULL) {
1564       SHELL_FREE_NON_NULL(NewNode);
1565       SHELL_FREE_NON_NULL(Buffer);
1566       return (NULL);
1567     }
1568     NewNode->Buffer     = Buffer;
1569 
1570     InsertHeadList(&mFileHandleList.Link, &NewNode->Link);
1571   }
1572   return ((SHELL_FILE_HANDLE)(Handle));
1573 }
1574 
1575 /**
1576   Find the path that was logged with the specified SHELL_FILE_HANDLE.
1577 
1578   @param[in] Handle     The SHELL_FILE_HANDLE to query on.
1579 
1580   @return A pointer to the path for the file.
1581 **/
1582 CONST CHAR16*
1583 EFIAPI
ShellFileHandleGetPath(IN CONST SHELL_FILE_HANDLE Handle)1584 ShellFileHandleGetPath(
1585   IN CONST SHELL_FILE_HANDLE Handle
1586   )
1587 {
1588   BUFFER_LIST               *Node;
1589 
1590   for (Node = (BUFFER_LIST*)GetFirstNode(&mFileHandleList.Link)
1591     ;  !IsNull(&mFileHandleList.Link, &Node->Link)
1592     ;  Node = (BUFFER_LIST*)GetNextNode(&mFileHandleList.Link, &Node->Link)
1593    ){
1594     if ((Node->Buffer) && (((SHELL_COMMAND_FILE_HANDLE *)Node->Buffer)->FileHandle == Handle)){
1595       return (((SHELL_COMMAND_FILE_HANDLE *)Node->Buffer)->Path);
1596     }
1597   }
1598   return (NULL);
1599 }
1600 
1601 /**
1602   Remove a SHELL_FILE_HANDLE from the list of SHELL_FILE_HANDLES.
1603 
1604   @param[in] Handle     The SHELL_FILE_HANDLE to remove.
1605 
1606   @retval TRUE          The item was removed.
1607   @retval FALSE         The item was not found.
1608 **/
1609 BOOLEAN
1610 EFIAPI
ShellFileHandleRemove(IN CONST SHELL_FILE_HANDLE Handle)1611 ShellFileHandleRemove(
1612   IN CONST SHELL_FILE_HANDLE Handle
1613   )
1614 {
1615   BUFFER_LIST               *Node;
1616 
1617   for (Node = (BUFFER_LIST*)GetFirstNode(&mFileHandleList.Link)
1618     ;  !IsNull(&mFileHandleList.Link, &Node->Link)
1619     ;  Node = (BUFFER_LIST*)GetNextNode(&mFileHandleList.Link, &Node->Link)
1620    ){
1621     if ((Node->Buffer) && (((SHELL_COMMAND_FILE_HANDLE *)Node->Buffer)->FileHandle == Handle)){
1622       RemoveEntryList(&Node->Link);
1623       SHELL_FREE_NON_NULL(((SHELL_COMMAND_FILE_HANDLE *)Node->Buffer)->Path);
1624       SHELL_FREE_NON_NULL(Node->Buffer);
1625       SHELL_FREE_NON_NULL(Node);
1626       return (TRUE);
1627     }
1628   }
1629   return (FALSE);
1630 }
1631 
1632 /**
1633   Function to determine if a SHELL_FILE_HANDLE is at the end of the file.
1634 
1635   This will NOT work on directories.
1636 
1637   If Handle is NULL, then ASSERT.
1638 
1639   @param[in] Handle     the file handle
1640 
1641   @retval TRUE          the position is at the end of the file
1642   @retval FALSE         the position is not at the end of the file
1643 **/
1644 BOOLEAN
1645 EFIAPI
ShellFileHandleEof(IN SHELL_FILE_HANDLE Handle)1646 ShellFileHandleEof(
1647   IN SHELL_FILE_HANDLE Handle
1648   )
1649 {
1650   EFI_FILE_INFO *Info;
1651   UINT64        Pos;
1652   BOOLEAN       RetVal;
1653 
1654   //
1655   // ASSERT if Handle is NULL
1656   //
1657   ASSERT(Handle != NULL);
1658 
1659   gEfiShellProtocol->GetFilePosition(Handle, &Pos);
1660   Info = gEfiShellProtocol->GetFileInfo (Handle);
1661   gEfiShellProtocol->SetFilePosition(Handle, Pos);
1662 
1663   if (Info == NULL) {
1664     return (FALSE);
1665   }
1666 
1667   if (Pos == Info->FileSize) {
1668     RetVal = TRUE;
1669   } else {
1670     RetVal = FALSE;
1671   }
1672 
1673   FreePool (Info);
1674 
1675   return (RetVal);
1676 }
1677 
1678 /**
1679   Frees any BUFFER_LIST defined type.
1680 
1681   @param[in] List     The BUFFER_LIST object to free.
1682 **/
1683 VOID
1684 EFIAPI
FreeBufferList(IN BUFFER_LIST * List)1685 FreeBufferList (
1686   IN BUFFER_LIST *List
1687   )
1688 {
1689   BUFFER_LIST               *BufferListEntry;
1690 
1691   if (List == NULL){
1692     return;
1693   }
1694   //
1695   // enumerate through the buffer list and free all memory
1696   //
1697   for ( BufferListEntry = ( BUFFER_LIST *)GetFirstNode(&List->Link)
1698       ; !IsListEmpty (&List->Link)
1699       ; BufferListEntry = (BUFFER_LIST *)GetFirstNode(&List->Link)
1700      ){
1701     RemoveEntryList(&BufferListEntry->Link);
1702     if (BufferListEntry->Buffer != NULL) {
1703       FreePool(BufferListEntry->Buffer);
1704     }
1705     FreePool(BufferListEntry);
1706   }
1707 }
1708 
1709 /**
1710   Dump some hexadecimal data to the screen.
1711 
1712   @param[in] Indent     How many spaces to indent the output.
1713   @param[in] Offset     The offset of the printing.
1714   @param[in] DataSize   The size in bytes of UserData.
1715   @param[in] UserData   The data to print out.
1716 **/
1717 VOID
1718 EFIAPI
DumpHex(IN UINTN Indent,IN UINTN Offset,IN UINTN DataSize,IN VOID * UserData)1719 DumpHex (
1720   IN UINTN        Indent,
1721   IN UINTN        Offset,
1722   IN UINTN        DataSize,
1723   IN VOID         *UserData
1724   )
1725 {
1726   UINT8 *Data;
1727 
1728   CHAR8 Val[50];
1729 
1730   CHAR8 Str[20];
1731 
1732   UINT8 TempByte;
1733   UINTN Size;
1734   UINTN Index;
1735 
1736   Data = UserData;
1737   while (DataSize != 0) {
1738     Size = 16;
1739     if (Size > DataSize) {
1740       Size = DataSize;
1741     }
1742 
1743     for (Index = 0; Index < Size; Index += 1) {
1744       TempByte            = Data[Index];
1745       Val[Index * 3 + 0]  = Hex[TempByte >> 4];
1746       Val[Index * 3 + 1]  = Hex[TempByte & 0xF];
1747       Val[Index * 3 + 2]  = (CHAR8) ((Index == 7) ? '-' : ' ');
1748       Str[Index]          = (CHAR8) ((TempByte < ' ' || TempByte > 'z') ? '.' : TempByte);
1749     }
1750 
1751     Val[Index * 3]  = 0;
1752     Str[Index]      = 0;
1753     ShellPrintEx(-1, -1, L"%*a%08X: %-48a *%a*\r\n", Indent, "", Offset, Val, Str);
1754 
1755     Data += Size;
1756     Offset += Size;
1757     DataSize -= Size;
1758   }
1759 }
1760 
1761 /**
1762   Dump HEX data into buffer.
1763 
1764   @param[in] Buffer     HEX data to be dumped in Buffer.
1765   @param[in] Indent     How many spaces to indent the output.
1766   @param[in] Offset     The offset of the printing.
1767   @param[in] DataSize   The size in bytes of UserData.
1768   @param[in] UserData   The data to print out.
1769 **/
1770 CHAR16*
1771 EFIAPI
CatSDumpHex(IN CHAR16 * Buffer,IN UINTN Indent,IN UINTN Offset,IN UINTN DataSize,IN VOID * UserData)1772 CatSDumpHex (
1773   IN CHAR16  *Buffer,
1774   IN UINTN   Indent,
1775   IN UINTN   Offset,
1776   IN UINTN   DataSize,
1777   IN VOID    *UserData
1778   )
1779 {
1780   UINT8   *Data;
1781   UINT8   TempByte;
1782   UINTN   Size;
1783   UINTN   Index;
1784   CHAR8   Val[50];
1785   CHAR8   Str[20];
1786   CHAR16  *RetVal;
1787   CHAR16  *TempRetVal;
1788 
1789   Data = UserData;
1790   RetVal = Buffer;
1791   while (DataSize != 0) {
1792     Size = 16;
1793     if (Size > DataSize) {
1794       Size = DataSize;
1795     }
1796 
1797     for (Index = 0; Index < Size; Index += 1) {
1798       TempByte            = Data[Index];
1799       Val[Index * 3 + 0]  = Hex[TempByte >> 4];
1800       Val[Index * 3 + 1]  = Hex[TempByte & 0xF];
1801       Val[Index * 3 + 2]  = (CHAR8) ((Index == 7) ? '-' : ' ');
1802       Str[Index]          = (CHAR8) ((TempByte < ' ' || TempByte > 'z') ? '.' : TempByte);
1803     }
1804 
1805     Val[Index * 3]  = 0;
1806     Str[Index]      = 0;
1807     TempRetVal = CatSPrint (RetVal, L"%*a%08X: %-48a *%a*\r\n", Indent, "", Offset, Val, Str);
1808     SHELL_FREE_NON_NULL (RetVal);
1809     RetVal = TempRetVal;
1810 
1811     Data += Size;
1812     Offset += Size;
1813     DataSize -= Size;
1814   }
1815 
1816   return RetVal;
1817 }
1818