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