X-Git-Url: https://git.proxmox.com/?p=mirror_edk2.git;a=blobdiff_plain;f=ShellPkg%2FApplication%2FShell%2FShell.c;h=41fa78004dcca81646bd377e7655a6506d5a9510;hp=3401bc064446abb8bb2520e6061e451cabc2fc24;hb=a308e0588b3ad87b94611391e9e7a04a8eb05ebf;hpb=a405b86d274d32b92f69842bfb9a1ab143128f57 diff --git a/ShellPkg/Application/Shell/Shell.c b/ShellPkg/Application/Shell/Shell.c index 3401bc0644..41fa78004d 100644 --- a/ShellPkg/Application/Shell/Shell.c +++ b/ShellPkg/Application/Shell/Shell.c @@ -1,7 +1,8 @@ /** @file This is THE shell (application) - Copyright (c) 2009 - 2010, Intel Corporation. All rights reserved.
+ Copyright (c) 2009 - 2014, Intel Corporation. All rights reserved.
+ (C) Copyright 2013-2014, Hewlett-Packard Development Company, L.P. This program and the accompanying materials are licensed and made available under the terms and conditions of the BSD License which accompanies this distribution. The full text of the license may be found at @@ -23,22 +24,24 @@ SHELL_INFO ShellInfoObject = { FALSE, FALSE, { - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, + {{ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0 + }}, 0, NULL, NULL }, - {0,0}, + {{NULL, NULL}, NULL}, { - {0,0}, + {{NULL, NULL}, NULL}, 0, 0, TRUE @@ -50,12 +53,174 @@ SHELL_INFO ShellInfoObject = { NULL, NULL, NULL, - {0,0,NULL,NULL}, - {0,0}, + {{NULL, NULL}, NULL, NULL}, + {{NULL, NULL}, NULL, NULL}, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + FALSE }; STATIC CONST CHAR16 mScriptExtension[] = L".NSH"; STATIC CONST CHAR16 mExecutableExtensions[] = L".NSH;.EFI"; +STATIC CONST CHAR16 mStartupScript[] = L"startup.nsh"; + +/** + Cleans off leading and trailing spaces and tabs. + + @param[in] String pointer to the string to trim them off. +**/ +EFI_STATUS +EFIAPI +TrimSpaces( + IN CHAR16 **String + ) +{ + ASSERT(String != NULL); + ASSERT(*String!= NULL); + // + // Remove any spaces and tabs at the beginning of the (*String). + // + while (((*String)[0] == L' ') || ((*String)[0] == L'\t')) { + CopyMem((*String), (*String)+1, StrSize((*String)) - sizeof((*String)[0])); + } + + // + // Remove any spaces and tabs at the end of the (*String). + // + while ((StrLen (*String) > 0) && (((*String)[StrLen((*String))-1] == L' ') || ((*String)[StrLen((*String))-1] == L'\t'))) { + (*String)[StrLen((*String))-1] = CHAR_NULL; + } + + return (EFI_SUCCESS); +} + +/** + Find a command line contains a split operation + + @param[in] CmdLine The command line to parse. + + @retval A pointer to the | character in CmdLine or NULL if not present. +**/ +CONST CHAR16* +EFIAPI +FindSplit( + IN CONST CHAR16 *CmdLine + ) +{ + CONST CHAR16 *TempSpot; + TempSpot = NULL; + if (StrStr(CmdLine, L"|") != NULL) { + for (TempSpot = CmdLine ; TempSpot != NULL && *TempSpot != CHAR_NULL ; TempSpot++) { + if (*TempSpot == L'^' && *(TempSpot+1) == L'|') { + TempSpot++; + } else if (*TempSpot == L'|') { + break; + } + } + } + return (TempSpot); +} + +/** + Determine if a command line contains a split operation + + @param[in] CmdLine The command line to parse. + + @retval TRUE CmdLine has a valid split. + @retval FALSE CmdLine does not have a valid split. +**/ +BOOLEAN +EFIAPI +ContainsSplit( + IN CONST CHAR16 *CmdLine + ) +{ + CONST CHAR16 *TempSpot; + TempSpot = FindSplit(CmdLine); + return (BOOLEAN) ((TempSpot != NULL) && (*TempSpot != CHAR_NULL)); +} + +/** + Function to start monitoring for CTRL-S using SimpleTextInputEx. This + feature's enabled state was not known when the shell initially launched. + + @retval EFI_SUCCESS The feature is enabled. + @retval EFI_OUT_OF_RESOURCES There is not enough mnemory available. +**/ +EFI_STATUS +EFIAPI +InternalEfiShellStartCtrlSMonitor( + VOID + ) +{ + EFI_SIMPLE_TEXT_INPUT_EX_PROTOCOL *SimpleEx; + EFI_KEY_DATA KeyData; + EFI_STATUS Status; + + Status = gBS->OpenProtocol( + gST->ConsoleInHandle, + &gEfiSimpleTextInputExProtocolGuid, + (VOID**)&SimpleEx, + gImageHandle, + NULL, + EFI_OPEN_PROTOCOL_GET_PROTOCOL); + if (EFI_ERROR(Status)) { + ShellPrintHiiEx( + -1, + -1, + NULL, + STRING_TOKEN (STR_SHELL_NO_IN_EX), + ShellInfoObject.HiiHandle); + return (EFI_SUCCESS); + } + + KeyData.KeyState.KeyToggleState = 0; + KeyData.Key.ScanCode = 0; + KeyData.KeyState.KeyShiftState = EFI_SHIFT_STATE_VALID|EFI_LEFT_CONTROL_PRESSED; + KeyData.Key.UnicodeChar = L's'; + + Status = SimpleEx->RegisterKeyNotify( + SimpleEx, + &KeyData, + NotificationFunction, + &ShellInfoObject.CtrlSNotifyHandle1); + + KeyData.KeyState.KeyShiftState = EFI_SHIFT_STATE_VALID|EFI_RIGHT_CONTROL_PRESSED; + if (!EFI_ERROR(Status)) { + Status = SimpleEx->RegisterKeyNotify( + SimpleEx, + &KeyData, + NotificationFunction, + &ShellInfoObject.CtrlSNotifyHandle2); + } + KeyData.KeyState.KeyShiftState = EFI_SHIFT_STATE_VALID|EFI_LEFT_CONTROL_PRESSED; + KeyData.Key.UnicodeChar = 19; + + if (!EFI_ERROR(Status)) { + Status = SimpleEx->RegisterKeyNotify( + SimpleEx, + &KeyData, + NotificationFunction, + &ShellInfoObject.CtrlSNotifyHandle3); + } + KeyData.KeyState.KeyShiftState = EFI_SHIFT_STATE_VALID|EFI_RIGHT_CONTROL_PRESSED; + if (!EFI_ERROR(Status)) { + Status = SimpleEx->RegisterKeyNotify( + SimpleEx, + &KeyData, + NotificationFunction, + &ShellInfoObject.CtrlSNotifyHandle4); + } + return (Status); +} + + /** The entry point for the application. @@ -74,17 +239,11 @@ UefiMain ( IN EFI_SYSTEM_TABLE *SystemTable ) { - EFI_STATUS Status; - CHAR16 *TempString; - UINTN Size; -// EFI_INPUT_KEY Key; - -// gST->ConOut->OutputString(gST->ConOut, L"ReadKeyStroke Calling\r\n"); -// -// Status = gST->ConIn->ReadKeyStroke (gST->ConIn, &Key); -// -// gST->ConOut->OutputString(gST->ConOut, L"ReadKeyStroke Done\r\n"); -// gBS->Stall (1000000); + EFI_STATUS Status; + CHAR16 *TempString; + UINTN Size; + EFI_HANDLE ConInHandle; + EFI_SIMPLE_TEXT_INPUT_PROTOCOL *OldConIn; if (PcdGet8(PcdShellSupportLevel) > 3) { return (EFI_UNSUPPORTED); @@ -94,7 +253,9 @@ UefiMain ( // Clear the screen // Status = gST->ConOut->ClearScreen(gST->ConOut); - ASSERT_EFI_ERROR(Status); + if (EFI_ERROR(Status)) { + return (Status); + } // // Populate the global structure from PCDs @@ -136,178 +297,229 @@ UefiMain ( // install our console logger. This will keep a log of the output for back-browsing // Status = ConsoleLoggerInstall(ShellInfoObject.LogScreenCount, &ShellInfoObject.ConsoleInfo); - ASSERT_EFI_ERROR(Status); - - // - // Enable the cursor to be visible - // - gST->ConOut->EnableCursor (gST->ConOut, TRUE); + if (!EFI_ERROR(Status)) { + // + // Enable the cursor to be visible + // + gST->ConOut->EnableCursor (gST->ConOut, TRUE); - // - // If supporting EFI 1.1 we need to install HII protocol - // only do this if PcdShellRequireHiiPlatform == FALSE - // - // remove EFI_UNSUPPORTED check above when complete. - ///@todo add support for Framework HII + // + // If supporting EFI 1.1 we need to install HII protocol + // only do this if PcdShellRequireHiiPlatform == FALSE + // + // remove EFI_UNSUPPORTED check above when complete. + ///@todo add support for Framework HII - // - // install our (solitary) HII package - // - ShellInfoObject.HiiHandle = HiiAddPackages (&gEfiCallerIdGuid, gImageHandle, ShellStrings, NULL); - if (ShellInfoObject.HiiHandle == NULL) { - if (PcdGetBool(PcdShellSupportFrameworkHii)) { - ///@todo Add our package into Framework HII - } + // + // install our (solitary) HII package + // + ShellInfoObject.HiiHandle = HiiAddPackages (&gEfiCallerIdGuid, gImageHandle, ShellStrings, NULL); if (ShellInfoObject.HiiHandle == NULL) { - return (EFI_NOT_STARTED); + if (PcdGetBool(PcdShellSupportFrameworkHii)) { + ///@todo Add our package into Framework HII + } + if (ShellInfoObject.HiiHandle == NULL) { + Status = EFI_NOT_STARTED; + goto FreeResources; + } } - } - // - // create and install the EfiShellParametersProtocol - // - Status = CreatePopulateInstallShellParametersProtocol(&ShellInfoObject.NewShellParametersProtocol, &ShellInfoObject.RootShellInstance); - ASSERT_EFI_ERROR(Status); - ASSERT(ShellInfoObject.NewShellParametersProtocol != NULL); - - // - // create and install the EfiShellProtocol - // - Status = CreatePopulateInstallShellProtocol(&ShellInfoObject.NewEfiShellProtocol); - ASSERT_EFI_ERROR(Status); - ASSERT(ShellInfoObject.NewEfiShellProtocol != NULL); - - // - // Now initialize the shell library (it requires Shell Parameters protocol) - // - Status = ShellInitialize(); - ASSERT_EFI_ERROR(Status); + // + // create and install the EfiShellParametersProtocol + // + Status = CreatePopulateInstallShellParametersProtocol(&ShellInfoObject.NewShellParametersProtocol, &ShellInfoObject.RootShellInstance); + ASSERT_EFI_ERROR(Status); + ASSERT(ShellInfoObject.NewShellParametersProtocol != NULL); - Status = CommandInit(); - ASSERT_EFI_ERROR(Status); + // + // create and install the EfiShellProtocol + // + Status = CreatePopulateInstallShellProtocol(&ShellInfoObject.NewEfiShellProtocol); + ASSERT_EFI_ERROR(Status); + ASSERT(ShellInfoObject.NewEfiShellProtocol != NULL); - // - // Check the command line - // - Status = ProcessCommandLine(); + // + // Now initialize the shell library (it requires Shell Parameters protocol) + // + Status = ShellInitialize(); + ASSERT_EFI_ERROR(Status); - // - // If shell support level is >= 1 create the mappings and paths - // - if (PcdGet8(PcdShellSupportLevel) >= 1) { - Status = ShellCommandCreateInitialMappingsAndPaths(); - } + Status = CommandInit(); + ASSERT_EFI_ERROR(Status); - // - // save the device path for the loaded image and the device path for the filepath (under loaded image) - // These are where to look for the startup.nsh file - // - Status = GetDevicePathsForImageAndFile(&ShellInfoObject.ImageDevPath, &ShellInfoObject.FileDevPath); - ASSERT_EFI_ERROR(Status); + // + // Check the command line + // + Status = ProcessCommandLine (); + if (EFI_ERROR (Status)) { + goto FreeResources; + } - // - // Display the version - // - if (!ShellInfoObject.ShellInitSettings.BitUnion.Bits.NoVersion) { - ShellPrintHiiEx ( - 0, - gST->ConOut->Mode->CursorRow, - NULL, - STRING_TOKEN (STR_VER_OUTPUT_MAIN), - ShellInfoObject.HiiHandle, - SupportLevel[PcdGet8(PcdShellSupportLevel)], - gEfiShellProtocol->MajorVersion, - gEfiShellProtocol->MinorVersion, - (gST->Hdr.Revision&0xffff0000)>>16, - (gST->Hdr.Revision&0x0000ffff), - gST->FirmwareVendor, - gST->FirmwareRevision - ); - } + // + // If shell support level is >= 1 create the mappings and paths + // + if (PcdGet8(PcdShellSupportLevel) >= 1) { + Status = ShellCommandCreateInitialMappingsAndPaths(); + } - // - // Display the mapping - // - if (PcdGet8(PcdShellSupportLevel) >= 2 && !ShellInfoObject.ShellInitSettings.BitUnion.Bits.NoMap) { - Status = RunCommand(L"map"); + // + // save the device path for the loaded image and the device path for the filepath (under loaded image) + // These are where to look for the startup.nsh file + // + Status = GetDevicePathsForImageAndFile(&ShellInfoObject.ImageDevPath, &ShellInfoObject.FileDevPath); ASSERT_EFI_ERROR(Status); - } - // - // init all the built in alias' - // - Status = SetBuiltInAlias(); - ASSERT_EFI_ERROR(Status); + // + // Display the version + // + if (!ShellInfoObject.ShellInitSettings.BitUnion.Bits.NoVersion) { + ShellPrintHiiEx ( + 0, + gST->ConOut->Mode->CursorRow, + NULL, + STRING_TOKEN (STR_VER_OUTPUT_MAIN_SHELL), + ShellInfoObject.HiiHandle, + SupportLevel[PcdGet8(PcdShellSupportLevel)], + gEfiShellProtocol->MajorVersion, + gEfiShellProtocol->MinorVersion + ); + + ShellPrintHiiEx ( + -1, + -1, + NULL, + STRING_TOKEN (STR_VER_OUTPUT_MAIN_SUPPLIER), + ShellInfoObject.HiiHandle, + (CHAR16 *) PcdGetPtr (PcdShellSupplier) + ); + + ShellPrintHiiEx ( + -1, + -1, + NULL, + STRING_TOKEN (STR_VER_OUTPUT_MAIN_UEFI), + ShellInfoObject.HiiHandle, + (gST->Hdr.Revision&0xffff0000)>>16, + (gST->Hdr.Revision&0x0000ffff), + gST->FirmwareVendor, + gST->FirmwareRevision + ); + } - // - // Initialize environment variables - // - if (ShellCommandGetProfileList() != NULL) { - Status = InternalEfiShellSetEnv(L"profiles", ShellCommandGetProfileList(), TRUE); + // + // Display the mapping + // + if (PcdGet8(PcdShellSupportLevel) >= 2 && !ShellInfoObject.ShellInitSettings.BitUnion.Bits.NoMap) { + Status = RunCommand(L"map"); + ASSERT_EFI_ERROR(Status); + } + + // + // init all the built in alias' + // + Status = SetBuiltInAlias(); ASSERT_EFI_ERROR(Status); - } - Size = 100; - TempString = AllocateZeroPool(Size); + // + // Initialize environment variables + // + if (ShellCommandGetProfileList() != NULL) { + Status = InternalEfiShellSetEnv(L"profiles", ShellCommandGetProfileList(), TRUE); + ASSERT_EFI_ERROR(Status); + } - UnicodeSPrint(TempString, Size, L"%d", PcdGet8(PcdShellSupportLevel)); - Status = InternalEfiShellSetEnv(L"uefishellsupport", TempString, TRUE); - ASSERT_EFI_ERROR(Status); + Size = 100; + TempString = AllocateZeroPool(Size); - UnicodeSPrint(TempString, Size, L"%d.%d", ShellInfoObject.NewEfiShellProtocol->MajorVersion, ShellInfoObject.NewEfiShellProtocol->MinorVersion); - Status = InternalEfiShellSetEnv(L"uefishellversion", TempString, TRUE); - ASSERT_EFI_ERROR(Status); + UnicodeSPrint(TempString, Size, L"%d", PcdGet8(PcdShellSupportLevel)); + Status = InternalEfiShellSetEnv(L"uefishellsupport", TempString, TRUE); + ASSERT_EFI_ERROR(Status); - UnicodeSPrint(TempString, Size, L"%d.%d", (gST->Hdr.Revision & 0xFFFF0000) >> 16, gST->Hdr.Revision & 0x0000FFFF); - Status = InternalEfiShellSetEnv(L"uefiversion", TempString, TRUE); - ASSERT_EFI_ERROR(Status); + UnicodeSPrint(TempString, Size, L"%d.%d", ShellInfoObject.NewEfiShellProtocol->MajorVersion, ShellInfoObject.NewEfiShellProtocol->MinorVersion); + Status = InternalEfiShellSetEnv(L"uefishellversion", TempString, TRUE); + ASSERT_EFI_ERROR(Status); - FreePool(TempString); + UnicodeSPrint(TempString, Size, L"%d.%d", (gST->Hdr.Revision & 0xFFFF0000) >> 16, gST->Hdr.Revision & 0x0000FFFF); + Status = InternalEfiShellSetEnv(L"uefiversion", TempString, TRUE); + ASSERT_EFI_ERROR(Status); - if (!EFI_ERROR(Status)) { - if (!ShellInfoObject.ShellInitSettings.BitUnion.Bits.NoInterrupt) { - // - // Set up the event for CTRL-C monitoring... - // + FreePool(TempString); - ///@todo add support for using SimpleInputEx here - // if SimpleInputEx is not available display a warning. - } + if (!EFI_ERROR(Status)) { + if (!ShellInfoObject.ShellInitSettings.BitUnion.Bits.NoInterrupt) { + // + // Set up the event for CTRL-C monitoring... + // + Status = InernalEfiShellStartMonitor(); + } - if (!EFI_ERROR(Status) && PcdGet8(PcdShellSupportLevel) >= 1) { - // - // process the startup script or launch the called app. - // - Status = DoStartupScript(ShellInfoObject.ImageDevPath, ShellInfoObject.FileDevPath); - } + if (!EFI_ERROR(Status) && !ShellInfoObject.ShellInitSettings.BitUnion.Bits.NoConsoleIn) { + // + // Set up the event for CTRL-S monitoring... + // + Status = InternalEfiShellStartCtrlSMonitor(); + } - if ((PcdGet8(PcdShellSupportLevel) >= 3 || PcdGetBool(PcdShellForceConsole)) && !EFI_ERROR(Status) && !ShellInfoObject.ShellInitSettings.BitUnion.Bits.NoConsoleIn) { - // - // begin the UI waiting loop - // - do { + if (!EFI_ERROR(Status) && ShellInfoObject.ShellInitSettings.BitUnion.Bits.NoConsoleIn) { // - // clean out all the memory allocated for CONST * return values - // between each shell prompt presentation + // close off the gST->ConIn // - if (!IsListEmpty(&ShellInfoObject.BufferToFreeList.Link)){ - FreeBufferList(&ShellInfoObject.BufferToFreeList); - } + OldConIn = gST->ConIn; + ConInHandle = gST->ConsoleInHandle; + gST->ConIn = CreateSimpleTextInOnFile((SHELL_FILE_HANDLE)&FileInterfaceNulFile, &gST->ConsoleInHandle); + } else { + OldConIn = NULL; + ConInHandle = NULL; + } + if (!EFI_ERROR(Status) && PcdGet8(PcdShellSupportLevel) >= 1) { // - // Reset page break back to default. + // process the startup script or launch the called app. // - ShellInfoObject.PageBreakEnabled = PcdGetBool(PcdShellPageBreakDefault); - ShellInfoObject.ConsoleInfo->Enabled = TRUE; - ShellInfoObject.ConsoleInfo->RowCounter = 0; + Status = DoStartupScript(ShellInfoObject.ImageDevPath, ShellInfoObject.FileDevPath); + } + if (!ShellInfoObject.ShellInitSettings.BitUnion.Bits.Exit && !ShellCommandGetExit() && (PcdGet8(PcdShellSupportLevel) >= 3 || PcdGetBool(PcdShellForceConsole)) && !EFI_ERROR(Status) && !ShellInfoObject.ShellInitSettings.BitUnion.Bits.NoConsoleIn) { // - // Display Prompt + // begin the UI waiting loop // - Status = DoShellPrompt(); - } while (!ShellCommandGetExit()); + do { + // + // clean out all the memory allocated for CONST * return values + // between each shell prompt presentation + // + if (!IsListEmpty(&ShellInfoObject.BufferToFreeList.Link)){ + FreeBufferList(&ShellInfoObject.BufferToFreeList); + } + + // + // Reset page break back to default. + // + ShellInfoObject.PageBreakEnabled = PcdGetBool(PcdShellPageBreakDefault); + ASSERT (ShellInfoObject.ConsoleInfo != NULL); + ShellInfoObject.ConsoleInfo->Enabled = TRUE; + ShellInfoObject.ConsoleInfo->RowCounter = 0; + + // + // Reset the CTRL-C event (yes we ignore the return values) + // + Status = gBS->CheckEvent (ShellInfoObject.NewEfiShellProtocol->ExecutionBreak); + + // + // Display Prompt + // + Status = DoShellPrompt(); + } while (!ShellCommandGetExit()); + } + if (OldConIn != NULL && ConInHandle != NULL) { + CloseSimpleTextInOnFile (gST->ConIn); + gST->ConIn = OldConIn; + gST->ConsoleInHandle = ConInHandle; + } } } + +FreeResources: // // uninstall protocols / free memory / etc... // @@ -315,11 +527,6 @@ UefiMain ( gBS->CloseEvent(ShellInfoObject.UserBreakTimer); DEBUG_CODE(ShellInfoObject.UserBreakTimer = NULL;); } - - if (ShellInfoObject.NewEfiShellProtocol->IsRootShell()){ - ShellInfoObject.NewEfiShellProtocol->SetEnv(L"cwd", L"", TRUE); - } - if (ShellInfoObject.ImageDevPath != NULL) { FreePool(ShellInfoObject.ImageDevPath); DEBUG_CODE(ShellInfoObject.ImageDevPath = NULL;); @@ -333,6 +540,9 @@ UefiMain ( DEBUG_CODE(ShellInfoObject.NewShellParametersProtocol = NULL;); } if (ShellInfoObject.NewEfiShellProtocol != NULL){ + if (ShellInfoObject.NewEfiShellProtocol->IsRootShell()){ + InternalEfiShellSetEnv(L"cwd", NULL, TRUE); + } CleanUpShellProtocol(ShellInfoObject.NewEfiShellProtocol); DEBUG_CODE(ShellInfoObject.NewEfiShellProtocol = NULL;); } @@ -342,7 +552,7 @@ UefiMain ( } if (!IsListEmpty(&ShellInfoObject.SplitList.Link)){ - ASSERT(FALSE); + ASSERT(FALSE); ///@todo finish this de-allocation. } if (ShellInfoObject.ShellInitSettings.FileName != NULL) { @@ -371,6 +581,9 @@ UefiMain ( DEBUG_CODE(ShellInfoObject.ConsoleInfo = NULL;); } + if (ShellCommandGetExit()) { + return ((EFI_STATUS)ShellCommandGetExitCode()); + } return (Status); } @@ -456,16 +669,14 @@ IsScriptOnlyCommand( return (FALSE); } - - /** This function will populate the 2 device path protocol parameters based on the global gImageHandle. The DevPath will point to the device path for the handle that has loaded image protocol installed on it. The FilePath will point to the device path for the file that was loaded. - @param[in,out] DevPath On a sucessful return the device path to the loaded image. - @param[in,out] FilePath On a sucessful return the device path to the file. + @param[in, out] DevPath On a sucessful return the device path to the loaded image. + @param[in, out] FilePath On a sucessful return the device path to the file. @retval EFI_SUCCESS The 2 device paths were sucessfully returned. @retval other A error from gBS->HandleProtocol. @@ -506,6 +717,11 @@ GetDevicePathsForImageAndFile ( if (!EFI_ERROR (Status)) { *DevPath = DuplicateDevicePath (ImageDevicePath); *FilePath = DuplicateDevicePath (LoadedImage->FilePath); + gBS->CloseProtocol( + LoadedImage->DeviceHandle, + &gEfiDevicePathProtocolGuid, + gImageHandle, + NULL); } gBS->CloseProtocol( gImageHandle, @@ -516,18 +732,6 @@ GetDevicePathsForImageAndFile ( return (Status); } -STATIC CONST SHELL_PARAM_ITEM mShellParamList[] = { - {L"-nostartup", TypeFlag}, - {L"-startup", TypeFlag}, - {L"-noconsoleout", TypeFlag}, - {L"-noconsolein", TypeFlag}, - {L"-nointerrupt", TypeFlag}, - {L"-nomap", TypeFlag}, - {L"-noversion", TypeFlag}, - {L"-startup", TypeFlag}, - {L"-delay", TypeValue}, - {NULL, TypeMax} - }; /** Process all Uefi Shell 2.0 command line options. @@ -561,80 +765,180 @@ ProcessCommandLine( VOID ) { - EFI_STATUS Status; - LIST_ENTRY *Package; - UINTN Size; - CONST CHAR16 *TempConst; - UINTN Count; - UINTN LoopVar; - CHAR16 *ProblemParam; - - Package = NULL; - ProblemParam = NULL; - - Status = ShellCommandLineParse (mShellParamList, &Package, NULL, FALSE); - - Count = 1; - Size = 0; - TempConst = ShellCommandLineGetRawValue(Package, Count++); - if (TempConst != NULL && StrLen(TempConst)) { - ShellInfoObject.ShellInitSettings.FileName = AllocatePool(StrSize(TempConst)); - StrCpy(ShellInfoObject.ShellInitSettings.FileName, TempConst); - ShellInfoObject.ShellInitSettings.BitUnion.Bits.NoStartup = 1; - for (LoopVar = 0 ; LoopVar < gEfiShellParametersProtocol->Argc ; LoopVar++) { - if (StrCmp(gEfiShellParametersProtocol->Argv[LoopVar], ShellInfoObject.ShellInitSettings.FileName)==0) { - LoopVar++; - // - // We found the file... add the rest of the params... - // - for ( ; LoopVar < gEfiShellParametersProtocol->Argc ; LoopVar++) { - ASSERT((ShellInfoObject.ShellInitSettings.FileOptions == NULL && Size == 0) || (ShellInfoObject.ShellInitSettings.FileOptions != NULL)); - StrnCatGrow(&ShellInfoObject.ShellInitSettings.FileOptions, - &Size, - L" ", - 0); - StrnCatGrow(&ShellInfoObject.ShellInitSettings.FileOptions, - &Size, - gEfiShellParametersProtocol->Argv[LoopVar], - 0); + UINTN Size; + UINTN LoopVar; + CHAR16 *CurrentArg; + CHAR16 *DelayValueStr; + UINT64 DelayValue; + EFI_STATUS Status; + EFI_UNICODE_COLLATION_PROTOCOL *UnicodeCollation; + + // `file-name-options` will contain arguments to `file-name` that we don't + // know about. This would cause ShellCommandLineParse to error, so we parse + // arguments manually, ignoring those after the first thing that doesn't look + // like a shell option (which is assumed to be `file-name`). + + Status = gBS->LocateProtocol ( + &gEfiUnicodeCollationProtocolGuid, + NULL, + (VOID **) &UnicodeCollation + ); + if (EFI_ERROR (Status)) { + return Status; + } + + // Set default options + ShellInfoObject.ShellInitSettings.BitUnion.Bits.Startup = FALSE; + ShellInfoObject.ShellInitSettings.BitUnion.Bits.NoStartup = FALSE; + ShellInfoObject.ShellInitSettings.BitUnion.Bits.NoConsoleOut = FALSE; + ShellInfoObject.ShellInitSettings.BitUnion.Bits.NoConsoleIn = FALSE; + ShellInfoObject.ShellInitSettings.BitUnion.Bits.NoInterrupt = FALSE; + ShellInfoObject.ShellInitSettings.BitUnion.Bits.NoMap = FALSE; + ShellInfoObject.ShellInitSettings.BitUnion.Bits.NoVersion = FALSE; + ShellInfoObject.ShellInitSettings.BitUnion.Bits.Delay = FALSE; + ShellInfoObject.ShellInitSettings.BitUnion.Bits.Exit = FALSE; + ShellInfoObject.ShellInitSettings.Delay = 5; + + // + // Start LoopVar at 0 to parse only optional arguments at Argv[0] + // and parse other parameters from Argv[1]. This is for use case that + // UEFI Shell boot option is created, and OptionalData is provided + // that starts with shell command-line options. + // + for (LoopVar = 0 ; LoopVar < gEfiShellParametersProtocol->Argc ; LoopVar++) { + CurrentArg = gEfiShellParametersProtocol->Argv[LoopVar]; + if (UnicodeCollation->StriColl ( + UnicodeCollation, + L"-startup", + CurrentArg + ) == 0) { + ShellInfoObject.ShellInitSettings.BitUnion.Bits.Startup = TRUE; + } + else if (UnicodeCollation->StriColl ( + UnicodeCollation, + L"-nostartup", + CurrentArg + ) == 0) { + ShellInfoObject.ShellInitSettings.BitUnion.Bits.NoStartup = TRUE; + } + else if (UnicodeCollation->StriColl ( + UnicodeCollation, + L"-noconsoleout", + CurrentArg + ) == 0) { + ShellInfoObject.ShellInitSettings.BitUnion.Bits.NoConsoleOut = TRUE; + } + else if (UnicodeCollation->StriColl ( + UnicodeCollation, + L"-noconsolein", + CurrentArg + ) == 0) { + ShellInfoObject.ShellInitSettings.BitUnion.Bits.NoConsoleIn = TRUE; + } + else if (UnicodeCollation->StriColl ( + UnicodeCollation, + L"-nointerrupt", + CurrentArg + ) == 0) { + ShellInfoObject.ShellInitSettings.BitUnion.Bits.NoInterrupt = TRUE; + } + else if (UnicodeCollation->StriColl ( + UnicodeCollation, + L"-nomap", + CurrentArg + ) == 0) { + ShellInfoObject.ShellInitSettings.BitUnion.Bits.NoMap = TRUE; + } + else if (UnicodeCollation->StriColl ( + UnicodeCollation, + L"-noversion", + CurrentArg + ) == 0) { + ShellInfoObject.ShellInitSettings.BitUnion.Bits.NoVersion = TRUE; + } + else if (UnicodeCollation->StriColl ( + UnicodeCollation, + L"-delay", + CurrentArg + ) == 0) { + ShellInfoObject.ShellInitSettings.BitUnion.Bits.Delay = TRUE; + // Check for optional delay value following "-delay" + DelayValueStr = gEfiShellParametersProtocol->Argv[LoopVar + 1]; + if (DelayValueStr != NULL){ + if (*DelayValueStr == L':') { + DelayValueStr++; + } + if (!EFI_ERROR(ShellConvertStringToUint64 ( + DelayValueStr, + &DelayValue, + FALSE, + FALSE + ))) { + ShellInfoObject.ShellInitSettings.Delay = (UINTN)DelayValue; + LoopVar++; + } + } + } else if (UnicodeCollation->StriColl ( + UnicodeCollation, + L"-_exit", + CurrentArg + ) == 0) { + ShellInfoObject.ShellInitSettings.BitUnion.Bits.Exit = TRUE; + } else if (StrnCmp (L"-", CurrentArg, 1) == 0) { + // Unrecognised option + ShellPrintHiiEx(-1, -1, NULL, + STRING_TOKEN (STR_GEN_PROBLEM), + ShellInfoObject.HiiHandle, + CurrentArg + ); + return EFI_INVALID_PARAMETER; + } else { + // + // First argument should be Shell.efi image name + // + if (LoopVar == 0) { + continue; + } + + ShellInfoObject.ShellInitSettings.FileName = AllocateCopyPool(StrSize(CurrentArg), CurrentArg); + if (ShellInfoObject.ShellInitSettings.FileName == NULL) { + return (EFI_OUT_OF_RESOURCES); + } + // + // We found `file-name`. + // + ShellInfoObject.ShellInitSettings.BitUnion.Bits.NoStartup = 1; + LoopVar++; + + // Add `file-name-options` + for (Size = 0 ; LoopVar < gEfiShellParametersProtocol->Argc ; LoopVar++) { + ASSERT((ShellInfoObject.ShellInitSettings.FileOptions == NULL && Size == 0) || (ShellInfoObject.ShellInitSettings.FileOptions != NULL)); + StrnCatGrow(&ShellInfoObject.ShellInitSettings.FileOptions, + &Size, + L" ", + 0); + if (ShellInfoObject.ShellInitSettings.FileOptions == NULL) { + SHELL_FREE_NON_NULL(ShellInfoObject.ShellInitSettings.FileName); + return (EFI_OUT_OF_RESOURCES); + } + StrnCatGrow(&ShellInfoObject.ShellInitSettings.FileOptions, + &Size, + gEfiShellParametersProtocol->Argv[LoopVar], + 0); + if (ShellInfoObject.ShellInitSettings.FileOptions == NULL) { + SHELL_FREE_NON_NULL(ShellInfoObject.ShellInitSettings.FileName); + return (EFI_OUT_OF_RESOURCES); } } - } - } else { - ShellCommandLineFreeVarList(Package); - Package = NULL; - Status = ShellCommandLineParse (mShellParamList, &Package, &ProblemParam, FALSE); - if (EFI_ERROR(Status)) { - ShellPrintHiiEx(-1, -1, NULL, STRING_TOKEN (STR_GEN_PROBLEM), ShellInfoObject.HiiHandle, ProblemParam); - FreePool(ProblemParam); - ShellCommandLineFreeVarList(Package); - return (EFI_INVALID_PARAMETER); } } - ShellInfoObject.ShellInitSettings.BitUnion.Bits.Startup = ShellCommandLineGetFlag(Package, L"-startup"); - ShellInfoObject.ShellInitSettings.BitUnion.Bits.NoStartup = ShellCommandLineGetFlag(Package, L"-nostartup"); - ShellInfoObject.ShellInitSettings.BitUnion.Bits.NoConsoleOut = ShellCommandLineGetFlag(Package, L"-noconsoleout"); - ShellInfoObject.ShellInitSettings.BitUnion.Bits.NoConsoleIn = ShellCommandLineGetFlag(Package, L"-noconsolein"); - ShellInfoObject.ShellInitSettings.BitUnion.Bits.NoInterrupt = ShellCommandLineGetFlag(Package, L"-nointerrupt"); - ShellInfoObject.ShellInitSettings.BitUnion.Bits.NoMap = ShellCommandLineGetFlag(Package, L"-nomap"); - ShellInfoObject.ShellInitSettings.BitUnion.Bits.NoVersion = ShellCommandLineGetFlag(Package, L"-noversion"); - ShellInfoObject.ShellInitSettings.BitUnion.Bits.Delay = ShellCommandLineGetFlag(Package, L"-delay"); + // "-nointerrupt" overrides "-delay" + if (ShellInfoObject.ShellInitSettings.BitUnion.Bits.NoInterrupt) { + ShellInfoObject.ShellInitSettings.Delay = 0; + } - if (ShellInfoObject.ShellInitSettings.BitUnion.Bits.Delay) { - TempConst = ShellCommandLineGetValue(Package, L"-delay"); - if (TempConst != NULL) { - ShellInfoObject.ShellInitSettings.Delay = StrDecimalToUintn (TempConst); - } else { - ShellInfoObject.ShellInitSettings.Delay = 5; - } - } else { - ShellInfoObject.ShellInitSettings.Delay = 5; - } - - ShellCommandLineFreeVarList(Package); - - return (Status); + return EFI_SUCCESS; } /** @@ -650,8 +954,8 @@ ProcessCommandLine( EFI_STATUS EFIAPI DoStartupScript( - EFI_DEVICE_PATH_PROTOCOL *ImagePath, - EFI_DEVICE_PATH_PROTOCOL *FilePath + IN EFI_DEVICE_PATH_PROTOCOL *ImagePath, + IN EFI_DEVICE_PATH_PROTOCOL *FilePath ) { EFI_STATUS Status; @@ -661,7 +965,9 @@ DoStartupScript( EFI_DEVICE_PATH_PROTOCOL *NewPath; EFI_DEVICE_PATH_PROTOCOL *NamePath; CHAR16 *FileStringPath; + CHAR16 *TempSpot; UINTN NewSize; + CONST CHAR16 *MapName; Key.UnicodeChar = CHAR_NULL; Key.ScanCode = 0; @@ -676,10 +982,13 @@ DoStartupScript( NewSize += StrSize(ShellInfoObject.ShellInitSettings.FileOptions) + sizeof(CHAR16); } FileStringPath = AllocateZeroPool(NewSize); - StrCpy(FileStringPath, ShellInfoObject.ShellInitSettings.FileName); + if (FileStringPath == NULL) { + return (EFI_OUT_OF_RESOURCES); + } + StrnCpy(FileStringPath, ShellInfoObject.ShellInitSettings.FileName, NewSize/sizeof(CHAR16) -1); if (ShellInfoObject.ShellInitSettings.FileOptions != NULL) { - StrCat (FileStringPath, L" "); - StrCat(FileStringPath, ShellInfoObject.ShellInitSettings.FileOptions); + StrnCat(FileStringPath, L" ", NewSize/sizeof(CHAR16) - StrLen(FileStringPath) -1); + StrnCat(FileStringPath, ShellInfoObject.ShellInitSettings.FileOptions, NewSize/sizeof(CHAR16) - StrLen(FileStringPath) -1); } Status = RunCommand(FileStringPath); FreePool(FileStringPath); @@ -697,18 +1006,22 @@ DoStartupScript( return (EFI_SUCCESS); } + gST->ConOut->EnableCursor(gST->ConOut, FALSE); // // print out our warning and see if they press a key // - for ( Status = EFI_UNSUPPORTED, Delay = (ShellInfoObject.ShellInitSettings.Delay * 10) - ; Delay > 0 && EFI_ERROR(Status) + for ( Status = EFI_UNSUPPORTED, Delay = ShellInfoObject.ShellInitSettings.Delay + ; Delay != 0 && EFI_ERROR(Status) ; Delay-- ){ - ShellPrintHiiEx(0, gST->ConOut->Mode->CursorRow, NULL, STRING_TOKEN (STR_SHELL_STARTUP_QUESTION), ShellInfoObject.HiiHandle, Delay/10); - gBS->Stall (100000); - Status = gST->ConIn->ReadKeyStroke (gST->ConIn, &Key); + ShellPrintHiiEx(0, gST->ConOut->Mode->CursorRow, NULL, STRING_TOKEN (STR_SHELL_STARTUP_QUESTION), ShellInfoObject.HiiHandle, Delay); + gBS->Stall (1000000); + if (!ShellInfoObject.ShellInitSettings.BitUnion.Bits.NoConsoleIn) { + Status = gST->ConIn->ReadKeyStroke (gST->ConIn, &Key); + } } ShellPrintHiiEx(-1, -1, NULL, STRING_TOKEN (STR_SHELL_CRLF), ShellInfoObject.HiiHandle); + gST->ConOut->EnableCursor(gST->ConOut, TRUE); // // ESC was pressed @@ -717,37 +1030,59 @@ DoStartupScript( return (EFI_SUCCESS); } - NamePath = FileDevicePath (NULL, L"startup.nsh"); // - // Try the first location + // Try the first location (must be file system) // - NewPath = AppendDevicePathNode (ImagePath, NamePath); - Status = InternalOpenFileDevicePath(NewPath, &FileHandle, EFI_FILE_MODE_READ, 0); + MapName = ShellInfoObject.NewEfiShellProtocol->GetMapFromDevicePath(&ImagePath); + if (MapName != NULL) { + FileStringPath = NULL; + NewSize = 0; + FileStringPath = StrnCatGrow(&FileStringPath, &NewSize, MapName, 0); + if (FileStringPath == NULL) { + Status = EFI_OUT_OF_RESOURCES; + } else { + TempSpot = StrStr(FileStringPath, L";"); + if (TempSpot != NULL) { + *TempSpot = CHAR_NULL; + } + FileStringPath = StrnCatGrow(&FileStringPath, &NewSize, ((FILEPATH_DEVICE_PATH*)FilePath)->PathName, 0); + PathRemoveLastItem(FileStringPath); + FileStringPath = StrnCatGrow(&FileStringPath, &NewSize, mStartupScript, 0); + Status = ShellInfoObject.NewEfiShellProtocol->OpenFileByName(FileStringPath, &FileHandle, EFI_FILE_MODE_READ); + FreePool(FileStringPath); + } + } if (EFI_ERROR(Status)) { + NamePath = FileDevicePath (NULL, mStartupScript); + NewPath = AppendDevicePathNode (ImagePath, NamePath); + FreePool(NamePath); + // - // Try the second location + // Try the location // - FreePool(NewPath); - NewPath = AppendDevicePathNode (FilePath , NamePath); Status = InternalOpenFileDevicePath(NewPath, &FileHandle, EFI_FILE_MODE_READ, 0); + FreePool(NewPath); } - // // If we got a file, run it // - if (!EFI_ERROR(Status)) { - Status = RunScriptFileHandle (FileHandle, L"startup.nsh"); + if (!EFI_ERROR(Status) && FileHandle != NULL) { + Status = RunScriptFile (mStartupScript, FileHandle, L"", ShellInfoObject.NewShellParametersProtocol); ShellInfoObject.NewEfiShellProtocol->CloseFile(FileHandle); } else { - // - // we return success since we dont need to have a startup script - // - Status = EFI_SUCCESS; - ASSERT(FileHandle == NULL); + FileStringPath = ShellFindFilePath(mStartupScript); + if (FileStringPath == NULL) { + // + // we return success since we dont need to have a startup script + // + Status = EFI_SUCCESS; + ASSERT(FileHandle == NULL); + } else { + Status = RunScriptFile(FileStringPath, NULL, L"", ShellInfoObject.NewShellParametersProtocol); + FreePool(FileStringPath); + } } - FreePool(NamePath); - FreePool(NewPath); return (Status); } @@ -809,7 +1144,7 @@ DoShellPrompt ( if (!EFI_ERROR (Status)) { CmdLine[BufferSize / sizeof (CHAR16)] = CHAR_NULL; Status = RunCommand(CmdLine); - } + } // // Done with this command @@ -858,9 +1193,8 @@ AddLineToCommandHistory( Node = AllocateZeroPool(sizeof(BUFFER_LIST)); ASSERT(Node != NULL); - Node->Buffer = AllocateZeroPool(StrSize(Buffer)); + Node->Buffer = AllocateCopyPool(StrSize(Buffer), Buffer); ASSERT(Node->Buffer != NULL); - StrCpy(Node->Buffer, Buffer); InsertTailList(&ShellInfoObject.ViewingSettings.CommandHistory.Link, &Node->Link); } @@ -869,10 +1203,10 @@ AddLineToCommandHistory( Checks if a string is an alias for another command. If yes, then it replaces the alias name with the correct command name. - @param[in,out] CommandString Upon entry the potential alias. Upon return the - command name if it was an alias. If it was not - an alias it will be unchanged. This function may - change the buffer to fit the command name. + @param[in, out] CommandString Upon entry the potential alias. Upon return the + command name if it was an alias. If it was not + an alias it will be unchanged. This function may + change the buffer to fit the command name. @retval EFI_SUCCESS The name was changed. @retval EFI_SUCCESS The name was not an alias. @@ -891,11 +1225,117 @@ ShellConvertAlias( return (EFI_SUCCESS); } FreePool(*CommandString); - *CommandString = AllocatePool(StrSize(NewString)); + *CommandString = AllocateCopyPool(StrSize(NewString), NewString); if (*CommandString == NULL) { return (EFI_OUT_OF_RESOURCES); } - StrCpy(*CommandString, NewString); + return (EFI_SUCCESS); +} + +/** + Parse for the next instance of one string within another string. Can optionally make sure that + the string was not escaped (^ character) per the shell specification. + + @param[in] SourceString The string to search within + @param[in] FindString The string to look for + @param[in] CheckForEscapeCharacter TRUE to skip escaped instances of FinfString, otherwise will return even escaped instances +**/ +CHAR16* +EFIAPI +FindNextInstance( + IN CONST CHAR16 *SourceString, + IN CONST CHAR16 *FindString, + IN CONST BOOLEAN CheckForEscapeCharacter + ) +{ + CHAR16 *Temp; + if (SourceString == NULL) { + return (NULL); + } + Temp = StrStr(SourceString, FindString); + + // + // If nothing found, or we dont care about escape characters + // + if (Temp == NULL || !CheckForEscapeCharacter) { + return (Temp); + } + + // + // If we found an escaped character, try again on the remainder of the string + // + if ((Temp > (SourceString)) && *(Temp-1) == L'^') { + return FindNextInstance(Temp+1, FindString, CheckForEscapeCharacter); + } + + // + // we found the right character + // + return (Temp); +} + +/** + This function will eliminate unreplaced (and therefore non-found) environment variables. + + @param[in,out] CmdLine The command line to update. +**/ +EFI_STATUS +EFIAPI +StripUnreplacedEnvironmentVariables( + IN OUT CHAR16 *CmdLine + ) +{ + CHAR16 *FirstPercent; + CHAR16 *FirstQuote; + CHAR16 *SecondPercent; + CHAR16 *SecondQuote; + CHAR16 *CurrentLocator; + + for (CurrentLocator = CmdLine ; CurrentLocator != NULL ; ) { + FirstQuote = FindNextInstance(CurrentLocator, L"\"", TRUE); + FirstPercent = FindNextInstance(CurrentLocator, L"%", TRUE); + SecondPercent = FirstPercent!=NULL?FindNextInstance(FirstPercent+1, L"%", TRUE):NULL; + if (FirstPercent == NULL || SecondPercent == NULL) { + // + // If we ever dont have 2 % we are done. + // + break; + } + + if (FirstQuote < FirstPercent) { + SecondQuote = FirstQuote!= NULL?FindNextInstance(FirstQuote+1, L"\"", TRUE):NULL; + // + // Quote is first found + // + + if (SecondQuote < FirstPercent) { + // + // restart after the pair of " + // + CurrentLocator = SecondQuote + 1; + } else /* FirstPercent < SecondQuote */{ + // + // Restart on the first percent + // + CurrentLocator = FirstPercent; + } + continue; + } + ASSERT(FirstPercent < FirstQuote); + if (SecondPercent < FirstQuote) { + FirstPercent[0] = L'\"'; + SecondPercent[0] = L'\"'; + + // + // We need to remove from FirstPercent to SecondPercent + // + CopyMem(FirstPercent + 1, SecondPercent, StrSize(SecondPercent)); + CurrentLocator = FirstPercent + 2; + continue; + } + ASSERT(FirstQuote < SecondPercent); + CurrentLocator = FirstQuote; + } return (EFI_SUCCESS); } @@ -978,31 +1418,27 @@ ShellConvertVariables ( } } - // - // Quick out if none were found... - // - if (NewSize == StrSize(OriginalCommandLine)) { - ASSERT(Temp == NULL); - Temp = StrnCatGrow(&Temp, NULL, OriginalCommandLine, 0); - return (Temp); - } - // // now do the replacements... // - NewCommandLine1 = AllocateZeroPool(NewSize); + NewCommandLine1 = AllocateCopyPool(NewSize, OriginalCommandLine); NewCommandLine2 = AllocateZeroPool(NewSize); ItemTemp = AllocateZeroPool(ItemSize+(2*sizeof(CHAR16))); - StrCpy(NewCommandLine1, OriginalCommandLine); + if (NewCommandLine1 == NULL || NewCommandLine2 == NULL || ItemTemp == NULL) { + SHELL_FREE_NON_NULL(NewCommandLine1); + SHELL_FREE_NON_NULL(NewCommandLine2); + SHELL_FREE_NON_NULL(ItemTemp); + return (NULL); + } for (MasterEnvList = EfiShellGetEnv(NULL) - ; MasterEnvList != NULL && *MasterEnvList != CHAR_NULL //&& *(MasterEnvList+1) != CHAR_NULL + ; MasterEnvList != NULL && *MasterEnvList != CHAR_NULL ; MasterEnvList += StrLen(MasterEnvList) + 1 ){ - StrCpy(ItemTemp, L"%"); - StrCat(ItemTemp, MasterEnvList); - StrCat(ItemTemp, L"%"); + StrnCpy(ItemTemp, L"%", ((ItemSize+(2*sizeof(CHAR16)))/sizeof(CHAR16))-1); + StrnCat(ItemTemp, MasterEnvList, ((ItemSize+(2*sizeof(CHAR16)))/sizeof(CHAR16))-1 - StrLen(ItemTemp)); + StrnCat(ItemTemp, L"%", ((ItemSize+(2*sizeof(CHAR16)))/sizeof(CHAR16))-1 - StrLen(ItemTemp)); ShellCopySearchAndReplace(NewCommandLine1, NewCommandLine2, NewSize, ItemTemp, EfiShellGetEnv(MasterEnvList), TRUE, FALSE); - StrCpy(NewCommandLine1, NewCommandLine2); + StrnCpy(NewCommandLine1, NewCommandLine2, NewSize/sizeof(CHAR16)-1); } if (CurrentScriptFile != NULL) { for (AliasListNode = (ALIAS_LIST*)GetFirstNode(&CurrentScriptFile->SubstList) @@ -1010,10 +1446,21 @@ ShellConvertVariables ( ; AliasListNode = (ALIAS_LIST*)GetNextNode(&CurrentScriptFile->SubstList, &AliasListNode->Link) ){ ShellCopySearchAndReplace(NewCommandLine1, NewCommandLine2, NewSize, AliasListNode->Alias, AliasListNode->CommandString, TRUE, FALSE); - StrCpy(NewCommandLine1, NewCommandLine2); + StrnCpy(NewCommandLine1, NewCommandLine2, NewSize/sizeof(CHAR16)-1); } + + // + // Remove non-existant environment variables in scripts only + // + StripUnreplacedEnvironmentVariables(NewCommandLine1); } + // + // Now cleanup any straggler intentionally ignored "%" characters + // + ShellCopySearchAndReplace(NewCommandLine1, NewCommandLine2, NewSize, L"^%", L"%", TRUE, FALSE); + StrnCpy(NewCommandLine1, NewCommandLine2, NewSize/sizeof(CHAR16)-1); + FreePool(NewCommandLine2); FreePool(ItemTemp); @@ -1059,7 +1506,16 @@ RunSplitCommand( NextCommandLine = StrnCatGrow(&NextCommandLine, &Size1, StrStr(CmdLine, L"|")+1, 0); OurCommandLine = StrnCatGrow(&OurCommandLine , &Size2, CmdLine , StrStr(CmdLine, L"|") - CmdLine); - if (NextCommandLine[0] != CHAR_NULL && + + if (NextCommandLine == NULL || OurCommandLine == NULL) { + SHELL_FREE_NON_NULL(OurCommandLine); + SHELL_FREE_NON_NULL(NextCommandLine); + return (EFI_OUT_OF_RESOURCES); + } else if (StrStr(OurCommandLine, L"|") != NULL || Size1 == 0 || Size2 == 0) { + SHELL_FREE_NON_NULL(OurCommandLine); + SHELL_FREE_NON_NULL(NextCommandLine); + return (EFI_INVALID_PARAMETER); + } else if (NextCommandLine[0] != CHAR_NULL && NextCommandLine[0] == L'a' && NextCommandLine[1] == L' ' ){ @@ -1080,7 +1536,6 @@ RunSplitCommand( ASSERT(Split->SplitStdOut != NULL); InsertHeadList(&ShellInfoObject.SplitList.Link, &Split->Link); - ASSERT(StrStr(OurCommandLine, L"|") == NULL); Status = RunCommand(OurCommandLine); // @@ -1123,319 +1578,894 @@ RunSplitCommand( } /** - Function will process and run a command line. - - This will determine if the command line represents an internal shell - command or dispatch an external application. + Take the original command line, substitute any variables, free + the original string, return the modified copy. - @param[in] CmdLine The command line to parse. + @param[in] CmdLine pointer to the command line to update. - @retval EFI_SUCCESS The command was completed. - @retval EFI_ABORTED The command's operation was aborted. + @retval EFI_SUCCESS the function was successful. + @retval EFI_OUT_OF_RESOURCES a memory allocation failed. **/ EFI_STATUS EFIAPI -RunCommand( - IN CONST CHAR16 *CmdLine +ShellSubstituteVariables( + IN CHAR16 **CmdLine ) { - EFI_STATUS Status; - CHAR16 *CommandName; - SHELL_STATUS ShellStatus; - UINTN Argc; - CHAR16 **Argv; - BOOLEAN LastError; - CHAR16 LeString[11]; - CHAR16 *PostAliasCmdLine; - UINTN PostAliasSize; - CHAR16 *PostVariableCmdLine; - CHAR16 *CommandWithPath; - EFI_DEVICE_PATH_PROTOCOL *DevPath; - CONST CHAR16 *TempLocation; - CONST CHAR16 *TempLocation2; - SHELL_FILE_HANDLE OriginalStdIn; - SHELL_FILE_HANDLE OriginalStdOut; - SHELL_FILE_HANDLE OriginalStdErr; - CHAR16 *TempLocation3; - UINTN Count; - UINTN Count2; - CHAR16 *CleanOriginal; - SPLIT_LIST *Split; - - ASSERT(CmdLine != NULL); - if (StrLen(CmdLine) == 0) { - return (EFI_SUCCESS); + CHAR16 *NewCmdLine; + NewCmdLine = ShellConvertVariables(*CmdLine); + SHELL_FREE_NON_NULL(*CmdLine); + if (NewCmdLine == NULL) { + return (EFI_OUT_OF_RESOURCES); } + *CmdLine = NewCmdLine; + return (EFI_SUCCESS); +} - CommandName = NULL; - PostVariableCmdLine = NULL; - PostAliasCmdLine = NULL; - CommandWithPath = NULL; - DevPath = NULL; - Status = EFI_SUCCESS; - CleanOriginal = NULL; - Split = NULL; +/** + Take the original command line, substitute any alias in the first group of space delimited characters, free + the original string, return the modified copy. + + @param[in] CmdLine pointer to the command line to update. + + @retval EFI_SUCCESS the function was successful. + @retval EFI_OUT_OF_RESOURCES a memory allocation failed. +**/ +EFI_STATUS +EFIAPI +ShellSubstituteAliases( + IN CHAR16 **CmdLine + ) +{ + CHAR16 *NewCmdLine; + CHAR16 *CommandName; + EFI_STATUS Status; + UINTN PostAliasSize; + ASSERT(CmdLine != NULL); + ASSERT(*CmdLine!= NULL); - CleanOriginal = StrnCatGrow(&CleanOriginal, NULL, CmdLine, 0); - while (CleanOriginal[StrLen(CleanOriginal)-1] == L' ') { - CleanOriginal[StrLen(CleanOriginal)-1] = CHAR_NULL; - } - while (CleanOriginal[0] == L' ') { - CopyMem(CleanOriginal, CleanOriginal+1, StrSize(CleanOriginal) - sizeof(CleanOriginal[0])); - } CommandName = NULL; - if (StrStr(CleanOriginal, L" ") == NULL){ - StrnCatGrow(&CommandName, NULL, CleanOriginal, 0); + if (StrStr((*CmdLine), L" ") == NULL){ + StrnCatGrow(&CommandName, NULL, (*CmdLine), 0); } else { - StrnCatGrow(&CommandName, NULL, CleanOriginal, StrStr(CleanOriginal, L" ") - CleanOriginal); + StrnCatGrow(&CommandName, NULL, (*CmdLine), StrStr((*CmdLine), L" ") - (*CmdLine)); } - ASSERT(PostAliasCmdLine == NULL); + // + // This cannot happen 'inline' since the CmdLine can need extra space. + // + NewCmdLine = NULL; if (!ShellCommandIsCommandOnList(CommandName)) { // // Convert via alias // Status = ShellConvertAlias(&CommandName); + if (EFI_ERROR(Status)){ + return (Status); + } PostAliasSize = 0; - PostAliasCmdLine = StrnCatGrow(&PostAliasCmdLine, &PostAliasSize, CommandName, 0); - PostAliasCmdLine = StrnCatGrow(&PostAliasCmdLine, &PostAliasSize, StrStr(CleanOriginal, L" "), 0); - ASSERT_EFI_ERROR(Status); + NewCmdLine = StrnCatGrow(&NewCmdLine, &PostAliasSize, CommandName, 0); + if (NewCmdLine == NULL) { + SHELL_FREE_NON_NULL(CommandName); + SHELL_FREE_NON_NULL(*CmdLine); + return (EFI_OUT_OF_RESOURCES); + } + NewCmdLine = StrnCatGrow(&NewCmdLine, &PostAliasSize, StrStr((*CmdLine), L" "), 0); + if (NewCmdLine == NULL) { + SHELL_FREE_NON_NULL(CommandName); + SHELL_FREE_NON_NULL(*CmdLine); + return (EFI_OUT_OF_RESOURCES); + } } else { - PostAliasCmdLine = StrnCatGrow(&PostAliasCmdLine, NULL, CleanOriginal, 0); + NewCmdLine = StrnCatGrow(&NewCmdLine, NULL, (*CmdLine), 0); } - if (CleanOriginal != NULL) { - FreePool(CleanOriginal); - CleanOriginal = NULL; - } + SHELL_FREE_NON_NULL(*CmdLine); + SHELL_FREE_NON_NULL(CommandName); + + // + // re-assign the passed in double pointer to point to our newly allocated buffer + // + *CmdLine = NewCmdLine; - if (CommandName != NULL) { - FreePool(CommandName); - CommandName = NULL; - } + return (EFI_SUCCESS); +} - PostVariableCmdLine = ShellConvertVariables(PostAliasCmdLine); +/** + Takes the Argv[0] part of the command line and determine the meaning of it. + + @param[in] CmdName pointer to the command line to update. + + @retval Internal_Command The name is an internal command. + @retval File_Sys_Change the name is a file system change. + @retval Script_File_Name the name is a NSH script file. + @retval Unknown_Invalid the name is unknown. + @retval Efi_Application the name is an application (.EFI). +**/ +SHELL_OPERATION_TYPES +EFIAPI +GetOperationType( + IN CONST CHAR16 *CmdName + ) +{ + CHAR16* FileWithPath; + CONST CHAR16* TempLocation; + CONST CHAR16* TempLocation2; + FileWithPath = NULL; // - // we can now free the modified by alias command line + // test for an internal command. // - if (PostAliasCmdLine != NULL) { - FreePool(PostAliasCmdLine); - PostAliasCmdLine = NULL; - } - - while (PostVariableCmdLine[StrLen(PostVariableCmdLine)-1] == L' ') { - PostVariableCmdLine[StrLen(PostVariableCmdLine)-1] = CHAR_NULL; - } - while (PostVariableCmdLine[0] == L' ') { - CopyMem(PostVariableCmdLine, PostVariableCmdLine+1, StrSize(PostVariableCmdLine) - sizeof(PostVariableCmdLine[0])); + if (ShellCommandIsCommandOnList(CmdName)) { + return (Internal_Command); } // - // We dont do normal processing with a split command line (output from one command input to another) + // Test for file system change request. anything ending with first : and cant have spaces. // - TempLocation3 = NULL; - if (StrStr(PostVariableCmdLine, L"|") != NULL) { - for (TempLocation3 = PostVariableCmdLine ; TempLocation3 != NULL && *TempLocation3 != CHAR_NULL ; TempLocation3++) { - if (*TempLocation3 == L'^' && *(TempLocation3+1) == L'|') { - TempLocation3++; - } else if (*TempLocation3 == L'|') { - break; - } + if (CmdName[(StrLen(CmdName)-1)] == L':') { + if ( StrStr(CmdName, L" ") != NULL + || StrLen(StrStr(CmdName, L":")) > 1 + ) { + return (Unknown_Invalid); } + return (File_Sys_Change); } - if (TempLocation3 != NULL && *TempLocation3 != CHAR_NULL) { - // - // are we in an existing split??? - // - if (!IsListEmpty(&ShellInfoObject.SplitList.Link)) { - Split = (SPLIT_LIST*)GetFirstNode(&ShellInfoObject.SplitList.Link); - } - - if (Split == NULL) { - Status = RunSplitCommand(PostVariableCmdLine, NULL, NULL); - } else { - Status = RunSplitCommand(PostVariableCmdLine, Split->SplitStdIn, Split->SplitStdOut); - } - } else { + // + // Test for a file + // + if ((FileWithPath = ShellFindFilePathEx(CmdName, mExecutableExtensions)) != NULL) { // - // If this is a mapped drive change handle that... + // See if that file has a script file extension // - if (PostVariableCmdLine[(StrLen(PostVariableCmdLine)-1)] == L':' && StrStr(PostVariableCmdLine, L" ") == NULL) { - Status = ShellInfoObject.NewEfiShellProtocol->SetCurDir(NULL, PostVariableCmdLine); - if (EFI_ERROR(Status)) { - ShellPrintHiiEx(-1, -1, NULL, STRING_TOKEN (STR_SHELL_INVALID_MAPPING), ShellInfoObject.HiiHandle, PostVariableCmdLine); + if (StrLen(FileWithPath) > 4) { + TempLocation = FileWithPath+StrLen(FileWithPath)-4; + TempLocation2 = mScriptExtension; + if (StringNoCaseCompare((VOID*)(&TempLocation), (VOID*)(&TempLocation2)) == 0) { + SHELL_FREE_NON_NULL(FileWithPath); + return (Script_File_Name); } - FreePool(PostVariableCmdLine); - return (Status); } - ///@todo update this section to divide into 3 ways - run internal command, run split (above), and run an external file... - /// We waste a lot of time doing processing like StdIn,StdOut,Argv,Argc for things that are external files... + // + // Was a file, but not a script. we treat this as an application. + // + SHELL_FREE_NON_NULL(FileWithPath); + return (Efi_Application); + } + + SHELL_FREE_NON_NULL(FileWithPath); + // + // No clue what this is... return invalid flag... + // + return (Unknown_Invalid); +} +/** + Determine if the first item in a command line is valid. + @param[in] CmdLine The command line to parse. - Status = UpdateStdInStdOutStdErr(ShellInfoObject.NewShellParametersProtocol, PostVariableCmdLine, &OriginalStdIn, &OriginalStdOut, &OriginalStdErr); - if (EFI_ERROR(Status)) { - ShellPrintHiiEx(-1, -1, NULL, STRING_TOKEN (STR_SHELL_INVALID_REDIR), ShellInfoObject.HiiHandle); - } else { - // - // remove the < and/or > from the command line now - // - for (TempLocation3 = PostVariableCmdLine ; TempLocation3 != NULL && *TempLocation3 != CHAR_NULL ; TempLocation3++) { - if (*TempLocation3 == L'^') { - if (*(TempLocation3+1) == L'<' || *(TempLocation3+1) == L'>') { - CopyMem(TempLocation3, TempLocation3+1, StrSize(TempLocation3) - sizeof(TempLocation3[0])); - } - } else if (*TempLocation3 == L'>') { - *TempLocation3 = CHAR_NULL; - } else if ((*TempLocation3 == L'1' || *TempLocation3 == L'2')&&(*(TempLocation3+1) == L'>')) { - *TempLocation3 = CHAR_NULL; - } - } + @retval EFI_SUCCESS The item is valid. + @retval EFI_OUT_OF_RESOURCES A memory allocation failed. + @retval EFI_NOT_FOUND The operation type is unknown or invalid. +**/ +EFI_STATUS +EFIAPI +IsValidSplit( + IN CONST CHAR16 *CmdLine + ) +{ + CHAR16 *Temp; + CHAR16 *FirstParameter; + CHAR16 *TempWalker; + EFI_STATUS Status; - while (PostVariableCmdLine[StrLen(PostVariableCmdLine)-1] == L' ') { - PostVariableCmdLine[StrLen(PostVariableCmdLine)-1] = CHAR_NULL; - } - while (PostVariableCmdLine[0] == L' ') { - CopyMem(PostVariableCmdLine, PostVariableCmdLine+1, StrSize(PostVariableCmdLine) - sizeof(PostVariableCmdLine[0])); - } + Temp = NULL; - // - // get the argc and argv updated for internal commands - // - Status = UpdateArgcArgv(ShellInfoObject.NewShellParametersProtocol, PostVariableCmdLine, &Argv, &Argc); - ASSERT_EFI_ERROR(Status); + Temp = StrnCatGrow(&Temp, NULL, CmdLine, 0); + if (Temp == NULL) { + return (EFI_OUT_OF_RESOURCES); + } - for (Count = 0 ; Count < ShellInfoObject.NewShellParametersProtocol->Argc ; Count++) { - if (StrStr(ShellInfoObject.NewShellParametersProtocol->Argv[Count], L"-?") == ShellInfoObject.NewShellParametersProtocol->Argv[Count] - || (ShellInfoObject.NewShellParametersProtocol->Argv[0][0] == L'?' && ShellInfoObject.NewShellParametersProtocol->Argv[0][1] == CHAR_NULL) - ) { - // - // We need to redo the arguments since a parameter was -? - // move them all down 1 to the end, then up one then replace the first with help - // - FreePool(ShellInfoObject.NewShellParametersProtocol->Argv[Count]); - ShellInfoObject.NewShellParametersProtocol->Argv[Count] = NULL; - for (Count2 = Count ; (Count2 + 1) < ShellInfoObject.NewShellParametersProtocol->Argc ; Count2++) { - ShellInfoObject.NewShellParametersProtocol->Argv[Count2] = ShellInfoObject.NewShellParametersProtocol->Argv[Count2+1]; - } - ShellInfoObject.NewShellParametersProtocol->Argv[Count2] = NULL; - for (Count2 = ShellInfoObject.NewShellParametersProtocol->Argc -1 ; Count2 > 0 ; Count2--) { - ShellInfoObject.NewShellParametersProtocol->Argv[Count2] = ShellInfoObject.NewShellParametersProtocol->Argv[Count2-1]; - } - ShellInfoObject.NewShellParametersProtocol->Argv[0] = NULL; - ShellInfoObject.NewShellParametersProtocol->Argv[0] = StrnCatGrow(&ShellInfoObject.NewShellParametersProtocol->Argv[0], NULL, L"help", 0); - break; - } - } + FirstParameter = StrStr(Temp, L"|"); + if (FirstParameter != NULL) { + *FirstParameter = CHAR_NULL; + } - // - // command or file? - // - if (ShellCommandIsCommandOnList(ShellInfoObject.NewShellParametersProtocol->Argv[0])) { - // - // Run the command (which was converted if it was an alias) - // - if (!EFI_ERROR(Status)) { - Status = ShellCommandRunCommandHandler(ShellInfoObject.NewShellParametersProtocol->Argv[0], &ShellStatus, &LastError); - ASSERT_EFI_ERROR(Status); - UnicodeSPrint(LeString, sizeof(LeString)*sizeof(LeString[0]), L"0x%08x", ShellStatus); - DEBUG_CODE(InternalEfiShellSetEnv(L"DebugLasterror", LeString, TRUE);); - if (LastError) { - InternalEfiShellSetEnv(L"Lasterror", LeString, TRUE); - } - // - // Pass thru the exitcode from the app. - // - if (ShellCommandGetExit()) { - Status = ShellStatus; - } else if (ShellStatus != 0 && IsScriptOnlyCommand(ShellInfoObject.NewShellParametersProtocol->Argv[0])) { - Status = EFI_ABORTED; - } - } - } else { - // - // run an external file (or script) - // - if (StrStr(ShellInfoObject.NewShellParametersProtocol->Argv[0], L":") != NULL) { - ASSERT (CommandWithPath == NULL); - if (ShellIsFile(ShellInfoObject.NewShellParametersProtocol->Argv[0]) == EFI_SUCCESS) { - CommandWithPath = StrnCatGrow(&CommandWithPath, NULL, ShellInfoObject.NewShellParametersProtocol->Argv[0], 0); - } - } - if (CommandWithPath == NULL) { - CommandWithPath = ShellFindFilePathEx(ShellInfoObject.NewShellParametersProtocol->Argv[0], mExecutableExtensions); - } - if (CommandWithPath == NULL || ShellIsDirectory(CommandWithPath) == EFI_SUCCESS) { - ShellPrintHiiEx(-1, -1, NULL, STRING_TOKEN (STR_SHELL_NOT_FOUND), ShellInfoObject.HiiHandle, ShellInfoObject.NewShellParametersProtocol->Argv[0]); - } else { - // - // Check if it's a NSH (script) file. - // - TempLocation = CommandWithPath+StrLen(CommandWithPath)-4; - TempLocation2 = mScriptExtension; - if ((StrLen(CommandWithPath) > 4) && (StringNoCaseCompare((VOID*)(&TempLocation), (VOID*)(&TempLocation2)) == 0)) { - Status = RunScriptFile (CommandWithPath); - } else { - DevPath = ShellInfoObject.NewEfiShellProtocol->GetDevicePathFromFilePath(CommandWithPath); - ASSERT(DevPath != NULL); - Status = InternalShellExecuteDevicePath( - &gImageHandle, - DevPath, - PostVariableCmdLine, - NULL, - NULL - ); - } - } - } - CommandName = StrnCatGrow(&CommandName, NULL, ShellInfoObject.NewShellParametersProtocol->Argv[0], 0); + FirstParameter = NULL; - RestoreArgcArgv(ShellInfoObject.NewShellParametersProtocol, &Argv, &Argc); + // + // Process the command line + // + Status = ProcessCommandLineToFinal(&Temp); - RestoreStdInStdOutStdErr(ShellInfoObject.NewShellParametersProtocol, &OriginalStdIn, &OriginalStdOut, &OriginalStdErr); + if (!EFI_ERROR(Status)) { + FirstParameter = AllocateZeroPool(StrSize(CmdLine)); + if (FirstParameter == NULL) { + SHELL_FREE_NON_NULL(Temp); + return (EFI_OUT_OF_RESOURCES); } - if (CommandName != NULL) { - if (ShellCommandGetCurrentScriptFile() != NULL && !IsScriptOnlyCommand(CommandName)) { - // - // if this is NOT a scipt only command return success so the script won't quit. - // prevent killing the script - this is the only place where we know the actual command name (after alias and variable replacement...) - // - Status = EFI_SUCCESS; - } + TempWalker = (CHAR16*)Temp; + GetNextParameter(&TempWalker, &FirstParameter, StrSize(CmdLine)); + + if (GetOperationType(FirstParameter) == Unknown_Invalid) { + ShellPrintHiiEx(-1, -1, NULL, STRING_TOKEN (STR_SHELL_NOT_FOUND), ShellInfoObject.HiiHandle, FirstParameter); + SetLastError(SHELL_NOT_FOUND); + Status = EFI_NOT_FOUND; } } - SHELL_FREE_NON_NULL(CommandName); - SHELL_FREE_NON_NULL(CommandWithPath); - SHELL_FREE_NON_NULL(PostVariableCmdLine); - SHELL_FREE_NON_NULL(DevPath); - - return (Status); + SHELL_FREE_NON_NULL(Temp); + SHELL_FREE_NON_NULL(FirstParameter); + return Status; } -STATIC CONST UINT16 InvalidChars[] = {L'*', L'?', L'<', L'>', L'\\', L'/', L'\"', 0x0001, 0x0002}; /** - Function determins if the CommandName COULD be a valid command. It does not determine whether - this is a valid command. It only checks for invalid characters. + Determine if a command line contains with a split contains only valid commands. - @param[in] CommandName The name to check + @param[in] CmdLine The command line to parse. - @retval TRUE CommandName could be a command name - @retval FALSE CommandName could not be a valid command name + @retval EFI_SUCCESS CmdLine has only valid commands, application, or has no split. + @retval EFI_ABORTED CmdLine has at least one invalid command or application. **/ -BOOLEAN +EFI_STATUS EFIAPI -IsValidCommandName( - IN CONST CHAR16 *CommandName +VerifySplit( + IN CONST CHAR16 *CmdLine ) { - UINTN Count; - if (CommandName == NULL) { - ASSERT(FALSE); + CONST CHAR16 *TempSpot; + EFI_STATUS Status; + + // + // Verify up to the pipe or end character + // + Status = IsValidSplit(CmdLine); + if (EFI_ERROR(Status)) { + return (Status); + } + + // + // If this was the only item, then get out + // + if (!ContainsSplit(CmdLine)) { + return (EFI_SUCCESS); + } + + // + // recurse to verify the next item + // + TempSpot = FindSplit(CmdLine)+1; + return (VerifySplit(TempSpot)); +} + +/** + Process a split based operation. + + @param[in] CmdLine pointer to the command line to process + + @retval EFI_SUCCESS The operation was successful + @return an error occured. +**/ +EFI_STATUS +EFIAPI +ProcessNewSplitCommandLine( + IN CONST CHAR16 *CmdLine + ) +{ + SPLIT_LIST *Split; + EFI_STATUS Status; + + Status = VerifySplit(CmdLine); + if (EFI_ERROR(Status)) { + return (Status); + } + + Split = NULL; + + // + // are we in an existing split??? + // + if (!IsListEmpty(&ShellInfoObject.SplitList.Link)) { + Split = (SPLIT_LIST*)GetFirstNode(&ShellInfoObject.SplitList.Link); + } + + if (Split == NULL) { + Status = RunSplitCommand(CmdLine, NULL, NULL); + } else { + Status = RunSplitCommand(CmdLine, Split->SplitStdIn, Split->SplitStdOut); + } + if (EFI_ERROR(Status)) { + ShellPrintHiiEx(-1, -1, NULL, STRING_TOKEN (STR_SHELL_INVALID_SPLIT), ShellInfoObject.HiiHandle, CmdLine); + } + return (Status); +} + +/** + Handle a request to change the current file system. + + @param[in] CmdLine The passed in command line. + + @retval EFI_SUCCESS The operation was successful. +**/ +EFI_STATUS +EFIAPI +ChangeMappedDrive( + IN CONST CHAR16 *CmdLine + ) +{ + EFI_STATUS Status; + Status = EFI_SUCCESS; + + // + // make sure we are the right operation + // + ASSERT(CmdLine[(StrLen(CmdLine)-1)] == L':' && StrStr(CmdLine, L" ") == NULL); + + // + // Call the protocol API to do the work + // + Status = ShellInfoObject.NewEfiShellProtocol->SetCurDir(NULL, CmdLine); + + // + // Report any errors + // + if (EFI_ERROR(Status)) { + ShellPrintHiiEx(-1, -1, NULL, STRING_TOKEN (STR_SHELL_INVALID_MAPPING), ShellInfoObject.HiiHandle, CmdLine); + } + + return (Status); +} + +/** + Reprocess the command line to direct all -? to the help command. + + if found, will add "help" as argv[0], and move the rest later. + + @param[in,out] CmdLine pointer to the command line to update +**/ +EFI_STATUS +EFIAPI +DoHelpUpdate( + IN OUT CHAR16 **CmdLine + ) +{ + CHAR16 *CurrentParameter; + CHAR16 *Walker; + CHAR16 *LastWalker; + CHAR16 *NewCommandLine; + EFI_STATUS Status; + + Status = EFI_SUCCESS; + + CurrentParameter = AllocateZeroPool(StrSize(*CmdLine)); + if (CurrentParameter == NULL) { + return (EFI_OUT_OF_RESOURCES); + } + + Walker = *CmdLine; + while(Walker != NULL && *Walker != CHAR_NULL) { + LastWalker = Walker; + GetNextParameter(&Walker, &CurrentParameter, StrSize(*CmdLine)); + if (StrStr(CurrentParameter, L"-?") == CurrentParameter) { + LastWalker[0] = L' '; + LastWalker[1] = L' '; + NewCommandLine = AllocateZeroPool(StrSize(L"help ") + StrSize(*CmdLine)); + if (NewCommandLine == NULL) { + Status = EFI_OUT_OF_RESOURCES; + break; + } + + // + // We know the space is sufficient since we just calculated it. + // + StrnCpy(NewCommandLine, L"help ", 5); + StrnCat(NewCommandLine, *CmdLine, StrLen(*CmdLine)); + SHELL_FREE_NON_NULL(*CmdLine); + *CmdLine = NewCommandLine; + break; + } + } + + SHELL_FREE_NON_NULL(CurrentParameter); + + return (Status); +} + +/** + Function to update the shell variable "lasterror". + + @param[in] ErrorCode the error code to put into lasterror. +**/ +EFI_STATUS +EFIAPI +SetLastError( + IN CONST SHELL_STATUS ErrorCode + ) +{ + CHAR16 LeString[19]; + if (sizeof(EFI_STATUS) == sizeof(UINT64)) { + UnicodeSPrint(LeString, sizeof(LeString), L"0x%Lx", ErrorCode); + } else { + UnicodeSPrint(LeString, sizeof(LeString), L"0x%x", ErrorCode); + } + DEBUG_CODE(InternalEfiShellSetEnv(L"debuglasterror", LeString, TRUE);); + InternalEfiShellSetEnv(L"lasterror", LeString, TRUE); + + return (EFI_SUCCESS); +} + +/** + Converts the command line to it's post-processed form. this replaces variables and alias' per UEFI Shell spec. + + @param[in,out] CmdLine pointer to the command line to update + + @retval EFI_SUCCESS The operation was successful + @retval EFI_OUT_OF_RESOURCES A memory allocation failed. + @return some other error occured +**/ +EFI_STATUS +EFIAPI +ProcessCommandLineToFinal( + IN OUT CHAR16 **CmdLine + ) +{ + EFI_STATUS Status; + TrimSpaces(CmdLine); + + Status = ShellSubstituteAliases(CmdLine); + if (EFI_ERROR(Status)) { + return (Status); + } + + TrimSpaces(CmdLine); + + Status = ShellSubstituteVariables(CmdLine); + if (EFI_ERROR(Status)) { + return (Status); + } + ASSERT (*CmdLine != NULL); + + TrimSpaces(CmdLine); + + // + // update for help parsing + // + if (StrStr(*CmdLine, L"?") != NULL) { + // + // This may do nothing if the ? does not indicate help. + // Save all the details for in the API below. + // + Status = DoHelpUpdate(CmdLine); + } + + TrimSpaces(CmdLine); + + return (EFI_SUCCESS); +} + +/** + Run an internal shell command. + + This API will upadate the shell's environment since these commands are libraries. + + @param[in] CmdLine the command line to run. + @param[in] FirstParameter the first parameter on the command line + @param[in] ParamProtocol the shell parameters protocol pointer + + @retval EFI_SUCCESS The command was completed. + @retval EFI_ABORTED The command's operation was aborted. +**/ +EFI_STATUS +EFIAPI +RunInternalCommand( + IN CONST CHAR16 *CmdLine, + IN CHAR16 *FirstParameter, + IN EFI_SHELL_PARAMETERS_PROTOCOL *ParamProtocol +) +{ + EFI_STATUS Status; + UINTN Argc; + CHAR16 **Argv; + SHELL_STATUS CommandReturnedStatus; + BOOLEAN LastError; + CHAR16 *Walker; + CHAR16 *NewCmdLine; + + NewCmdLine = AllocateCopyPool (StrSize (CmdLine), CmdLine); + if (NewCmdLine == NULL) { + return EFI_OUT_OF_RESOURCES; + } + + for (Walker = NewCmdLine; Walker != NULL && *Walker != CHAR_NULL ; Walker++) { + if (*Walker == L'^' && *(Walker+1) == L'#') { + CopyMem(Walker, Walker+1, StrSize(Walker) - sizeof(Walker[0])); + } + } + + // + // get the argc and argv updated for internal commands + // + Status = UpdateArgcArgv(ParamProtocol, NewCmdLine, &Argv, &Argc); + if (!EFI_ERROR(Status)) { + // + // Run the internal command. + // + Status = ShellCommandRunCommandHandler(FirstParameter, &CommandReturnedStatus, &LastError); + + if (!EFI_ERROR(Status)) { + // + // Update last error status. + // some commands do not update last error. + // + if (LastError) { + SetLastError(CommandReturnedStatus); + } + + // + // Pass thru the exitcode from the app. + // + if (ShellCommandGetExit()) { + // + // An Exit was requested ("exit" command), pass its value up. + // + Status = CommandReturnedStatus; + } else if (CommandReturnedStatus != SHELL_SUCCESS && IsScriptOnlyCommand(FirstParameter)) { + // + // Always abort when a script only command fails for any reason + // + Status = EFI_ABORTED; + } else if (ShellCommandGetCurrentScriptFile() != NULL && CommandReturnedStatus == SHELL_ABORTED) { + // + // Abort when in a script and a command aborted + // + Status = EFI_ABORTED; + } + } + } + + // + // This is guarenteed to be called after UpdateArgcArgv no matter what else happened. + // This is safe even if the update API failed. In this case, it may be a no-op. + // + RestoreArgcArgv(ParamProtocol, &Argv, &Argc); + + // + // If a script is running and the command is not a scipt only command, then + // change return value to success so the script won't halt (unless aborted). + // + // Script only commands have to be able halt the script since the script will + // not operate if they are failing. + // + if ( ShellCommandGetCurrentScriptFile() != NULL + && !IsScriptOnlyCommand(FirstParameter) + && Status != EFI_ABORTED + ) { + Status = EFI_SUCCESS; + } + + FreePool (NewCmdLine); + return (Status); +} + +/** + Function to run the command or file. + + @param[in] Type the type of operation being run. + @param[in] CmdLine the command line to run. + @param[in] FirstParameter the first parameter on the command line + @param[in] ParamProtocol the shell parameters protocol pointer + + @retval EFI_SUCCESS The command was completed. + @retval EFI_ABORTED The command's operation was aborted. +**/ +EFI_STATUS +EFIAPI +RunCommandOrFile( + IN SHELL_OPERATION_TYPES Type, + IN CONST CHAR16 *CmdLine, + IN CHAR16 *FirstParameter, + IN EFI_SHELL_PARAMETERS_PROTOCOL *ParamProtocol +) +{ + EFI_STATUS Status; + EFI_STATUS StartStatus; + CHAR16 *CommandWithPath; + EFI_DEVICE_PATH_PROTOCOL *DevPath; + SHELL_STATUS CalleeExitStatus; + + Status = EFI_SUCCESS; + CommandWithPath = NULL; + DevPath = NULL; + CalleeExitStatus = SHELL_INVALID_PARAMETER; + + switch (Type) { + case Internal_Command: + Status = RunInternalCommand(CmdLine, FirstParameter, ParamProtocol); + break; + case Script_File_Name: + case Efi_Application: + // + // Process a fully qualified path + // + if (StrStr(FirstParameter, L":") != NULL) { + ASSERT (CommandWithPath == NULL); + if (ShellIsFile(FirstParameter) == EFI_SUCCESS) { + CommandWithPath = StrnCatGrow(&CommandWithPath, NULL, FirstParameter, 0); + } + } + + // + // Process a relative path and also check in the path environment variable + // + if (CommandWithPath == NULL) { + CommandWithPath = ShellFindFilePathEx(FirstParameter, mExecutableExtensions); + } + + // + // This should be impossible now. + // + ASSERT(CommandWithPath != NULL); + + // + // Make sure that path is not just a directory (or not found) + // + if (!EFI_ERROR(ShellIsDirectory(CommandWithPath))) { + ShellPrintHiiEx(-1, -1, NULL, STRING_TOKEN (STR_SHELL_NOT_FOUND), ShellInfoObject.HiiHandle, FirstParameter); + SetLastError(SHELL_NOT_FOUND); + } + switch (Type) { + case Script_File_Name: + Status = RunScriptFile (CommandWithPath, NULL, CmdLine, ParamProtocol); + break; + case Efi_Application: + // + // Get the device path of the application image + // + DevPath = ShellInfoObject.NewEfiShellProtocol->GetDevicePathFromFilePath(CommandWithPath); + if (DevPath == NULL){ + Status = EFI_OUT_OF_RESOURCES; + break; + } + + // + // Execute the device path + // + Status = InternalShellExecuteDevicePath( + &gImageHandle, + DevPath, + CmdLine, + NULL, + &StartStatus + ); + + SHELL_FREE_NON_NULL(DevPath); + + if(EFI_ERROR (Status)) { + CalleeExitStatus = (SHELL_STATUS) (Status & (~MAX_BIT)); + } else { + CalleeExitStatus = (SHELL_STATUS) StartStatus; + } + + // + // Update last error status. + // + // Status is an EFI_STATUS. Clear top bit to convert to SHELL_STATUS + SetLastError(CalleeExitStatus); + break; + default: + // + // Do nothing. + // + break; + } + break; + default: + // + // Do nothing. + // + break; + } + + SHELL_FREE_NON_NULL(CommandWithPath); + + return (Status); +} + +/** + Function to setup StdIn, StdErr, StdOut, and then run the command or file. + + @param[in] Type the type of operation being run. + @param[in] CmdLine the command line to run. + @param[in] FirstParameter the first parameter on the command line. + @param[in] ParamProtocol the shell parameters protocol pointer + + @retval EFI_SUCCESS The command was completed. + @retval EFI_ABORTED The command's operation was aborted. +**/ +EFI_STATUS +EFIAPI +SetupAndRunCommandOrFile( + IN SHELL_OPERATION_TYPES Type, + IN CHAR16 *CmdLine, + IN CHAR16 *FirstParameter, + IN EFI_SHELL_PARAMETERS_PROTOCOL *ParamProtocol +) +{ + EFI_STATUS Status; + SHELL_FILE_HANDLE OriginalStdIn; + SHELL_FILE_HANDLE OriginalStdOut; + SHELL_FILE_HANDLE OriginalStdErr; + SYSTEM_TABLE_INFO OriginalSystemTableInfo; + + // + // Update the StdIn, StdOut, and StdErr for redirection to environment variables, files, etc... unicode and ASCII + // + Status = UpdateStdInStdOutStdErr(ParamProtocol, CmdLine, &OriginalStdIn, &OriginalStdOut, &OriginalStdErr, &OriginalSystemTableInfo); + + // + // The StdIn, StdOut, and StdErr are set up. + // Now run the command, script, or application + // + if (!EFI_ERROR(Status)) { + TrimSpaces(&CmdLine); + Status = RunCommandOrFile(Type, CmdLine, FirstParameter, ParamProtocol); + } + + // + // Now print errors + // + if (EFI_ERROR(Status)) { + ShellPrintHiiEx(-1, -1, NULL, STRING_TOKEN (STR_SHELL_ERROR), ShellInfoObject.HiiHandle, (VOID*)(Status)); + } + + // + // put back the original StdIn, StdOut, and StdErr + // + RestoreStdInStdOutStdErr(ParamProtocol, &OriginalStdIn, &OriginalStdOut, &OriginalStdErr, &OriginalSystemTableInfo); + + return (Status); +} + +/** + Function will process and run a command line. + + This will determine if the command line represents an internal shell + command or dispatch an external application. + + @param[in] CmdLine The command line to parse. + + @retval EFI_SUCCESS The command was completed. + @retval EFI_ABORTED The command's operation was aborted. +**/ +EFI_STATUS +EFIAPI +RunCommand( + IN CONST CHAR16 *CmdLine + ) +{ + EFI_STATUS Status; + CHAR16 *CleanOriginal; + CHAR16 *FirstParameter; + CHAR16 *TempWalker; + SHELL_OPERATION_TYPES Type; + + ASSERT(CmdLine != NULL); + if (StrLen(CmdLine) == 0) { + return (EFI_SUCCESS); + } + + Status = EFI_SUCCESS; + CleanOriginal = NULL; + + CleanOriginal = StrnCatGrow(&CleanOriginal, NULL, CmdLine, 0); + if (CleanOriginal == NULL) { + return (EFI_OUT_OF_RESOURCES); + } + + TrimSpaces(&CleanOriginal); + + // + // NULL out comments (leveraged from RunScriptFileHandle() ). + // The # character on a line is used to denote that all characters on the same line + // and to the right of the # are to be ignored by the shell. + // Afterward, again remove spaces, in case any were between the last command-parameter and '#'. + // + for (TempWalker = CleanOriginal; TempWalker != NULL && *TempWalker != CHAR_NULL; TempWalker++) { + if (*TempWalker == L'^') { + if (*(TempWalker + 1) == L'#') { + TempWalker++; + } + } else if (*TempWalker == L'#') { + *TempWalker = CHAR_NULL; + } + } + + TrimSpaces(&CleanOriginal); + + // + // Handle case that passed in command line is just 1 or more " " characters. + // + if (StrLen (CleanOriginal) == 0) { + SHELL_FREE_NON_NULL(CleanOriginal); + return (EFI_SUCCESS); + } + + Status = ProcessCommandLineToFinal(&CleanOriginal); + if (EFI_ERROR(Status)) { + SHELL_FREE_NON_NULL(CleanOriginal); + return (Status); + } + + // + // We dont do normal processing with a split command line (output from one command input to another) + // + if (ContainsSplit(CleanOriginal)) { + Status = ProcessNewSplitCommandLine(CleanOriginal); + SHELL_FREE_NON_NULL(CleanOriginal); + return (Status); + } + + // + // We need the first parameter information so we can determine the operation type + // + FirstParameter = AllocateZeroPool(StrSize(CleanOriginal)); + if (FirstParameter == NULL) { + SHELL_FREE_NON_NULL(CleanOriginal); + return (EFI_OUT_OF_RESOURCES); + } + TempWalker = CleanOriginal; + GetNextParameter(&TempWalker, &FirstParameter, StrSize(CleanOriginal)); + + // + // Depending on the first parameter we change the behavior + // + switch (Type = GetOperationType(FirstParameter)) { + case File_Sys_Change: + Status = ChangeMappedDrive (FirstParameter); + break; + case Internal_Command: + case Script_File_Name: + case Efi_Application: + Status = SetupAndRunCommandOrFile(Type, CleanOriginal, FirstParameter, ShellInfoObject.NewShellParametersProtocol); + break; + default: + // + // Whatever was typed, it was invalid. + // + ShellPrintHiiEx(-1, -1, NULL, STRING_TOKEN (STR_SHELL_NOT_FOUND), ShellInfoObject.HiiHandle, FirstParameter); + SetLastError(SHELL_NOT_FOUND); + break; + } + + SHELL_FREE_NON_NULL(CleanOriginal); + SHELL_FREE_NON_NULL(FirstParameter); + + return (Status); +} + +STATIC CONST UINT16 InvalidChars[] = {L'*', L'?', L'<', L'>', L'\\', L'/', L'\"', 0x0001, 0x0002}; +/** + Function determins if the CommandName COULD be a valid command. It does not determine whether + this is a valid command. It only checks for invalid characters. + + @param[in] CommandName The name to check + + @retval TRUE CommandName could be a command name + @retval FALSE CommandName could not be a valid command name +**/ +BOOLEAN +EFIAPI +IsValidCommandName( + IN CONST CHAR16 *CommandName + ) +{ + UINTN Count; + if (CommandName == NULL) { + ASSERT(FALSE); return (FALSE); } for ( Count = 0 @@ -1473,21 +2503,29 @@ RunScriptFileHandle ( SCRIPT_COMMAND_LIST *LastCommand; BOOLEAN Ascii; BOOLEAN PreScriptEchoState; + BOOLEAN PreCommandEchoState; CONST CHAR16 *CurDir; UINTN LineCount; + CHAR16 LeString[50]; ASSERT(!ShellCommandGetScriptExit()); PreScriptEchoState = ShellCommandGetEchoState(); NewScriptFile = (SCRIPT_FILE*)AllocateZeroPool(sizeof(SCRIPT_FILE)); - ASSERT(NewScriptFile != NULL); + if (NewScriptFile == NULL) { + return (EFI_OUT_OF_RESOURCES); + } // // Set up the name // ASSERT(NewScriptFile->ScriptName == NULL); NewScriptFile->ScriptName = StrnCatGrow(&NewScriptFile->ScriptName, NULL, Name, 0); + if (NewScriptFile->ScriptName == NULL) { + DeleteScriptFileStruct(NewScriptFile); + return (EFI_OUT_OF_RESOURCES); + } // // Save the parameters (used to replace %0 to %9 later on) @@ -1495,10 +2533,17 @@ RunScriptFileHandle ( NewScriptFile->Argc = ShellInfoObject.NewShellParametersProtocol->Argc; if (NewScriptFile->Argc != 0) { NewScriptFile->Argv = (CHAR16**)AllocateZeroPool(NewScriptFile->Argc * sizeof(CHAR16*)); - ASSERT(NewScriptFile->Argv != NULL); + if (NewScriptFile->Argv == NULL) { + DeleteScriptFileStruct(NewScriptFile); + return (EFI_OUT_OF_RESOURCES); + } for (LoopVar = 0 ; LoopVar < 10 && LoopVar < NewScriptFile->Argc; LoopVar++) { ASSERT(NewScriptFile->Argv[LoopVar] == NULL); NewScriptFile->Argv[LoopVar] = StrnCatGrow(&NewScriptFile->Argv[LoopVar], NULL, ShellInfoObject.NewShellParametersProtocol->Argv[LoopVar], 0); + if (NewScriptFile->Argv[LoopVar] == NULL) { + DeleteScriptFileStruct(NewScriptFile); + return (EFI_OUT_OF_RESOURCES); + } } } else { NewScriptFile->Argv = NULL; @@ -1514,11 +2559,16 @@ RunScriptFileHandle ( while(!ShellFileHandleEof(Handle)) { CommandLine = ShellFileHandleReturnLine(Handle, &Ascii); LineCount++; - if (CommandLine == NULL || StrLen(CommandLine) == 0) { + if (CommandLine == NULL || StrLen(CommandLine) == 0 || CommandLine[0] == '#') { + SHELL_FREE_NON_NULL(CommandLine); continue; } NewScriptFile->CurrentCommand = AllocateZeroPool(sizeof(SCRIPT_COMMAND_LIST)); - ASSERT(NewScriptFile->CurrentCommand != NULL); + if (NewScriptFile->CurrentCommand == NULL) { + SHELL_FREE_NON_NULL(CommandLine); + DeleteScriptFileStruct(NewScriptFile); + return (EFI_OUT_OF_RESOURCES); + } NewScriptFile->CurrentCommand->Cl = CommandLine; NewScriptFile->CurrentCommand->Data = NULL; @@ -1535,22 +2585,34 @@ RunScriptFileHandle ( // // Now enumerate through the commands and run each one. // - CommandLine = AllocatePool(PcdGet16(PcdShellPrintBufferSize)); - CommandLine2 = AllocatePool(PcdGet16(PcdShellPrintBufferSize)); + CommandLine = AllocateZeroPool(PcdGet16(PcdShellPrintBufferSize)); + if (CommandLine == NULL) { + DeleteScriptFileStruct(NewScriptFile); + return (EFI_OUT_OF_RESOURCES); + } + CommandLine2 = AllocateZeroPool(PcdGet16(PcdShellPrintBufferSize)); + if (CommandLine2 == NULL) { + FreePool(CommandLine); + DeleteScriptFileStruct(NewScriptFile); + return (EFI_OUT_OF_RESOURCES); + } for ( NewScriptFile->CurrentCommand = (SCRIPT_COMMAND_LIST *)GetFirstNode(&NewScriptFile->CommandList) ; !IsNull(&NewScriptFile->CommandList, &NewScriptFile->CurrentCommand->Link) ; // conditional increment in the body of the loop ){ - StrCpy(CommandLine2, NewScriptFile->CurrentCommand->Cl); + ASSERT(CommandLine2 != NULL); + StrnCpy(CommandLine2, NewScriptFile->CurrentCommand->Cl, PcdGet16(PcdShellPrintBufferSize)/sizeof(CHAR16)-1); // // NULL out comments // for (CommandLine3 = CommandLine2 ; CommandLine3 != NULL && *CommandLine3 != CHAR_NULL ; CommandLine3++) { if (*CommandLine3 == L'^') { - if (*(CommandLine3+1) == L'#' || *(CommandLine3+1) == L':') { + if ( *(CommandLine3+1) == L':') { CopyMem(CommandLine3, CommandLine3+1, StrSize(CommandLine3) - sizeof(CommandLine3[0])); + } else if (*(CommandLine3+1) == L'#') { + CommandLine3++; } } else if (*CommandLine3 == L'#') { *CommandLine3 = CHAR_NULL; @@ -1561,7 +2623,7 @@ RunScriptFileHandle ( // // Due to variability in starting the find and replace action we need to have both buffers the same. // - StrCpy(CommandLine, CommandLine2); + StrnCpy(CommandLine, CommandLine2, PcdGet16(PcdShellPrintBufferSize)/sizeof(CHAR16)-1); // // Remove the %0 to %9 from the command line (if we have some arguments) @@ -1569,34 +2631,34 @@ RunScriptFileHandle ( if (NewScriptFile->Argv != NULL) { switch (NewScriptFile->Argc) { default: - Status = ShellCopySearchAndReplace(CommandLine2, CommandLine, PcdGet16 (PcdShellPrintBufferSize), L"%9", NewScriptFile->Argv[9], FALSE, TRUE); + Status = ShellCopySearchAndReplace(CommandLine2, CommandLine, PcdGet16 (PcdShellPrintBufferSize), L"%9", NewScriptFile->Argv[9], FALSE, FALSE); ASSERT_EFI_ERROR(Status); case 9: - Status = ShellCopySearchAndReplace(CommandLine, CommandLine2, PcdGet16 (PcdShellPrintBufferSize), L"%8", NewScriptFile->Argv[8], FALSE, TRUE); + Status = ShellCopySearchAndReplace(CommandLine, CommandLine2, PcdGet16 (PcdShellPrintBufferSize), L"%8", NewScriptFile->Argv[8], FALSE, FALSE); ASSERT_EFI_ERROR(Status); case 8: - Status = ShellCopySearchAndReplace(CommandLine2, CommandLine, PcdGet16 (PcdShellPrintBufferSize), L"%7", NewScriptFile->Argv[7], FALSE, TRUE); + Status = ShellCopySearchAndReplace(CommandLine2, CommandLine, PcdGet16 (PcdShellPrintBufferSize), L"%7", NewScriptFile->Argv[7], FALSE, FALSE); ASSERT_EFI_ERROR(Status); case 7: - Status = ShellCopySearchAndReplace(CommandLine, CommandLine2, PcdGet16 (PcdShellPrintBufferSize), L"%6", NewScriptFile->Argv[6], FALSE, TRUE); + Status = ShellCopySearchAndReplace(CommandLine, CommandLine2, PcdGet16 (PcdShellPrintBufferSize), L"%6", NewScriptFile->Argv[6], FALSE, FALSE); ASSERT_EFI_ERROR(Status); case 6: - Status = ShellCopySearchAndReplace(CommandLine2, CommandLine, PcdGet16 (PcdShellPrintBufferSize), L"%5", NewScriptFile->Argv[5], FALSE, TRUE); + Status = ShellCopySearchAndReplace(CommandLine2, CommandLine, PcdGet16 (PcdShellPrintBufferSize), L"%5", NewScriptFile->Argv[5], FALSE, FALSE); ASSERT_EFI_ERROR(Status); case 5: - Status = ShellCopySearchAndReplace(CommandLine, CommandLine2, PcdGet16 (PcdShellPrintBufferSize), L"%4", NewScriptFile->Argv[4], FALSE, TRUE); + Status = ShellCopySearchAndReplace(CommandLine, CommandLine2, PcdGet16 (PcdShellPrintBufferSize), L"%4", NewScriptFile->Argv[4], FALSE, FALSE); ASSERT_EFI_ERROR(Status); case 4: - Status = ShellCopySearchAndReplace(CommandLine2, CommandLine, PcdGet16 (PcdShellPrintBufferSize), L"%3", NewScriptFile->Argv[3], FALSE, TRUE); + Status = ShellCopySearchAndReplace(CommandLine2, CommandLine, PcdGet16 (PcdShellPrintBufferSize), L"%3", NewScriptFile->Argv[3], FALSE, FALSE); ASSERT_EFI_ERROR(Status); case 3: - Status = ShellCopySearchAndReplace(CommandLine, CommandLine2, PcdGet16 (PcdShellPrintBufferSize), L"%2", NewScriptFile->Argv[2], FALSE, TRUE); + Status = ShellCopySearchAndReplace(CommandLine, CommandLine2, PcdGet16 (PcdShellPrintBufferSize), L"%2", NewScriptFile->Argv[2], FALSE, FALSE); ASSERT_EFI_ERROR(Status); case 2: - Status = ShellCopySearchAndReplace(CommandLine2, CommandLine, PcdGet16 (PcdShellPrintBufferSize), L"%1", NewScriptFile->Argv[1], FALSE, TRUE); + Status = ShellCopySearchAndReplace(CommandLine2, CommandLine, PcdGet16 (PcdShellPrintBufferSize), L"%1", NewScriptFile->Argv[1], FALSE, FALSE); ASSERT_EFI_ERROR(Status); case 1: - Status = ShellCopySearchAndReplace(CommandLine, CommandLine2, PcdGet16 (PcdShellPrintBufferSize), L"%0", NewScriptFile->Argv[0], FALSE, TRUE); + Status = ShellCopySearchAndReplace(CommandLine, CommandLine2, PcdGet16 (PcdShellPrintBufferSize), L"%0", NewScriptFile->Argv[0], FALSE, FALSE); ASSERT_EFI_ERROR(Status); break; case 0: @@ -1613,35 +2675,66 @@ RunScriptFileHandle ( Status = ShellCopySearchAndReplace(CommandLine, CommandLine2, PcdGet16 (PcdShellPrintBufferSize), L"%8", L"\"\"", FALSE, FALSE); Status = ShellCopySearchAndReplace(CommandLine2, CommandLine, PcdGet16 (PcdShellPrintBufferSize), L"%9", L"\"\"", FALSE, FALSE); - StrCpy(CommandLine2, CommandLine); + StrnCpy(CommandLine2, CommandLine, PcdGet16(PcdShellPrintBufferSize)/sizeof(CHAR16)-1); LastCommand = NewScriptFile->CurrentCommand; for (CommandLine3 = CommandLine2 ; CommandLine3[0] == L' ' ; CommandLine3++); - if (CommandLine3[0] == L':' ) { + if (CommandLine3 != NULL && CommandLine3[0] == L':' ) { // // This line is a goto target / label // } else { if (CommandLine3 != NULL && StrLen(CommandLine3) > 0) { - if (ShellCommandGetEchoState()) { - CurDir = ShellInfoObject.NewEfiShellProtocol->GetEnv(L"cwd"); - if (CurDir != NULL && StrLen(CurDir) > 1) { - ShellPrintHiiEx(-1, -1, NULL, STRING_TOKEN (STR_SHELL_CURDIR), ShellInfoObject.HiiHandle, CurDir); - } else { - ShellPrintHiiEx(-1, -1, NULL, STRING_TOKEN (STR_SHELL_SHELL), ShellInfoObject.HiiHandle); + if (CommandLine3[0] == L'@') { + // + // We need to save the current echo state + // and disable echo for just this command. + // + PreCommandEchoState = ShellCommandGetEchoState(); + ShellCommandSetEchoState(FALSE); + Status = RunCommand(CommandLine3+1); + + // + // If command was "@echo -off" or "@echo -on" then don't restore echo state + // + if (StrCmp (L"@echo -off", CommandLine3) != 0 && + StrCmp (L"@echo -on", CommandLine3) != 0) { + // + // Now restore the pre-'@' echo state. + // + ShellCommandSetEchoState(PreCommandEchoState); + } + } else { + if (ShellCommandGetEchoState()) { + CurDir = ShellInfoObject.NewEfiShellProtocol->GetEnv(L"cwd"); + if (CurDir != NULL && StrLen(CurDir) > 1) { + ShellPrintHiiEx(-1, -1, NULL, STRING_TOKEN (STR_SHELL_CURDIR), ShellInfoObject.HiiHandle, CurDir); + } else { + ShellPrintHiiEx(-1, -1, NULL, STRING_TOKEN (STR_SHELL_SHELL), ShellInfoObject.HiiHandle); + } + ShellPrintEx(-1, -1, L"%s\r\n", CommandLine2); } - ShellPrintEx(-1, -1, L"%s\r\n", CommandLine2); + Status = RunCommand(CommandLine3); } - Status = RunCommand(CommandLine3); } if (ShellCommandGetScriptExit()) { - ShellCommandRegisterExit(FALSE); + // + // ShellCommandGetExitCode() always returns a UINT64 + // + UnicodeSPrint(LeString, sizeof(LeString), L"0x%Lx", ShellCommandGetExitCode()); + DEBUG_CODE(InternalEfiShellSetEnv(L"debuglasterror", LeString, TRUE);); + InternalEfiShellSetEnv(L"lasterror", LeString, TRUE); + + ShellCommandRegisterExit(FALSE, 0); Status = EFI_SUCCESS; break; } + if (ShellGetExecutionBreakFlag()) { + break; + } if (EFI_ERROR(Status)) { break; } @@ -1666,11 +2759,17 @@ RunScriptFileHandle ( } } - ShellCommandSetEchoState(PreScriptEchoState); FreePool(CommandLine); FreePool(CommandLine2); ShellCommandSetNewScript (NULL); + + // + // Only if this was the last script reset the state. + // + if (ShellCommandGetCurrentScriptFile()==NULL) { + ShellCommandSetEchoState(PreScriptEchoState); + } return (EFI_SUCCESS); } @@ -1678,30 +2777,62 @@ RunScriptFileHandle ( Function to process a NSH script file. @param[in] ScriptPath Pointer to the script file name (including file system path). + @param[in] Handle the handle of the script file already opened. + @param[in] CmdLine the command line to run. + @param[in] ParamProtocol the shell parameters protocol pointer @retval EFI_SUCCESS the script completed sucessfully **/ EFI_STATUS EFIAPI RunScriptFile ( - IN CONST CHAR16 *ScriptPath + IN CONST CHAR16 *ScriptPath, + IN SHELL_FILE_HANDLE Handle OPTIONAL, + IN CONST CHAR16 *CmdLine, + IN EFI_SHELL_PARAMETERS_PROTOCOL *ParamProtocol ) { EFI_STATUS Status; SHELL_FILE_HANDLE FileHandle; + UINTN Argc; + CHAR16 **Argv; if (ShellIsFile(ScriptPath) != EFI_SUCCESS) { return (EFI_INVALID_PARAMETER); } - Status = ShellOpenFileByName(ScriptPath, &FileHandle, EFI_FILE_MODE_READ, 0); - if (EFI_ERROR(Status)) { - return (Status); - } + // + // get the argc and argv updated for scripts + // + Status = UpdateArgcArgv(ParamProtocol, CmdLine, &Argv, &Argc); + if (!EFI_ERROR(Status)) { - Status = RunScriptFileHandle(FileHandle, ScriptPath); + if (Handle == NULL) { + // + // open the file + // + Status = ShellOpenFileByName(ScriptPath, &FileHandle, EFI_FILE_MODE_READ, 0); + if (!EFI_ERROR(Status)) { + // + // run it + // + Status = RunScriptFileHandle(FileHandle, ScriptPath); + + // + // now close the file + // + ShellCloseFile(&FileHandle); + } + } else { + Status = RunScriptFileHandle(Handle, ScriptPath); + } + } - ShellCloseFile(&FileHandle); + // + // This is guarenteed to be called after UpdateArgcArgv no matter what else happened. + // This is safe even if the update API failed. In this case, it may be a no-op. + // + RestoreArgcArgv(ParamProtocol, &Argv, &Argc); return (Status); }