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