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