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