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