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