]> git.proxmox.com Git - mirror_edk2.git/blob - ShellPkg/Application/Shell/Shell.c
ShellPkg: Add code to handle the split ('|') in a double-quoted string.
[mirror_edk2.git] / ShellPkg / Application / Shell / Shell.c
1 /** @file
2 This is THE shell (application)
3
4 Copyright (c) 2009 - 2014, Intel Corporation. All rights reserved.<BR>
5 (C) Copyright 2013-2014, Hewlett-Packard Development Company, L.P.
6 This program and the accompanying materials
7 are licensed and made available under the terms and conditions of the BSD License
8 which accompanies this distribution. The full text of the license may be found at
9 http://opensource.org/licenses/bsd-license.php
10
11 THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
12 WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
13
14 **/
15
16 #include "Shell.h"
17
18 //
19 // Initialize the global structure
20 //
21 SHELL_INFO ShellInfoObject = {
22 NULL,
23 NULL,
24 FALSE,
25 FALSE,
26 {
27 {{
28 0,
29 0,
30 0,
31 0,
32 0,
33 0,
34 0,
35 0,
36 0
37 }},
38 0,
39 NULL,
40 NULL
41 },
42 {{NULL, NULL}, NULL},
43 {
44 {{NULL, NULL}, NULL},
45 0,
46 0,
47 TRUE
48 },
49 NULL,
50 0,
51 NULL,
52 NULL,
53 NULL,
54 NULL,
55 NULL,
56 {{NULL, NULL}, NULL, NULL},
57 {{NULL, NULL}, NULL, NULL},
58 NULL,
59 NULL,
60 NULL,
61 NULL,
62 NULL,
63 NULL,
64 NULL,
65 NULL,
66 FALSE
67 };
68
69 STATIC CONST CHAR16 mScriptExtension[] = L".NSH";
70 STATIC CONST CHAR16 mExecutableExtensions[] = L".NSH;.EFI";
71 STATIC CONST CHAR16 mStartupScript[] = L"startup.nsh";
72
73 /**
74 Cleans off leading and trailing spaces and tabs.
75
76 @param[in] String pointer to the string to trim them off.
77 **/
78 EFI_STATUS
79 EFIAPI
80 TrimSpaces(
81 IN CHAR16 **String
82 )
83 {
84 ASSERT(String != NULL);
85 ASSERT(*String!= NULL);
86 //
87 // Remove any spaces and tabs at the beginning of the (*String).
88 //
89 while (((*String)[0] == L' ') || ((*String)[0] == L'\t')) {
90 CopyMem((*String), (*String)+1, StrSize((*String)) - sizeof((*String)[0]));
91 }
92
93 //
94 // Remove any spaces and tabs at the end of the (*String).
95 //
96 while ((StrLen (*String) > 0) && (((*String)[StrLen((*String))-1] == L' ') || ((*String)[StrLen((*String))-1] == L'\t'))) {
97 (*String)[StrLen((*String))-1] = CHAR_NULL;
98 }
99
100 return (EFI_SUCCESS);
101 }
102
103 /**
104 Parse for the next instance of one string within another string. Can optionally make sure that
105 the string was not escaped (^ character) per the shell specification.
106
107 @param[in] SourceString The string to search within
108 @param[in] FindString The string to look for
109 @param[in] CheckForEscapeCharacter TRUE to skip escaped instances of FinfString, otherwise will return even escaped instances
110 **/
111 CHAR16*
112 EFIAPI
113 FindNextInstance(
114 IN CONST CHAR16 *SourceString,
115 IN CONST CHAR16 *FindString,
116 IN CONST BOOLEAN CheckForEscapeCharacter
117 )
118 {
119 CHAR16 *Temp;
120 if (SourceString == NULL) {
121 return (NULL);
122 }
123 Temp = StrStr(SourceString, FindString);
124
125 //
126 // If nothing found, or we dont care about escape characters
127 //
128 if (Temp == NULL || !CheckForEscapeCharacter) {
129 return (Temp);
130 }
131
132 //
133 // If we found an escaped character, try again on the remainder of the string
134 //
135 if ((Temp > (SourceString)) && *(Temp-1) == L'^') {
136 return FindNextInstance(Temp+1, FindString, CheckForEscapeCharacter);
137 }
138
139 //
140 // we found the right character
141 //
142 return (Temp);
143 }
144
145 /**
146 Find a command line contains a split operation
147
148 @param[in] CmdLine The command line to parse.
149
150 @retval A pointer to the | character in CmdLine or NULL if not present.
151 **/
152 CONST CHAR16*
153 EFIAPI
154 FindSplit(
155 IN CONST CHAR16 *CmdLine
156 )
157 {
158 CONST CHAR16 *TempSpot;
159 TempSpot = NULL;
160 if (StrStr(CmdLine, L"|") != NULL) {
161 for (TempSpot = CmdLine ; TempSpot != NULL && *TempSpot != CHAR_NULL ; TempSpot++) {
162 if (*TempSpot == L'^' && *(TempSpot+1) == L'|') {
163 TempSpot++;
164 } else if (*TempSpot == L'|') {
165 break;
166 }
167 }
168 }
169 return (TempSpot);
170 }
171
172 /**
173 Determine if a command line contains a split operation
174
175 @param[in] CmdLine The command line to parse.
176
177 @retval TRUE CmdLine has a valid split.
178 @retval FALSE CmdLine does not have a valid split.
179 **/
180 BOOLEAN
181 EFIAPI
182 ContainsSplit(
183 IN CONST CHAR16 *CmdLine
184 )
185 {
186 CONST CHAR16 *TempSpot;
187 CONST CHAR16 *FirstQuote;
188 CONST CHAR16 *SecondQuote;
189
190 FirstQuote = FindNextInstance (CmdLine, L"\"", TRUE);
191 SecondQuote = NULL;
192 TempSpot = FindSplit(CmdLine);
193
194 if (FirstQuote == NULL ||
195 TempSpot == NULL ||
196 TempSpot == CHAR_NULL ||
197 FirstQuote > TempSpot
198 ) {
199 return (BOOLEAN) ((TempSpot != NULL) && (*TempSpot != CHAR_NULL));
200 }
201
202 while ((TempSpot != NULL) && (*TempSpot != CHAR_NULL)) {
203 if (FirstQuote == NULL || FirstQuote > TempSpot) {
204 break;
205 }
206 SecondQuote = FindNextInstance (FirstQuote + 1, L"\"", TRUE);
207 if (SecondQuote == NULL) {
208 break;
209 }
210 if (SecondQuote < TempSpot) {
211 FirstQuote = FindNextInstance (SecondQuote + 1, L"\"", TRUE);
212 continue;
213 } else {
214 FirstQuote = FindNextInstance (SecondQuote + 1, L"\"", TRUE);
215 TempSpot = FindSplit(TempSpot + 1);
216 continue;
217 }
218 }
219
220 return (BOOLEAN) ((TempSpot != NULL) && (*TempSpot != CHAR_NULL));
221 }
222
223 /**
224 Function to start monitoring for CTRL-S using SimpleTextInputEx. This
225 feature's enabled state was not known when the shell initially launched.
226
227 @retval EFI_SUCCESS The feature is enabled.
228 @retval EFI_OUT_OF_RESOURCES There is not enough mnemory available.
229 **/
230 EFI_STATUS
231 EFIAPI
232 InternalEfiShellStartCtrlSMonitor(
233 VOID
234 )
235 {
236 EFI_SIMPLE_TEXT_INPUT_EX_PROTOCOL *SimpleEx;
237 EFI_KEY_DATA KeyData;
238 EFI_STATUS Status;
239
240 Status = gBS->OpenProtocol(
241 gST->ConsoleInHandle,
242 &gEfiSimpleTextInputExProtocolGuid,
243 (VOID**)&SimpleEx,
244 gImageHandle,
245 NULL,
246 EFI_OPEN_PROTOCOL_GET_PROTOCOL);
247 if (EFI_ERROR(Status)) {
248 ShellPrintHiiEx(
249 -1,
250 -1,
251 NULL,
252 STRING_TOKEN (STR_SHELL_NO_IN_EX),
253 ShellInfoObject.HiiHandle);
254 return (EFI_SUCCESS);
255 }
256
257 KeyData.KeyState.KeyToggleState = 0;
258 KeyData.Key.ScanCode = 0;
259 KeyData.KeyState.KeyShiftState = EFI_SHIFT_STATE_VALID|EFI_LEFT_CONTROL_PRESSED;
260 KeyData.Key.UnicodeChar = L's';
261
262 Status = SimpleEx->RegisterKeyNotify(
263 SimpleEx,
264 &KeyData,
265 NotificationFunction,
266 &ShellInfoObject.CtrlSNotifyHandle1);
267
268 KeyData.KeyState.KeyShiftState = EFI_SHIFT_STATE_VALID|EFI_RIGHT_CONTROL_PRESSED;
269 if (!EFI_ERROR(Status)) {
270 Status = SimpleEx->RegisterKeyNotify(
271 SimpleEx,
272 &KeyData,
273 NotificationFunction,
274 &ShellInfoObject.CtrlSNotifyHandle2);
275 }
276 KeyData.KeyState.KeyShiftState = EFI_SHIFT_STATE_VALID|EFI_LEFT_CONTROL_PRESSED;
277 KeyData.Key.UnicodeChar = 19;
278
279 if (!EFI_ERROR(Status)) {
280 Status = SimpleEx->RegisterKeyNotify(
281 SimpleEx,
282 &KeyData,
283 NotificationFunction,
284 &ShellInfoObject.CtrlSNotifyHandle3);
285 }
286 KeyData.KeyState.KeyShiftState = EFI_SHIFT_STATE_VALID|EFI_RIGHT_CONTROL_PRESSED;
287 if (!EFI_ERROR(Status)) {
288 Status = SimpleEx->RegisterKeyNotify(
289 SimpleEx,
290 &KeyData,
291 NotificationFunction,
292 &ShellInfoObject.CtrlSNotifyHandle4);
293 }
294 return (Status);
295 }
296
297
298
299 /**
300 The entry point for the application.
301
302 @param[in] ImageHandle The firmware allocated handle for the EFI image.
303 @param[in] SystemTable A pointer to the EFI System Table.
304
305 @retval EFI_SUCCESS The entry point is executed successfully.
306 @retval other Some error occurs when executing this entry point.
307
308 **/
309 EFI_STATUS
310 EFIAPI
311 UefiMain (
312 IN EFI_HANDLE ImageHandle,
313 IN EFI_SYSTEM_TABLE *SystemTable
314 )
315 {
316 EFI_STATUS Status;
317 CHAR16 *TempString;
318 UINTN Size;
319 EFI_HANDLE ConInHandle;
320 EFI_SIMPLE_TEXT_INPUT_PROTOCOL *OldConIn;
321
322 if (PcdGet8(PcdShellSupportLevel) > 3) {
323 return (EFI_UNSUPPORTED);
324 }
325
326 //
327 // Clear the screen
328 //
329 Status = gST->ConOut->ClearScreen(gST->ConOut);
330 if (EFI_ERROR(Status)) {
331 return (Status);
332 }
333
334 //
335 // Populate the global structure from PCDs
336 //
337 ShellInfoObject.ImageDevPath = NULL;
338 ShellInfoObject.FileDevPath = NULL;
339 ShellInfoObject.PageBreakEnabled = PcdGetBool(PcdShellPageBreakDefault);
340 ShellInfoObject.ViewingSettings.InsertMode = PcdGetBool(PcdShellInsertModeDefault);
341 ShellInfoObject.LogScreenCount = PcdGet8 (PcdShellScreenLogCount );
342
343 //
344 // verify we dont allow for spec violation
345 //
346 ASSERT(ShellInfoObject.LogScreenCount >= 3);
347
348 //
349 // Initialize the LIST ENTRY objects...
350 //
351 InitializeListHead(&ShellInfoObject.BufferToFreeList.Link);
352 InitializeListHead(&ShellInfoObject.ViewingSettings.CommandHistory.Link);
353 InitializeListHead(&ShellInfoObject.SplitList.Link);
354
355 //
356 // Check PCDs for optional features that are not implemented yet.
357 //
358 if ( PcdGetBool(PcdShellSupportOldProtocols)
359 || !FeaturePcdGet(PcdShellRequireHiiPlatform)
360 || FeaturePcdGet(PcdShellSupportFrameworkHii)
361 ) {
362 return (EFI_UNSUPPORTED);
363 }
364
365 //
366 // turn off the watchdog timer
367 //
368 gBS->SetWatchdogTimer (0, 0, 0, NULL);
369
370 //
371 // install our console logger. This will keep a log of the output for back-browsing
372 //
373 Status = ConsoleLoggerInstall(ShellInfoObject.LogScreenCount, &ShellInfoObject.ConsoleInfo);
374 if (!EFI_ERROR(Status)) {
375 //
376 // Enable the cursor to be visible
377 //
378 gST->ConOut->EnableCursor (gST->ConOut, TRUE);
379
380 //
381 // If supporting EFI 1.1 we need to install HII protocol
382 // only do this if PcdShellRequireHiiPlatform == FALSE
383 //
384 // remove EFI_UNSUPPORTED check above when complete.
385 ///@todo add support for Framework HII
386
387 //
388 // install our (solitary) HII package
389 //
390 ShellInfoObject.HiiHandle = HiiAddPackages (&gEfiCallerIdGuid, gImageHandle, ShellStrings, NULL);
391 if (ShellInfoObject.HiiHandle == NULL) {
392 if (PcdGetBool(PcdShellSupportFrameworkHii)) {
393 ///@todo Add our package into Framework HII
394 }
395 if (ShellInfoObject.HiiHandle == NULL) {
396 Status = EFI_NOT_STARTED;
397 goto FreeResources;
398 }
399 }
400
401 //
402 // create and install the EfiShellParametersProtocol
403 //
404 Status = CreatePopulateInstallShellParametersProtocol(&ShellInfoObject.NewShellParametersProtocol, &ShellInfoObject.RootShellInstance);
405 ASSERT_EFI_ERROR(Status);
406 ASSERT(ShellInfoObject.NewShellParametersProtocol != NULL);
407
408 //
409 // create and install the EfiShellProtocol
410 //
411 Status = CreatePopulateInstallShellProtocol(&ShellInfoObject.NewEfiShellProtocol);
412 ASSERT_EFI_ERROR(Status);
413 ASSERT(ShellInfoObject.NewEfiShellProtocol != NULL);
414
415 //
416 // Now initialize the shell library (it requires Shell Parameters protocol)
417 //
418 Status = ShellInitialize();
419 ASSERT_EFI_ERROR(Status);
420
421 Status = CommandInit();
422 ASSERT_EFI_ERROR(Status);
423
424 //
425 // Check the command line
426 //
427 Status = ProcessCommandLine ();
428 if (EFI_ERROR (Status)) {
429 goto FreeResources;
430 }
431
432 //
433 // If shell support level is >= 1 create the mappings and paths
434 //
435 if (PcdGet8(PcdShellSupportLevel) >= 1) {
436 Status = ShellCommandCreateInitialMappingsAndPaths();
437 }
438
439 //
440 // save the device path for the loaded image and the device path for the filepath (under loaded image)
441 // These are where to look for the startup.nsh file
442 //
443 Status = GetDevicePathsForImageAndFile(&ShellInfoObject.ImageDevPath, &ShellInfoObject.FileDevPath);
444 ASSERT_EFI_ERROR(Status);
445
446 //
447 // Display the version
448 //
449 if (!ShellInfoObject.ShellInitSettings.BitUnion.Bits.NoVersion) {
450 ShellPrintHiiEx (
451 0,
452 gST->ConOut->Mode->CursorRow,
453 NULL,
454 STRING_TOKEN (STR_VER_OUTPUT_MAIN_SHELL),
455 ShellInfoObject.HiiHandle,
456 SupportLevel[PcdGet8(PcdShellSupportLevel)],
457 gEfiShellProtocol->MajorVersion,
458 gEfiShellProtocol->MinorVersion
459 );
460
461 ShellPrintHiiEx (
462 -1,
463 -1,
464 NULL,
465 STRING_TOKEN (STR_VER_OUTPUT_MAIN_SUPPLIER),
466 ShellInfoObject.HiiHandle,
467 (CHAR16 *) PcdGetPtr (PcdShellSupplier)
468 );
469
470 ShellPrintHiiEx (
471 -1,
472 -1,
473 NULL,
474 STRING_TOKEN (STR_VER_OUTPUT_MAIN_UEFI),
475 ShellInfoObject.HiiHandle,
476 (gST->Hdr.Revision&0xffff0000)>>16,
477 (gST->Hdr.Revision&0x0000ffff),
478 gST->FirmwareVendor,
479 gST->FirmwareRevision
480 );
481 }
482
483 //
484 // Display the mapping
485 //
486 if (PcdGet8(PcdShellSupportLevel) >= 2 && !ShellInfoObject.ShellInitSettings.BitUnion.Bits.NoMap) {
487 Status = RunCommand(L"map");
488 ASSERT_EFI_ERROR(Status);
489 }
490
491 //
492 // init all the built in alias'
493 //
494 Status = SetBuiltInAlias();
495 ASSERT_EFI_ERROR(Status);
496
497 //
498 // Initialize environment variables
499 //
500 if (ShellCommandGetProfileList() != NULL) {
501 Status = InternalEfiShellSetEnv(L"profiles", ShellCommandGetProfileList(), TRUE);
502 ASSERT_EFI_ERROR(Status);
503 }
504
505 Size = 100;
506 TempString = AllocateZeroPool(Size);
507
508 UnicodeSPrint(TempString, Size, L"%d", PcdGet8(PcdShellSupportLevel));
509 Status = InternalEfiShellSetEnv(L"uefishellsupport", TempString, TRUE);
510 ASSERT_EFI_ERROR(Status);
511
512 UnicodeSPrint(TempString, Size, L"%d.%d", ShellInfoObject.NewEfiShellProtocol->MajorVersion, ShellInfoObject.NewEfiShellProtocol->MinorVersion);
513 Status = InternalEfiShellSetEnv(L"uefishellversion", TempString, TRUE);
514 ASSERT_EFI_ERROR(Status);
515
516 UnicodeSPrint(TempString, Size, L"%d.%d", (gST->Hdr.Revision & 0xFFFF0000) >> 16, gST->Hdr.Revision & 0x0000FFFF);
517 Status = InternalEfiShellSetEnv(L"uefiversion", TempString, TRUE);
518 ASSERT_EFI_ERROR(Status);
519
520 FreePool(TempString);
521
522 if (!EFI_ERROR(Status)) {
523 if (!ShellInfoObject.ShellInitSettings.BitUnion.Bits.NoInterrupt) {
524 //
525 // Set up the event for CTRL-C monitoring...
526 //
527 Status = InernalEfiShellStartMonitor();
528 }
529
530 if (!EFI_ERROR(Status) && !ShellInfoObject.ShellInitSettings.BitUnion.Bits.NoConsoleIn) {
531 //
532 // Set up the event for CTRL-S monitoring...
533 //
534 Status = InternalEfiShellStartCtrlSMonitor();
535 }
536
537 if (!EFI_ERROR(Status) && ShellInfoObject.ShellInitSettings.BitUnion.Bits.NoConsoleIn) {
538 //
539 // close off the gST->ConIn
540 //
541 OldConIn = gST->ConIn;
542 ConInHandle = gST->ConsoleInHandle;
543 gST->ConIn = CreateSimpleTextInOnFile((SHELL_FILE_HANDLE)&FileInterfaceNulFile, &gST->ConsoleInHandle);
544 } else {
545 OldConIn = NULL;
546 ConInHandle = NULL;
547 }
548
549 if (!EFI_ERROR(Status) && PcdGet8(PcdShellSupportLevel) >= 1) {
550 //
551 // process the startup script or launch the called app.
552 //
553 Status = DoStartupScript(ShellInfoObject.ImageDevPath, ShellInfoObject.FileDevPath);
554 }
555
556 if (!ShellInfoObject.ShellInitSettings.BitUnion.Bits.Exit && !ShellCommandGetExit() && (PcdGet8(PcdShellSupportLevel) >= 3 || PcdGetBool(PcdShellForceConsole)) && !EFI_ERROR(Status) && !ShellInfoObject.ShellInitSettings.BitUnion.Bits.NoConsoleIn) {
557 //
558 // begin the UI waiting loop
559 //
560 do {
561 //
562 // clean out all the memory allocated for CONST <something> * return values
563 // between each shell prompt presentation
564 //
565 if (!IsListEmpty(&ShellInfoObject.BufferToFreeList.Link)){
566 FreeBufferList(&ShellInfoObject.BufferToFreeList);
567 }
568
569 //
570 // Reset page break back to default.
571 //
572 ShellInfoObject.PageBreakEnabled = PcdGetBool(PcdShellPageBreakDefault);
573 ASSERT (ShellInfoObject.ConsoleInfo != NULL);
574 ShellInfoObject.ConsoleInfo->Enabled = TRUE;
575 ShellInfoObject.ConsoleInfo->RowCounter = 0;
576
577 //
578 // Reset the CTRL-C event (yes we ignore the return values)
579 //
580 Status = gBS->CheckEvent (ShellInfoObject.NewEfiShellProtocol->ExecutionBreak);
581
582 //
583 // Display Prompt
584 //
585 Status = DoShellPrompt();
586 } while (!ShellCommandGetExit());
587 }
588 if (OldConIn != NULL && ConInHandle != NULL) {
589 CloseSimpleTextInOnFile (gST->ConIn);
590 gST->ConIn = OldConIn;
591 gST->ConsoleInHandle = ConInHandle;
592 }
593 }
594 }
595
596 FreeResources:
597 //
598 // uninstall protocols / free memory / etc...
599 //
600 if (ShellInfoObject.UserBreakTimer != NULL) {
601 gBS->CloseEvent(ShellInfoObject.UserBreakTimer);
602 DEBUG_CODE(ShellInfoObject.UserBreakTimer = NULL;);
603 }
604 if (ShellInfoObject.ImageDevPath != NULL) {
605 FreePool(ShellInfoObject.ImageDevPath);
606 DEBUG_CODE(ShellInfoObject.ImageDevPath = NULL;);
607 }
608 if (ShellInfoObject.FileDevPath != NULL) {
609 FreePool(ShellInfoObject.FileDevPath);
610 DEBUG_CODE(ShellInfoObject.FileDevPath = NULL;);
611 }
612 if (ShellInfoObject.NewShellParametersProtocol != NULL) {
613 CleanUpShellParametersProtocol(ShellInfoObject.NewShellParametersProtocol);
614 DEBUG_CODE(ShellInfoObject.NewShellParametersProtocol = NULL;);
615 }
616 if (ShellInfoObject.NewEfiShellProtocol != NULL){
617 if (ShellInfoObject.NewEfiShellProtocol->IsRootShell()){
618 InternalEfiShellSetEnv(L"cwd", NULL, TRUE);
619 }
620 CleanUpShellProtocol(ShellInfoObject.NewEfiShellProtocol);
621 DEBUG_CODE(ShellInfoObject.NewEfiShellProtocol = NULL;);
622 }
623
624 if (!IsListEmpty(&ShellInfoObject.BufferToFreeList.Link)){
625 FreeBufferList(&ShellInfoObject.BufferToFreeList);
626 }
627
628 if (!IsListEmpty(&ShellInfoObject.SplitList.Link)){
629 ASSERT(FALSE); ///@todo finish this de-allocation.
630 }
631
632 if (ShellInfoObject.ShellInitSettings.FileName != NULL) {
633 FreePool(ShellInfoObject.ShellInitSettings.FileName);
634 DEBUG_CODE(ShellInfoObject.ShellInitSettings.FileName = NULL;);
635 }
636
637 if (ShellInfoObject.ShellInitSettings.FileOptions != NULL) {
638 FreePool(ShellInfoObject.ShellInitSettings.FileOptions);
639 DEBUG_CODE(ShellInfoObject.ShellInitSettings.FileOptions = NULL;);
640 }
641
642 if (ShellInfoObject.HiiHandle != NULL) {
643 HiiRemovePackages(ShellInfoObject.HiiHandle);
644 DEBUG_CODE(ShellInfoObject.HiiHandle = NULL;);
645 }
646
647 if (!IsListEmpty(&ShellInfoObject.ViewingSettings.CommandHistory.Link)){
648 FreeBufferList(&ShellInfoObject.ViewingSettings.CommandHistory);
649 }
650
651 ASSERT(ShellInfoObject.ConsoleInfo != NULL);
652 if (ShellInfoObject.ConsoleInfo != NULL) {
653 ConsoleLoggerUninstall(ShellInfoObject.ConsoleInfo);
654 FreePool(ShellInfoObject.ConsoleInfo);
655 DEBUG_CODE(ShellInfoObject.ConsoleInfo = NULL;);
656 }
657
658 if (ShellCommandGetExit()) {
659 return ((EFI_STATUS)ShellCommandGetExitCode());
660 }
661 return (Status);
662 }
663
664 /**
665 Sets all the alias' that were registered with the ShellCommandLib library.
666
667 @retval EFI_SUCCESS all init commands were run sucessfully.
668 **/
669 EFI_STATUS
670 EFIAPI
671 SetBuiltInAlias(
672 )
673 {
674 EFI_STATUS Status;
675 CONST ALIAS_LIST *List;
676 ALIAS_LIST *Node;
677
678 //
679 // Get all the commands we want to run
680 //
681 List = ShellCommandGetInitAliasList();
682
683 //
684 // for each command in the List
685 //
686 for ( Node = (ALIAS_LIST*)GetFirstNode(&List->Link)
687 ; !IsNull (&List->Link, &Node->Link)
688 ; Node = (ALIAS_LIST *)GetNextNode(&List->Link, &Node->Link)
689 ){
690 //
691 // install the alias'
692 //
693 Status = InternalSetAlias(Node->CommandString, Node->Alias, TRUE);
694 ASSERT_EFI_ERROR(Status);
695 }
696 return (EFI_SUCCESS);
697 }
698
699 /**
700 Internal function to determine if 2 command names are really the same.
701
702 @param[in] Command1 The pointer to the first command name.
703 @param[in] Command2 The pointer to the second command name.
704
705 @retval TRUE The 2 command names are the same.
706 @retval FALSE The 2 command names are not the same.
707 **/
708 BOOLEAN
709 EFIAPI
710 IsCommand(
711 IN CONST CHAR16 *Command1,
712 IN CONST CHAR16 *Command2
713 )
714 {
715 if (StringNoCaseCompare(&Command1, &Command2) == 0) {
716 return (TRUE);
717 }
718 return (FALSE);
719 }
720
721 /**
722 Internal function to determine if a command is a script only command.
723
724 @param[in] CommandName The pointer to the command name.
725
726 @retval TRUE The command is a script only command.
727 @retval FALSE The command is not a script only command.
728 **/
729 BOOLEAN
730 EFIAPI
731 IsScriptOnlyCommand(
732 IN CONST CHAR16 *CommandName
733 )
734 {
735 if (IsCommand(CommandName, L"for")
736 ||IsCommand(CommandName, L"endfor")
737 ||IsCommand(CommandName, L"if")
738 ||IsCommand(CommandName, L"else")
739 ||IsCommand(CommandName, L"endif")
740 ||IsCommand(CommandName, L"goto")) {
741 return (TRUE);
742 }
743 return (FALSE);
744 }
745
746 /**
747 This function will populate the 2 device path protocol parameters based on the
748 global gImageHandle. The DevPath will point to the device path for the handle that has
749 loaded image protocol installed on it. The FilePath will point to the device path
750 for the file that was loaded.
751
752 @param[in, out] DevPath On a sucessful return the device path to the loaded image.
753 @param[in, out] FilePath On a sucessful return the device path to the file.
754
755 @retval EFI_SUCCESS The 2 device paths were sucessfully returned.
756 @retval other A error from gBS->HandleProtocol.
757
758 @sa HandleProtocol
759 **/
760 EFI_STATUS
761 EFIAPI
762 GetDevicePathsForImageAndFile (
763 IN OUT EFI_DEVICE_PATH_PROTOCOL **DevPath,
764 IN OUT EFI_DEVICE_PATH_PROTOCOL **FilePath
765 )
766 {
767 EFI_STATUS Status;
768 EFI_LOADED_IMAGE_PROTOCOL *LoadedImage;
769 EFI_DEVICE_PATH_PROTOCOL *ImageDevicePath;
770
771 ASSERT(DevPath != NULL);
772 ASSERT(FilePath != NULL);
773
774 Status = gBS->OpenProtocol (
775 gImageHandle,
776 &gEfiLoadedImageProtocolGuid,
777 (VOID**)&LoadedImage,
778 gImageHandle,
779 NULL,
780 EFI_OPEN_PROTOCOL_GET_PROTOCOL
781 );
782 if (!EFI_ERROR (Status)) {
783 Status = gBS->OpenProtocol (
784 LoadedImage->DeviceHandle,
785 &gEfiDevicePathProtocolGuid,
786 (VOID**)&ImageDevicePath,
787 gImageHandle,
788 NULL,
789 EFI_OPEN_PROTOCOL_GET_PROTOCOL
790 );
791 if (!EFI_ERROR (Status)) {
792 *DevPath = DuplicateDevicePath (ImageDevicePath);
793 *FilePath = DuplicateDevicePath (LoadedImage->FilePath);
794 gBS->CloseProtocol(
795 LoadedImage->DeviceHandle,
796 &gEfiDevicePathProtocolGuid,
797 gImageHandle,
798 NULL);
799 }
800 gBS->CloseProtocol(
801 gImageHandle,
802 &gEfiLoadedImageProtocolGuid,
803 gImageHandle,
804 NULL);
805 }
806 return (Status);
807 }
808
809 /**
810 Process all Uefi Shell 2.0 command line options.
811
812 see Uefi Shell 2.0 section 3.2 for full details.
813
814 the command line must resemble the following:
815
816 shell.efi [ShellOpt-options] [options] [file-name [file-name-options]]
817
818 ShellOpt-options Options which control the initialization behavior of the shell.
819 These options are read from the EFI global variable "ShellOpt"
820 and are processed before options or file-name.
821
822 options Options which control the initialization behavior of the shell.
823
824 file-name The name of a UEFI shell application or script to be executed
825 after initialization is complete. By default, if file-name is
826 specified, then -nostartup is implied. Scripts are not supported
827 by level 0.
828
829 file-name-options The command-line options that are passed to file-name when it
830 is invoked.
831
832 This will initialize the ShellInfoObject.ShellInitSettings global variable.
833
834 @retval EFI_SUCCESS The variable is initialized.
835 **/
836 EFI_STATUS
837 EFIAPI
838 ProcessCommandLine(
839 VOID
840 )
841 {
842 UINTN Size;
843 UINTN LoopVar;
844 CHAR16 *CurrentArg;
845 CHAR16 *DelayValueStr;
846 UINT64 DelayValue;
847 EFI_STATUS Status;
848 EFI_UNICODE_COLLATION_PROTOCOL *UnicodeCollation;
849
850 // `file-name-options` will contain arguments to `file-name` that we don't
851 // know about. This would cause ShellCommandLineParse to error, so we parse
852 // arguments manually, ignoring those after the first thing that doesn't look
853 // like a shell option (which is assumed to be `file-name`).
854
855 Status = gBS->LocateProtocol (
856 &gEfiUnicodeCollationProtocolGuid,
857 NULL,
858 (VOID **) &UnicodeCollation
859 );
860 if (EFI_ERROR (Status)) {
861 return Status;
862 }
863
864 // Set default options
865 ShellInfoObject.ShellInitSettings.BitUnion.Bits.Startup = FALSE;
866 ShellInfoObject.ShellInitSettings.BitUnion.Bits.NoStartup = FALSE;
867 ShellInfoObject.ShellInitSettings.BitUnion.Bits.NoConsoleOut = FALSE;
868 ShellInfoObject.ShellInitSettings.BitUnion.Bits.NoConsoleIn = FALSE;
869 ShellInfoObject.ShellInitSettings.BitUnion.Bits.NoInterrupt = FALSE;
870 ShellInfoObject.ShellInitSettings.BitUnion.Bits.NoMap = FALSE;
871 ShellInfoObject.ShellInitSettings.BitUnion.Bits.NoVersion = FALSE;
872 ShellInfoObject.ShellInitSettings.BitUnion.Bits.Delay = FALSE;
873 ShellInfoObject.ShellInitSettings.BitUnion.Bits.Exit = FALSE;
874 ShellInfoObject.ShellInitSettings.Delay = 5;
875
876 //
877 // Start LoopVar at 0 to parse only optional arguments at Argv[0]
878 // and parse other parameters from Argv[1]. This is for use case that
879 // UEFI Shell boot option is created, and OptionalData is provided
880 // that starts with shell command-line options.
881 //
882 for (LoopVar = 0 ; LoopVar < gEfiShellParametersProtocol->Argc ; LoopVar++) {
883 CurrentArg = gEfiShellParametersProtocol->Argv[LoopVar];
884 if (UnicodeCollation->StriColl (
885 UnicodeCollation,
886 L"-startup",
887 CurrentArg
888 ) == 0) {
889 ShellInfoObject.ShellInitSettings.BitUnion.Bits.Startup = TRUE;
890 }
891 else if (UnicodeCollation->StriColl (
892 UnicodeCollation,
893 L"-nostartup",
894 CurrentArg
895 ) == 0) {
896 ShellInfoObject.ShellInitSettings.BitUnion.Bits.NoStartup = TRUE;
897 }
898 else if (UnicodeCollation->StriColl (
899 UnicodeCollation,
900 L"-noconsoleout",
901 CurrentArg
902 ) == 0) {
903 ShellInfoObject.ShellInitSettings.BitUnion.Bits.NoConsoleOut = TRUE;
904 }
905 else if (UnicodeCollation->StriColl (
906 UnicodeCollation,
907 L"-noconsolein",
908 CurrentArg
909 ) == 0) {
910 ShellInfoObject.ShellInitSettings.BitUnion.Bits.NoConsoleIn = TRUE;
911 }
912 else if (UnicodeCollation->StriColl (
913 UnicodeCollation,
914 L"-nointerrupt",
915 CurrentArg
916 ) == 0) {
917 ShellInfoObject.ShellInitSettings.BitUnion.Bits.NoInterrupt = TRUE;
918 }
919 else if (UnicodeCollation->StriColl (
920 UnicodeCollation,
921 L"-nomap",
922 CurrentArg
923 ) == 0) {
924 ShellInfoObject.ShellInitSettings.BitUnion.Bits.NoMap = TRUE;
925 }
926 else if (UnicodeCollation->StriColl (
927 UnicodeCollation,
928 L"-noversion",
929 CurrentArg
930 ) == 0) {
931 ShellInfoObject.ShellInitSettings.BitUnion.Bits.NoVersion = TRUE;
932 }
933 else if (UnicodeCollation->StriColl (
934 UnicodeCollation,
935 L"-delay",
936 CurrentArg
937 ) == 0) {
938 ShellInfoObject.ShellInitSettings.BitUnion.Bits.Delay = TRUE;
939 // Check for optional delay value following "-delay"
940 DelayValueStr = gEfiShellParametersProtocol->Argv[LoopVar + 1];
941 if (DelayValueStr != NULL){
942 if (*DelayValueStr == L':') {
943 DelayValueStr++;
944 }
945 if (!EFI_ERROR(ShellConvertStringToUint64 (
946 DelayValueStr,
947 &DelayValue,
948 FALSE,
949 FALSE
950 ))) {
951 ShellInfoObject.ShellInitSettings.Delay = (UINTN)DelayValue;
952 LoopVar++;
953 }
954 }
955 } else if (UnicodeCollation->StriColl (
956 UnicodeCollation,
957 L"-_exit",
958 CurrentArg
959 ) == 0) {
960 ShellInfoObject.ShellInitSettings.BitUnion.Bits.Exit = TRUE;
961 } else if (StrnCmp (L"-", CurrentArg, 1) == 0) {
962 // Unrecognised option
963 ShellPrintHiiEx(-1, -1, NULL,
964 STRING_TOKEN (STR_GEN_PROBLEM),
965 ShellInfoObject.HiiHandle,
966 CurrentArg
967 );
968 return EFI_INVALID_PARAMETER;
969 } else {
970 //
971 // First argument should be Shell.efi image name
972 //
973 if (LoopVar == 0) {
974 continue;
975 }
976
977 ShellInfoObject.ShellInitSettings.FileName = AllocateCopyPool(StrSize(CurrentArg), CurrentArg);
978 if (ShellInfoObject.ShellInitSettings.FileName == NULL) {
979 return (EFI_OUT_OF_RESOURCES);
980 }
981 //
982 // We found `file-name`.
983 //
984 ShellInfoObject.ShellInitSettings.BitUnion.Bits.NoStartup = 1;
985 LoopVar++;
986
987 // Add `file-name-options`
988 for (Size = 0 ; LoopVar < gEfiShellParametersProtocol->Argc ; LoopVar++) {
989 ASSERT((ShellInfoObject.ShellInitSettings.FileOptions == NULL && Size == 0) || (ShellInfoObject.ShellInitSettings.FileOptions != NULL));
990 StrnCatGrow(&ShellInfoObject.ShellInitSettings.FileOptions,
991 &Size,
992 L" ",
993 0);
994 if (ShellInfoObject.ShellInitSettings.FileOptions == NULL) {
995 SHELL_FREE_NON_NULL(ShellInfoObject.ShellInitSettings.FileName);
996 return (EFI_OUT_OF_RESOURCES);
997 }
998 StrnCatGrow(&ShellInfoObject.ShellInitSettings.FileOptions,
999 &Size,
1000 gEfiShellParametersProtocol->Argv[LoopVar],
1001 0);
1002 if (ShellInfoObject.ShellInitSettings.FileOptions == NULL) {
1003 SHELL_FREE_NON_NULL(ShellInfoObject.ShellInitSettings.FileName);
1004 return (EFI_OUT_OF_RESOURCES);
1005 }
1006 }
1007 }
1008 }
1009
1010 // "-nointerrupt" overrides "-delay"
1011 if (ShellInfoObject.ShellInitSettings.BitUnion.Bits.NoInterrupt) {
1012 ShellInfoObject.ShellInitSettings.Delay = 0;
1013 }
1014
1015 return EFI_SUCCESS;
1016 }
1017
1018 /**
1019 Handles all interaction with the default startup script.
1020
1021 this will check that the correct command line parameters were passed, handle the delay, and then start running the script.
1022
1023 @param ImagePath the path to the image for shell. first place to look for the startup script
1024 @param FilePath the path to the file for shell. second place to look for the startup script.
1025
1026 @retval EFI_SUCCESS the variable is initialized.
1027 **/
1028 EFI_STATUS
1029 EFIAPI
1030 DoStartupScript(
1031 IN EFI_DEVICE_PATH_PROTOCOL *ImagePath,
1032 IN EFI_DEVICE_PATH_PROTOCOL *FilePath
1033 )
1034 {
1035 EFI_STATUS Status;
1036 UINTN Delay;
1037 EFI_INPUT_KEY Key;
1038 SHELL_FILE_HANDLE FileHandle;
1039 EFI_DEVICE_PATH_PROTOCOL *NewPath;
1040 EFI_DEVICE_PATH_PROTOCOL *NamePath;
1041 CHAR16 *FileStringPath;
1042 CHAR16 *TempSpot;
1043 UINTN NewSize;
1044 CONST CHAR16 *MapName;
1045
1046 Key.UnicodeChar = CHAR_NULL;
1047 Key.ScanCode = 0;
1048 FileHandle = NULL;
1049
1050 if (!ShellInfoObject.ShellInitSettings.BitUnion.Bits.Startup && ShellInfoObject.ShellInitSettings.FileName != NULL) {
1051 //
1052 // launch something else instead
1053 //
1054 NewSize = StrSize(ShellInfoObject.ShellInitSettings.FileName);
1055 if (ShellInfoObject.ShellInitSettings.FileOptions != NULL) {
1056 NewSize += StrSize(ShellInfoObject.ShellInitSettings.FileOptions) + sizeof(CHAR16);
1057 }
1058 FileStringPath = AllocateZeroPool(NewSize);
1059 if (FileStringPath == NULL) {
1060 return (EFI_OUT_OF_RESOURCES);
1061 }
1062 StrnCpy(FileStringPath, ShellInfoObject.ShellInitSettings.FileName, NewSize/sizeof(CHAR16) -1);
1063 if (ShellInfoObject.ShellInitSettings.FileOptions != NULL) {
1064 StrnCat(FileStringPath, L" ", NewSize/sizeof(CHAR16) - StrLen(FileStringPath) -1);
1065 StrnCat(FileStringPath, ShellInfoObject.ShellInitSettings.FileOptions, NewSize/sizeof(CHAR16) - StrLen(FileStringPath) -1);
1066 }
1067 Status = RunCommand(FileStringPath);
1068 FreePool(FileStringPath);
1069 return (Status);
1070
1071 }
1072
1073 //
1074 // for shell level 0 we do no scripts
1075 // Without the Startup bit overriding we allow for nostartup to prevent scripts
1076 //
1077 if ( (PcdGet8(PcdShellSupportLevel) < 1)
1078 || (ShellInfoObject.ShellInitSettings.BitUnion.Bits.NoStartup && !ShellInfoObject.ShellInitSettings.BitUnion.Bits.Startup)
1079 ){
1080 return (EFI_SUCCESS);
1081 }
1082
1083 gST->ConOut->EnableCursor(gST->ConOut, FALSE);
1084 //
1085 // print out our warning and see if they press a key
1086 //
1087 for ( Status = EFI_UNSUPPORTED, Delay = ShellInfoObject.ShellInitSettings.Delay
1088 ; Delay != 0 && EFI_ERROR(Status)
1089 ; Delay--
1090 ){
1091 ShellPrintHiiEx(0, gST->ConOut->Mode->CursorRow, NULL, STRING_TOKEN (STR_SHELL_STARTUP_QUESTION), ShellInfoObject.HiiHandle, Delay);
1092 gBS->Stall (1000000);
1093 if (!ShellInfoObject.ShellInitSettings.BitUnion.Bits.NoConsoleIn) {
1094 Status = gST->ConIn->ReadKeyStroke (gST->ConIn, &Key);
1095 }
1096 }
1097 ShellPrintHiiEx(-1, -1, NULL, STRING_TOKEN (STR_SHELL_CRLF), ShellInfoObject.HiiHandle);
1098 gST->ConOut->EnableCursor(gST->ConOut, TRUE);
1099
1100 //
1101 // ESC was pressed
1102 //
1103 if (Status == EFI_SUCCESS && Key.UnicodeChar == 0 && Key.ScanCode == SCAN_ESC) {
1104 return (EFI_SUCCESS);
1105 }
1106
1107 //
1108 // Try the first location (must be file system)
1109 //
1110 MapName = ShellInfoObject.NewEfiShellProtocol->GetMapFromDevicePath(&ImagePath);
1111 if (MapName != NULL) {
1112 FileStringPath = NULL;
1113 NewSize = 0;
1114 FileStringPath = StrnCatGrow(&FileStringPath, &NewSize, MapName, 0);
1115 if (FileStringPath == NULL) {
1116 Status = EFI_OUT_OF_RESOURCES;
1117 } else {
1118 TempSpot = StrStr(FileStringPath, L";");
1119 if (TempSpot != NULL) {
1120 *TempSpot = CHAR_NULL;
1121 }
1122 FileStringPath = StrnCatGrow(&FileStringPath, &NewSize, ((FILEPATH_DEVICE_PATH*)FilePath)->PathName, 0);
1123 PathRemoveLastItem(FileStringPath);
1124 FileStringPath = StrnCatGrow(&FileStringPath, &NewSize, mStartupScript, 0);
1125 Status = ShellInfoObject.NewEfiShellProtocol->OpenFileByName(FileStringPath, &FileHandle, EFI_FILE_MODE_READ);
1126 FreePool(FileStringPath);
1127 }
1128 }
1129 if (EFI_ERROR(Status)) {
1130 NamePath = FileDevicePath (NULL, mStartupScript);
1131 NewPath = AppendDevicePathNode (ImagePath, NamePath);
1132 FreePool(NamePath);
1133
1134 //
1135 // Try the location
1136 //
1137 Status = InternalOpenFileDevicePath(NewPath, &FileHandle, EFI_FILE_MODE_READ, 0);
1138 FreePool(NewPath);
1139 }
1140 //
1141 // If we got a file, run it
1142 //
1143 if (!EFI_ERROR(Status) && FileHandle != NULL) {
1144 Status = RunScriptFile (mStartupScript, FileHandle, L"", ShellInfoObject.NewShellParametersProtocol);
1145 ShellInfoObject.NewEfiShellProtocol->CloseFile(FileHandle);
1146 } else {
1147 FileStringPath = ShellFindFilePath(mStartupScript);
1148 if (FileStringPath == NULL) {
1149 //
1150 // we return success since we dont need to have a startup script
1151 //
1152 Status = EFI_SUCCESS;
1153 ASSERT(FileHandle == NULL);
1154 } else {
1155 Status = RunScriptFile(FileStringPath, NULL, L"", ShellInfoObject.NewShellParametersProtocol);
1156 FreePool(FileStringPath);
1157 }
1158 }
1159
1160
1161 return (Status);
1162 }
1163
1164 /**
1165 Function to perform the shell prompt looping. It will do a single prompt,
1166 dispatch the result, and then return. It is expected that the caller will
1167 call this function in a loop many times.
1168
1169 @retval EFI_SUCCESS
1170 @retval RETURN_ABORTED
1171 **/
1172 EFI_STATUS
1173 EFIAPI
1174 DoShellPrompt (
1175 VOID
1176 )
1177 {
1178 UINTN Column;
1179 UINTN Row;
1180 CHAR16 *CmdLine;
1181 CONST CHAR16 *CurDir;
1182 UINTN BufferSize;
1183 EFI_STATUS Status;
1184
1185 CurDir = NULL;
1186
1187 //
1188 // Get screen setting to decide size of the command line buffer
1189 //
1190 gST->ConOut->QueryMode (gST->ConOut, gST->ConOut->Mode->Mode, &Column, &Row);
1191 BufferSize = Column * Row * sizeof (CHAR16);
1192 CmdLine = AllocateZeroPool (BufferSize);
1193 if (CmdLine == NULL) {
1194 return EFI_OUT_OF_RESOURCES;
1195 }
1196
1197 CurDir = ShellInfoObject.NewEfiShellProtocol->GetEnv(L"cwd");
1198
1199 //
1200 // Prompt for input
1201 //
1202 gST->ConOut->SetCursorPosition (gST->ConOut, 0, gST->ConOut->Mode->CursorRow);
1203
1204 if (CurDir != NULL && StrLen(CurDir) > 1) {
1205 ShellPrintHiiEx(-1, -1, NULL, STRING_TOKEN (STR_SHELL_CURDIR), ShellInfoObject.HiiHandle, CurDir);
1206 } else {
1207 ShellPrintHiiEx(-1, -1, NULL, STRING_TOKEN (STR_SHELL_SHELL), ShellInfoObject.HiiHandle);
1208 }
1209
1210 //
1211 // Read a line from the console
1212 //
1213 Status = ShellInfoObject.NewEfiShellProtocol->ReadFile(ShellInfoObject.NewShellParametersProtocol->StdIn, &BufferSize, CmdLine);
1214
1215 //
1216 // Null terminate the string and parse it
1217 //
1218 if (!EFI_ERROR (Status)) {
1219 CmdLine[BufferSize / sizeof (CHAR16)] = CHAR_NULL;
1220 Status = RunCommand(CmdLine);
1221 }
1222
1223 //
1224 // Done with this command
1225 //
1226 FreePool (CmdLine);
1227 return Status;
1228 }
1229
1230 /**
1231 Add a buffer to the Buffer To Free List for safely returning buffers to other
1232 places without risking letting them modify internal shell information.
1233
1234 @param Buffer Something to pass to FreePool when the shell is exiting.
1235 **/
1236 VOID*
1237 EFIAPI
1238 AddBufferToFreeList(
1239 VOID *Buffer
1240 )
1241 {
1242 BUFFER_LIST *BufferListEntry;
1243
1244 if (Buffer == NULL) {
1245 return (NULL);
1246 }
1247
1248 BufferListEntry = AllocateZeroPool(sizeof(BUFFER_LIST));
1249 ASSERT(BufferListEntry != NULL);
1250 BufferListEntry->Buffer = Buffer;
1251 InsertTailList(&ShellInfoObject.BufferToFreeList.Link, &BufferListEntry->Link);
1252 return (Buffer);
1253 }
1254
1255 /**
1256 Add a buffer to the Line History List
1257
1258 @param Buffer The line buffer to add.
1259 **/
1260 VOID
1261 EFIAPI
1262 AddLineToCommandHistory(
1263 IN CONST CHAR16 *Buffer
1264 )
1265 {
1266 BUFFER_LIST *Node;
1267
1268 Node = AllocateZeroPool(sizeof(BUFFER_LIST));
1269 ASSERT(Node != NULL);
1270 Node->Buffer = AllocateCopyPool(StrSize(Buffer), Buffer);
1271 ASSERT(Node->Buffer != NULL);
1272
1273 InsertTailList(&ShellInfoObject.ViewingSettings.CommandHistory.Link, &Node->Link);
1274 }
1275
1276 /**
1277 Checks if a string is an alias for another command. If yes, then it replaces the alias name
1278 with the correct command name.
1279
1280 @param[in, out] CommandString Upon entry the potential alias. Upon return the
1281 command name if it was an alias. If it was not
1282 an alias it will be unchanged. This function may
1283 change the buffer to fit the command name.
1284
1285 @retval EFI_SUCCESS The name was changed.
1286 @retval EFI_SUCCESS The name was not an alias.
1287 @retval EFI_OUT_OF_RESOURCES A memory allocation failed.
1288 **/
1289 EFI_STATUS
1290 EFIAPI
1291 ShellConvertAlias(
1292 IN OUT CHAR16 **CommandString
1293 )
1294 {
1295 CONST CHAR16 *NewString;
1296
1297 NewString = ShellInfoObject.NewEfiShellProtocol->GetAlias(*CommandString, NULL);
1298 if (NewString == NULL) {
1299 return (EFI_SUCCESS);
1300 }
1301 FreePool(*CommandString);
1302 *CommandString = AllocateCopyPool(StrSize(NewString), NewString);
1303 if (*CommandString == NULL) {
1304 return (EFI_OUT_OF_RESOURCES);
1305 }
1306 return (EFI_SUCCESS);
1307 }
1308
1309 /**
1310 This function will eliminate unreplaced (and therefore non-found) environment variables.
1311
1312 @param[in,out] CmdLine The command line to update.
1313 **/
1314 EFI_STATUS
1315 EFIAPI
1316 StripUnreplacedEnvironmentVariables(
1317 IN OUT CHAR16 *CmdLine
1318 )
1319 {
1320 CHAR16 *FirstPercent;
1321 CHAR16 *FirstQuote;
1322 CHAR16 *SecondPercent;
1323 CHAR16 *SecondQuote;
1324 CHAR16 *CurrentLocator;
1325
1326 for (CurrentLocator = CmdLine ; CurrentLocator != NULL ; ) {
1327 FirstQuote = FindNextInstance(CurrentLocator, L"\"", TRUE);
1328 FirstPercent = FindNextInstance(CurrentLocator, L"%", TRUE);
1329 SecondPercent = FirstPercent!=NULL?FindNextInstance(FirstPercent+1, L"%", TRUE):NULL;
1330 if (FirstPercent == NULL || SecondPercent == NULL) {
1331 //
1332 // If we ever dont have 2 % we are done.
1333 //
1334 break;
1335 }
1336
1337 if (FirstQuote < FirstPercent) {
1338 SecondQuote = FirstQuote!= NULL?FindNextInstance(FirstQuote+1, L"\"", TRUE):NULL;
1339 //
1340 // Quote is first found
1341 //
1342
1343 if (SecondQuote < FirstPercent) {
1344 //
1345 // restart after the pair of "
1346 //
1347 CurrentLocator = SecondQuote + 1;
1348 } else /* FirstPercent < SecondQuote */{
1349 //
1350 // Restart on the first percent
1351 //
1352 CurrentLocator = FirstPercent;
1353 }
1354 continue;
1355 }
1356 ASSERT(FirstPercent < FirstQuote);
1357 if (SecondPercent < FirstQuote) {
1358 FirstPercent[0] = L'\"';
1359 SecondPercent[0] = L'\"';
1360
1361 //
1362 // We need to remove from FirstPercent to SecondPercent
1363 //
1364 CopyMem(FirstPercent + 1, SecondPercent, StrSize(SecondPercent));
1365 CurrentLocator = FirstPercent + 2;
1366 continue;
1367 }
1368 ASSERT(FirstQuote < SecondPercent);
1369 CurrentLocator = FirstQuote;
1370 }
1371 return (EFI_SUCCESS);
1372 }
1373
1374 /**
1375 Function allocates a new command line and replaces all instances of environment
1376 variable names that are correctly preset to their values.
1377
1378 If the return value is not NULL the memory must be caller freed.
1379
1380 @param[in] OriginalCommandLine The original command line
1381
1382 @retval NULL An error ocurred.
1383 @return The new command line with no environment variables present.
1384 **/
1385 CHAR16*
1386 EFIAPI
1387 ShellConvertVariables (
1388 IN CONST CHAR16 *OriginalCommandLine
1389 )
1390 {
1391 CONST CHAR16 *MasterEnvList;
1392 UINTN NewSize;
1393 CHAR16 *NewCommandLine1;
1394 CHAR16 *NewCommandLine2;
1395 CHAR16 *Temp;
1396 UINTN ItemSize;
1397 CHAR16 *ItemTemp;
1398 SCRIPT_FILE *CurrentScriptFile;
1399 ALIAS_LIST *AliasListNode;
1400
1401 ASSERT(OriginalCommandLine != NULL);
1402
1403 ItemSize = 0;
1404 NewSize = StrSize(OriginalCommandLine);
1405 CurrentScriptFile = ShellCommandGetCurrentScriptFile();
1406 Temp = NULL;
1407
1408 ///@todo update this to handle the %0 - %9 for scripting only (borrow from line 1256 area) ? ? ?
1409
1410 //
1411 // calculate the size required for the post-conversion string...
1412 //
1413 if (CurrentScriptFile != NULL) {
1414 for (AliasListNode = (ALIAS_LIST*)GetFirstNode(&CurrentScriptFile->SubstList)
1415 ; !IsNull(&CurrentScriptFile->SubstList, &AliasListNode->Link)
1416 ; AliasListNode = (ALIAS_LIST*)GetNextNode(&CurrentScriptFile->SubstList, &AliasListNode->Link)
1417 ){
1418 for (Temp = StrStr(OriginalCommandLine, AliasListNode->Alias)
1419 ; Temp != NULL
1420 ; Temp = StrStr(Temp+1, AliasListNode->Alias)
1421 ){
1422 //
1423 // we need a preceeding and if there is space no ^ preceeding (if no space ignore)
1424 //
1425 if ((((Temp-OriginalCommandLine)>2) && *(Temp-2) != L'^') || ((Temp-OriginalCommandLine)<=2)) {
1426 NewSize += StrSize(AliasListNode->CommandString);
1427 }
1428 }
1429 }
1430 }
1431
1432 for (MasterEnvList = EfiShellGetEnv(NULL)
1433 ; MasterEnvList != NULL && *MasterEnvList != CHAR_NULL //&& *(MasterEnvList+1) != CHAR_NULL
1434 ; MasterEnvList += StrLen(MasterEnvList) + 1
1435 ){
1436 if (StrSize(MasterEnvList) > ItemSize) {
1437 ItemSize = StrSize(MasterEnvList);
1438 }
1439 for (Temp = StrStr(OriginalCommandLine, MasterEnvList)
1440 ; Temp != NULL
1441 ; Temp = StrStr(Temp+1, MasterEnvList)
1442 ){
1443 //
1444 // we need a preceeding and following % and if there is space no ^ preceeding (if no space ignore)
1445 //
1446 if (*(Temp-1) == L'%' && *(Temp+StrLen(MasterEnvList)) == L'%' &&
1447 ((((Temp-OriginalCommandLine)>2) && *(Temp-2) != L'^') || ((Temp-OriginalCommandLine)<=2))) {
1448 NewSize+=StrSize(EfiShellGetEnv(MasterEnvList));
1449 }
1450 }
1451 }
1452
1453 //
1454 // now do the replacements...
1455 //
1456 NewCommandLine1 = AllocateCopyPool(NewSize, OriginalCommandLine);
1457 NewCommandLine2 = AllocateZeroPool(NewSize);
1458 ItemTemp = AllocateZeroPool(ItemSize+(2*sizeof(CHAR16)));
1459 if (NewCommandLine1 == NULL || NewCommandLine2 == NULL || ItemTemp == NULL) {
1460 SHELL_FREE_NON_NULL(NewCommandLine1);
1461 SHELL_FREE_NON_NULL(NewCommandLine2);
1462 SHELL_FREE_NON_NULL(ItemTemp);
1463 return (NULL);
1464 }
1465 for (MasterEnvList = EfiShellGetEnv(NULL)
1466 ; MasterEnvList != NULL && *MasterEnvList != CHAR_NULL
1467 ; MasterEnvList += StrLen(MasterEnvList) + 1
1468 ){
1469 StrnCpy(ItemTemp, L"%", ((ItemSize+(2*sizeof(CHAR16)))/sizeof(CHAR16))-1);
1470 StrnCat(ItemTemp, MasterEnvList, ((ItemSize+(2*sizeof(CHAR16)))/sizeof(CHAR16))-1 - StrLen(ItemTemp));
1471 StrnCat(ItemTemp, L"%", ((ItemSize+(2*sizeof(CHAR16)))/sizeof(CHAR16))-1 - StrLen(ItemTemp));
1472 ShellCopySearchAndReplace(NewCommandLine1, NewCommandLine2, NewSize, ItemTemp, EfiShellGetEnv(MasterEnvList), TRUE, FALSE);
1473 StrnCpy(NewCommandLine1, NewCommandLine2, NewSize/sizeof(CHAR16)-1);
1474 }
1475 if (CurrentScriptFile != NULL) {
1476 for (AliasListNode = (ALIAS_LIST*)GetFirstNode(&CurrentScriptFile->SubstList)
1477 ; !IsNull(&CurrentScriptFile->SubstList, &AliasListNode->Link)
1478 ; AliasListNode = (ALIAS_LIST*)GetNextNode(&CurrentScriptFile->SubstList, &AliasListNode->Link)
1479 ){
1480 ShellCopySearchAndReplace(NewCommandLine1, NewCommandLine2, NewSize, AliasListNode->Alias, AliasListNode->CommandString, TRUE, FALSE);
1481 StrnCpy(NewCommandLine1, NewCommandLine2, NewSize/sizeof(CHAR16)-1);
1482 }
1483
1484 //
1485 // Remove non-existant environment variables in scripts only
1486 //
1487 StripUnreplacedEnvironmentVariables(NewCommandLine1);
1488 }
1489
1490 //
1491 // Now cleanup any straggler intentionally ignored "%" characters
1492 //
1493 ShellCopySearchAndReplace(NewCommandLine1, NewCommandLine2, NewSize, L"^%", L"%", TRUE, FALSE);
1494 StrnCpy(NewCommandLine1, NewCommandLine2, NewSize/sizeof(CHAR16)-1);
1495
1496 FreePool(NewCommandLine2);
1497 FreePool(ItemTemp);
1498
1499 return (NewCommandLine1);
1500 }
1501
1502 /**
1503 Internal function to run a command line with pipe usage.
1504
1505 @param[in] CmdLine The pointer to the command line.
1506 @param[in] StdIn The pointer to the Standard input.
1507 @param[in] StdOut The pointer to the Standard output.
1508
1509 @retval EFI_SUCCESS The split command is executed successfully.
1510 @retval other Some error occurs when executing the split command.
1511 **/
1512 EFI_STATUS
1513 EFIAPI
1514 RunSplitCommand(
1515 IN CONST CHAR16 *CmdLine,
1516 IN SHELL_FILE_HANDLE *StdIn,
1517 IN SHELL_FILE_HANDLE *StdOut
1518 )
1519 {
1520 EFI_STATUS Status;
1521 CHAR16 *NextCommandLine;
1522 CHAR16 *OurCommandLine;
1523 UINTN Size1;
1524 UINTN Size2;
1525 SPLIT_LIST *Split;
1526 SHELL_FILE_HANDLE *TempFileHandle;
1527 BOOLEAN Unicode;
1528
1529 ASSERT(StdOut == NULL);
1530
1531 ASSERT(StrStr(CmdLine, L"|") != NULL);
1532
1533 Status = EFI_SUCCESS;
1534 NextCommandLine = NULL;
1535 OurCommandLine = NULL;
1536 Size1 = 0;
1537 Size2 = 0;
1538
1539 NextCommandLine = StrnCatGrow(&NextCommandLine, &Size1, StrStr(CmdLine, L"|")+1, 0);
1540 OurCommandLine = StrnCatGrow(&OurCommandLine , &Size2, CmdLine , StrStr(CmdLine, L"|") - CmdLine);
1541
1542 if (NextCommandLine == NULL || OurCommandLine == NULL) {
1543 SHELL_FREE_NON_NULL(OurCommandLine);
1544 SHELL_FREE_NON_NULL(NextCommandLine);
1545 return (EFI_OUT_OF_RESOURCES);
1546 } else if (StrStr(OurCommandLine, L"|") != NULL || Size1 == 0 || Size2 == 0) {
1547 SHELL_FREE_NON_NULL(OurCommandLine);
1548 SHELL_FREE_NON_NULL(NextCommandLine);
1549 return (EFI_INVALID_PARAMETER);
1550 } else if (NextCommandLine[0] != CHAR_NULL &&
1551 NextCommandLine[0] == L'a' &&
1552 NextCommandLine[1] == L' '
1553 ){
1554 CopyMem(NextCommandLine, NextCommandLine+1, StrSize(NextCommandLine) - sizeof(NextCommandLine[0]));
1555 Unicode = FALSE;
1556 } else {
1557 Unicode = TRUE;
1558 }
1559
1560
1561 //
1562 // make a SPLIT_LIST item and add to list
1563 //
1564 Split = AllocateZeroPool(sizeof(SPLIT_LIST));
1565 ASSERT(Split != NULL);
1566 Split->SplitStdIn = StdIn;
1567 Split->SplitStdOut = ConvertEfiFileProtocolToShellHandle(CreateFileInterfaceMem(Unicode), NULL);
1568 ASSERT(Split->SplitStdOut != NULL);
1569 InsertHeadList(&ShellInfoObject.SplitList.Link, &Split->Link);
1570
1571 Status = RunCommand(OurCommandLine);
1572
1573 //
1574 // move the output from the first to the in to the second.
1575 //
1576 TempFileHandle = Split->SplitStdOut;
1577 if (Split->SplitStdIn == StdIn) {
1578 Split->SplitStdOut = NULL;
1579 } else {
1580 Split->SplitStdOut = Split->SplitStdIn;
1581 }
1582 Split->SplitStdIn = TempFileHandle;
1583 ShellInfoObject.NewEfiShellProtocol->SetFilePosition(ConvertShellHandleToEfiFileProtocol(Split->SplitStdIn), 0);
1584
1585 if (!EFI_ERROR(Status)) {
1586 Status = RunCommand(NextCommandLine);
1587 }
1588
1589 //
1590 // remove the top level from the ScriptList
1591 //
1592 ASSERT((SPLIT_LIST*)GetFirstNode(&ShellInfoObject.SplitList.Link) == Split);
1593 RemoveEntryList(&Split->Link);
1594
1595 //
1596 // Note that the original StdIn is now the StdOut...
1597 //
1598 if (Split->SplitStdOut != NULL && Split->SplitStdOut != StdIn) {
1599 ShellInfoObject.NewEfiShellProtocol->CloseFile(ConvertShellHandleToEfiFileProtocol(Split->SplitStdOut));
1600 }
1601 if (Split->SplitStdIn != NULL) {
1602 ShellInfoObject.NewEfiShellProtocol->CloseFile(ConvertShellHandleToEfiFileProtocol(Split->SplitStdIn));
1603 }
1604
1605 FreePool(Split);
1606 FreePool(NextCommandLine);
1607 FreePool(OurCommandLine);
1608
1609 return (Status);
1610 }
1611
1612 /**
1613 Take the original command line, substitute any variables, free
1614 the original string, return the modified copy.
1615
1616 @param[in] CmdLine pointer to the command line to update.
1617
1618 @retval EFI_SUCCESS the function was successful.
1619 @retval EFI_OUT_OF_RESOURCES a memory allocation failed.
1620 **/
1621 EFI_STATUS
1622 EFIAPI
1623 ShellSubstituteVariables(
1624 IN CHAR16 **CmdLine
1625 )
1626 {
1627 CHAR16 *NewCmdLine;
1628 NewCmdLine = ShellConvertVariables(*CmdLine);
1629 SHELL_FREE_NON_NULL(*CmdLine);
1630 if (NewCmdLine == NULL) {
1631 return (EFI_OUT_OF_RESOURCES);
1632 }
1633 *CmdLine = NewCmdLine;
1634 return (EFI_SUCCESS);
1635 }
1636
1637 /**
1638 Take the original command line, substitute any alias in the first group of space delimited characters, free
1639 the original string, return the modified copy.
1640
1641 @param[in] CmdLine pointer to the command line to update.
1642
1643 @retval EFI_SUCCESS the function was successful.
1644 @retval EFI_OUT_OF_RESOURCES a memory allocation failed.
1645 **/
1646 EFI_STATUS
1647 EFIAPI
1648 ShellSubstituteAliases(
1649 IN CHAR16 **CmdLine
1650 )
1651 {
1652 CHAR16 *NewCmdLine;
1653 CHAR16 *CommandName;
1654 EFI_STATUS Status;
1655 UINTN PostAliasSize;
1656 ASSERT(CmdLine != NULL);
1657 ASSERT(*CmdLine!= NULL);
1658
1659
1660 CommandName = NULL;
1661 if (StrStr((*CmdLine), L" ") == NULL){
1662 StrnCatGrow(&CommandName, NULL, (*CmdLine), 0);
1663 } else {
1664 StrnCatGrow(&CommandName, NULL, (*CmdLine), StrStr((*CmdLine), L" ") - (*CmdLine));
1665 }
1666
1667 //
1668 // This cannot happen 'inline' since the CmdLine can need extra space.
1669 //
1670 NewCmdLine = NULL;
1671 if (!ShellCommandIsCommandOnList(CommandName)) {
1672 //
1673 // Convert via alias
1674 //
1675 Status = ShellConvertAlias(&CommandName);
1676 if (EFI_ERROR(Status)){
1677 return (Status);
1678 }
1679 PostAliasSize = 0;
1680 NewCmdLine = StrnCatGrow(&NewCmdLine, &PostAliasSize, CommandName, 0);
1681 if (NewCmdLine == NULL) {
1682 SHELL_FREE_NON_NULL(CommandName);
1683 SHELL_FREE_NON_NULL(*CmdLine);
1684 return (EFI_OUT_OF_RESOURCES);
1685 }
1686 NewCmdLine = StrnCatGrow(&NewCmdLine, &PostAliasSize, StrStr((*CmdLine), L" "), 0);
1687 if (NewCmdLine == NULL) {
1688 SHELL_FREE_NON_NULL(CommandName);
1689 SHELL_FREE_NON_NULL(*CmdLine);
1690 return (EFI_OUT_OF_RESOURCES);
1691 }
1692 } else {
1693 NewCmdLine = StrnCatGrow(&NewCmdLine, NULL, (*CmdLine), 0);
1694 }
1695
1696 SHELL_FREE_NON_NULL(*CmdLine);
1697 SHELL_FREE_NON_NULL(CommandName);
1698
1699 //
1700 // re-assign the passed in double pointer to point to our newly allocated buffer
1701 //
1702 *CmdLine = NewCmdLine;
1703
1704 return (EFI_SUCCESS);
1705 }
1706
1707 /**
1708 Takes the Argv[0] part of the command line and determine the meaning of it.
1709
1710 @param[in] CmdName pointer to the command line to update.
1711
1712 @retval Internal_Command The name is an internal command.
1713 @retval File_Sys_Change the name is a file system change.
1714 @retval Script_File_Name the name is a NSH script file.
1715 @retval Unknown_Invalid the name is unknown.
1716 @retval Efi_Application the name is an application (.EFI).
1717 **/
1718 SHELL_OPERATION_TYPES
1719 EFIAPI
1720 GetOperationType(
1721 IN CONST CHAR16 *CmdName
1722 )
1723 {
1724 CHAR16* FileWithPath;
1725 CONST CHAR16* TempLocation;
1726 CONST CHAR16* TempLocation2;
1727
1728 FileWithPath = NULL;
1729 //
1730 // test for an internal command.
1731 //
1732 if (ShellCommandIsCommandOnList(CmdName)) {
1733 return (Internal_Command);
1734 }
1735
1736 //
1737 // Test for file system change request. anything ending with first : and cant have spaces.
1738 //
1739 if (CmdName[(StrLen(CmdName)-1)] == L':') {
1740 if ( StrStr(CmdName, L" ") != NULL
1741 || StrLen(StrStr(CmdName, L":")) > 1
1742 ) {
1743 return (Unknown_Invalid);
1744 }
1745 return (File_Sys_Change);
1746 }
1747
1748 //
1749 // Test for a file
1750 //
1751 if ((FileWithPath = ShellFindFilePathEx(CmdName, mExecutableExtensions)) != NULL) {
1752 //
1753 // See if that file has a script file extension
1754 //
1755 if (StrLen(FileWithPath) > 4) {
1756 TempLocation = FileWithPath+StrLen(FileWithPath)-4;
1757 TempLocation2 = mScriptExtension;
1758 if (StringNoCaseCompare((VOID*)(&TempLocation), (VOID*)(&TempLocation2)) == 0) {
1759 SHELL_FREE_NON_NULL(FileWithPath);
1760 return (Script_File_Name);
1761 }
1762 }
1763
1764 //
1765 // Was a file, but not a script. we treat this as an application.
1766 //
1767 SHELL_FREE_NON_NULL(FileWithPath);
1768 return (Efi_Application);
1769 }
1770
1771 SHELL_FREE_NON_NULL(FileWithPath);
1772 //
1773 // No clue what this is... return invalid flag...
1774 //
1775 return (Unknown_Invalid);
1776 }
1777
1778 /**
1779 Determine if the first item in a command line is valid.
1780
1781 @param[in] CmdLine The command line to parse.
1782
1783 @retval EFI_SUCCESS The item is valid.
1784 @retval EFI_OUT_OF_RESOURCES A memory allocation failed.
1785 @retval EFI_NOT_FOUND The operation type is unknown or invalid.
1786 **/
1787 EFI_STATUS
1788 EFIAPI
1789 IsValidSplit(
1790 IN CONST CHAR16 *CmdLine
1791 )
1792 {
1793 CHAR16 *Temp;
1794 CHAR16 *FirstParameter;
1795 CHAR16 *TempWalker;
1796 EFI_STATUS Status;
1797
1798 Temp = NULL;
1799
1800 Temp = StrnCatGrow(&Temp, NULL, CmdLine, 0);
1801 if (Temp == NULL) {
1802 return (EFI_OUT_OF_RESOURCES);
1803 }
1804
1805 FirstParameter = StrStr(Temp, L"|");
1806 if (FirstParameter != NULL) {
1807 *FirstParameter = CHAR_NULL;
1808 }
1809
1810 FirstParameter = NULL;
1811
1812 //
1813 // Process the command line
1814 //
1815 Status = ProcessCommandLineToFinal(&Temp);
1816
1817 if (!EFI_ERROR(Status)) {
1818 FirstParameter = AllocateZeroPool(StrSize(CmdLine));
1819 if (FirstParameter == NULL) {
1820 SHELL_FREE_NON_NULL(Temp);
1821 return (EFI_OUT_OF_RESOURCES);
1822 }
1823 TempWalker = (CHAR16*)Temp;
1824 GetNextParameter(&TempWalker, &FirstParameter, StrSize(CmdLine));
1825
1826 if (GetOperationType(FirstParameter) == Unknown_Invalid) {
1827 ShellPrintHiiEx(-1, -1, NULL, STRING_TOKEN (STR_SHELL_NOT_FOUND), ShellInfoObject.HiiHandle, FirstParameter);
1828 SetLastError(SHELL_NOT_FOUND);
1829 Status = EFI_NOT_FOUND;
1830 }
1831 }
1832
1833 SHELL_FREE_NON_NULL(Temp);
1834 SHELL_FREE_NON_NULL(FirstParameter);
1835 return Status;
1836 }
1837
1838 /**
1839 Determine if a command line contains with a split contains only valid commands.
1840
1841 @param[in] CmdLine The command line to parse.
1842
1843 @retval EFI_SUCCESS CmdLine has only valid commands, application, or has no split.
1844 @retval EFI_ABORTED CmdLine has at least one invalid command or application.
1845 **/
1846 EFI_STATUS
1847 EFIAPI
1848 VerifySplit(
1849 IN CONST CHAR16 *CmdLine
1850 )
1851 {
1852 CONST CHAR16 *TempSpot;
1853 EFI_STATUS Status;
1854
1855 //
1856 // Verify up to the pipe or end character
1857 //
1858 Status = IsValidSplit(CmdLine);
1859 if (EFI_ERROR(Status)) {
1860 return (Status);
1861 }
1862
1863 //
1864 // If this was the only item, then get out
1865 //
1866 if (!ContainsSplit(CmdLine)) {
1867 return (EFI_SUCCESS);
1868 }
1869
1870 //
1871 // recurse to verify the next item
1872 //
1873 TempSpot = FindSplit(CmdLine)+1;
1874 return (VerifySplit(TempSpot));
1875 }
1876
1877 /**
1878 Process a split based operation.
1879
1880 @param[in] CmdLine pointer to the command line to process
1881
1882 @retval EFI_SUCCESS The operation was successful
1883 @return an error occured.
1884 **/
1885 EFI_STATUS
1886 EFIAPI
1887 ProcessNewSplitCommandLine(
1888 IN CONST CHAR16 *CmdLine
1889 )
1890 {
1891 SPLIT_LIST *Split;
1892 EFI_STATUS Status;
1893
1894 Status = VerifySplit(CmdLine);
1895 if (EFI_ERROR(Status)) {
1896 return (Status);
1897 }
1898
1899 Split = NULL;
1900
1901 //
1902 // are we in an existing split???
1903 //
1904 if (!IsListEmpty(&ShellInfoObject.SplitList.Link)) {
1905 Split = (SPLIT_LIST*)GetFirstNode(&ShellInfoObject.SplitList.Link);
1906 }
1907
1908 if (Split == NULL) {
1909 Status = RunSplitCommand(CmdLine, NULL, NULL);
1910 } else {
1911 Status = RunSplitCommand(CmdLine, Split->SplitStdIn, Split->SplitStdOut);
1912 }
1913 if (EFI_ERROR(Status)) {
1914 ShellPrintHiiEx(-1, -1, NULL, STRING_TOKEN (STR_SHELL_INVALID_SPLIT), ShellInfoObject.HiiHandle, CmdLine);
1915 }
1916 return (Status);
1917 }
1918
1919 /**
1920 Handle a request to change the current file system.
1921
1922 @param[in] CmdLine The passed in command line.
1923
1924 @retval EFI_SUCCESS The operation was successful.
1925 **/
1926 EFI_STATUS
1927 EFIAPI
1928 ChangeMappedDrive(
1929 IN CONST CHAR16 *CmdLine
1930 )
1931 {
1932 EFI_STATUS Status;
1933 Status = EFI_SUCCESS;
1934
1935 //
1936 // make sure we are the right operation
1937 //
1938 ASSERT(CmdLine[(StrLen(CmdLine)-1)] == L':' && StrStr(CmdLine, L" ") == NULL);
1939
1940 //
1941 // Call the protocol API to do the work
1942 //
1943 Status = ShellInfoObject.NewEfiShellProtocol->SetCurDir(NULL, CmdLine);
1944
1945 //
1946 // Report any errors
1947 //
1948 if (EFI_ERROR(Status)) {
1949 ShellPrintHiiEx(-1, -1, NULL, STRING_TOKEN (STR_SHELL_INVALID_MAPPING), ShellInfoObject.HiiHandle, CmdLine);
1950 }
1951
1952 return (Status);
1953 }
1954
1955 /**
1956 Reprocess the command line to direct all -? to the help command.
1957
1958 if found, will add "help" as argv[0], and move the rest later.
1959
1960 @param[in,out] CmdLine pointer to the command line to update
1961 **/
1962 EFI_STATUS
1963 EFIAPI
1964 DoHelpUpdate(
1965 IN OUT CHAR16 **CmdLine
1966 )
1967 {
1968 CHAR16 *CurrentParameter;
1969 CHAR16 *Walker;
1970 CHAR16 *LastWalker;
1971 CHAR16 *NewCommandLine;
1972 EFI_STATUS Status;
1973
1974 Status = EFI_SUCCESS;
1975
1976 CurrentParameter = AllocateZeroPool(StrSize(*CmdLine));
1977 if (CurrentParameter == NULL) {
1978 return (EFI_OUT_OF_RESOURCES);
1979 }
1980
1981 Walker = *CmdLine;
1982 while(Walker != NULL && *Walker != CHAR_NULL) {
1983 LastWalker = Walker;
1984 GetNextParameter(&Walker, &CurrentParameter, StrSize(*CmdLine));
1985 if (StrStr(CurrentParameter, L"-?") == CurrentParameter) {
1986 LastWalker[0] = L' ';
1987 LastWalker[1] = L' ';
1988 NewCommandLine = AllocateZeroPool(StrSize(L"help ") + StrSize(*CmdLine));
1989 if (NewCommandLine == NULL) {
1990 Status = EFI_OUT_OF_RESOURCES;
1991 break;
1992 }
1993
1994 //
1995 // We know the space is sufficient since we just calculated it.
1996 //
1997 StrnCpy(NewCommandLine, L"help ", 5);
1998 StrnCat(NewCommandLine, *CmdLine, StrLen(*CmdLine));
1999 SHELL_FREE_NON_NULL(*CmdLine);
2000 *CmdLine = NewCommandLine;
2001 break;
2002 }
2003 }
2004
2005 SHELL_FREE_NON_NULL(CurrentParameter);
2006
2007 return (Status);
2008 }
2009
2010 /**
2011 Function to update the shell variable "lasterror".
2012
2013 @param[in] ErrorCode the error code to put into lasterror.
2014 **/
2015 EFI_STATUS
2016 EFIAPI
2017 SetLastError(
2018 IN CONST SHELL_STATUS ErrorCode
2019 )
2020 {
2021 CHAR16 LeString[19];
2022 if (sizeof(EFI_STATUS) == sizeof(UINT64)) {
2023 UnicodeSPrint(LeString, sizeof(LeString), L"0x%Lx", ErrorCode);
2024 } else {
2025 UnicodeSPrint(LeString, sizeof(LeString), L"0x%x", ErrorCode);
2026 }
2027 DEBUG_CODE(InternalEfiShellSetEnv(L"debuglasterror", LeString, TRUE););
2028 InternalEfiShellSetEnv(L"lasterror", LeString, TRUE);
2029
2030 return (EFI_SUCCESS);
2031 }
2032
2033 /**
2034 Converts the command line to it's post-processed form. this replaces variables and alias' per UEFI Shell spec.
2035
2036 @param[in,out] CmdLine pointer to the command line to update
2037
2038 @retval EFI_SUCCESS The operation was successful
2039 @retval EFI_OUT_OF_RESOURCES A memory allocation failed.
2040 @return some other error occured
2041 **/
2042 EFI_STATUS
2043 EFIAPI
2044 ProcessCommandLineToFinal(
2045 IN OUT CHAR16 **CmdLine
2046 )
2047 {
2048 EFI_STATUS Status;
2049 TrimSpaces(CmdLine);
2050
2051 Status = ShellSubstituteAliases(CmdLine);
2052 if (EFI_ERROR(Status)) {
2053 return (Status);
2054 }
2055
2056 TrimSpaces(CmdLine);
2057
2058 Status = ShellSubstituteVariables(CmdLine);
2059 if (EFI_ERROR(Status)) {
2060 return (Status);
2061 }
2062 ASSERT (*CmdLine != NULL);
2063
2064 TrimSpaces(CmdLine);
2065
2066 //
2067 // update for help parsing
2068 //
2069 if (StrStr(*CmdLine, L"?") != NULL) {
2070 //
2071 // This may do nothing if the ? does not indicate help.
2072 // Save all the details for in the API below.
2073 //
2074 Status = DoHelpUpdate(CmdLine);
2075 }
2076
2077 TrimSpaces(CmdLine);
2078
2079 return (EFI_SUCCESS);
2080 }
2081
2082 /**
2083 Run an internal shell command.
2084
2085 This API will upadate the shell's environment since these commands are libraries.
2086
2087 @param[in] CmdLine the command line to run.
2088 @param[in] FirstParameter the first parameter on the command line
2089 @param[in] ParamProtocol the shell parameters protocol pointer
2090
2091 @retval EFI_SUCCESS The command was completed.
2092 @retval EFI_ABORTED The command's operation was aborted.
2093 **/
2094 EFI_STATUS
2095 EFIAPI
2096 RunInternalCommand(
2097 IN CONST CHAR16 *CmdLine,
2098 IN CHAR16 *FirstParameter,
2099 IN EFI_SHELL_PARAMETERS_PROTOCOL *ParamProtocol
2100 )
2101 {
2102 EFI_STATUS Status;
2103 UINTN Argc;
2104 CHAR16 **Argv;
2105 SHELL_STATUS CommandReturnedStatus;
2106 BOOLEAN LastError;
2107 CHAR16 *Walker;
2108 CHAR16 *NewCmdLine;
2109
2110 NewCmdLine = AllocateCopyPool (StrSize (CmdLine), CmdLine);
2111 if (NewCmdLine == NULL) {
2112 return EFI_OUT_OF_RESOURCES;
2113 }
2114
2115 for (Walker = NewCmdLine; Walker != NULL && *Walker != CHAR_NULL ; Walker++) {
2116 if (*Walker == L'^' && *(Walker+1) == L'#') {
2117 CopyMem(Walker, Walker+1, StrSize(Walker) - sizeof(Walker[0]));
2118 }
2119 }
2120
2121 //
2122 // get the argc and argv updated for internal commands
2123 //
2124 Status = UpdateArgcArgv(ParamProtocol, NewCmdLine, &Argv, &Argc);
2125 if (!EFI_ERROR(Status)) {
2126 //
2127 // Run the internal command.
2128 //
2129 Status = ShellCommandRunCommandHandler(FirstParameter, &CommandReturnedStatus, &LastError);
2130
2131 if (!EFI_ERROR(Status)) {
2132 //
2133 // Update last error status.
2134 // some commands do not update last error.
2135 //
2136 if (LastError) {
2137 SetLastError(CommandReturnedStatus);
2138 }
2139
2140 //
2141 // Pass thru the exitcode from the app.
2142 //
2143 if (ShellCommandGetExit()) {
2144 //
2145 // An Exit was requested ("exit" command), pass its value up.
2146 //
2147 Status = CommandReturnedStatus;
2148 } else if (CommandReturnedStatus != SHELL_SUCCESS && IsScriptOnlyCommand(FirstParameter)) {
2149 //
2150 // Always abort when a script only command fails for any reason
2151 //
2152 Status = EFI_ABORTED;
2153 } else if (ShellCommandGetCurrentScriptFile() != NULL && CommandReturnedStatus == SHELL_ABORTED) {
2154 //
2155 // Abort when in a script and a command aborted
2156 //
2157 Status = EFI_ABORTED;
2158 }
2159 }
2160 }
2161
2162 //
2163 // This is guarenteed to be called after UpdateArgcArgv no matter what else happened.
2164 // This is safe even if the update API failed. In this case, it may be a no-op.
2165 //
2166 RestoreArgcArgv(ParamProtocol, &Argv, &Argc);
2167
2168 //
2169 // If a script is running and the command is not a scipt only command, then
2170 // change return value to success so the script won't halt (unless aborted).
2171 //
2172 // Script only commands have to be able halt the script since the script will
2173 // not operate if they are failing.
2174 //
2175 if ( ShellCommandGetCurrentScriptFile() != NULL
2176 && !IsScriptOnlyCommand(FirstParameter)
2177 && Status != EFI_ABORTED
2178 ) {
2179 Status = EFI_SUCCESS;
2180 }
2181
2182 FreePool (NewCmdLine);
2183 return (Status);
2184 }
2185
2186 /**
2187 Function to run the command or file.
2188
2189 @param[in] Type the type of operation being run.
2190 @param[in] CmdLine the command line to run.
2191 @param[in] FirstParameter the first parameter on the command line
2192 @param[in] ParamProtocol the shell parameters protocol pointer
2193
2194 @retval EFI_SUCCESS The command was completed.
2195 @retval EFI_ABORTED The command's operation was aborted.
2196 **/
2197 EFI_STATUS
2198 EFIAPI
2199 RunCommandOrFile(
2200 IN SHELL_OPERATION_TYPES Type,
2201 IN CONST CHAR16 *CmdLine,
2202 IN CHAR16 *FirstParameter,
2203 IN EFI_SHELL_PARAMETERS_PROTOCOL *ParamProtocol
2204 )
2205 {
2206 EFI_STATUS Status;
2207 EFI_STATUS StartStatus;
2208 CHAR16 *CommandWithPath;
2209 EFI_DEVICE_PATH_PROTOCOL *DevPath;
2210 SHELL_STATUS CalleeExitStatus;
2211
2212 Status = EFI_SUCCESS;
2213 CommandWithPath = NULL;
2214 DevPath = NULL;
2215 CalleeExitStatus = SHELL_INVALID_PARAMETER;
2216
2217 switch (Type) {
2218 case Internal_Command:
2219 Status = RunInternalCommand(CmdLine, FirstParameter, ParamProtocol);
2220 break;
2221 case Script_File_Name:
2222 case Efi_Application:
2223 //
2224 // Process a fully qualified path
2225 //
2226 if (StrStr(FirstParameter, L":") != NULL) {
2227 ASSERT (CommandWithPath == NULL);
2228 if (ShellIsFile(FirstParameter) == EFI_SUCCESS) {
2229 CommandWithPath = StrnCatGrow(&CommandWithPath, NULL, FirstParameter, 0);
2230 }
2231 }
2232
2233 //
2234 // Process a relative path and also check in the path environment variable
2235 //
2236 if (CommandWithPath == NULL) {
2237 CommandWithPath = ShellFindFilePathEx(FirstParameter, mExecutableExtensions);
2238 }
2239
2240 //
2241 // This should be impossible now.
2242 //
2243 ASSERT(CommandWithPath != NULL);
2244
2245 //
2246 // Make sure that path is not just a directory (or not found)
2247 //
2248 if (!EFI_ERROR(ShellIsDirectory(CommandWithPath))) {
2249 ShellPrintHiiEx(-1, -1, NULL, STRING_TOKEN (STR_SHELL_NOT_FOUND), ShellInfoObject.HiiHandle, FirstParameter);
2250 SetLastError(SHELL_NOT_FOUND);
2251 }
2252 switch (Type) {
2253 case Script_File_Name:
2254 Status = RunScriptFile (CommandWithPath, NULL, CmdLine, ParamProtocol);
2255 break;
2256 case Efi_Application:
2257 //
2258 // Get the device path of the application image
2259 //
2260 DevPath = ShellInfoObject.NewEfiShellProtocol->GetDevicePathFromFilePath(CommandWithPath);
2261 if (DevPath == NULL){
2262 Status = EFI_OUT_OF_RESOURCES;
2263 break;
2264 }
2265
2266 //
2267 // Execute the device path
2268 //
2269 Status = InternalShellExecuteDevicePath(
2270 &gImageHandle,
2271 DevPath,
2272 CmdLine,
2273 NULL,
2274 &StartStatus
2275 );
2276
2277 SHELL_FREE_NON_NULL(DevPath);
2278
2279 if(EFI_ERROR (Status)) {
2280 CalleeExitStatus = (SHELL_STATUS) (Status & (~MAX_BIT));
2281 } else {
2282 CalleeExitStatus = (SHELL_STATUS) StartStatus;
2283 }
2284
2285 //
2286 // Update last error status.
2287 //
2288 // Status is an EFI_STATUS. Clear top bit to convert to SHELL_STATUS
2289 SetLastError(CalleeExitStatus);
2290 break;
2291 default:
2292 //
2293 // Do nothing.
2294 //
2295 break;
2296 }
2297 break;
2298 default:
2299 //
2300 // Do nothing.
2301 //
2302 break;
2303 }
2304
2305 SHELL_FREE_NON_NULL(CommandWithPath);
2306
2307 return (Status);
2308 }
2309
2310 /**
2311 Function to setup StdIn, StdErr, StdOut, and then run the command or file.
2312
2313 @param[in] Type the type of operation being run.
2314 @param[in] CmdLine the command line to run.
2315 @param[in] FirstParameter the first parameter on the command line.
2316 @param[in] ParamProtocol the shell parameters protocol pointer
2317
2318 @retval EFI_SUCCESS The command was completed.
2319 @retval EFI_ABORTED The command's operation was aborted.
2320 **/
2321 EFI_STATUS
2322 EFIAPI
2323 SetupAndRunCommandOrFile(
2324 IN SHELL_OPERATION_TYPES Type,
2325 IN CHAR16 *CmdLine,
2326 IN CHAR16 *FirstParameter,
2327 IN EFI_SHELL_PARAMETERS_PROTOCOL *ParamProtocol
2328 )
2329 {
2330 EFI_STATUS Status;
2331 SHELL_FILE_HANDLE OriginalStdIn;
2332 SHELL_FILE_HANDLE OriginalStdOut;
2333 SHELL_FILE_HANDLE OriginalStdErr;
2334 SYSTEM_TABLE_INFO OriginalSystemTableInfo;
2335
2336 //
2337 // Update the StdIn, StdOut, and StdErr for redirection to environment variables, files, etc... unicode and ASCII
2338 //
2339 Status = UpdateStdInStdOutStdErr(ParamProtocol, CmdLine, &OriginalStdIn, &OriginalStdOut, &OriginalStdErr, &OriginalSystemTableInfo);
2340
2341 //
2342 // The StdIn, StdOut, and StdErr are set up.
2343 // Now run the command, script, or application
2344 //
2345 if (!EFI_ERROR(Status)) {
2346 TrimSpaces(&CmdLine);
2347 Status = RunCommandOrFile(Type, CmdLine, FirstParameter, ParamProtocol);
2348 }
2349
2350 //
2351 // Now print errors
2352 //
2353 if (EFI_ERROR(Status)) {
2354 ShellPrintHiiEx(-1, -1, NULL, STRING_TOKEN (STR_SHELL_ERROR), ShellInfoObject.HiiHandle, (VOID*)(Status));
2355 }
2356
2357 //
2358 // put back the original StdIn, StdOut, and StdErr
2359 //
2360 RestoreStdInStdOutStdErr(ParamProtocol, &OriginalStdIn, &OriginalStdOut, &OriginalStdErr, &OriginalSystemTableInfo);
2361
2362 return (Status);
2363 }
2364
2365 /**
2366 Function will process and run a command line.
2367
2368 This will determine if the command line represents an internal shell
2369 command or dispatch an external application.
2370
2371 @param[in] CmdLine The command line to parse.
2372
2373 @retval EFI_SUCCESS The command was completed.
2374 @retval EFI_ABORTED The command's operation was aborted.
2375 **/
2376 EFI_STATUS
2377 EFIAPI
2378 RunCommand(
2379 IN CONST CHAR16 *CmdLine
2380 )
2381 {
2382 EFI_STATUS Status;
2383 CHAR16 *CleanOriginal;
2384 CHAR16 *FirstParameter;
2385 CHAR16 *TempWalker;
2386 SHELL_OPERATION_TYPES Type;
2387
2388 ASSERT(CmdLine != NULL);
2389 if (StrLen(CmdLine) == 0) {
2390 return (EFI_SUCCESS);
2391 }
2392
2393 Status = EFI_SUCCESS;
2394 CleanOriginal = NULL;
2395
2396 CleanOriginal = StrnCatGrow(&CleanOriginal, NULL, CmdLine, 0);
2397 if (CleanOriginal == NULL) {
2398 return (EFI_OUT_OF_RESOURCES);
2399 }
2400
2401 TrimSpaces(&CleanOriginal);
2402
2403 //
2404 // NULL out comments (leveraged from RunScriptFileHandle() ).
2405 // The # character on a line is used to denote that all characters on the same line
2406 // and to the right of the # are to be ignored by the shell.
2407 // Afterward, again remove spaces, in case any were between the last command-parameter and '#'.
2408 //
2409 for (TempWalker = CleanOriginal; TempWalker != NULL && *TempWalker != CHAR_NULL; TempWalker++) {
2410 if (*TempWalker == L'^') {
2411 if (*(TempWalker + 1) == L'#') {
2412 TempWalker++;
2413 }
2414 } else if (*TempWalker == L'#') {
2415 *TempWalker = CHAR_NULL;
2416 }
2417 }
2418
2419 TrimSpaces(&CleanOriginal);
2420
2421 //
2422 // Handle case that passed in command line is just 1 or more " " characters.
2423 //
2424 if (StrLen (CleanOriginal) == 0) {
2425 SHELL_FREE_NON_NULL(CleanOriginal);
2426 return (EFI_SUCCESS);
2427 }
2428
2429 Status = ProcessCommandLineToFinal(&CleanOriginal);
2430 if (EFI_ERROR(Status)) {
2431 SHELL_FREE_NON_NULL(CleanOriginal);
2432 return (Status);
2433 }
2434
2435 //
2436 // We dont do normal processing with a split command line (output from one command input to another)
2437 //
2438 if (ContainsSplit(CleanOriginal)) {
2439 Status = ProcessNewSplitCommandLine(CleanOriginal);
2440 SHELL_FREE_NON_NULL(CleanOriginal);
2441 return (Status);
2442 }
2443
2444 //
2445 // We need the first parameter information so we can determine the operation type
2446 //
2447 FirstParameter = AllocateZeroPool(StrSize(CleanOriginal));
2448 if (FirstParameter == NULL) {
2449 SHELL_FREE_NON_NULL(CleanOriginal);
2450 return (EFI_OUT_OF_RESOURCES);
2451 }
2452 TempWalker = CleanOriginal;
2453 GetNextParameter(&TempWalker, &FirstParameter, StrSize(CleanOriginal));
2454
2455 //
2456 // Depending on the first parameter we change the behavior
2457 //
2458 switch (Type = GetOperationType(FirstParameter)) {
2459 case File_Sys_Change:
2460 Status = ChangeMappedDrive (FirstParameter);
2461 break;
2462 case Internal_Command:
2463 case Script_File_Name:
2464 case Efi_Application:
2465 Status = SetupAndRunCommandOrFile(Type, CleanOriginal, FirstParameter, ShellInfoObject.NewShellParametersProtocol);
2466 break;
2467 default:
2468 //
2469 // Whatever was typed, it was invalid.
2470 //
2471 ShellPrintHiiEx(-1, -1, NULL, STRING_TOKEN (STR_SHELL_NOT_FOUND), ShellInfoObject.HiiHandle, FirstParameter);
2472 SetLastError(SHELL_NOT_FOUND);
2473 break;
2474 }
2475
2476 SHELL_FREE_NON_NULL(CleanOriginal);
2477 SHELL_FREE_NON_NULL(FirstParameter);
2478
2479 return (Status);
2480 }
2481
2482 STATIC CONST UINT16 InvalidChars[] = {L'*', L'?', L'<', L'>', L'\\', L'/', L'\"', 0x0001, 0x0002};
2483 /**
2484 Function determins if the CommandName COULD be a valid command. It does not determine whether
2485 this is a valid command. It only checks for invalid characters.
2486
2487 @param[in] CommandName The name to check
2488
2489 @retval TRUE CommandName could be a command name
2490 @retval FALSE CommandName could not be a valid command name
2491 **/
2492 BOOLEAN
2493 EFIAPI
2494 IsValidCommandName(
2495 IN CONST CHAR16 *CommandName
2496 )
2497 {
2498 UINTN Count;
2499 if (CommandName == NULL) {
2500 ASSERT(FALSE);
2501 return (FALSE);
2502 }
2503 for ( Count = 0
2504 ; Count < sizeof(InvalidChars) / sizeof(InvalidChars[0])
2505 ; Count++
2506 ){
2507 if (ScanMem16(CommandName, StrSize(CommandName), InvalidChars[Count]) != NULL) {
2508 return (FALSE);
2509 }
2510 }
2511 return (TRUE);
2512 }
2513
2514 /**
2515 Function to process a NSH script file via SHELL_FILE_HANDLE.
2516
2517 @param[in] Handle The handle to the already opened file.
2518 @param[in] Name The name of the script file.
2519
2520 @retval EFI_SUCCESS the script completed sucessfully
2521 **/
2522 EFI_STATUS
2523 EFIAPI
2524 RunScriptFileHandle (
2525 IN SHELL_FILE_HANDLE Handle,
2526 IN CONST CHAR16 *Name
2527 )
2528 {
2529 EFI_STATUS Status;
2530 SCRIPT_FILE *NewScriptFile;
2531 UINTN LoopVar;
2532 CHAR16 *CommandLine;
2533 CHAR16 *CommandLine2;
2534 CHAR16 *CommandLine3;
2535 SCRIPT_COMMAND_LIST *LastCommand;
2536 BOOLEAN Ascii;
2537 BOOLEAN PreScriptEchoState;
2538 BOOLEAN PreCommandEchoState;
2539 CONST CHAR16 *CurDir;
2540 UINTN LineCount;
2541 CHAR16 LeString[50];
2542
2543 ASSERT(!ShellCommandGetScriptExit());
2544
2545 PreScriptEchoState = ShellCommandGetEchoState();
2546
2547 NewScriptFile = (SCRIPT_FILE*)AllocateZeroPool(sizeof(SCRIPT_FILE));
2548 if (NewScriptFile == NULL) {
2549 return (EFI_OUT_OF_RESOURCES);
2550 }
2551
2552 //
2553 // Set up the name
2554 //
2555 ASSERT(NewScriptFile->ScriptName == NULL);
2556 NewScriptFile->ScriptName = StrnCatGrow(&NewScriptFile->ScriptName, NULL, Name, 0);
2557 if (NewScriptFile->ScriptName == NULL) {
2558 DeleteScriptFileStruct(NewScriptFile);
2559 return (EFI_OUT_OF_RESOURCES);
2560 }
2561
2562 //
2563 // Save the parameters (used to replace %0 to %9 later on)
2564 //
2565 NewScriptFile->Argc = ShellInfoObject.NewShellParametersProtocol->Argc;
2566 if (NewScriptFile->Argc != 0) {
2567 NewScriptFile->Argv = (CHAR16**)AllocateZeroPool(NewScriptFile->Argc * sizeof(CHAR16*));
2568 if (NewScriptFile->Argv == NULL) {
2569 DeleteScriptFileStruct(NewScriptFile);
2570 return (EFI_OUT_OF_RESOURCES);
2571 }
2572 for (LoopVar = 0 ; LoopVar < 10 && LoopVar < NewScriptFile->Argc; LoopVar++) {
2573 ASSERT(NewScriptFile->Argv[LoopVar] == NULL);
2574 NewScriptFile->Argv[LoopVar] = StrnCatGrow(&NewScriptFile->Argv[LoopVar], NULL, ShellInfoObject.NewShellParametersProtocol->Argv[LoopVar], 0);
2575 if (NewScriptFile->Argv[LoopVar] == NULL) {
2576 DeleteScriptFileStruct(NewScriptFile);
2577 return (EFI_OUT_OF_RESOURCES);
2578 }
2579 }
2580 } else {
2581 NewScriptFile->Argv = NULL;
2582 }
2583
2584 InitializeListHead(&NewScriptFile->CommandList);
2585 InitializeListHead(&NewScriptFile->SubstList);
2586
2587 //
2588 // Now build the list of all script commands.
2589 //
2590 LineCount = 0;
2591 while(!ShellFileHandleEof(Handle)) {
2592 CommandLine = ShellFileHandleReturnLine(Handle, &Ascii);
2593 LineCount++;
2594 if (CommandLine == NULL || StrLen(CommandLine) == 0 || CommandLine[0] == '#') {
2595 SHELL_FREE_NON_NULL(CommandLine);
2596 continue;
2597 }
2598 NewScriptFile->CurrentCommand = AllocateZeroPool(sizeof(SCRIPT_COMMAND_LIST));
2599 if (NewScriptFile->CurrentCommand == NULL) {
2600 SHELL_FREE_NON_NULL(CommandLine);
2601 DeleteScriptFileStruct(NewScriptFile);
2602 return (EFI_OUT_OF_RESOURCES);
2603 }
2604
2605 NewScriptFile->CurrentCommand->Cl = CommandLine;
2606 NewScriptFile->CurrentCommand->Data = NULL;
2607 NewScriptFile->CurrentCommand->Line = LineCount;
2608
2609 InsertTailList(&NewScriptFile->CommandList, &NewScriptFile->CurrentCommand->Link);
2610 }
2611
2612 //
2613 // Add this as the topmost script file
2614 //
2615 ShellCommandSetNewScript (NewScriptFile);
2616
2617 //
2618 // Now enumerate through the commands and run each one.
2619 //
2620 CommandLine = AllocateZeroPool(PcdGet16(PcdShellPrintBufferSize));
2621 if (CommandLine == NULL) {
2622 DeleteScriptFileStruct(NewScriptFile);
2623 return (EFI_OUT_OF_RESOURCES);
2624 }
2625 CommandLine2 = AllocateZeroPool(PcdGet16(PcdShellPrintBufferSize));
2626 if (CommandLine2 == NULL) {
2627 FreePool(CommandLine);
2628 DeleteScriptFileStruct(NewScriptFile);
2629 return (EFI_OUT_OF_RESOURCES);
2630 }
2631
2632 for ( NewScriptFile->CurrentCommand = (SCRIPT_COMMAND_LIST *)GetFirstNode(&NewScriptFile->CommandList)
2633 ; !IsNull(&NewScriptFile->CommandList, &NewScriptFile->CurrentCommand->Link)
2634 ; // conditional increment in the body of the loop
2635 ){
2636 ASSERT(CommandLine2 != NULL);
2637 StrnCpy(CommandLine2, NewScriptFile->CurrentCommand->Cl, PcdGet16(PcdShellPrintBufferSize)/sizeof(CHAR16)-1);
2638
2639 //
2640 // NULL out comments
2641 //
2642 for (CommandLine3 = CommandLine2 ; CommandLine3 != NULL && *CommandLine3 != CHAR_NULL ; CommandLine3++) {
2643 if (*CommandLine3 == L'^') {
2644 if ( *(CommandLine3+1) == L':') {
2645 CopyMem(CommandLine3, CommandLine3+1, StrSize(CommandLine3) - sizeof(CommandLine3[0]));
2646 } else if (*(CommandLine3+1) == L'#') {
2647 CommandLine3++;
2648 }
2649 } else if (*CommandLine3 == L'#') {
2650 *CommandLine3 = CHAR_NULL;
2651 }
2652 }
2653
2654 if (CommandLine2 != NULL && StrLen(CommandLine2) >= 1) {
2655 //
2656 // Due to variability in starting the find and replace action we need to have both buffers the same.
2657 //
2658 StrnCpy(CommandLine, CommandLine2, PcdGet16(PcdShellPrintBufferSize)/sizeof(CHAR16)-1);
2659
2660 //
2661 // Remove the %0 to %9 from the command line (if we have some arguments)
2662 //
2663 if (NewScriptFile->Argv != NULL) {
2664 switch (NewScriptFile->Argc) {
2665 default:
2666 Status = ShellCopySearchAndReplace(CommandLine2, CommandLine, PcdGet16 (PcdShellPrintBufferSize), L"%9", NewScriptFile->Argv[9], FALSE, FALSE);
2667 ASSERT_EFI_ERROR(Status);
2668 case 9:
2669 Status = ShellCopySearchAndReplace(CommandLine, CommandLine2, PcdGet16 (PcdShellPrintBufferSize), L"%8", NewScriptFile->Argv[8], FALSE, FALSE);
2670 ASSERT_EFI_ERROR(Status);
2671 case 8:
2672 Status = ShellCopySearchAndReplace(CommandLine2, CommandLine, PcdGet16 (PcdShellPrintBufferSize), L"%7", NewScriptFile->Argv[7], FALSE, FALSE);
2673 ASSERT_EFI_ERROR(Status);
2674 case 7:
2675 Status = ShellCopySearchAndReplace(CommandLine, CommandLine2, PcdGet16 (PcdShellPrintBufferSize), L"%6", NewScriptFile->Argv[6], FALSE, FALSE);
2676 ASSERT_EFI_ERROR(Status);
2677 case 6:
2678 Status = ShellCopySearchAndReplace(CommandLine2, CommandLine, PcdGet16 (PcdShellPrintBufferSize), L"%5", NewScriptFile->Argv[5], FALSE, FALSE);
2679 ASSERT_EFI_ERROR(Status);
2680 case 5:
2681 Status = ShellCopySearchAndReplace(CommandLine, CommandLine2, PcdGet16 (PcdShellPrintBufferSize), L"%4", NewScriptFile->Argv[4], FALSE, FALSE);
2682 ASSERT_EFI_ERROR(Status);
2683 case 4:
2684 Status = ShellCopySearchAndReplace(CommandLine2, CommandLine, PcdGet16 (PcdShellPrintBufferSize), L"%3", NewScriptFile->Argv[3], FALSE, FALSE);
2685 ASSERT_EFI_ERROR(Status);
2686 case 3:
2687 Status = ShellCopySearchAndReplace(CommandLine, CommandLine2, PcdGet16 (PcdShellPrintBufferSize), L"%2", NewScriptFile->Argv[2], FALSE, FALSE);
2688 ASSERT_EFI_ERROR(Status);
2689 case 2:
2690 Status = ShellCopySearchAndReplace(CommandLine2, CommandLine, PcdGet16 (PcdShellPrintBufferSize), L"%1", NewScriptFile->Argv[1], FALSE, FALSE);
2691 ASSERT_EFI_ERROR(Status);
2692 case 1:
2693 Status = ShellCopySearchAndReplace(CommandLine, CommandLine2, PcdGet16 (PcdShellPrintBufferSize), L"%0", NewScriptFile->Argv[0], FALSE, FALSE);
2694 ASSERT_EFI_ERROR(Status);
2695 break;
2696 case 0:
2697 break;
2698 }
2699 }
2700 Status = ShellCopySearchAndReplace(CommandLine2, CommandLine, PcdGet16 (PcdShellPrintBufferSize), L"%1", L"\"\"", FALSE, FALSE);
2701 Status = ShellCopySearchAndReplace(CommandLine, CommandLine2, PcdGet16 (PcdShellPrintBufferSize), L"%2", L"\"\"", FALSE, FALSE);
2702 Status = ShellCopySearchAndReplace(CommandLine2, CommandLine, PcdGet16 (PcdShellPrintBufferSize), L"%3", L"\"\"", FALSE, FALSE);
2703 Status = ShellCopySearchAndReplace(CommandLine, CommandLine2, PcdGet16 (PcdShellPrintBufferSize), L"%4", L"\"\"", FALSE, FALSE);
2704 Status = ShellCopySearchAndReplace(CommandLine2, CommandLine, PcdGet16 (PcdShellPrintBufferSize), L"%5", L"\"\"", FALSE, FALSE);
2705 Status = ShellCopySearchAndReplace(CommandLine, CommandLine2, PcdGet16 (PcdShellPrintBufferSize), L"%6", L"\"\"", FALSE, FALSE);
2706 Status = ShellCopySearchAndReplace(CommandLine2, CommandLine, PcdGet16 (PcdShellPrintBufferSize), L"%7", L"\"\"", FALSE, FALSE);
2707 Status = ShellCopySearchAndReplace(CommandLine, CommandLine2, PcdGet16 (PcdShellPrintBufferSize), L"%8", L"\"\"", FALSE, FALSE);
2708 Status = ShellCopySearchAndReplace(CommandLine2, CommandLine, PcdGet16 (PcdShellPrintBufferSize), L"%9", L"\"\"", FALSE, FALSE);
2709
2710 StrnCpy(CommandLine2, CommandLine, PcdGet16(PcdShellPrintBufferSize)/sizeof(CHAR16)-1);
2711
2712 LastCommand = NewScriptFile->CurrentCommand;
2713
2714 for (CommandLine3 = CommandLine2 ; CommandLine3[0] == L' ' ; CommandLine3++);
2715
2716 if (CommandLine3 != NULL && CommandLine3[0] == L':' ) {
2717 //
2718 // This line is a goto target / label
2719 //
2720 } else {
2721 if (CommandLine3 != NULL && StrLen(CommandLine3) > 0) {
2722 if (CommandLine3[0] == L'@') {
2723 //
2724 // We need to save the current echo state
2725 // and disable echo for just this command.
2726 //
2727 PreCommandEchoState = ShellCommandGetEchoState();
2728 ShellCommandSetEchoState(FALSE);
2729 Status = RunCommand(CommandLine3+1);
2730
2731 //
2732 // If command was "@echo -off" or "@echo -on" then don't restore echo state
2733 //
2734 if (StrCmp (L"@echo -off", CommandLine3) != 0 &&
2735 StrCmp (L"@echo -on", CommandLine3) != 0) {
2736 //
2737 // Now restore the pre-'@' echo state.
2738 //
2739 ShellCommandSetEchoState(PreCommandEchoState);
2740 }
2741 } else {
2742 if (ShellCommandGetEchoState()) {
2743 CurDir = ShellInfoObject.NewEfiShellProtocol->GetEnv(L"cwd");
2744 if (CurDir != NULL && StrLen(CurDir) > 1) {
2745 ShellPrintHiiEx(-1, -1, NULL, STRING_TOKEN (STR_SHELL_CURDIR), ShellInfoObject.HiiHandle, CurDir);
2746 } else {
2747 ShellPrintHiiEx(-1, -1, NULL, STRING_TOKEN (STR_SHELL_SHELL), ShellInfoObject.HiiHandle);
2748 }
2749 ShellPrintEx(-1, -1, L"%s\r\n", CommandLine2);
2750 }
2751 Status = RunCommand(CommandLine3);
2752 }
2753 }
2754
2755 if (ShellCommandGetScriptExit()) {
2756 //
2757 // ShellCommandGetExitCode() always returns a UINT64
2758 //
2759 UnicodeSPrint(LeString, sizeof(LeString), L"0x%Lx", ShellCommandGetExitCode());
2760 DEBUG_CODE(InternalEfiShellSetEnv(L"debuglasterror", LeString, TRUE););
2761 InternalEfiShellSetEnv(L"lasterror", LeString, TRUE);
2762
2763 ShellCommandRegisterExit(FALSE, 0);
2764 Status = EFI_SUCCESS;
2765 break;
2766 }
2767 if (ShellGetExecutionBreakFlag()) {
2768 break;
2769 }
2770 if (EFI_ERROR(Status)) {
2771 break;
2772 }
2773 if (ShellCommandGetExit()) {
2774 break;
2775 }
2776 }
2777 //
2778 // If that commend did not update the CurrentCommand then we need to advance it...
2779 //
2780 if (LastCommand == NewScriptFile->CurrentCommand) {
2781 NewScriptFile->CurrentCommand = (SCRIPT_COMMAND_LIST *)GetNextNode(&NewScriptFile->CommandList, &NewScriptFile->CurrentCommand->Link);
2782 if (!IsNull(&NewScriptFile->CommandList, &NewScriptFile->CurrentCommand->Link)) {
2783 NewScriptFile->CurrentCommand->Reset = TRUE;
2784 }
2785 }
2786 } else {
2787 NewScriptFile->CurrentCommand = (SCRIPT_COMMAND_LIST *)GetNextNode(&NewScriptFile->CommandList, &NewScriptFile->CurrentCommand->Link);
2788 if (!IsNull(&NewScriptFile->CommandList, &NewScriptFile->CurrentCommand->Link)) {
2789 NewScriptFile->CurrentCommand->Reset = TRUE;
2790 }
2791 }
2792 }
2793
2794
2795 FreePool(CommandLine);
2796 FreePool(CommandLine2);
2797 ShellCommandSetNewScript (NULL);
2798
2799 //
2800 // Only if this was the last script reset the state.
2801 //
2802 if (ShellCommandGetCurrentScriptFile()==NULL) {
2803 ShellCommandSetEchoState(PreScriptEchoState);
2804 }
2805 return (EFI_SUCCESS);
2806 }
2807
2808 /**
2809 Function to process a NSH script file.
2810
2811 @param[in] ScriptPath Pointer to the script file name (including file system path).
2812 @param[in] Handle the handle of the script file already opened.
2813 @param[in] CmdLine the command line to run.
2814 @param[in] ParamProtocol the shell parameters protocol pointer
2815
2816 @retval EFI_SUCCESS the script completed sucessfully
2817 **/
2818 EFI_STATUS
2819 EFIAPI
2820 RunScriptFile (
2821 IN CONST CHAR16 *ScriptPath,
2822 IN SHELL_FILE_HANDLE Handle OPTIONAL,
2823 IN CONST CHAR16 *CmdLine,
2824 IN EFI_SHELL_PARAMETERS_PROTOCOL *ParamProtocol
2825 )
2826 {
2827 EFI_STATUS Status;
2828 SHELL_FILE_HANDLE FileHandle;
2829 UINTN Argc;
2830 CHAR16 **Argv;
2831
2832 if (ShellIsFile(ScriptPath) != EFI_SUCCESS) {
2833 return (EFI_INVALID_PARAMETER);
2834 }
2835
2836 //
2837 // get the argc and argv updated for scripts
2838 //
2839 Status = UpdateArgcArgv(ParamProtocol, CmdLine, &Argv, &Argc);
2840 if (!EFI_ERROR(Status)) {
2841
2842 if (Handle == NULL) {
2843 //
2844 // open the file
2845 //
2846 Status = ShellOpenFileByName(ScriptPath, &FileHandle, EFI_FILE_MODE_READ, 0);
2847 if (!EFI_ERROR(Status)) {
2848 //
2849 // run it
2850 //
2851 Status = RunScriptFileHandle(FileHandle, ScriptPath);
2852
2853 //
2854 // now close the file
2855 //
2856 ShellCloseFile(&FileHandle);
2857 }
2858 } else {
2859 Status = RunScriptFileHandle(Handle, ScriptPath);
2860 }
2861 }
2862
2863 //
2864 // This is guarenteed to be called after UpdateArgcArgv no matter what else happened.
2865 // This is safe even if the update API failed. In this case, it may be a no-op.
2866 //
2867 RestoreArgcArgv(ParamProtocol, &Argv, &Argc);
2868
2869 return (Status);
2870 }