]> git.proxmox.com Git - mirror_edk2.git/blob - ShellPkg/Application/Shell/Shell.c
ShellPkg: Fix MSFT C4255 warning
[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 VOID
730 )
731 {
732 EFI_STATUS Status;
733 CONST ALIAS_LIST *List;
734 ALIAS_LIST *Node;
735
736 //
737 // Get all the commands we want to run
738 //
739 List = ShellCommandGetInitAliasList();
740
741 //
742 // for each command in the List
743 //
744 for ( Node = (ALIAS_LIST*)GetFirstNode(&List->Link)
745 ; !IsNull (&List->Link, &Node->Link)
746 ; Node = (ALIAS_LIST *)GetNextNode(&List->Link, &Node->Link)
747 ){
748 //
749 // install the alias'
750 //
751 Status = InternalSetAlias(Node->CommandString, Node->Alias, TRUE);
752 ASSERT_EFI_ERROR(Status);
753 }
754 return (EFI_SUCCESS);
755 }
756
757 /**
758 Internal function to determine if 2 command names are really the same.
759
760 @param[in] Command1 The pointer to the first command name.
761 @param[in] Command2 The pointer to the second command name.
762
763 @retval TRUE The 2 command names are the same.
764 @retval FALSE The 2 command names are not the same.
765 **/
766 BOOLEAN
767 IsCommand(
768 IN CONST CHAR16 *Command1,
769 IN CONST CHAR16 *Command2
770 )
771 {
772 if (StringNoCaseCompare(&Command1, &Command2) == 0) {
773 return (TRUE);
774 }
775 return (FALSE);
776 }
777
778 /**
779 Internal function to determine if a command is a script only command.
780
781 @param[in] CommandName The pointer to the command name.
782
783 @retval TRUE The command is a script only command.
784 @retval FALSE The command is not a script only command.
785 **/
786 BOOLEAN
787 IsScriptOnlyCommand(
788 IN CONST CHAR16 *CommandName
789 )
790 {
791 if (IsCommand(CommandName, L"for")
792 ||IsCommand(CommandName, L"endfor")
793 ||IsCommand(CommandName, L"if")
794 ||IsCommand(CommandName, L"else")
795 ||IsCommand(CommandName, L"endif")
796 ||IsCommand(CommandName, L"goto")) {
797 return (TRUE);
798 }
799 return (FALSE);
800 }
801
802 /**
803 This function will populate the 2 device path protocol parameters based on the
804 global gImageHandle. The DevPath will point to the device path for the handle that has
805 loaded image protocol installed on it. The FilePath will point to the device path
806 for the file that was loaded.
807
808 @param[in, out] DevPath On a successful return the device path to the loaded image.
809 @param[in, out] FilePath On a successful return the device path to the file.
810
811 @retval EFI_SUCCESS The 2 device paths were successfully returned.
812 @retval other A error from gBS->HandleProtocol.
813
814 @sa HandleProtocol
815 **/
816 EFI_STATUS
817 GetDevicePathsForImageAndFile (
818 IN OUT EFI_DEVICE_PATH_PROTOCOL **DevPath,
819 IN OUT EFI_DEVICE_PATH_PROTOCOL **FilePath
820 )
821 {
822 EFI_STATUS Status;
823 EFI_LOADED_IMAGE_PROTOCOL *LoadedImage;
824 EFI_DEVICE_PATH_PROTOCOL *ImageDevicePath;
825
826 ASSERT(DevPath != NULL);
827 ASSERT(FilePath != NULL);
828
829 Status = gBS->OpenProtocol (
830 gImageHandle,
831 &gEfiLoadedImageProtocolGuid,
832 (VOID**)&LoadedImage,
833 gImageHandle,
834 NULL,
835 EFI_OPEN_PROTOCOL_GET_PROTOCOL
836 );
837 if (!EFI_ERROR (Status)) {
838 Status = gBS->OpenProtocol (
839 LoadedImage->DeviceHandle,
840 &gEfiDevicePathProtocolGuid,
841 (VOID**)&ImageDevicePath,
842 gImageHandle,
843 NULL,
844 EFI_OPEN_PROTOCOL_GET_PROTOCOL
845 );
846 if (!EFI_ERROR (Status)) {
847 *DevPath = DuplicateDevicePath (ImageDevicePath);
848 *FilePath = DuplicateDevicePath (LoadedImage->FilePath);
849 gBS->CloseProtocol(
850 LoadedImage->DeviceHandle,
851 &gEfiDevicePathProtocolGuid,
852 gImageHandle,
853 NULL);
854 }
855 gBS->CloseProtocol(
856 gImageHandle,
857 &gEfiLoadedImageProtocolGuid,
858 gImageHandle,
859 NULL);
860 }
861 return (Status);
862 }
863
864 /**
865 Process all Uefi Shell 2.0 command line options.
866
867 see Uefi Shell 2.0 section 3.2 for full details.
868
869 the command line must resemble the following:
870
871 shell.efi [ShellOpt-options] [options] [file-name [file-name-options]]
872
873 ShellOpt-options Options which control the initialization behavior of the shell.
874 These options are read from the EFI global variable "ShellOpt"
875 and are processed before options or file-name.
876
877 options Options which control the initialization behavior of the shell.
878
879 file-name The name of a UEFI shell application or script to be executed
880 after initialization is complete. By default, if file-name is
881 specified, then -nostartup is implied. Scripts are not supported
882 by level 0.
883
884 file-name-options The command-line options that are passed to file-name when it
885 is invoked.
886
887 This will initialize the ShellInfoObject.ShellInitSettings global variable.
888
889 @retval EFI_SUCCESS The variable is initialized.
890 **/
891 EFI_STATUS
892 ProcessCommandLine(
893 VOID
894 )
895 {
896 UINTN Size;
897 UINTN LoopVar;
898 CHAR16 *CurrentArg;
899 CHAR16 *DelayValueStr;
900 UINT64 DelayValue;
901 EFI_STATUS Status;
902 EFI_UNICODE_COLLATION_PROTOCOL *UnicodeCollation;
903
904 // `file-name-options` will contain arguments to `file-name` that we don't
905 // know about. This would cause ShellCommandLineParse to error, so we parse
906 // arguments manually, ignoring those after the first thing that doesn't look
907 // like a shell option (which is assumed to be `file-name`).
908
909 Status = gBS->LocateProtocol (
910 &gEfiUnicodeCollation2ProtocolGuid,
911 NULL,
912 (VOID **) &UnicodeCollation
913 );
914 if (EFI_ERROR (Status)) {
915 Status = gBS->LocateProtocol (
916 &gEfiUnicodeCollationProtocolGuid,
917 NULL,
918 (VOID **) &UnicodeCollation
919 );
920 if (EFI_ERROR (Status)) {
921 return Status;
922 }
923 }
924
925 // Set default options
926 ShellInfoObject.ShellInitSettings.BitUnion.Bits.Startup = FALSE;
927 ShellInfoObject.ShellInitSettings.BitUnion.Bits.NoStartup = FALSE;
928 ShellInfoObject.ShellInitSettings.BitUnion.Bits.NoConsoleOut = FALSE;
929 ShellInfoObject.ShellInitSettings.BitUnion.Bits.NoConsoleIn = FALSE;
930 ShellInfoObject.ShellInitSettings.BitUnion.Bits.NoInterrupt = FALSE;
931 ShellInfoObject.ShellInitSettings.BitUnion.Bits.NoMap = FALSE;
932 ShellInfoObject.ShellInitSettings.BitUnion.Bits.NoVersion = FALSE;
933 ShellInfoObject.ShellInitSettings.BitUnion.Bits.Delay = FALSE;
934 ShellInfoObject.ShellInitSettings.BitUnion.Bits.Exit = FALSE;
935 ShellInfoObject.ShellInitSettings.BitUnion.Bits.NoNest = FALSE;
936 ShellInfoObject.ShellInitSettings.Delay = 5;
937
938 //
939 // Start LoopVar at 0 to parse only optional arguments at Argv[0]
940 // and parse other parameters from Argv[1]. This is for use case that
941 // UEFI Shell boot option is created, and OptionalData is provided
942 // that starts with shell command-line options.
943 //
944 for (LoopVar = 0 ; LoopVar < gEfiShellParametersProtocol->Argc ; LoopVar++) {
945 CurrentArg = gEfiShellParametersProtocol->Argv[LoopVar];
946 if (UnicodeCollation->StriColl (
947 UnicodeCollation,
948 L"-startup",
949 CurrentArg
950 ) == 0) {
951 ShellInfoObject.ShellInitSettings.BitUnion.Bits.Startup = TRUE;
952 }
953 else if (UnicodeCollation->StriColl (
954 UnicodeCollation,
955 L"-nostartup",
956 CurrentArg
957 ) == 0) {
958 ShellInfoObject.ShellInitSettings.BitUnion.Bits.NoStartup = TRUE;
959 }
960 else if (UnicodeCollation->StriColl (
961 UnicodeCollation,
962 L"-noconsoleout",
963 CurrentArg
964 ) == 0) {
965 ShellInfoObject.ShellInitSettings.BitUnion.Bits.NoConsoleOut = TRUE;
966 }
967 else if (UnicodeCollation->StriColl (
968 UnicodeCollation,
969 L"-noconsolein",
970 CurrentArg
971 ) == 0) {
972 ShellInfoObject.ShellInitSettings.BitUnion.Bits.NoConsoleIn = TRUE;
973 }
974 else if (UnicodeCollation->StriColl (
975 UnicodeCollation,
976 L"-nointerrupt",
977 CurrentArg
978 ) == 0) {
979 ShellInfoObject.ShellInitSettings.BitUnion.Bits.NoInterrupt = TRUE;
980 }
981 else if (UnicodeCollation->StriColl (
982 UnicodeCollation,
983 L"-nomap",
984 CurrentArg
985 ) == 0) {
986 ShellInfoObject.ShellInitSettings.BitUnion.Bits.NoMap = TRUE;
987 }
988 else if (UnicodeCollation->StriColl (
989 UnicodeCollation,
990 L"-noversion",
991 CurrentArg
992 ) == 0) {
993 ShellInfoObject.ShellInitSettings.BitUnion.Bits.NoVersion = TRUE;
994 }
995 else if (UnicodeCollation->StriColl (
996 UnicodeCollation,
997 L"-nonest",
998 CurrentArg
999 ) == 0) {
1000 ShellInfoObject.ShellInitSettings.BitUnion.Bits.NoNest = TRUE;
1001 }
1002 else if (UnicodeCollation->StriColl (
1003 UnicodeCollation,
1004 L"-delay",
1005 CurrentArg
1006 ) == 0) {
1007 ShellInfoObject.ShellInitSettings.BitUnion.Bits.Delay = TRUE;
1008 // Check for optional delay value following "-delay"
1009 DelayValueStr = gEfiShellParametersProtocol->Argv[LoopVar + 1];
1010 if (DelayValueStr != NULL){
1011 if (*DelayValueStr == L':') {
1012 DelayValueStr++;
1013 }
1014 if (!EFI_ERROR(ShellConvertStringToUint64 (
1015 DelayValueStr,
1016 &DelayValue,
1017 FALSE,
1018 FALSE
1019 ))) {
1020 ShellInfoObject.ShellInitSettings.Delay = (UINTN)DelayValue;
1021 LoopVar++;
1022 }
1023 }
1024 } else if (UnicodeCollation->StriColl (
1025 UnicodeCollation,
1026 L"-exit",
1027 CurrentArg
1028 ) == 0) {
1029 ShellInfoObject.ShellInitSettings.BitUnion.Bits.Exit = TRUE;
1030 } else if (StrnCmp (L"-", CurrentArg, 1) == 0) {
1031 // Unrecognized option
1032 ShellPrintHiiEx(-1, -1, NULL,
1033 STRING_TOKEN (STR_GEN_PROBLEM),
1034 ShellInfoObject.HiiHandle,
1035 CurrentArg
1036 );
1037 return EFI_INVALID_PARAMETER;
1038 } else {
1039 //
1040 // First argument should be Shell.efi image name
1041 //
1042 if (LoopVar == 0) {
1043 continue;
1044 }
1045
1046 ShellInfoObject.ShellInitSettings.FileName = NULL;
1047 Size = 0;
1048 //
1049 // If first argument contains a space, then add double quotes before the argument
1050 //
1051 if (StrStr (CurrentArg, L" ") != NULL) {
1052 StrnCatGrow(&ShellInfoObject.ShellInitSettings.FileName, &Size, L"\"", 0);
1053 if (ShellInfoObject.ShellInitSettings.FileName == NULL) {
1054 return (EFI_OUT_OF_RESOURCES);
1055 }
1056 }
1057 StrnCatGrow(&ShellInfoObject.ShellInitSettings.FileName, &Size, CurrentArg, 0);
1058 if (ShellInfoObject.ShellInitSettings.FileName == NULL) {
1059 return (EFI_OUT_OF_RESOURCES);
1060 }
1061 //
1062 // If first argument contains a space, then add double quotes after the argument
1063 //
1064 if (StrStr (CurrentArg, L" ") != NULL) {
1065 StrnCatGrow(&ShellInfoObject.ShellInitSettings.FileName, &Size, L"\"", 0);
1066 if (ShellInfoObject.ShellInitSettings.FileName == NULL) {
1067 return (EFI_OUT_OF_RESOURCES);
1068 }
1069 }
1070 //
1071 // We found `file-name`.
1072 //
1073 ShellInfoObject.ShellInitSettings.BitUnion.Bits.NoStartup = 1;
1074 LoopVar++;
1075
1076 // Add `file-name-options`
1077 for (Size = 0 ; LoopVar < gEfiShellParametersProtocol->Argc ; LoopVar++) {
1078 ASSERT((ShellInfoObject.ShellInitSettings.FileOptions == NULL && Size == 0) || (ShellInfoObject.ShellInitSettings.FileOptions != NULL));
1079 //
1080 // Add a space between arguments
1081 //
1082 if (ShellInfoObject.ShellInitSettings.FileOptions != NULL) {
1083 StrnCatGrow(&ShellInfoObject.ShellInitSettings.FileOptions, &Size, L" ", 0);
1084 if (ShellInfoObject.ShellInitSettings.FileOptions == NULL) {
1085 SHELL_FREE_NON_NULL(ShellInfoObject.ShellInitSettings.FileName);
1086 return (EFI_OUT_OF_RESOURCES);
1087 }
1088 }
1089 //
1090 // If an argumnent contains a space, then add double quotes before the argument
1091 //
1092 if (StrStr (gEfiShellParametersProtocol->Argv[LoopVar], L" ") != NULL) {
1093 StrnCatGrow(&ShellInfoObject.ShellInitSettings.FileOptions,
1094 &Size,
1095 L"\"",
1096 0);
1097 if (ShellInfoObject.ShellInitSettings.FileOptions == NULL) {
1098 SHELL_FREE_NON_NULL(ShellInfoObject.ShellInitSettings.FileName);
1099 return (EFI_OUT_OF_RESOURCES);
1100 }
1101 }
1102 StrnCatGrow(&ShellInfoObject.ShellInitSettings.FileOptions,
1103 &Size,
1104 gEfiShellParametersProtocol->Argv[LoopVar],
1105 0);
1106 if (ShellInfoObject.ShellInitSettings.FileOptions == NULL) {
1107 SHELL_FREE_NON_NULL(ShellInfoObject.ShellInitSettings.FileName);
1108 return (EFI_OUT_OF_RESOURCES);
1109 }
1110 //
1111 // If an argumnent contains a space, then add double quotes after the argument
1112 //
1113 if (StrStr (gEfiShellParametersProtocol->Argv[LoopVar], L" ") != NULL) {
1114 StrnCatGrow(&ShellInfoObject.ShellInitSettings.FileOptions,
1115 &Size,
1116 L"\"",
1117 0);
1118 if (ShellInfoObject.ShellInitSettings.FileOptions == NULL) {
1119 SHELL_FREE_NON_NULL(ShellInfoObject.ShellInitSettings.FileName);
1120 return (EFI_OUT_OF_RESOURCES);
1121 }
1122 }
1123 }
1124 }
1125 }
1126
1127 // "-nointerrupt" overrides "-delay"
1128 if (ShellInfoObject.ShellInitSettings.BitUnion.Bits.NoInterrupt) {
1129 ShellInfoObject.ShellInitSettings.Delay = 0;
1130 }
1131
1132 return EFI_SUCCESS;
1133 }
1134
1135 /**
1136 Function try to find location of the Startup.nsh file.
1137
1138 The buffer is callee allocated and should be freed by the caller.
1139
1140 @param ImageDevicePath The path to the image for shell. first place to look for the startup script
1141 @param FileDevicePath The path to the file for shell. second place to look for the startup script.
1142
1143 @retval NULL No Startup.nsh file was found.
1144 @return !=NULL Pointer to NULL-terminated path.
1145 **/
1146 CHAR16 *
1147 LocateStartupScript (
1148 IN EFI_DEVICE_PATH_PROTOCOL *ImageDevicePath,
1149 IN EFI_DEVICE_PATH_PROTOCOL *FileDevicePath
1150 )
1151 {
1152 CHAR16 *StartupScriptPath;
1153 CHAR16 *TempSpot;
1154 CONST CHAR16 *MapName;
1155 UINTN Size;
1156
1157 StartupScriptPath = NULL;
1158 Size = 0;
1159
1160 //
1161 // Try to find 'Startup.nsh' in the directory where the shell itself was launched.
1162 //
1163 MapName = ShellInfoObject.NewEfiShellProtocol->GetMapFromDevicePath (&ImageDevicePath);
1164 if (MapName != NULL) {
1165 StartupScriptPath = StrnCatGrow (&StartupScriptPath, &Size, MapName, 0);
1166 if (StartupScriptPath == NULL) {
1167 //
1168 // Do not locate the startup script in sys path when out of resource.
1169 //
1170 return NULL;
1171 }
1172 TempSpot = StrStr (StartupScriptPath, L";");
1173 if (TempSpot != NULL) {
1174 *TempSpot = CHAR_NULL;
1175 }
1176
1177 StartupScriptPath = StrnCatGrow (&StartupScriptPath, &Size, ((FILEPATH_DEVICE_PATH *)FileDevicePath)->PathName, 0);
1178 PathRemoveLastItem (StartupScriptPath);
1179 StartupScriptPath = StrnCatGrow (&StartupScriptPath, &Size, mStartupScript, 0);
1180 }
1181
1182 //
1183 // Try to find 'Startup.nsh' in the execution path defined by the envrionment variable PATH.
1184 //
1185 if ((StartupScriptPath == NULL) || EFI_ERROR (ShellIsFile (StartupScriptPath))) {
1186 SHELL_FREE_NON_NULL (StartupScriptPath);
1187 StartupScriptPath = ShellFindFilePath (mStartupScript);
1188 }
1189
1190 return StartupScriptPath;
1191 }
1192
1193 /**
1194 Handles all interaction with the default startup script.
1195
1196 this will check that the correct command line parameters were passed, handle the delay, and then start running the script.
1197
1198 @param ImagePath the path to the image for shell. first place to look for the startup script
1199 @param FilePath the path to the file for shell. second place to look for the startup script.
1200
1201 @retval EFI_SUCCESS the variable is initialized.
1202 **/
1203 EFI_STATUS
1204 DoStartupScript(
1205 IN EFI_DEVICE_PATH_PROTOCOL *ImagePath,
1206 IN EFI_DEVICE_PATH_PROTOCOL *FilePath
1207 )
1208 {
1209 EFI_STATUS Status;
1210 EFI_STATUS CalleeStatus;
1211 UINTN Delay;
1212 EFI_INPUT_KEY Key;
1213 CHAR16 *FileStringPath;
1214 UINTN NewSize;
1215
1216 Key.UnicodeChar = CHAR_NULL;
1217 Key.ScanCode = 0;
1218
1219 if (!ShellInfoObject.ShellInitSettings.BitUnion.Bits.Startup && ShellInfoObject.ShellInitSettings.FileName != NULL) {
1220 //
1221 // launch something else instead
1222 //
1223 NewSize = StrSize(ShellInfoObject.ShellInitSettings.FileName);
1224 if (ShellInfoObject.ShellInitSettings.FileOptions != NULL) {
1225 NewSize += StrSize(ShellInfoObject.ShellInitSettings.FileOptions) + sizeof(CHAR16);
1226 }
1227 FileStringPath = AllocateZeroPool(NewSize);
1228 if (FileStringPath == NULL) {
1229 return (EFI_OUT_OF_RESOURCES);
1230 }
1231 StrCpyS(FileStringPath, NewSize/sizeof(CHAR16), ShellInfoObject.ShellInitSettings.FileName);
1232 if (ShellInfoObject.ShellInitSettings.FileOptions != NULL) {
1233 StrnCatS(FileStringPath, NewSize/sizeof(CHAR16), L" ", NewSize/sizeof(CHAR16) - StrLen(FileStringPath) -1);
1234 StrnCatS(FileStringPath, NewSize/sizeof(CHAR16), ShellInfoObject.ShellInitSettings.FileOptions, NewSize/sizeof(CHAR16) - StrLen(FileStringPath) -1);
1235 }
1236 Status = RunShellCommand(FileStringPath, &CalleeStatus);
1237 if (ShellInfoObject.ShellInitSettings.BitUnion.Bits.Exit == TRUE) {
1238 ShellCommandRegisterExit(gEfiShellProtocol->BatchIsActive(), (UINT64)CalleeStatus);
1239 }
1240 FreePool(FileStringPath);
1241 return (Status);
1242
1243 }
1244
1245 //
1246 // for shell level 0 we do no scripts
1247 // Without the Startup bit overriding we allow for nostartup to prevent scripts
1248 //
1249 if ( (PcdGet8(PcdShellSupportLevel) < 1)
1250 || (ShellInfoObject.ShellInitSettings.BitUnion.Bits.NoStartup && !ShellInfoObject.ShellInitSettings.BitUnion.Bits.Startup)
1251 ){
1252 return (EFI_SUCCESS);
1253 }
1254
1255 gST->ConOut->EnableCursor(gST->ConOut, FALSE);
1256 //
1257 // print out our warning and see if they press a key
1258 //
1259 for ( Status = EFI_UNSUPPORTED, Delay = ShellInfoObject.ShellInitSettings.Delay
1260 ; Delay != 0 && EFI_ERROR(Status)
1261 ; Delay--
1262 ){
1263 ShellPrintHiiEx(0, gST->ConOut->Mode->CursorRow, NULL, STRING_TOKEN (STR_SHELL_STARTUP_QUESTION), ShellInfoObject.HiiHandle, Delay);
1264 gBS->Stall (1000000);
1265 if (!ShellInfoObject.ShellInitSettings.BitUnion.Bits.NoConsoleIn) {
1266 Status = gST->ConIn->ReadKeyStroke (gST->ConIn, &Key);
1267 }
1268 }
1269 ShellPrintHiiEx(-1, -1, NULL, STRING_TOKEN (STR_SHELL_CRLF), ShellInfoObject.HiiHandle);
1270 gST->ConOut->EnableCursor(gST->ConOut, TRUE);
1271
1272 //
1273 // ESC was pressed
1274 //
1275 if (Status == EFI_SUCCESS && Key.UnicodeChar == 0 && Key.ScanCode == SCAN_ESC) {
1276 return (EFI_SUCCESS);
1277 }
1278
1279 FileStringPath = LocateStartupScript (ImagePath, FilePath);
1280 if (FileStringPath != NULL) {
1281 Status = RunScriptFile (FileStringPath, NULL, L"", ShellInfoObject.NewShellParametersProtocol);
1282 FreePool (FileStringPath);
1283 } else {
1284 //
1285 // we return success since startup script is not mandatory.
1286 //
1287 Status = EFI_SUCCESS;
1288 }
1289
1290 return (Status);
1291 }
1292
1293 /**
1294 Function to perform the shell prompt looping. It will do a single prompt,
1295 dispatch the result, and then return. It is expected that the caller will
1296 call this function in a loop many times.
1297
1298 @retval EFI_SUCCESS
1299 @retval RETURN_ABORTED
1300 **/
1301 EFI_STATUS
1302 DoShellPrompt (
1303 VOID
1304 )
1305 {
1306 UINTN Column;
1307 UINTN Row;
1308 CHAR16 *CmdLine;
1309 CONST CHAR16 *CurDir;
1310 UINTN BufferSize;
1311 EFI_STATUS Status;
1312 LIST_ENTRY OldBufferList;
1313
1314 CurDir = NULL;
1315
1316 //
1317 // Get screen setting to decide size of the command line buffer
1318 //
1319 gST->ConOut->QueryMode (gST->ConOut, gST->ConOut->Mode->Mode, &Column, &Row);
1320 BufferSize = Column * Row * sizeof (CHAR16);
1321 CmdLine = AllocateZeroPool (BufferSize);
1322 if (CmdLine == NULL) {
1323 return EFI_OUT_OF_RESOURCES;
1324 }
1325
1326 SaveBufferList(&OldBufferList);
1327 CurDir = ShellInfoObject.NewEfiShellProtocol->GetEnv(L"cwd");
1328
1329 //
1330 // Prompt for input
1331 //
1332 gST->ConOut->SetCursorPosition (gST->ConOut, 0, gST->ConOut->Mode->CursorRow);
1333
1334 if (CurDir != NULL && StrLen(CurDir) > 1) {
1335 ShellPrintHiiEx(-1, -1, NULL, STRING_TOKEN (STR_SHELL_CURDIR), ShellInfoObject.HiiHandle, CurDir);
1336 } else {
1337 ShellPrintHiiEx(-1, -1, NULL, STRING_TOKEN (STR_SHELL_SHELL), ShellInfoObject.HiiHandle);
1338 }
1339
1340 //
1341 // Read a line from the console
1342 //
1343 Status = ShellInfoObject.NewEfiShellProtocol->ReadFile(ShellInfoObject.NewShellParametersProtocol->StdIn, &BufferSize, CmdLine);
1344
1345 //
1346 // Null terminate the string and parse it
1347 //
1348 if (!EFI_ERROR (Status)) {
1349 CmdLine[BufferSize / sizeof (CHAR16)] = CHAR_NULL;
1350 Status = RunCommand(CmdLine);
1351 }
1352
1353 //
1354 // Done with this command
1355 //
1356 RestoreBufferList(&OldBufferList);
1357 FreePool (CmdLine);
1358 return Status;
1359 }
1360
1361 /**
1362 Add a buffer to the Buffer To Free List for safely returning buffers to other
1363 places without risking letting them modify internal shell information.
1364
1365 @param Buffer Something to pass to FreePool when the shell is exiting.
1366 **/
1367 VOID*
1368 AddBufferToFreeList (
1369 VOID *Buffer
1370 )
1371 {
1372 BUFFER_LIST *BufferListEntry;
1373
1374 if (Buffer == NULL) {
1375 return (NULL);
1376 }
1377
1378 BufferListEntry = AllocateZeroPool (sizeof (BUFFER_LIST));
1379 if (BufferListEntry == NULL) {
1380 return NULL;
1381 }
1382
1383 BufferListEntry->Buffer = Buffer;
1384 InsertTailList (&ShellInfoObject.BufferToFreeList.Link, &BufferListEntry->Link);
1385 return (Buffer);
1386 }
1387
1388
1389 /**
1390 Create a new buffer list and stores the old one to OldBufferList
1391
1392 @param OldBufferList The temporary list head used to store the nodes in BufferToFreeList.
1393 **/
1394 VOID
1395 SaveBufferList (
1396 OUT LIST_ENTRY *OldBufferList
1397 )
1398 {
1399 CopyMem (OldBufferList, &ShellInfoObject.BufferToFreeList.Link, sizeof (LIST_ENTRY));
1400 InitializeListHead (&ShellInfoObject.BufferToFreeList.Link);
1401 }
1402
1403 /**
1404 Restore previous nodes into BufferToFreeList .
1405
1406 @param OldBufferList The temporary list head used to store the nodes in BufferToFreeList.
1407 **/
1408 VOID
1409 RestoreBufferList (
1410 IN OUT LIST_ENTRY *OldBufferList
1411 )
1412 {
1413 FreeBufferList (&ShellInfoObject.BufferToFreeList);
1414 CopyMem (&ShellInfoObject.BufferToFreeList.Link, OldBufferList, sizeof (LIST_ENTRY));
1415 }
1416
1417
1418 /**
1419 Add a buffer to the Line History List
1420
1421 @param Buffer The line buffer to add.
1422 **/
1423 VOID
1424 AddLineToCommandHistory(
1425 IN CONST CHAR16 *Buffer
1426 )
1427 {
1428 BUFFER_LIST *Node;
1429 BUFFER_LIST *Walker;
1430 UINT16 MaxHistoryCmdCount;
1431 UINT16 Count;
1432
1433 Count = 0;
1434 MaxHistoryCmdCount = PcdGet16(PcdShellMaxHistoryCommandCount);
1435
1436 if (MaxHistoryCmdCount == 0) {
1437 return ;
1438 }
1439
1440
1441 Node = AllocateZeroPool(sizeof(BUFFER_LIST));
1442 if (Node == NULL) {
1443 return;
1444 }
1445
1446 Node->Buffer = AllocateCopyPool (StrSize (Buffer), Buffer);
1447 if (Node->Buffer == NULL) {
1448 FreePool (Node);
1449 return;
1450 }
1451
1452 for ( Walker = (BUFFER_LIST*)GetFirstNode(&ShellInfoObject.ViewingSettings.CommandHistory.Link)
1453 ; !IsNull(&ShellInfoObject.ViewingSettings.CommandHistory.Link, &Walker->Link)
1454 ; Walker = (BUFFER_LIST*)GetNextNode(&ShellInfoObject.ViewingSettings.CommandHistory.Link, &Walker->Link)
1455 ){
1456 Count++;
1457 }
1458 if (Count < MaxHistoryCmdCount){
1459 InsertTailList(&ShellInfoObject.ViewingSettings.CommandHistory.Link, &Node->Link);
1460 } else {
1461 Walker = (BUFFER_LIST*)GetFirstNode(&ShellInfoObject.ViewingSettings.CommandHistory.Link);
1462 RemoveEntryList(&Walker->Link);
1463 if (Walker->Buffer != NULL) {
1464 FreePool(Walker->Buffer);
1465 }
1466 FreePool(Walker);
1467 InsertTailList(&ShellInfoObject.ViewingSettings.CommandHistory.Link, &Node->Link);
1468 }
1469 }
1470
1471 /**
1472 Checks if a string is an alias for another command. If yes, then it replaces the alias name
1473 with the correct command name.
1474
1475 @param[in, out] CommandString Upon entry the potential alias. Upon return the
1476 command name if it was an alias. If it was not
1477 an alias it will be unchanged. This function may
1478 change the buffer to fit the command name.
1479
1480 @retval EFI_SUCCESS The name was changed.
1481 @retval EFI_SUCCESS The name was not an alias.
1482 @retval EFI_OUT_OF_RESOURCES A memory allocation failed.
1483 **/
1484 EFI_STATUS
1485 ShellConvertAlias(
1486 IN OUT CHAR16 **CommandString
1487 )
1488 {
1489 CONST CHAR16 *NewString;
1490
1491 NewString = ShellInfoObject.NewEfiShellProtocol->GetAlias(*CommandString, NULL);
1492 if (NewString == NULL) {
1493 return (EFI_SUCCESS);
1494 }
1495 FreePool(*CommandString);
1496 *CommandString = AllocateCopyPool(StrSize(NewString), NewString);
1497 if (*CommandString == NULL) {
1498 return (EFI_OUT_OF_RESOURCES);
1499 }
1500 return (EFI_SUCCESS);
1501 }
1502
1503 /**
1504 This function will eliminate unreplaced (and therefore non-found) environment variables.
1505
1506 @param[in,out] CmdLine The command line to update.
1507 **/
1508 EFI_STATUS
1509 StripUnreplacedEnvironmentVariables(
1510 IN OUT CHAR16 *CmdLine
1511 )
1512 {
1513 CHAR16 *FirstPercent;
1514 CHAR16 *FirstQuote;
1515 CHAR16 *SecondPercent;
1516 CHAR16 *SecondQuote;
1517 CHAR16 *CurrentLocator;
1518
1519 for (CurrentLocator = CmdLine ; CurrentLocator != NULL ; ) {
1520 FirstQuote = FindNextInstance(CurrentLocator, L"\"", TRUE);
1521 FirstPercent = FindNextInstance(CurrentLocator, L"%", TRUE);
1522 SecondPercent = FirstPercent!=NULL?FindNextInstance(FirstPercent+1, L"%", TRUE):NULL;
1523 if (FirstPercent == NULL || SecondPercent == NULL) {
1524 //
1525 // If we ever don't have 2 % we are done.
1526 //
1527 break;
1528 }
1529
1530 if (FirstQuote!= NULL && FirstQuote < FirstPercent) {
1531 SecondQuote = FindNextInstance(FirstQuote+1, L"\"", TRUE);
1532 //
1533 // Quote is first found
1534 //
1535
1536 if (SecondQuote < FirstPercent) {
1537 //
1538 // restart after the pair of "
1539 //
1540 CurrentLocator = SecondQuote + 1;
1541 } else /* FirstPercent < SecondQuote */{
1542 //
1543 // Restart on the first percent
1544 //
1545 CurrentLocator = FirstPercent;
1546 }
1547 continue;
1548 }
1549
1550 if (FirstQuote == NULL || SecondPercent < FirstQuote) {
1551 if (IsValidEnvironmentVariableName(FirstPercent, SecondPercent)) {
1552 //
1553 // We need to remove from FirstPercent to SecondPercent
1554 //
1555 CopyMem(FirstPercent, SecondPercent + 1, StrSize(SecondPercent + 1));
1556 //
1557 // don't need to update the locator. both % characters are gone.
1558 //
1559 } else {
1560 CurrentLocator = SecondPercent + 1;
1561 }
1562 continue;
1563 }
1564 CurrentLocator = FirstQuote;
1565 }
1566 return (EFI_SUCCESS);
1567 }
1568
1569 /**
1570 Function allocates a new command line and replaces all instances of environment
1571 variable names that are correctly preset to their values.
1572
1573 If the return value is not NULL the memory must be caller freed.
1574
1575 @param[in] OriginalCommandLine The original command line
1576
1577 @retval NULL An error occurred.
1578 @return The new command line with no environment variables present.
1579 **/
1580 CHAR16*
1581 ShellConvertVariables (
1582 IN CONST CHAR16 *OriginalCommandLine
1583 )
1584 {
1585 CONST CHAR16 *MasterEnvList;
1586 UINTN NewSize;
1587 CHAR16 *NewCommandLine1;
1588 CHAR16 *NewCommandLine2;
1589 CHAR16 *Temp;
1590 UINTN ItemSize;
1591 CHAR16 *ItemTemp;
1592 SCRIPT_FILE *CurrentScriptFile;
1593 ALIAS_LIST *AliasListNode;
1594
1595 ASSERT(OriginalCommandLine != NULL);
1596
1597 ItemSize = 0;
1598 NewSize = StrSize(OriginalCommandLine);
1599 CurrentScriptFile = ShellCommandGetCurrentScriptFile();
1600 Temp = NULL;
1601
1602 ///@todo update this to handle the %0 - %9 for scripting only (borrow from line 1256 area) ? ? ?
1603
1604 //
1605 // calculate the size required for the post-conversion string...
1606 //
1607 if (CurrentScriptFile != NULL) {
1608 for (AliasListNode = (ALIAS_LIST*)GetFirstNode(&CurrentScriptFile->SubstList)
1609 ; !IsNull(&CurrentScriptFile->SubstList, &AliasListNode->Link)
1610 ; AliasListNode = (ALIAS_LIST*)GetNextNode(&CurrentScriptFile->SubstList, &AliasListNode->Link)
1611 ){
1612 for (Temp = StrStr(OriginalCommandLine, AliasListNode->Alias)
1613 ; Temp != NULL
1614 ; Temp = StrStr(Temp+1, AliasListNode->Alias)
1615 ){
1616 //
1617 // we need a preceding and if there is space no ^ preceding (if no space ignore)
1618 //
1619 if ((((Temp-OriginalCommandLine)>2) && *(Temp-2) != L'^') || ((Temp-OriginalCommandLine)<=2)) {
1620 NewSize += StrSize(AliasListNode->CommandString);
1621 }
1622 }
1623 }
1624 }
1625
1626 for (MasterEnvList = EfiShellGetEnv(NULL)
1627 ; MasterEnvList != NULL && *MasterEnvList != CHAR_NULL //&& *(MasterEnvList+1) != CHAR_NULL
1628 ; MasterEnvList += StrLen(MasterEnvList) + 1
1629 ){
1630 if (StrSize(MasterEnvList) > ItemSize) {
1631 ItemSize = StrSize(MasterEnvList);
1632 }
1633 for (Temp = StrStr(OriginalCommandLine, MasterEnvList)
1634 ; Temp != NULL
1635 ; Temp = StrStr(Temp+1, MasterEnvList)
1636 ){
1637 //
1638 // we need a preceding and following % and if there is space no ^ preceding (if no space ignore)
1639 //
1640 if (*(Temp-1) == L'%' && *(Temp+StrLen(MasterEnvList)) == L'%' &&
1641 ((((Temp-OriginalCommandLine)>2) && *(Temp-2) != L'^') || ((Temp-OriginalCommandLine)<=2))) {
1642 NewSize+=StrSize(EfiShellGetEnv(MasterEnvList));
1643 }
1644 }
1645 }
1646
1647 //
1648 // now do the replacements...
1649 //
1650 NewCommandLine1 = AllocateZeroPool (NewSize);
1651 NewCommandLine2 = AllocateZeroPool(NewSize);
1652 ItemTemp = AllocateZeroPool(ItemSize+(2*sizeof(CHAR16)));
1653 if (NewCommandLine1 == NULL || NewCommandLine2 == NULL || ItemTemp == NULL) {
1654 SHELL_FREE_NON_NULL(NewCommandLine1);
1655 SHELL_FREE_NON_NULL(NewCommandLine2);
1656 SHELL_FREE_NON_NULL(ItemTemp);
1657 return (NULL);
1658 }
1659 CopyMem (NewCommandLine1, OriginalCommandLine, StrSize (OriginalCommandLine));
1660
1661 for (MasterEnvList = EfiShellGetEnv(NULL)
1662 ; MasterEnvList != NULL && *MasterEnvList != CHAR_NULL
1663 ; MasterEnvList += StrLen(MasterEnvList) + 1
1664 ){
1665 StrCpyS( ItemTemp,
1666 ((ItemSize+(2*sizeof(CHAR16)))/sizeof(CHAR16)),
1667 L"%"
1668 );
1669 StrCatS( ItemTemp,
1670 ((ItemSize+(2*sizeof(CHAR16)))/sizeof(CHAR16)),
1671 MasterEnvList
1672 );
1673 StrCatS( ItemTemp,
1674 ((ItemSize+(2*sizeof(CHAR16)))/sizeof(CHAR16)),
1675 L"%"
1676 );
1677 ShellCopySearchAndReplace(NewCommandLine1, NewCommandLine2, NewSize, ItemTemp, EfiShellGetEnv(MasterEnvList), TRUE, FALSE);
1678 StrCpyS(NewCommandLine1, NewSize/sizeof(CHAR16), NewCommandLine2);
1679 }
1680 if (CurrentScriptFile != NULL) {
1681 for (AliasListNode = (ALIAS_LIST*)GetFirstNode(&CurrentScriptFile->SubstList)
1682 ; !IsNull(&CurrentScriptFile->SubstList, &AliasListNode->Link)
1683 ; AliasListNode = (ALIAS_LIST*)GetNextNode(&CurrentScriptFile->SubstList, &AliasListNode->Link)
1684 ){
1685 ShellCopySearchAndReplace(NewCommandLine1, NewCommandLine2, NewSize, AliasListNode->Alias, AliasListNode->CommandString, TRUE, FALSE);
1686 StrCpyS(NewCommandLine1, NewSize/sizeof(CHAR16), NewCommandLine2);
1687 }
1688 }
1689
1690 //
1691 // Remove non-existent environment variables
1692 //
1693 StripUnreplacedEnvironmentVariables(NewCommandLine1);
1694
1695 //
1696 // Now cleanup any straggler intentionally ignored "%" characters
1697 //
1698 ShellCopySearchAndReplace(NewCommandLine1, NewCommandLine2, NewSize, L"^%", L"%", TRUE, FALSE);
1699 StrCpyS(NewCommandLine1, NewSize/sizeof(CHAR16), NewCommandLine2);
1700
1701 FreePool(NewCommandLine2);
1702 FreePool(ItemTemp);
1703
1704 return (NewCommandLine1);
1705 }
1706
1707 /**
1708 Internal function to run a command line with pipe usage.
1709
1710 @param[in] CmdLine The pointer to the command line.
1711 @param[in] StdIn The pointer to the Standard input.
1712 @param[in] StdOut The pointer to the Standard output.
1713
1714 @retval EFI_SUCCESS The split command is executed successfully.
1715 @retval other Some error occurs when executing the split command.
1716 **/
1717 EFI_STATUS
1718 RunSplitCommand(
1719 IN CONST CHAR16 *CmdLine,
1720 IN SHELL_FILE_HANDLE StdIn,
1721 IN SHELL_FILE_HANDLE StdOut
1722 )
1723 {
1724 EFI_STATUS Status;
1725 CHAR16 *NextCommandLine;
1726 CHAR16 *OurCommandLine;
1727 UINTN Size1;
1728 UINTN Size2;
1729 SPLIT_LIST *Split;
1730 SHELL_FILE_HANDLE TempFileHandle;
1731 BOOLEAN Unicode;
1732
1733 ASSERT(StdOut == NULL);
1734
1735 ASSERT(StrStr(CmdLine, L"|") != NULL);
1736
1737 Status = EFI_SUCCESS;
1738 NextCommandLine = NULL;
1739 OurCommandLine = NULL;
1740 Size1 = 0;
1741 Size2 = 0;
1742
1743 NextCommandLine = StrnCatGrow(&NextCommandLine, &Size1, StrStr(CmdLine, L"|")+1, 0);
1744 OurCommandLine = StrnCatGrow(&OurCommandLine , &Size2, CmdLine , StrStr(CmdLine, L"|") - CmdLine);
1745
1746 if (NextCommandLine == NULL || OurCommandLine == NULL) {
1747 SHELL_FREE_NON_NULL(OurCommandLine);
1748 SHELL_FREE_NON_NULL(NextCommandLine);
1749 return (EFI_OUT_OF_RESOURCES);
1750 } else if (StrStr(OurCommandLine, L"|") != NULL || Size1 == 0 || Size2 == 0) {
1751 SHELL_FREE_NON_NULL(OurCommandLine);
1752 SHELL_FREE_NON_NULL(NextCommandLine);
1753 return (EFI_INVALID_PARAMETER);
1754 } else if (NextCommandLine[0] == L'a' &&
1755 (NextCommandLine[1] == L' ' || NextCommandLine[1] == CHAR_NULL)
1756 ){
1757 CopyMem(NextCommandLine, NextCommandLine+1, StrSize(NextCommandLine) - sizeof(NextCommandLine[0]));
1758 while (NextCommandLine[0] == L' ') {
1759 CopyMem(NextCommandLine, NextCommandLine+1, StrSize(NextCommandLine) - sizeof(NextCommandLine[0]));
1760 }
1761 if (NextCommandLine[0] == CHAR_NULL) {
1762 SHELL_FREE_NON_NULL(OurCommandLine);
1763 SHELL_FREE_NON_NULL(NextCommandLine);
1764 return (EFI_INVALID_PARAMETER);
1765 }
1766 Unicode = FALSE;
1767 } else {
1768 Unicode = TRUE;
1769 }
1770
1771
1772 //
1773 // make a SPLIT_LIST item and add to list
1774 //
1775 Split = AllocateZeroPool(sizeof(SPLIT_LIST));
1776 if (Split == NULL) {
1777 return EFI_OUT_OF_RESOURCES;
1778 }
1779 Split->SplitStdIn = StdIn;
1780 Split->SplitStdOut = ConvertEfiFileProtocolToShellHandle(CreateFileInterfaceMem(Unicode), NULL);
1781 ASSERT(Split->SplitStdOut != NULL);
1782 InsertHeadList(&ShellInfoObject.SplitList.Link, &Split->Link);
1783
1784 Status = RunCommand(OurCommandLine);
1785
1786 //
1787 // move the output from the first to the in to the second.
1788 //
1789 TempFileHandle = Split->SplitStdOut;
1790 if (Split->SplitStdIn == StdIn) {
1791 Split->SplitStdOut = NULL;
1792 } else {
1793 Split->SplitStdOut = Split->SplitStdIn;
1794 }
1795 Split->SplitStdIn = TempFileHandle;
1796 ShellInfoObject.NewEfiShellProtocol->SetFilePosition (Split->SplitStdIn, 0);
1797
1798 if (!EFI_ERROR(Status)) {
1799 Status = RunCommand(NextCommandLine);
1800 }
1801
1802 //
1803 // remove the top level from the ScriptList
1804 //
1805 ASSERT((SPLIT_LIST*)GetFirstNode(&ShellInfoObject.SplitList.Link) == Split);
1806 RemoveEntryList(&Split->Link);
1807
1808 //
1809 // Note that the original StdIn is now the StdOut...
1810 //
1811 if (Split->SplitStdOut != NULL) {
1812 ShellInfoObject.NewEfiShellProtocol->CloseFile (Split->SplitStdOut);
1813 }
1814 if (Split->SplitStdIn != NULL) {
1815 ShellInfoObject.NewEfiShellProtocol->CloseFile (Split->SplitStdIn);
1816 }
1817
1818 FreePool(Split);
1819 FreePool(NextCommandLine);
1820 FreePool(OurCommandLine);
1821
1822 return (Status);
1823 }
1824
1825 /**
1826 Take the original command line, substitute any variables, free
1827 the original string, return the modified copy.
1828
1829 @param[in] CmdLine pointer to the command line to update.
1830
1831 @retval EFI_SUCCESS the function was successful.
1832 @retval EFI_OUT_OF_RESOURCES a memory allocation failed.
1833 **/
1834 EFI_STATUS
1835 ShellSubstituteVariables(
1836 IN CHAR16 **CmdLine
1837 )
1838 {
1839 CHAR16 *NewCmdLine;
1840 NewCmdLine = ShellConvertVariables(*CmdLine);
1841 SHELL_FREE_NON_NULL(*CmdLine);
1842 if (NewCmdLine == NULL) {
1843 return (EFI_OUT_OF_RESOURCES);
1844 }
1845 *CmdLine = NewCmdLine;
1846 return (EFI_SUCCESS);
1847 }
1848
1849 /**
1850 Take the original command line, substitute any alias in the first group of space delimited characters, free
1851 the original string, return the modified copy.
1852
1853 @param[in] CmdLine pointer to the command line to update.
1854
1855 @retval EFI_SUCCESS the function was successful.
1856 @retval EFI_OUT_OF_RESOURCES a memory allocation failed.
1857 **/
1858 EFI_STATUS
1859 ShellSubstituteAliases(
1860 IN CHAR16 **CmdLine
1861 )
1862 {
1863 CHAR16 *NewCmdLine;
1864 CHAR16 *CommandName;
1865 EFI_STATUS Status;
1866 UINTN PostAliasSize;
1867 ASSERT(CmdLine != NULL);
1868 ASSERT(*CmdLine!= NULL);
1869
1870
1871 CommandName = NULL;
1872 if (StrStr((*CmdLine), L" ") == NULL){
1873 StrnCatGrow(&CommandName, NULL, (*CmdLine), 0);
1874 } else {
1875 StrnCatGrow(&CommandName, NULL, (*CmdLine), StrStr((*CmdLine), L" ") - (*CmdLine));
1876 }
1877
1878 //
1879 // This cannot happen 'inline' since the CmdLine can need extra space.
1880 //
1881 NewCmdLine = NULL;
1882 if (!ShellCommandIsCommandOnList(CommandName)) {
1883 //
1884 // Convert via alias
1885 //
1886 Status = ShellConvertAlias(&CommandName);
1887 if (EFI_ERROR(Status)){
1888 return (Status);
1889 }
1890 PostAliasSize = 0;
1891 NewCmdLine = StrnCatGrow(&NewCmdLine, &PostAliasSize, CommandName, 0);
1892 if (NewCmdLine == NULL) {
1893 SHELL_FREE_NON_NULL(CommandName);
1894 SHELL_FREE_NON_NULL(*CmdLine);
1895 return (EFI_OUT_OF_RESOURCES);
1896 }
1897 NewCmdLine = StrnCatGrow(&NewCmdLine, &PostAliasSize, StrStr((*CmdLine), L" "), 0);
1898 if (NewCmdLine == NULL) {
1899 SHELL_FREE_NON_NULL(CommandName);
1900 SHELL_FREE_NON_NULL(*CmdLine);
1901 return (EFI_OUT_OF_RESOURCES);
1902 }
1903 } else {
1904 NewCmdLine = StrnCatGrow(&NewCmdLine, NULL, (*CmdLine), 0);
1905 }
1906
1907 SHELL_FREE_NON_NULL(*CmdLine);
1908 SHELL_FREE_NON_NULL(CommandName);
1909
1910 //
1911 // re-assign the passed in double pointer to point to our newly allocated buffer
1912 //
1913 *CmdLine = NewCmdLine;
1914
1915 return (EFI_SUCCESS);
1916 }
1917
1918 /**
1919 Takes the Argv[0] part of the command line and determine the meaning of it.
1920
1921 @param[in] CmdName pointer to the command line to update.
1922
1923 @retval Internal_Command The name is an internal command.
1924 @retval File_Sys_Change the name is a file system change.
1925 @retval Script_File_Name the name is a NSH script file.
1926 @retval Unknown_Invalid the name is unknown.
1927 @retval Efi_Application the name is an application (.EFI).
1928 **/
1929 SHELL_OPERATION_TYPES
1930 GetOperationType(
1931 IN CONST CHAR16 *CmdName
1932 )
1933 {
1934 CHAR16* FileWithPath;
1935 CONST CHAR16* TempLocation;
1936 CONST CHAR16* TempLocation2;
1937
1938 FileWithPath = NULL;
1939 //
1940 // test for an internal command.
1941 //
1942 if (ShellCommandIsCommandOnList(CmdName)) {
1943 return (Internal_Command);
1944 }
1945
1946 //
1947 // Test for file system change request. anything ending with first : and cant have spaces.
1948 //
1949 if (CmdName[(StrLen(CmdName)-1)] == L':') {
1950 if ( StrStr(CmdName, L" ") != NULL
1951 || StrLen(StrStr(CmdName, L":")) > 1
1952 ) {
1953 return (Unknown_Invalid);
1954 }
1955 return (File_Sys_Change);
1956 }
1957
1958 //
1959 // Test for a file
1960 //
1961 if ((FileWithPath = ShellFindFilePathEx(CmdName, mExecutableExtensions)) != NULL) {
1962 //
1963 // See if that file has a script file extension
1964 //
1965 if (StrLen(FileWithPath) > 4) {
1966 TempLocation = FileWithPath+StrLen(FileWithPath)-4;
1967 TempLocation2 = mScriptExtension;
1968 if (StringNoCaseCompare((VOID*)(&TempLocation), (VOID*)(&TempLocation2)) == 0) {
1969 SHELL_FREE_NON_NULL(FileWithPath);
1970 return (Script_File_Name);
1971 }
1972 }
1973
1974 //
1975 // Was a file, but not a script. we treat this as an application.
1976 //
1977 SHELL_FREE_NON_NULL(FileWithPath);
1978 return (Efi_Application);
1979 }
1980
1981 SHELL_FREE_NON_NULL(FileWithPath);
1982 //
1983 // No clue what this is... return invalid flag...
1984 //
1985 return (Unknown_Invalid);
1986 }
1987
1988 /**
1989 Determine if the first item in a command line is valid.
1990
1991 @param[in] CmdLine The command line to parse.
1992
1993 @retval EFI_SUCCESS The item is valid.
1994 @retval EFI_OUT_OF_RESOURCES A memory allocation failed.
1995 @retval EFI_NOT_FOUND The operation type is unknown or invalid.
1996 **/
1997 EFI_STATUS
1998 IsValidSplit(
1999 IN CONST CHAR16 *CmdLine
2000 )
2001 {
2002 CHAR16 *Temp;
2003 CHAR16 *FirstParameter;
2004 CHAR16 *TempWalker;
2005 EFI_STATUS Status;
2006
2007 Temp = NULL;
2008
2009 Temp = StrnCatGrow(&Temp, NULL, CmdLine, 0);
2010 if (Temp == NULL) {
2011 return (EFI_OUT_OF_RESOURCES);
2012 }
2013
2014 FirstParameter = StrStr(Temp, L"|");
2015 if (FirstParameter != NULL) {
2016 *FirstParameter = CHAR_NULL;
2017 }
2018
2019 FirstParameter = NULL;
2020
2021 //
2022 // Process the command line
2023 //
2024 Status = ProcessCommandLineToFinal(&Temp);
2025
2026 if (!EFI_ERROR(Status)) {
2027 FirstParameter = AllocateZeroPool(StrSize(CmdLine));
2028 if (FirstParameter == NULL) {
2029 SHELL_FREE_NON_NULL(Temp);
2030 return (EFI_OUT_OF_RESOURCES);
2031 }
2032 TempWalker = (CHAR16*)Temp;
2033 if (!EFI_ERROR(GetNextParameter(&TempWalker, &FirstParameter, StrSize(CmdLine), TRUE))) {
2034 if (GetOperationType(FirstParameter) == Unknown_Invalid) {
2035 ShellPrintHiiEx(-1, -1, NULL, STRING_TOKEN (STR_SHELL_NOT_FOUND), ShellInfoObject.HiiHandle, FirstParameter);
2036 SetLastError(SHELL_NOT_FOUND);
2037 Status = EFI_NOT_FOUND;
2038 }
2039 }
2040 }
2041
2042 SHELL_FREE_NON_NULL(Temp);
2043 SHELL_FREE_NON_NULL(FirstParameter);
2044 return Status;
2045 }
2046
2047 /**
2048 Determine if a command line contains with a split contains only valid commands.
2049
2050 @param[in] CmdLine The command line to parse.
2051
2052 @retval EFI_SUCCESS CmdLine has only valid commands, application, or has no split.
2053 @retval EFI_ABORTED CmdLine has at least one invalid command or application.
2054 **/
2055 EFI_STATUS
2056 VerifySplit(
2057 IN CONST CHAR16 *CmdLine
2058 )
2059 {
2060 CONST CHAR16 *TempSpot;
2061 EFI_STATUS Status;
2062
2063 //
2064 // If this was the only item, then get out
2065 //
2066 if (!ContainsSplit(CmdLine)) {
2067 return (EFI_SUCCESS);
2068 }
2069
2070 //
2071 // Verify up to the pipe or end character
2072 //
2073 Status = IsValidSplit(CmdLine);
2074 if (EFI_ERROR(Status)) {
2075 return (Status);
2076 }
2077
2078 //
2079 // recurse to verify the next item
2080 //
2081 TempSpot = FindFirstCharacter(CmdLine, L"|", L'^') + 1;
2082 if (*TempSpot == L'a' &&
2083 (*(TempSpot + 1) == L' ' || *(TempSpot + 1) == CHAR_NULL)
2084 ) {
2085 // If it's an ASCII pipe '|a'
2086 TempSpot += 1;
2087 }
2088
2089 return (VerifySplit(TempSpot));
2090 }
2091
2092 /**
2093 Process a split based operation.
2094
2095 @param[in] CmdLine pointer to the command line to process
2096
2097 @retval EFI_SUCCESS The operation was successful
2098 @return an error occurred.
2099 **/
2100 EFI_STATUS
2101 ProcessNewSplitCommandLine(
2102 IN CONST CHAR16 *CmdLine
2103 )
2104 {
2105 SPLIT_LIST *Split;
2106 EFI_STATUS Status;
2107
2108 Status = VerifySplit(CmdLine);
2109 if (EFI_ERROR(Status)) {
2110 return (Status);
2111 }
2112
2113 Split = NULL;
2114
2115 //
2116 // are we in an existing split???
2117 //
2118 if (!IsListEmpty(&ShellInfoObject.SplitList.Link)) {
2119 Split = (SPLIT_LIST*)GetFirstNode(&ShellInfoObject.SplitList.Link);
2120 }
2121
2122 if (Split == NULL) {
2123 Status = RunSplitCommand(CmdLine, NULL, NULL);
2124 } else {
2125 Status = RunSplitCommand(CmdLine, Split->SplitStdIn, Split->SplitStdOut);
2126 }
2127 if (EFI_ERROR(Status)) {
2128 ShellPrintHiiEx(-1, -1, NULL, STRING_TOKEN (STR_SHELL_INVALID_SPLIT), ShellInfoObject.HiiHandle, CmdLine);
2129 }
2130 return (Status);
2131 }
2132
2133 /**
2134 Handle a request to change the current file system.
2135
2136 @param[in] CmdLine The passed in command line.
2137
2138 @retval EFI_SUCCESS The operation was successful.
2139 **/
2140 EFI_STATUS
2141 ChangeMappedDrive(
2142 IN CONST CHAR16 *CmdLine
2143 )
2144 {
2145 EFI_STATUS Status;
2146 Status = EFI_SUCCESS;
2147
2148 //
2149 // make sure we are the right operation
2150 //
2151 ASSERT(CmdLine[(StrLen(CmdLine)-1)] == L':' && StrStr(CmdLine, L" ") == NULL);
2152
2153 //
2154 // Call the protocol API to do the work
2155 //
2156 Status = ShellInfoObject.NewEfiShellProtocol->SetCurDir(NULL, CmdLine);
2157
2158 //
2159 // Report any errors
2160 //
2161 if (EFI_ERROR(Status)) {
2162 ShellPrintHiiEx(-1, -1, NULL, STRING_TOKEN (STR_SHELL_INVALID_MAPPING), ShellInfoObject.HiiHandle, CmdLine);
2163 }
2164
2165 return (Status);
2166 }
2167
2168 /**
2169 Reprocess the command line to direct all -? to the help command.
2170
2171 if found, will add "help" as argv[0], and move the rest later.
2172
2173 @param[in,out] CmdLine pointer to the command line to update
2174 **/
2175 EFI_STATUS
2176 DoHelpUpdate(
2177 IN OUT CHAR16 **CmdLine
2178 )
2179 {
2180 CHAR16 *CurrentParameter;
2181 CHAR16 *Walker;
2182 CHAR16 *NewCommandLine;
2183 EFI_STATUS Status;
2184 UINTN NewCmdLineSize;
2185
2186 Status = EFI_SUCCESS;
2187
2188 CurrentParameter = AllocateZeroPool(StrSize(*CmdLine));
2189 if (CurrentParameter == NULL) {
2190 return (EFI_OUT_OF_RESOURCES);
2191 }
2192
2193 Walker = *CmdLine;
2194 while(Walker != NULL && *Walker != CHAR_NULL) {
2195 if (!EFI_ERROR(GetNextParameter(&Walker, &CurrentParameter, StrSize(*CmdLine), TRUE))) {
2196 if (StrStr(CurrentParameter, L"-?") == CurrentParameter) {
2197 CurrentParameter[0] = L' ';
2198 CurrentParameter[1] = L' ';
2199 NewCmdLineSize = StrSize(L"help ") + StrSize(*CmdLine);
2200 NewCommandLine = AllocateZeroPool(NewCmdLineSize);
2201 if (NewCommandLine == NULL) {
2202 Status = EFI_OUT_OF_RESOURCES;
2203 break;
2204 }
2205
2206 //
2207 // We know the space is sufficient since we just calculated it.
2208 //
2209 StrnCpyS(NewCommandLine, NewCmdLineSize/sizeof(CHAR16), L"help ", 5);
2210 StrnCatS(NewCommandLine, NewCmdLineSize/sizeof(CHAR16), *CmdLine, StrLen(*CmdLine));
2211 SHELL_FREE_NON_NULL(*CmdLine);
2212 *CmdLine = NewCommandLine;
2213 break;
2214 }
2215 }
2216 }
2217
2218 SHELL_FREE_NON_NULL(CurrentParameter);
2219
2220 return (Status);
2221 }
2222
2223 /**
2224 Function to update the shell variable "lasterror".
2225
2226 @param[in] ErrorCode the error code to put into lasterror.
2227 **/
2228 EFI_STATUS
2229 SetLastError(
2230 IN CONST SHELL_STATUS ErrorCode
2231 )
2232 {
2233 CHAR16 LeString[19];
2234 if (sizeof(EFI_STATUS) == sizeof(UINT64)) {
2235 UnicodeSPrint(LeString, sizeof(LeString), L"0x%Lx", ErrorCode);
2236 } else {
2237 UnicodeSPrint(LeString, sizeof(LeString), L"0x%x", ErrorCode);
2238 }
2239 DEBUG_CODE(InternalEfiShellSetEnv(L"debuglasterror", LeString, TRUE););
2240 InternalEfiShellSetEnv(L"lasterror", LeString, TRUE);
2241
2242 return (EFI_SUCCESS);
2243 }
2244
2245 /**
2246 Converts the command line to it's post-processed form. this replaces variables and alias' per UEFI Shell spec.
2247
2248 @param[in,out] CmdLine pointer to the command line to update
2249
2250 @retval EFI_SUCCESS The operation was successful
2251 @retval EFI_OUT_OF_RESOURCES A memory allocation failed.
2252 @return some other error occurred
2253 **/
2254 EFI_STATUS
2255 ProcessCommandLineToFinal(
2256 IN OUT CHAR16 **CmdLine
2257 )
2258 {
2259 EFI_STATUS Status;
2260 TrimSpaces(CmdLine);
2261
2262 Status = ShellSubstituteAliases(CmdLine);
2263 if (EFI_ERROR(Status)) {
2264 return (Status);
2265 }
2266
2267 TrimSpaces(CmdLine);
2268
2269 Status = ShellSubstituteVariables(CmdLine);
2270 if (EFI_ERROR(Status)) {
2271 return (Status);
2272 }
2273 ASSERT (*CmdLine != NULL);
2274
2275 TrimSpaces(CmdLine);
2276
2277 //
2278 // update for help parsing
2279 //
2280 if (StrStr(*CmdLine, L"?") != NULL) {
2281 //
2282 // This may do nothing if the ? does not indicate help.
2283 // Save all the details for in the API below.
2284 //
2285 Status = DoHelpUpdate(CmdLine);
2286 }
2287
2288 TrimSpaces(CmdLine);
2289
2290 return (EFI_SUCCESS);
2291 }
2292
2293 /**
2294 Run an internal shell command.
2295
2296 This API will update the shell's environment since these commands are libraries.
2297
2298 @param[in] CmdLine the command line to run.
2299 @param[in] FirstParameter the first parameter on the command line
2300 @param[in] ParamProtocol the shell parameters protocol pointer
2301 @param[out] CommandStatus the status from the command line.
2302
2303 @retval EFI_SUCCESS The command was completed.
2304 @retval EFI_ABORTED The command's operation was aborted.
2305 **/
2306 EFI_STATUS
2307 RunInternalCommand(
2308 IN CONST CHAR16 *CmdLine,
2309 IN CHAR16 *FirstParameter,
2310 IN EFI_SHELL_PARAMETERS_PROTOCOL *ParamProtocol,
2311 OUT EFI_STATUS *CommandStatus
2312 )
2313 {
2314 EFI_STATUS Status;
2315 UINTN Argc;
2316 CHAR16 **Argv;
2317 SHELL_STATUS CommandReturnedStatus;
2318 BOOLEAN LastError;
2319 CHAR16 *Walker;
2320 CHAR16 *NewCmdLine;
2321
2322 NewCmdLine = AllocateCopyPool (StrSize (CmdLine), CmdLine);
2323 if (NewCmdLine == NULL) {
2324 return EFI_OUT_OF_RESOURCES;
2325 }
2326
2327 for (Walker = NewCmdLine; Walker != NULL && *Walker != CHAR_NULL ; Walker++) {
2328 if (*Walker == L'^' && *(Walker+1) == L'#') {
2329 CopyMem(Walker, Walker+1, StrSize(Walker) - sizeof(Walker[0]));
2330 }
2331 }
2332
2333 //
2334 // get the argc and argv updated for internal commands
2335 //
2336 Status = UpdateArgcArgv(ParamProtocol, NewCmdLine, Internal_Command, &Argv, &Argc);
2337 if (!EFI_ERROR(Status)) {
2338 //
2339 // Run the internal command.
2340 //
2341 Status = ShellCommandRunCommandHandler(FirstParameter, &CommandReturnedStatus, &LastError);
2342
2343 if (!EFI_ERROR(Status)) {
2344 if (CommandStatus != NULL) {
2345 if (CommandReturnedStatus != SHELL_SUCCESS) {
2346 *CommandStatus = (EFI_STATUS)(CommandReturnedStatus | MAX_BIT);
2347 } else {
2348 *CommandStatus = EFI_SUCCESS;
2349 }
2350 }
2351
2352 //
2353 // Update last error status.
2354 // some commands do not update last error.
2355 //
2356 if (LastError) {
2357 SetLastError(CommandReturnedStatus);
2358 }
2359
2360 //
2361 // Pass thru the exitcode from the app.
2362 //
2363 if (ShellCommandGetExit()) {
2364 //
2365 // An Exit was requested ("exit" command), pass its value up.
2366 //
2367 Status = CommandReturnedStatus;
2368 } else if (CommandReturnedStatus != SHELL_SUCCESS && IsScriptOnlyCommand(FirstParameter)) {
2369 //
2370 // Always abort when a script only command fails for any reason
2371 //
2372 Status = EFI_ABORTED;
2373 } else if (ShellCommandGetCurrentScriptFile() != NULL && CommandReturnedStatus == SHELL_ABORTED) {
2374 //
2375 // Abort when in a script and a command aborted
2376 //
2377 Status = EFI_ABORTED;
2378 }
2379 }
2380 }
2381
2382 //
2383 // This is guaranteed to be called after UpdateArgcArgv no matter what else happened.
2384 // This is safe even if the update API failed. In this case, it may be a no-op.
2385 //
2386 RestoreArgcArgv(ParamProtocol, &Argv, &Argc);
2387
2388 //
2389 // If a script is running and the command is not a script only command, then
2390 // change return value to success so the script won't halt (unless aborted).
2391 //
2392 // Script only commands have to be able halt the script since the script will
2393 // not operate if they are failing.
2394 //
2395 if ( ShellCommandGetCurrentScriptFile() != NULL
2396 && !IsScriptOnlyCommand(FirstParameter)
2397 && Status != EFI_ABORTED
2398 ) {
2399 Status = EFI_SUCCESS;
2400 }
2401
2402 FreePool (NewCmdLine);
2403 return (Status);
2404 }
2405
2406 /**
2407 Function to run the command or file.
2408
2409 @param[in] Type the type of operation being run.
2410 @param[in] CmdLine the command line to run.
2411 @param[in] FirstParameter the first parameter on the command line
2412 @param[in] ParamProtocol the shell parameters protocol pointer
2413 @param[out] CommandStatus the status from the command line.
2414
2415 @retval EFI_SUCCESS The command was completed.
2416 @retval EFI_ABORTED The command's operation was aborted.
2417 **/
2418 EFI_STATUS
2419 RunCommandOrFile(
2420 IN SHELL_OPERATION_TYPES Type,
2421 IN CONST CHAR16 *CmdLine,
2422 IN CHAR16 *FirstParameter,
2423 IN EFI_SHELL_PARAMETERS_PROTOCOL *ParamProtocol,
2424 OUT EFI_STATUS *CommandStatus
2425 )
2426 {
2427 EFI_STATUS Status;
2428 EFI_STATUS StartStatus;
2429 CHAR16 *CommandWithPath;
2430 EFI_DEVICE_PATH_PROTOCOL *DevPath;
2431 SHELL_STATUS CalleeExitStatus;
2432
2433 Status = EFI_SUCCESS;
2434 CommandWithPath = NULL;
2435 DevPath = NULL;
2436 CalleeExitStatus = SHELL_INVALID_PARAMETER;
2437
2438 switch (Type) {
2439 case Internal_Command:
2440 Status = RunInternalCommand(CmdLine, FirstParameter, ParamProtocol, CommandStatus);
2441 break;
2442 case Script_File_Name:
2443 case Efi_Application:
2444 //
2445 // Process a fully qualified path
2446 //
2447 if (StrStr(FirstParameter, L":") != NULL) {
2448 ASSERT (CommandWithPath == NULL);
2449 if (ShellIsFile(FirstParameter) == EFI_SUCCESS) {
2450 CommandWithPath = StrnCatGrow(&CommandWithPath, NULL, FirstParameter, 0);
2451 }
2452 }
2453
2454 //
2455 // Process a relative path and also check in the path environment variable
2456 //
2457 if (CommandWithPath == NULL) {
2458 CommandWithPath = ShellFindFilePathEx(FirstParameter, mExecutableExtensions);
2459 }
2460
2461 //
2462 // This should be impossible now.
2463 //
2464 ASSERT(CommandWithPath != NULL);
2465
2466 //
2467 // Make sure that path is not just a directory (or not found)
2468 //
2469 if (!EFI_ERROR(ShellIsDirectory(CommandWithPath))) {
2470 ShellPrintHiiEx(-1, -1, NULL, STRING_TOKEN (STR_SHELL_NOT_FOUND), ShellInfoObject.HiiHandle, FirstParameter);
2471 SetLastError(SHELL_NOT_FOUND);
2472 }
2473 switch (Type) {
2474 case Script_File_Name:
2475 Status = RunScriptFile (CommandWithPath, NULL, CmdLine, ParamProtocol);
2476 break;
2477 case Efi_Application:
2478 //
2479 // Get the device path of the application image
2480 //
2481 DevPath = ShellInfoObject.NewEfiShellProtocol->GetDevicePathFromFilePath(CommandWithPath);
2482 if (DevPath == NULL){
2483 Status = EFI_OUT_OF_RESOURCES;
2484 break;
2485 }
2486
2487 //
2488 // Execute the device path
2489 //
2490 Status = InternalShellExecuteDevicePath(
2491 &gImageHandle,
2492 DevPath,
2493 CmdLine,
2494 NULL,
2495 &StartStatus
2496 );
2497
2498 SHELL_FREE_NON_NULL(DevPath);
2499
2500 if(EFI_ERROR (Status)) {
2501 CalleeExitStatus = (SHELL_STATUS) (Status & (~MAX_BIT));
2502 } else {
2503 CalleeExitStatus = (SHELL_STATUS) StartStatus;
2504 }
2505
2506 if (CommandStatus != NULL) {
2507 *CommandStatus = CalleeExitStatus;
2508 }
2509
2510 //
2511 // Update last error status.
2512 //
2513 // Status is an EFI_STATUS. Clear top bit to convert to SHELL_STATUS
2514 SetLastError(CalleeExitStatus);
2515 break;
2516 default:
2517 //
2518 // Do nothing.
2519 //
2520 break;
2521 }
2522 break;
2523 default:
2524 //
2525 // Do nothing.
2526 //
2527 break;
2528 }
2529
2530 SHELL_FREE_NON_NULL(CommandWithPath);
2531
2532 return (Status);
2533 }
2534
2535 /**
2536 Function to setup StdIn, StdErr, StdOut, and then run the command or file.
2537
2538 @param[in] Type the type of operation being run.
2539 @param[in] CmdLine the command line to run.
2540 @param[in] FirstParameter the first parameter on the command line.
2541 @param[in] ParamProtocol the shell parameters protocol pointer
2542 @param[out] CommandStatus the status from the command line.
2543
2544 @retval EFI_SUCCESS The command was completed.
2545 @retval EFI_ABORTED The command's operation was aborted.
2546 **/
2547 EFI_STATUS
2548 SetupAndRunCommandOrFile(
2549 IN SHELL_OPERATION_TYPES Type,
2550 IN CHAR16 *CmdLine,
2551 IN CHAR16 *FirstParameter,
2552 IN EFI_SHELL_PARAMETERS_PROTOCOL *ParamProtocol,
2553 OUT EFI_STATUS *CommandStatus
2554 )
2555 {
2556 EFI_STATUS Status;
2557 SHELL_FILE_HANDLE OriginalStdIn;
2558 SHELL_FILE_HANDLE OriginalStdOut;
2559 SHELL_FILE_HANDLE OriginalStdErr;
2560 SYSTEM_TABLE_INFO OriginalSystemTableInfo;
2561 CONST SCRIPT_FILE *ConstScriptFile;
2562
2563 //
2564 // Update the StdIn, StdOut, and StdErr for redirection to environment variables, files, etc... unicode and ASCII
2565 //
2566 Status = UpdateStdInStdOutStdErr(ParamProtocol, CmdLine, &OriginalStdIn, &OriginalStdOut, &OriginalStdErr, &OriginalSystemTableInfo);
2567
2568 //
2569 // The StdIn, StdOut, and StdErr are set up.
2570 // Now run the command, script, or application
2571 //
2572 if (!EFI_ERROR(Status)) {
2573 TrimSpaces(&CmdLine);
2574 Status = RunCommandOrFile(Type, CmdLine, FirstParameter, ParamProtocol, CommandStatus);
2575 }
2576
2577 //
2578 // Now print errors
2579 //
2580 if (EFI_ERROR(Status)) {
2581 ConstScriptFile = ShellCommandGetCurrentScriptFile();
2582 if (ConstScriptFile == NULL || ConstScriptFile->CurrentCommand == NULL) {
2583 ShellPrintHiiEx(-1, -1, NULL, STRING_TOKEN (STR_SHELL_ERROR), ShellInfoObject.HiiHandle, (VOID*)(Status));
2584 } else {
2585 ShellPrintHiiEx(-1, -1, NULL, STRING_TOKEN (STR_SHELL_ERROR_SCRIPT), ShellInfoObject.HiiHandle, (VOID*)(Status), ConstScriptFile->CurrentCommand->Line);
2586 }
2587 }
2588
2589 //
2590 // put back the original StdIn, StdOut, and StdErr
2591 //
2592 RestoreStdInStdOutStdErr(ParamProtocol, &OriginalStdIn, &OriginalStdOut, &OriginalStdErr, &OriginalSystemTableInfo);
2593
2594 return (Status);
2595 }
2596
2597 /**
2598 Function will process and run a command line.
2599
2600 This will determine if the command line represents an internal shell
2601 command or dispatch an external application.
2602
2603 @param[in] CmdLine The command line to parse.
2604 @param[out] CommandStatus The status from the command line.
2605
2606 @retval EFI_SUCCESS The command was completed.
2607 @retval EFI_ABORTED The command's operation was aborted.
2608 **/
2609 EFI_STATUS
2610 RunShellCommand(
2611 IN CONST CHAR16 *CmdLine,
2612 OUT EFI_STATUS *CommandStatus
2613 )
2614 {
2615 EFI_STATUS Status;
2616 CHAR16 *CleanOriginal;
2617 CHAR16 *FirstParameter;
2618 CHAR16 *TempWalker;
2619 SHELL_OPERATION_TYPES Type;
2620 CONST CHAR16 *CurDir;
2621
2622 ASSERT(CmdLine != NULL);
2623 if (StrLen(CmdLine) == 0) {
2624 return (EFI_SUCCESS);
2625 }
2626
2627 Status = EFI_SUCCESS;
2628 CleanOriginal = NULL;
2629
2630 CleanOriginal = StrnCatGrow(&CleanOriginal, NULL, CmdLine, 0);
2631 if (CleanOriginal == NULL) {
2632 return (EFI_OUT_OF_RESOURCES);
2633 }
2634
2635 TrimSpaces(&CleanOriginal);
2636
2637 //
2638 // NULL out comments (leveraged from RunScriptFileHandle() ).
2639 // The # character on a line is used to denote that all characters on the same line
2640 // and to the right of the # are to be ignored by the shell.
2641 // Afterwards, again remove spaces, in case any were between the last command-parameter and '#'.
2642 //
2643 for (TempWalker = CleanOriginal; TempWalker != NULL && *TempWalker != CHAR_NULL; TempWalker++) {
2644 if (*TempWalker == L'^') {
2645 if (*(TempWalker + 1) == L'#') {
2646 TempWalker++;
2647 }
2648 } else if (*TempWalker == L'#') {
2649 *TempWalker = CHAR_NULL;
2650 }
2651 }
2652
2653 TrimSpaces(&CleanOriginal);
2654
2655 //
2656 // Handle case that passed in command line is just 1 or more " " characters.
2657 //
2658 if (StrLen (CleanOriginal) == 0) {
2659 SHELL_FREE_NON_NULL(CleanOriginal);
2660 return (EFI_SUCCESS);
2661 }
2662
2663 Status = ProcessCommandLineToFinal(&CleanOriginal);
2664 if (EFI_ERROR(Status)) {
2665 SHELL_FREE_NON_NULL(CleanOriginal);
2666 return (Status);
2667 }
2668
2669 //
2670 // We don't do normal processing with a split command line (output from one command input to another)
2671 //
2672 if (ContainsSplit(CleanOriginal)) {
2673 Status = ProcessNewSplitCommandLine(CleanOriginal);
2674 SHELL_FREE_NON_NULL(CleanOriginal);
2675 return (Status);
2676 }
2677
2678 //
2679 // We need the first parameter information so we can determine the operation type
2680 //
2681 FirstParameter = AllocateZeroPool(StrSize(CleanOriginal));
2682 if (FirstParameter == NULL) {
2683 SHELL_FREE_NON_NULL(CleanOriginal);
2684 return (EFI_OUT_OF_RESOURCES);
2685 }
2686 TempWalker = CleanOriginal;
2687 if (!EFI_ERROR(GetNextParameter(&TempWalker, &FirstParameter, StrSize(CleanOriginal), TRUE))) {
2688 //
2689 // Depending on the first parameter we change the behavior
2690 //
2691 switch (Type = GetOperationType(FirstParameter)) {
2692 case File_Sys_Change:
2693 Status = ChangeMappedDrive (FirstParameter);
2694 break;
2695 case Internal_Command:
2696 case Script_File_Name:
2697 case Efi_Application:
2698 Status = SetupAndRunCommandOrFile(Type, CleanOriginal, FirstParameter, ShellInfoObject.NewShellParametersProtocol, CommandStatus);
2699 break;
2700 default:
2701 //
2702 // Whatever was typed, it was invalid.
2703 //
2704 ShellPrintHiiEx(-1, -1, NULL, STRING_TOKEN (STR_SHELL_NOT_FOUND), ShellInfoObject.HiiHandle, FirstParameter);
2705 SetLastError(SHELL_NOT_FOUND);
2706 break;
2707 }
2708 } else {
2709 ShellPrintHiiEx(-1, -1, NULL, STRING_TOKEN (STR_SHELL_NOT_FOUND), ShellInfoObject.HiiHandle, FirstParameter);
2710 SetLastError(SHELL_NOT_FOUND);
2711 }
2712 //
2713 // Check whether the current file system still exists. If not exist, we need update "cwd" and gShellCurMapping.
2714 //
2715 CurDir = EfiShellGetCurDir (NULL);
2716 if (CurDir != NULL) {
2717 if (EFI_ERROR(ShellFileExists (CurDir))) {
2718 //
2719 // EfiShellSetCurDir() cannot set current directory to NULL.
2720 // EfiShellSetEnv() is not allowed to set the "cwd" variable.
2721 // Only InternalEfiShellSetEnv () is allowed setting the "cwd" variable.
2722 //
2723 InternalEfiShellSetEnv (L"cwd", NULL, TRUE);
2724 gShellCurMapping = NULL;
2725 }
2726 }
2727
2728 SHELL_FREE_NON_NULL(CleanOriginal);
2729 SHELL_FREE_NON_NULL(FirstParameter);
2730
2731 return (Status);
2732 }
2733
2734 /**
2735 Function will process and run a command line.
2736
2737 This will determine if the command line represents an internal shell
2738 command or dispatch an external application.
2739
2740 @param[in] CmdLine The command line to parse.
2741
2742 @retval EFI_SUCCESS The command was completed.
2743 @retval EFI_ABORTED The command's operation was aborted.
2744 **/
2745 EFI_STATUS
2746 RunCommand(
2747 IN CONST CHAR16 *CmdLine
2748 )
2749 {
2750 return (RunShellCommand(CmdLine, NULL));
2751 }
2752
2753
2754 STATIC CONST UINT16 InvalidChars[] = {L'*', L'?', L'<', L'>', L'\\', L'/', L'\"', 0x0001, 0x0002};
2755 /**
2756 Function determines if the CommandName COULD be a valid command. It does not determine whether
2757 this is a valid command. It only checks for invalid characters.
2758
2759 @param[in] CommandName The name to check
2760
2761 @retval TRUE CommandName could be a command name
2762 @retval FALSE CommandName could not be a valid command name
2763 **/
2764 BOOLEAN
2765 IsValidCommandName(
2766 IN CONST CHAR16 *CommandName
2767 )
2768 {
2769 UINTN Count;
2770 if (CommandName == NULL) {
2771 ASSERT(FALSE);
2772 return (FALSE);
2773 }
2774 for ( Count = 0
2775 ; Count < sizeof(InvalidChars) / sizeof(InvalidChars[0])
2776 ; Count++
2777 ){
2778 if (ScanMem16(CommandName, StrSize(CommandName), InvalidChars[Count]) != NULL) {
2779 return (FALSE);
2780 }
2781 }
2782 return (TRUE);
2783 }
2784
2785 /**
2786 Function to process a NSH script file via SHELL_FILE_HANDLE.
2787
2788 @param[in] Handle The handle to the already opened file.
2789 @param[in] Name The name of the script file.
2790
2791 @retval EFI_SUCCESS the script completed successfully
2792 **/
2793 EFI_STATUS
2794 RunScriptFileHandle (
2795 IN SHELL_FILE_HANDLE Handle,
2796 IN CONST CHAR16 *Name
2797 )
2798 {
2799 EFI_STATUS Status;
2800 SCRIPT_FILE *NewScriptFile;
2801 UINTN LoopVar;
2802 UINTN PrintBuffSize;
2803 CHAR16 *CommandLine;
2804 CHAR16 *CommandLine2;
2805 CHAR16 *CommandLine3;
2806 SCRIPT_COMMAND_LIST *LastCommand;
2807 BOOLEAN Ascii;
2808 BOOLEAN PreScriptEchoState;
2809 BOOLEAN PreCommandEchoState;
2810 CONST CHAR16 *CurDir;
2811 UINTN LineCount;
2812 CHAR16 LeString[50];
2813 LIST_ENTRY OldBufferList;
2814
2815 ASSERT(!ShellCommandGetScriptExit());
2816
2817 PreScriptEchoState = ShellCommandGetEchoState();
2818 PrintBuffSize = PcdGet16(PcdShellPrintBufferSize);
2819
2820 NewScriptFile = (SCRIPT_FILE*)AllocateZeroPool(sizeof(SCRIPT_FILE));
2821 if (NewScriptFile == NULL) {
2822 return (EFI_OUT_OF_RESOURCES);
2823 }
2824
2825 //
2826 // Set up the name
2827 //
2828 ASSERT(NewScriptFile->ScriptName == NULL);
2829 NewScriptFile->ScriptName = StrnCatGrow(&NewScriptFile->ScriptName, NULL, Name, 0);
2830 if (NewScriptFile->ScriptName == NULL) {
2831 DeleteScriptFileStruct(NewScriptFile);
2832 return (EFI_OUT_OF_RESOURCES);
2833 }
2834
2835 //
2836 // Save the parameters (used to replace %0 to %9 later on)
2837 //
2838 NewScriptFile->Argc = ShellInfoObject.NewShellParametersProtocol->Argc;
2839 if (NewScriptFile->Argc != 0) {
2840 NewScriptFile->Argv = (CHAR16**)AllocateZeroPool(NewScriptFile->Argc * sizeof(CHAR16*));
2841 if (NewScriptFile->Argv == NULL) {
2842 DeleteScriptFileStruct(NewScriptFile);
2843 return (EFI_OUT_OF_RESOURCES);
2844 }
2845 for (LoopVar = 0 ; LoopVar < 10 && LoopVar < NewScriptFile->Argc; LoopVar++) {
2846 ASSERT(NewScriptFile->Argv[LoopVar] == NULL);
2847 NewScriptFile->Argv[LoopVar] = StrnCatGrow(&NewScriptFile->Argv[LoopVar], NULL, ShellInfoObject.NewShellParametersProtocol->Argv[LoopVar], 0);
2848 if (NewScriptFile->Argv[LoopVar] == NULL) {
2849 DeleteScriptFileStruct(NewScriptFile);
2850 return (EFI_OUT_OF_RESOURCES);
2851 }
2852 }
2853 } else {
2854 NewScriptFile->Argv = NULL;
2855 }
2856
2857 InitializeListHead(&NewScriptFile->CommandList);
2858 InitializeListHead(&NewScriptFile->SubstList);
2859
2860 //
2861 // Now build the list of all script commands.
2862 //
2863 LineCount = 0;
2864 while(!ShellFileHandleEof(Handle)) {
2865 CommandLine = ShellFileHandleReturnLine(Handle, &Ascii);
2866 LineCount++;
2867 if (CommandLine == NULL || StrLen(CommandLine) == 0 || CommandLine[0] == '#') {
2868 SHELL_FREE_NON_NULL(CommandLine);
2869 continue;
2870 }
2871 NewScriptFile->CurrentCommand = AllocateZeroPool(sizeof(SCRIPT_COMMAND_LIST));
2872 if (NewScriptFile->CurrentCommand == NULL) {
2873 SHELL_FREE_NON_NULL(CommandLine);
2874 DeleteScriptFileStruct(NewScriptFile);
2875 return (EFI_OUT_OF_RESOURCES);
2876 }
2877
2878 NewScriptFile->CurrentCommand->Cl = CommandLine;
2879 NewScriptFile->CurrentCommand->Data = NULL;
2880 NewScriptFile->CurrentCommand->Line = LineCount;
2881
2882 InsertTailList(&NewScriptFile->CommandList, &NewScriptFile->CurrentCommand->Link);
2883 }
2884
2885 //
2886 // Add this as the topmost script file
2887 //
2888 ShellCommandSetNewScript (NewScriptFile);
2889
2890 //
2891 // Now enumerate through the commands and run each one.
2892 //
2893 CommandLine = AllocateZeroPool(PrintBuffSize);
2894 if (CommandLine == NULL) {
2895 DeleteScriptFileStruct(NewScriptFile);
2896 return (EFI_OUT_OF_RESOURCES);
2897 }
2898 CommandLine2 = AllocateZeroPool(PrintBuffSize);
2899 if (CommandLine2 == NULL) {
2900 FreePool(CommandLine);
2901 DeleteScriptFileStruct(NewScriptFile);
2902 return (EFI_OUT_OF_RESOURCES);
2903 }
2904
2905 for ( NewScriptFile->CurrentCommand = (SCRIPT_COMMAND_LIST *)GetFirstNode(&NewScriptFile->CommandList)
2906 ; !IsNull(&NewScriptFile->CommandList, &NewScriptFile->CurrentCommand->Link)
2907 ; // conditional increment in the body of the loop
2908 ){
2909 ASSERT(CommandLine2 != NULL);
2910 StrnCpyS( CommandLine2,
2911 PrintBuffSize/sizeof(CHAR16),
2912 NewScriptFile->CurrentCommand->Cl,
2913 PrintBuffSize/sizeof(CHAR16) - 1
2914 );
2915
2916 SaveBufferList(&OldBufferList);
2917
2918 //
2919 // NULL out comments
2920 //
2921 for (CommandLine3 = CommandLine2 ; CommandLine3 != NULL && *CommandLine3 != CHAR_NULL ; CommandLine3++) {
2922 if (*CommandLine3 == L'^') {
2923 if ( *(CommandLine3+1) == L':') {
2924 CopyMem(CommandLine3, CommandLine3+1, StrSize(CommandLine3) - sizeof(CommandLine3[0]));
2925 } else if (*(CommandLine3+1) == L'#') {
2926 CommandLine3++;
2927 }
2928 } else if (*CommandLine3 == L'#') {
2929 *CommandLine3 = CHAR_NULL;
2930 }
2931 }
2932
2933 if (CommandLine2 != NULL && StrLen(CommandLine2) >= 1) {
2934 //
2935 // Due to variability in starting the find and replace action we need to have both buffers the same.
2936 //
2937 StrnCpyS( CommandLine,
2938 PrintBuffSize/sizeof(CHAR16),
2939 CommandLine2,
2940 PrintBuffSize/sizeof(CHAR16) - 1
2941 );
2942
2943 //
2944 // Remove the %0 to %9 from the command line (if we have some arguments)
2945 //
2946 if (NewScriptFile->Argv != NULL) {
2947 switch (NewScriptFile->Argc) {
2948 default:
2949 Status = ShellCopySearchAndReplace(CommandLine2, CommandLine, PrintBuffSize, L"%9", NewScriptFile->Argv[9], FALSE, FALSE);
2950 ASSERT_EFI_ERROR(Status);
2951 case 9:
2952 Status = ShellCopySearchAndReplace(CommandLine, CommandLine2, PrintBuffSize, L"%8", NewScriptFile->Argv[8], FALSE, FALSE);
2953 ASSERT_EFI_ERROR(Status);
2954 case 8:
2955 Status = ShellCopySearchAndReplace(CommandLine2, CommandLine, PrintBuffSize, L"%7", NewScriptFile->Argv[7], FALSE, FALSE);
2956 ASSERT_EFI_ERROR(Status);
2957 case 7:
2958 Status = ShellCopySearchAndReplace(CommandLine, CommandLine2, PrintBuffSize, L"%6", NewScriptFile->Argv[6], FALSE, FALSE);
2959 ASSERT_EFI_ERROR(Status);
2960 case 6:
2961 Status = ShellCopySearchAndReplace(CommandLine2, CommandLine, PrintBuffSize, L"%5", NewScriptFile->Argv[5], FALSE, FALSE);
2962 ASSERT_EFI_ERROR(Status);
2963 case 5:
2964 Status = ShellCopySearchAndReplace(CommandLine, CommandLine2, PrintBuffSize, L"%4", NewScriptFile->Argv[4], FALSE, FALSE);
2965 ASSERT_EFI_ERROR(Status);
2966 case 4:
2967 Status = ShellCopySearchAndReplace(CommandLine2, CommandLine, PrintBuffSize, L"%3", NewScriptFile->Argv[3], FALSE, FALSE);
2968 ASSERT_EFI_ERROR(Status);
2969 case 3:
2970 Status = ShellCopySearchAndReplace(CommandLine, CommandLine2, PrintBuffSize, L"%2", NewScriptFile->Argv[2], FALSE, FALSE);
2971 ASSERT_EFI_ERROR(Status);
2972 case 2:
2973 Status = ShellCopySearchAndReplace(CommandLine2, CommandLine, PrintBuffSize, L"%1", NewScriptFile->Argv[1], FALSE, FALSE);
2974 ASSERT_EFI_ERROR(Status);
2975 case 1:
2976 Status = ShellCopySearchAndReplace(CommandLine, CommandLine2, PrintBuffSize, L"%0", NewScriptFile->Argv[0], FALSE, FALSE);
2977 ASSERT_EFI_ERROR(Status);
2978 break;
2979 case 0:
2980 break;
2981 }
2982 }
2983 Status = ShellCopySearchAndReplace(CommandLine2, CommandLine, PrintBuffSize, L"%1", L"\"\"", FALSE, FALSE);
2984 Status = ShellCopySearchAndReplace(CommandLine, CommandLine2, PrintBuffSize, L"%2", L"\"\"", FALSE, FALSE);
2985 Status = ShellCopySearchAndReplace(CommandLine2, CommandLine, PrintBuffSize, L"%3", L"\"\"", FALSE, FALSE);
2986 Status = ShellCopySearchAndReplace(CommandLine, CommandLine2, PrintBuffSize, L"%4", L"\"\"", FALSE, FALSE);
2987 Status = ShellCopySearchAndReplace(CommandLine2, CommandLine, PrintBuffSize, L"%5", L"\"\"", FALSE, FALSE);
2988 Status = ShellCopySearchAndReplace(CommandLine, CommandLine2, PrintBuffSize, L"%6", L"\"\"", FALSE, FALSE);
2989 Status = ShellCopySearchAndReplace(CommandLine2, CommandLine, PrintBuffSize, L"%7", L"\"\"", FALSE, FALSE);
2990 Status = ShellCopySearchAndReplace(CommandLine, CommandLine2, PrintBuffSize, L"%8", L"\"\"", FALSE, FALSE);
2991 Status = ShellCopySearchAndReplace(CommandLine2, CommandLine, PrintBuffSize, L"%9", L"\"\"", FALSE, FALSE);
2992
2993 StrnCpyS( CommandLine2,
2994 PrintBuffSize/sizeof(CHAR16),
2995 CommandLine,
2996 PrintBuffSize/sizeof(CHAR16) - 1
2997 );
2998
2999 LastCommand = NewScriptFile->CurrentCommand;
3000
3001 for (CommandLine3 = CommandLine2 ; CommandLine3[0] == L' ' ; CommandLine3++);
3002
3003 if (CommandLine3 != NULL && CommandLine3[0] == L':' ) {
3004 //
3005 // This line is a goto target / label
3006 //
3007 } else {
3008 if (CommandLine3 != NULL && StrLen(CommandLine3) > 0) {
3009 if (CommandLine3[0] == L'@') {
3010 //
3011 // We need to save the current echo state
3012 // and disable echo for just this command.
3013 //
3014 PreCommandEchoState = ShellCommandGetEchoState();
3015 ShellCommandSetEchoState(FALSE);
3016 Status = RunCommand(CommandLine3+1);
3017
3018 //
3019 // If command was "@echo -off" or "@echo -on" then don't restore echo state
3020 //
3021 if (StrCmp (L"@echo -off", CommandLine3) != 0 &&
3022 StrCmp (L"@echo -on", CommandLine3) != 0) {
3023 //
3024 // Now restore the pre-'@' echo state.
3025 //
3026 ShellCommandSetEchoState(PreCommandEchoState);
3027 }
3028 } else {
3029 if (ShellCommandGetEchoState()) {
3030 CurDir = ShellInfoObject.NewEfiShellProtocol->GetEnv(L"cwd");
3031 if (CurDir != NULL && StrLen(CurDir) > 1) {
3032 ShellPrintHiiEx(-1, -1, NULL, STRING_TOKEN (STR_SHELL_CURDIR), ShellInfoObject.HiiHandle, CurDir);
3033 } else {
3034 ShellPrintHiiEx(-1, -1, NULL, STRING_TOKEN (STR_SHELL_SHELL), ShellInfoObject.HiiHandle);
3035 }
3036 ShellPrintEx(-1, -1, L"%s\r\n", CommandLine2);
3037 }
3038 Status = RunCommand(CommandLine3);
3039 }
3040 }
3041
3042 if (ShellCommandGetScriptExit()) {
3043 //
3044 // ShellCommandGetExitCode() always returns a UINT64
3045 //
3046 UnicodeSPrint(LeString, sizeof(LeString), L"0x%Lx", ShellCommandGetExitCode());
3047 DEBUG_CODE(InternalEfiShellSetEnv(L"debuglasterror", LeString, TRUE););
3048 InternalEfiShellSetEnv(L"lasterror", LeString, TRUE);
3049
3050 ShellCommandRegisterExit(FALSE, 0);
3051 Status = EFI_SUCCESS;
3052 RestoreBufferList(&OldBufferList);
3053 break;
3054 }
3055 if (ShellGetExecutionBreakFlag()) {
3056 RestoreBufferList(&OldBufferList);
3057 break;
3058 }
3059 if (EFI_ERROR(Status)) {
3060 RestoreBufferList(&OldBufferList);
3061 break;
3062 }
3063 if (ShellCommandGetExit()) {
3064 RestoreBufferList(&OldBufferList);
3065 break;
3066 }
3067 }
3068 //
3069 // If that commend did not update the CurrentCommand then we need to advance it...
3070 //
3071 if (LastCommand == NewScriptFile->CurrentCommand) {
3072 NewScriptFile->CurrentCommand = (SCRIPT_COMMAND_LIST *)GetNextNode(&NewScriptFile->CommandList, &NewScriptFile->CurrentCommand->Link);
3073 if (!IsNull(&NewScriptFile->CommandList, &NewScriptFile->CurrentCommand->Link)) {
3074 NewScriptFile->CurrentCommand->Reset = TRUE;
3075 }
3076 }
3077 } else {
3078 NewScriptFile->CurrentCommand = (SCRIPT_COMMAND_LIST *)GetNextNode(&NewScriptFile->CommandList, &NewScriptFile->CurrentCommand->Link);
3079 if (!IsNull(&NewScriptFile->CommandList, &NewScriptFile->CurrentCommand->Link)) {
3080 NewScriptFile->CurrentCommand->Reset = TRUE;
3081 }
3082 }
3083 RestoreBufferList(&OldBufferList);
3084 }
3085
3086
3087 FreePool(CommandLine);
3088 FreePool(CommandLine2);
3089 ShellCommandSetNewScript (NULL);
3090
3091 //
3092 // Only if this was the last script reset the state.
3093 //
3094 if (ShellCommandGetCurrentScriptFile()==NULL) {
3095 ShellCommandSetEchoState(PreScriptEchoState);
3096 }
3097 return (EFI_SUCCESS);
3098 }
3099
3100 /**
3101 Function to process a NSH script file.
3102
3103 @param[in] ScriptPath Pointer to the script file name (including file system path).
3104 @param[in] Handle the handle of the script file already opened.
3105 @param[in] CmdLine the command line to run.
3106 @param[in] ParamProtocol the shell parameters protocol pointer
3107
3108 @retval EFI_SUCCESS the script completed successfully
3109 **/
3110 EFI_STATUS
3111 RunScriptFile (
3112 IN CONST CHAR16 *ScriptPath,
3113 IN SHELL_FILE_HANDLE Handle OPTIONAL,
3114 IN CONST CHAR16 *CmdLine,
3115 IN EFI_SHELL_PARAMETERS_PROTOCOL *ParamProtocol
3116 )
3117 {
3118 EFI_STATUS Status;
3119 SHELL_FILE_HANDLE FileHandle;
3120 UINTN Argc;
3121 CHAR16 **Argv;
3122
3123 if (ShellIsFile(ScriptPath) != EFI_SUCCESS) {
3124 return (EFI_INVALID_PARAMETER);
3125 }
3126
3127 //
3128 // get the argc and argv updated for scripts
3129 //
3130 Status = UpdateArgcArgv(ParamProtocol, CmdLine, Script_File_Name, &Argv, &Argc);
3131 if (!EFI_ERROR(Status)) {
3132
3133 if (Handle == NULL) {
3134 //
3135 // open the file
3136 //
3137 Status = ShellOpenFileByName(ScriptPath, &FileHandle, EFI_FILE_MODE_READ, 0);
3138 if (!EFI_ERROR(Status)) {
3139 //
3140 // run it
3141 //
3142 Status = RunScriptFileHandle(FileHandle, ScriptPath);
3143
3144 //
3145 // now close the file
3146 //
3147 ShellCloseFile(&FileHandle);
3148 }
3149 } else {
3150 Status = RunScriptFileHandle(Handle, ScriptPath);
3151 }
3152 }
3153
3154 //
3155 // This is guaranteed to be called after UpdateArgcArgv no matter what else happened.
3156 // This is safe even if the update API failed. In this case, it may be a no-op.
3157 //
3158 RestoreArgcArgv(ParamProtocol, &Argv, &Argc);
3159
3160 return (Status);
3161 }
3162
3163 /**
3164 Return the pointer to the first occurrence of any character from a list of characters.
3165
3166 @param[in] String the string to parse
3167 @param[in] CharacterList the list of character to look for
3168 @param[in] EscapeCharacter An escape character to skip
3169
3170 @return the location of the first character in the string
3171 @retval CHAR_NULL no instance of any character in CharacterList was found in String
3172 **/
3173 CONST CHAR16*
3174 FindFirstCharacter(
3175 IN CONST CHAR16 *String,
3176 IN CONST CHAR16 *CharacterList,
3177 IN CONST CHAR16 EscapeCharacter
3178 )
3179 {
3180 UINT32 WalkChar;
3181 UINT32 WalkStr;
3182
3183 for (WalkStr = 0; WalkStr < StrLen(String); WalkStr++) {
3184 if (String[WalkStr] == EscapeCharacter) {
3185 WalkStr++;
3186 continue;
3187 }
3188 for (WalkChar = 0; WalkChar < StrLen(CharacterList); WalkChar++) {
3189 if (String[WalkStr] == CharacterList[WalkChar]) {
3190 return (&String[WalkStr]);
3191 }
3192 }
3193 }
3194 return (String + StrLen(String));
3195 }