Shell.c 102 KB

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