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