Shell.c 102 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349
  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. CalleeStatus = EFI_SUCCESS;
  1136. Key.UnicodeChar = CHAR_NULL;
  1137. Key.ScanCode = 0;
  1138. if (!ShellInfoObject.ShellInitSettings.BitUnion.Bits.Startup && (ShellInfoObject.ShellInitSettings.FileName != NULL)) {
  1139. //
  1140. // launch something else instead
  1141. //
  1142. NewSize = StrSize (ShellInfoObject.ShellInitSettings.FileName);
  1143. if (ShellInfoObject.ShellInitSettings.FileOptions != NULL) {
  1144. NewSize += StrSize (ShellInfoObject.ShellInitSettings.FileOptions) + sizeof (CHAR16);
  1145. }
  1146. FileStringPath = AllocateZeroPool (NewSize);
  1147. if (FileStringPath == NULL) {
  1148. return (EFI_OUT_OF_RESOURCES);
  1149. }
  1150. StrCpyS (FileStringPath, NewSize/sizeof (CHAR16), ShellInfoObject.ShellInitSettings.FileName);
  1151. if (ShellInfoObject.ShellInitSettings.FileOptions != NULL) {
  1152. StrnCatS (FileStringPath, NewSize/sizeof (CHAR16), L" ", NewSize/sizeof (CHAR16) - StrLen (FileStringPath) -1);
  1153. StrnCatS (FileStringPath, NewSize/sizeof (CHAR16), ShellInfoObject.ShellInitSettings.FileOptions, NewSize/sizeof (CHAR16) - StrLen (FileStringPath) -1);
  1154. }
  1155. Status = RunShellCommand (FileStringPath, &CalleeStatus);
  1156. if (ShellInfoObject.ShellInitSettings.BitUnion.Bits.Exit == TRUE) {
  1157. ShellCommandRegisterExit (gEfiShellProtocol->BatchIsActive (), (UINT64)CalleeStatus);
  1158. }
  1159. FreePool (FileStringPath);
  1160. return (Status);
  1161. }
  1162. //
  1163. // for shell level 0 we do no scripts
  1164. // Without the Startup bit overriding we allow for nostartup to prevent scripts
  1165. //
  1166. if ( (PcdGet8 (PcdShellSupportLevel) < 1)
  1167. || (ShellInfoObject.ShellInitSettings.BitUnion.Bits.NoStartup && !ShellInfoObject.ShellInitSettings.BitUnion.Bits.Startup)
  1168. )
  1169. {
  1170. return (EFI_SUCCESS);
  1171. }
  1172. gST->ConOut->EnableCursor (gST->ConOut, FALSE);
  1173. //
  1174. // print out our warning and see if they press a key
  1175. //
  1176. for ( Status = EFI_UNSUPPORTED, Delay = ShellInfoObject.ShellInitSettings.Delay
  1177. ; Delay != 0 && EFI_ERROR (Status)
  1178. ; Delay--
  1179. )
  1180. {
  1181. ShellPrintHiiEx (0, gST->ConOut->Mode->CursorRow, NULL, STRING_TOKEN (STR_SHELL_STARTUP_QUESTION), ShellInfoObject.HiiHandle, Delay);
  1182. gBS->Stall (1000000);
  1183. if (!ShellInfoObject.ShellInitSettings.BitUnion.Bits.NoConsoleIn) {
  1184. Status = gST->ConIn->ReadKeyStroke (gST->ConIn, &Key);
  1185. }
  1186. }
  1187. ShellPrintHiiEx (-1, -1, NULL, STRING_TOKEN (STR_SHELL_CRLF), ShellInfoObject.HiiHandle);
  1188. gST->ConOut->EnableCursor (gST->ConOut, TRUE);
  1189. //
  1190. // ESC was pressed
  1191. //
  1192. if ((Status == EFI_SUCCESS) && (Key.UnicodeChar == 0) && (Key.ScanCode == SCAN_ESC)) {
  1193. return (EFI_SUCCESS);
  1194. }
  1195. FileStringPath = LocateStartupScript (ImagePath, FilePath);
  1196. if (FileStringPath != NULL) {
  1197. FullFileStringPath = FullyQualifyPath (FileStringPath);
  1198. if (FullFileStringPath == NULL) {
  1199. Status = RunScriptFile (FileStringPath, NULL, FileStringPath, ShellInfoObject.NewShellParametersProtocol);
  1200. } else {
  1201. Status = RunScriptFile (FullFileStringPath, NULL, FullFileStringPath, ShellInfoObject.NewShellParametersProtocol);
  1202. FreePool (FullFileStringPath);
  1203. }
  1204. FreePool (FileStringPath);
  1205. } else {
  1206. //
  1207. // we return success since startup script is not mandatory.
  1208. //
  1209. Status = EFI_SUCCESS;
  1210. }
  1211. return (Status);
  1212. }
  1213. /**
  1214. Function to perform the shell prompt looping. It will do a single prompt,
  1215. dispatch the result, and then return. It is expected that the caller will
  1216. call this function in a loop many times.
  1217. @retval EFI_SUCCESS
  1218. @retval RETURN_ABORTED
  1219. **/
  1220. EFI_STATUS
  1221. DoShellPrompt (
  1222. VOID
  1223. )
  1224. {
  1225. UINTN Column;
  1226. UINTN Row;
  1227. CHAR16 *CmdLine;
  1228. CONST CHAR16 *CurDir;
  1229. UINTN BufferSize;
  1230. EFI_STATUS Status;
  1231. LIST_ENTRY OldBufferList;
  1232. CurDir = NULL;
  1233. //
  1234. // Get screen setting to decide size of the command line buffer
  1235. //
  1236. gST->ConOut->QueryMode (gST->ConOut, gST->ConOut->Mode->Mode, &Column, &Row);
  1237. BufferSize = Column * Row * sizeof (CHAR16);
  1238. CmdLine = AllocateZeroPool (BufferSize);
  1239. if (CmdLine == NULL) {
  1240. return EFI_OUT_OF_RESOURCES;
  1241. }
  1242. SaveBufferList (&OldBufferList);
  1243. CurDir = ShellInfoObject.NewEfiShellProtocol->GetEnv (L"cwd");
  1244. //
  1245. // Prompt for input
  1246. //
  1247. gST->ConOut->SetCursorPosition (gST->ConOut, 0, gST->ConOut->Mode->CursorRow);
  1248. if ((CurDir != NULL) && (StrLen (CurDir) > 1)) {
  1249. ShellPrintHiiEx (-1, -1, NULL, STRING_TOKEN (STR_SHELL_CURDIR), ShellInfoObject.HiiHandle, CurDir);
  1250. } else {
  1251. ShellPrintHiiEx (-1, -1, NULL, STRING_TOKEN (STR_SHELL_SHELL), ShellInfoObject.HiiHandle);
  1252. }
  1253. //
  1254. // Read a line from the console
  1255. //
  1256. Status = ShellInfoObject.NewEfiShellProtocol->ReadFile (ShellInfoObject.NewShellParametersProtocol->StdIn, &BufferSize, CmdLine);
  1257. //
  1258. // Null terminate the string and parse it
  1259. //
  1260. if (!EFI_ERROR (Status)) {
  1261. //
  1262. // Reset the CTRL-C event just before running the command (yes we ignore the return values)
  1263. //
  1264. Status = gBS->CheckEvent (ShellInfoObject.NewEfiShellProtocol->ExecutionBreak);
  1265. CmdLine[BufferSize / sizeof (CHAR16)] = CHAR_NULL;
  1266. Status = RunCommand (CmdLine);
  1267. }
  1268. //
  1269. // Done with this command
  1270. //
  1271. RestoreBufferList (&OldBufferList);
  1272. FreePool (CmdLine);
  1273. return Status;
  1274. }
  1275. /**
  1276. Add a buffer to the Buffer To Free List for safely returning buffers to other
  1277. places without risking letting them modify internal shell information.
  1278. @param Buffer Something to pass to FreePool when the shell is exiting.
  1279. **/
  1280. VOID *
  1281. AddBufferToFreeList (
  1282. VOID *Buffer
  1283. )
  1284. {
  1285. BUFFER_LIST *BufferListEntry;
  1286. if (Buffer == NULL) {
  1287. return (NULL);
  1288. }
  1289. BufferListEntry = AllocateZeroPool (sizeof (BUFFER_LIST));
  1290. if (BufferListEntry == NULL) {
  1291. return NULL;
  1292. }
  1293. BufferListEntry->Buffer = Buffer;
  1294. InsertTailList (&ShellInfoObject.BufferToFreeList.Link, &BufferListEntry->Link);
  1295. return (Buffer);
  1296. }
  1297. /**
  1298. Create a new buffer list and stores the old one to OldBufferList
  1299. @param OldBufferList The temporary list head used to store the nodes in BufferToFreeList.
  1300. **/
  1301. VOID
  1302. SaveBufferList (
  1303. OUT LIST_ENTRY *OldBufferList
  1304. )
  1305. {
  1306. CopyMem (OldBufferList, &ShellInfoObject.BufferToFreeList.Link, sizeof (LIST_ENTRY));
  1307. InitializeListHead (&ShellInfoObject.BufferToFreeList.Link);
  1308. }
  1309. /**
  1310. Restore previous nodes into BufferToFreeList .
  1311. @param OldBufferList The temporary list head used to store the nodes in BufferToFreeList.
  1312. **/
  1313. VOID
  1314. RestoreBufferList (
  1315. IN OUT LIST_ENTRY *OldBufferList
  1316. )
  1317. {
  1318. FreeBufferList (&ShellInfoObject.BufferToFreeList);
  1319. CopyMem (&ShellInfoObject.BufferToFreeList.Link, OldBufferList, sizeof (LIST_ENTRY));
  1320. }
  1321. /**
  1322. Add a buffer to the Line History List
  1323. @param Buffer The line buffer to add.
  1324. **/
  1325. VOID
  1326. AddLineToCommandHistory (
  1327. IN CONST CHAR16 *Buffer
  1328. )
  1329. {
  1330. BUFFER_LIST *Node;
  1331. BUFFER_LIST *Walker;
  1332. UINT16 MaxHistoryCmdCount;
  1333. UINT16 Count;
  1334. Count = 0;
  1335. MaxHistoryCmdCount = PcdGet16 (PcdShellMaxHistoryCommandCount);
  1336. if (MaxHistoryCmdCount == 0) {
  1337. return;
  1338. }
  1339. Node = AllocateZeroPool (sizeof (BUFFER_LIST));
  1340. if (Node == NULL) {
  1341. return;
  1342. }
  1343. Node->Buffer = AllocateCopyPool (StrSize (Buffer), Buffer);
  1344. if (Node->Buffer == NULL) {
  1345. FreePool (Node);
  1346. return;
  1347. }
  1348. for ( Walker = (BUFFER_LIST *)GetFirstNode (&ShellInfoObject.ViewingSettings.CommandHistory.Link)
  1349. ; !IsNull (&ShellInfoObject.ViewingSettings.CommandHistory.Link, &Walker->Link)
  1350. ; Walker = (BUFFER_LIST *)GetNextNode (&ShellInfoObject.ViewingSettings.CommandHistory.Link, &Walker->Link)
  1351. )
  1352. {
  1353. Count++;
  1354. }
  1355. if (Count < MaxHistoryCmdCount) {
  1356. InsertTailList (&ShellInfoObject.ViewingSettings.CommandHistory.Link, &Node->Link);
  1357. } else {
  1358. Walker = (BUFFER_LIST *)GetFirstNode (&ShellInfoObject.ViewingSettings.CommandHistory.Link);
  1359. RemoveEntryList (&Walker->Link);
  1360. if (Walker->Buffer != NULL) {
  1361. FreePool (Walker->Buffer);
  1362. }
  1363. FreePool (Walker);
  1364. InsertTailList (&ShellInfoObject.ViewingSettings.CommandHistory.Link, &Node->Link);
  1365. }
  1366. }
  1367. /**
  1368. Checks if a string is an alias for another command. If yes, then it replaces the alias name
  1369. with the correct command name.
  1370. @param[in, out] CommandString Upon entry the potential alias. Upon return the
  1371. command name if it was an alias. If it was not
  1372. an alias it will be unchanged. This function may
  1373. change the buffer to fit the command name.
  1374. @retval EFI_SUCCESS The name was changed.
  1375. @retval EFI_SUCCESS The name was not an alias.
  1376. @retval EFI_OUT_OF_RESOURCES A memory allocation failed.
  1377. **/
  1378. EFI_STATUS
  1379. ShellConvertAlias (
  1380. IN OUT CHAR16 **CommandString
  1381. )
  1382. {
  1383. CONST CHAR16 *NewString;
  1384. NewString = ShellInfoObject.NewEfiShellProtocol->GetAlias (*CommandString, NULL);
  1385. if (NewString == NULL) {
  1386. return (EFI_SUCCESS);
  1387. }
  1388. FreePool (*CommandString);
  1389. *CommandString = AllocateCopyPool (StrSize (NewString), NewString);
  1390. if (*CommandString == NULL) {
  1391. return (EFI_OUT_OF_RESOURCES);
  1392. }
  1393. return (EFI_SUCCESS);
  1394. }
  1395. /**
  1396. This function will eliminate unreplaced (and therefore non-found) environment variables.
  1397. @param[in,out] CmdLine The command line to update.
  1398. **/
  1399. EFI_STATUS
  1400. StripUnreplacedEnvironmentVariables (
  1401. IN OUT CHAR16 *CmdLine
  1402. )
  1403. {
  1404. CHAR16 *FirstPercent;
  1405. CHAR16 *FirstQuote;
  1406. CHAR16 *SecondPercent;
  1407. CHAR16 *SecondQuote;
  1408. CHAR16 *CurrentLocator;
  1409. for (CurrentLocator = CmdLine; CurrentLocator != NULL; ) {
  1410. FirstQuote = FindNextInstance (CurrentLocator, L"\"", TRUE);
  1411. FirstPercent = FindNextInstance (CurrentLocator, L"%", TRUE);
  1412. SecondPercent = FirstPercent != NULL ? FindNextInstance (FirstPercent+1, L"%", TRUE) : NULL;
  1413. if ((FirstPercent == NULL) || (SecondPercent == NULL)) {
  1414. //
  1415. // If we ever don't have 2 % we are done.
  1416. //
  1417. break;
  1418. }
  1419. if ((FirstQuote != NULL) && (FirstQuote < FirstPercent)) {
  1420. SecondQuote = FindNextInstance (FirstQuote+1, L"\"", TRUE);
  1421. //
  1422. // Quote is first found
  1423. //
  1424. if (SecondQuote < FirstPercent) {
  1425. //
  1426. // restart after the pair of "
  1427. //
  1428. CurrentLocator = SecondQuote + 1;
  1429. } else {
  1430. /* FirstPercent < SecondQuote */
  1431. //
  1432. // Restart on the first percent
  1433. //
  1434. CurrentLocator = FirstPercent;
  1435. }
  1436. continue;
  1437. }
  1438. if ((FirstQuote == NULL) || (SecondPercent < FirstQuote)) {
  1439. if (IsValidEnvironmentVariableName (FirstPercent, SecondPercent)) {
  1440. //
  1441. // We need to remove from FirstPercent to SecondPercent
  1442. //
  1443. CopyMem (FirstPercent, SecondPercent + 1, StrSize (SecondPercent + 1));
  1444. //
  1445. // don't need to update the locator. both % characters are gone.
  1446. //
  1447. } else {
  1448. CurrentLocator = SecondPercent + 1;
  1449. }
  1450. continue;
  1451. }
  1452. CurrentLocator = FirstQuote;
  1453. }
  1454. return (EFI_SUCCESS);
  1455. }
  1456. /**
  1457. Function allocates a new command line and replaces all instances of environment
  1458. variable names that are correctly preset to their values.
  1459. If the return value is not NULL the memory must be caller freed.
  1460. @param[in] OriginalCommandLine The original command line
  1461. @retval NULL An error occurred.
  1462. @return The new command line with no environment variables present.
  1463. **/
  1464. CHAR16 *
  1465. ShellConvertVariables (
  1466. IN CONST CHAR16 *OriginalCommandLine
  1467. )
  1468. {
  1469. CONST CHAR16 *MasterEnvList;
  1470. UINTN NewSize;
  1471. CHAR16 *NewCommandLine1;
  1472. CHAR16 *NewCommandLine2;
  1473. CHAR16 *Temp;
  1474. UINTN ItemSize;
  1475. CHAR16 *ItemTemp;
  1476. SCRIPT_FILE *CurrentScriptFile;
  1477. ALIAS_LIST *AliasListNode;
  1478. ASSERT (OriginalCommandLine != NULL);
  1479. ItemSize = 0;
  1480. NewSize = StrSize (OriginalCommandLine);
  1481. CurrentScriptFile = ShellCommandGetCurrentScriptFile ();
  1482. Temp = NULL;
  1483. /// @todo update this to handle the %0 - %9 for scripting only (borrow from line 1256 area) ? ? ?
  1484. //
  1485. // calculate the size required for the post-conversion string...
  1486. //
  1487. if (CurrentScriptFile != NULL) {
  1488. for (AliasListNode = (ALIAS_LIST *)GetFirstNode (&CurrentScriptFile->SubstList)
  1489. ; !IsNull (&CurrentScriptFile->SubstList, &AliasListNode->Link)
  1490. ; AliasListNode = (ALIAS_LIST *)GetNextNode (&CurrentScriptFile->SubstList, &AliasListNode->Link)
  1491. )
  1492. {
  1493. for (Temp = StrStr (OriginalCommandLine, AliasListNode->Alias)
  1494. ; Temp != NULL
  1495. ; Temp = StrStr (Temp+1, AliasListNode->Alias)
  1496. )
  1497. {
  1498. //
  1499. // we need a preceding and if there is space no ^ preceding (if no space ignore)
  1500. //
  1501. if ((((Temp-OriginalCommandLine) > 2) && (*(Temp-2) != L'^')) || ((Temp-OriginalCommandLine) <= 2)) {
  1502. NewSize += StrSize (AliasListNode->CommandString);
  1503. }
  1504. }
  1505. }
  1506. }
  1507. for (MasterEnvList = EfiShellGetEnv (NULL)
  1508. ; MasterEnvList != NULL && *MasterEnvList != CHAR_NULL // && *(MasterEnvList+1) != CHAR_NULL
  1509. ; MasterEnvList += StrLen (MasterEnvList) + 1
  1510. )
  1511. {
  1512. if (StrSize (MasterEnvList) > ItemSize) {
  1513. ItemSize = StrSize (MasterEnvList);
  1514. }
  1515. for (Temp = StrStr (OriginalCommandLine, MasterEnvList)
  1516. ; Temp != NULL
  1517. ; Temp = StrStr (Temp+1, MasterEnvList)
  1518. )
  1519. {
  1520. //
  1521. // we need a preceding and following % and if there is space no ^ preceding (if no space ignore)
  1522. //
  1523. if ((*(Temp-1) == L'%') && (*(Temp+StrLen (MasterEnvList)) == L'%') &&
  1524. ((((Temp-OriginalCommandLine) > 2) && (*(Temp-2) != L'^')) || ((Temp-OriginalCommandLine) <= 2)))
  1525. {
  1526. NewSize += StrSize (EfiShellGetEnv (MasterEnvList));
  1527. }
  1528. }
  1529. }
  1530. //
  1531. // now do the replacements...
  1532. //
  1533. NewCommandLine1 = AllocateZeroPool (NewSize);
  1534. NewCommandLine2 = AllocateZeroPool (NewSize);
  1535. ItemTemp = AllocateZeroPool (ItemSize+(2*sizeof (CHAR16)));
  1536. if ((NewCommandLine1 == NULL) || (NewCommandLine2 == NULL) || (ItemTemp == NULL)) {
  1537. SHELL_FREE_NON_NULL (NewCommandLine1);
  1538. SHELL_FREE_NON_NULL (NewCommandLine2);
  1539. SHELL_FREE_NON_NULL (ItemTemp);
  1540. return (NULL);
  1541. }
  1542. CopyMem (NewCommandLine1, OriginalCommandLine, StrSize (OriginalCommandLine));
  1543. for (MasterEnvList = EfiShellGetEnv (NULL)
  1544. ; MasterEnvList != NULL && *MasterEnvList != CHAR_NULL
  1545. ; MasterEnvList += StrLen (MasterEnvList) + 1
  1546. )
  1547. {
  1548. StrCpyS (
  1549. ItemTemp,
  1550. ((ItemSize+(2*sizeof (CHAR16)))/sizeof (CHAR16)),
  1551. L"%"
  1552. );
  1553. StrCatS (
  1554. ItemTemp,
  1555. ((ItemSize+(2*sizeof (CHAR16)))/sizeof (CHAR16)),
  1556. MasterEnvList
  1557. );
  1558. StrCatS (
  1559. ItemTemp,
  1560. ((ItemSize+(2*sizeof (CHAR16)))/sizeof (CHAR16)),
  1561. L"%"
  1562. );
  1563. ShellCopySearchAndReplace (NewCommandLine1, NewCommandLine2, NewSize, ItemTemp, EfiShellGetEnv (MasterEnvList), TRUE, FALSE);
  1564. StrCpyS (NewCommandLine1, NewSize/sizeof (CHAR16), NewCommandLine2);
  1565. }
  1566. if (CurrentScriptFile != NULL) {
  1567. for (AliasListNode = (ALIAS_LIST *)GetFirstNode (&CurrentScriptFile->SubstList)
  1568. ; !IsNull (&CurrentScriptFile->SubstList, &AliasListNode->Link)
  1569. ; AliasListNode = (ALIAS_LIST *)GetNextNode (&CurrentScriptFile->SubstList, &AliasListNode->Link)
  1570. )
  1571. {
  1572. ShellCopySearchAndReplace (NewCommandLine1, NewCommandLine2, NewSize, AliasListNode->Alias, AliasListNode->CommandString, TRUE, FALSE);
  1573. StrCpyS (NewCommandLine1, NewSize/sizeof (CHAR16), NewCommandLine2);
  1574. }
  1575. }
  1576. //
  1577. // Remove non-existent environment variables
  1578. //
  1579. StripUnreplacedEnvironmentVariables (NewCommandLine1);
  1580. //
  1581. // Now cleanup any straggler intentionally ignored "%" characters
  1582. //
  1583. ShellCopySearchAndReplace (NewCommandLine1, NewCommandLine2, NewSize, L"^%", L"%", TRUE, FALSE);
  1584. StrCpyS (NewCommandLine1, NewSize/sizeof (CHAR16), NewCommandLine2);
  1585. FreePool (NewCommandLine2);
  1586. FreePool (ItemTemp);
  1587. return (NewCommandLine1);
  1588. }
  1589. /**
  1590. Internal function to run a command line with pipe usage.
  1591. @param[in] CmdLine The pointer to the command line.
  1592. @param[in] StdIn The pointer to the Standard input.
  1593. @param[in] StdOut The pointer to the Standard output.
  1594. @retval EFI_SUCCESS The split command is executed successfully.
  1595. @retval other Some error occurs when executing the split command.
  1596. **/
  1597. EFI_STATUS
  1598. RunSplitCommand (
  1599. IN CONST CHAR16 *CmdLine,
  1600. IN SHELL_FILE_HANDLE StdIn,
  1601. IN SHELL_FILE_HANDLE StdOut
  1602. )
  1603. {
  1604. EFI_STATUS Status;
  1605. CHAR16 *NextCommandLine;
  1606. CHAR16 *OurCommandLine;
  1607. UINTN Size1;
  1608. UINTN Size2;
  1609. SPLIT_LIST *Split;
  1610. SHELL_FILE_HANDLE TempFileHandle;
  1611. BOOLEAN Unicode;
  1612. ASSERT (StdOut == NULL);
  1613. ASSERT (StrStr (CmdLine, L"|") != NULL);
  1614. Status = EFI_SUCCESS;
  1615. NextCommandLine = NULL;
  1616. OurCommandLine = NULL;
  1617. Size1 = 0;
  1618. Size2 = 0;
  1619. NextCommandLine = StrnCatGrow (&NextCommandLine, &Size1, StrStr (CmdLine, L"|")+1, 0);
  1620. OurCommandLine = StrnCatGrow (&OurCommandLine, &Size2, CmdLine, StrStr (CmdLine, L"|") - CmdLine);
  1621. if ((NextCommandLine == NULL) || (OurCommandLine == NULL)) {
  1622. SHELL_FREE_NON_NULL (OurCommandLine);
  1623. SHELL_FREE_NON_NULL (NextCommandLine);
  1624. return (EFI_OUT_OF_RESOURCES);
  1625. } else if ((StrStr (OurCommandLine, L"|") != NULL) || (Size1 == 0) || (Size2 == 0)) {
  1626. SHELL_FREE_NON_NULL (OurCommandLine);
  1627. SHELL_FREE_NON_NULL (NextCommandLine);
  1628. return (EFI_INVALID_PARAMETER);
  1629. } else if ((NextCommandLine[0] == L'a') &&
  1630. ((NextCommandLine[1] == L' ') || (NextCommandLine[1] == CHAR_NULL))
  1631. )
  1632. {
  1633. CopyMem (NextCommandLine, NextCommandLine+1, StrSize (NextCommandLine) - sizeof (NextCommandLine[0]));
  1634. while (NextCommandLine[0] == L' ') {
  1635. CopyMem (NextCommandLine, NextCommandLine+1, StrSize (NextCommandLine) - sizeof (NextCommandLine[0]));
  1636. }
  1637. if (NextCommandLine[0] == CHAR_NULL) {
  1638. SHELL_FREE_NON_NULL (OurCommandLine);
  1639. SHELL_FREE_NON_NULL (NextCommandLine);
  1640. return (EFI_INVALID_PARAMETER);
  1641. }
  1642. Unicode = FALSE;
  1643. } else {
  1644. Unicode = TRUE;
  1645. }
  1646. //
  1647. // make a SPLIT_LIST item and add to list
  1648. //
  1649. Split = AllocateZeroPool (sizeof (SPLIT_LIST));
  1650. if (Split == NULL) {
  1651. return EFI_OUT_OF_RESOURCES;
  1652. }
  1653. Split->SplitStdIn = StdIn;
  1654. Split->SplitStdOut = ConvertEfiFileProtocolToShellHandle (CreateFileInterfaceMem (Unicode), NULL);
  1655. ASSERT (Split->SplitStdOut != NULL);
  1656. InsertHeadList (&ShellInfoObject.SplitList.Link, &Split->Link);
  1657. Status = RunCommand (OurCommandLine);
  1658. //
  1659. // move the output from the first to the in to the second.
  1660. //
  1661. TempFileHandle = Split->SplitStdOut;
  1662. if (Split->SplitStdIn == StdIn) {
  1663. Split->SplitStdOut = NULL;
  1664. } else {
  1665. Split->SplitStdOut = Split->SplitStdIn;
  1666. }
  1667. Split->SplitStdIn = TempFileHandle;
  1668. ShellInfoObject.NewEfiShellProtocol->SetFilePosition (Split->SplitStdIn, 0);
  1669. if (!EFI_ERROR (Status)) {
  1670. Status = RunCommand (NextCommandLine);
  1671. }
  1672. //
  1673. // remove the top level from the ScriptList
  1674. //
  1675. ASSERT ((SPLIT_LIST *)GetFirstNode (&ShellInfoObject.SplitList.Link) == Split);
  1676. RemoveEntryList (&Split->Link);
  1677. //
  1678. // Note that the original StdIn is now the StdOut...
  1679. //
  1680. if (Split->SplitStdOut != NULL) {
  1681. ShellInfoObject.NewEfiShellProtocol->CloseFile (Split->SplitStdOut);
  1682. }
  1683. if (Split->SplitStdIn != NULL) {
  1684. ShellInfoObject.NewEfiShellProtocol->CloseFile (Split->SplitStdIn);
  1685. }
  1686. FreePool (Split);
  1687. FreePool (NextCommandLine);
  1688. FreePool (OurCommandLine);
  1689. return (Status);
  1690. }
  1691. /**
  1692. Take the original command line, substitute any variables, free
  1693. the original string, return the modified copy.
  1694. @param[in] CmdLine pointer to the command line to update.
  1695. @retval EFI_SUCCESS the function was successful.
  1696. @retval EFI_OUT_OF_RESOURCES a memory allocation failed.
  1697. **/
  1698. EFI_STATUS
  1699. ShellSubstituteVariables (
  1700. IN CHAR16 **CmdLine
  1701. )
  1702. {
  1703. CHAR16 *NewCmdLine;
  1704. NewCmdLine = ShellConvertVariables (*CmdLine);
  1705. SHELL_FREE_NON_NULL (*CmdLine);
  1706. if (NewCmdLine == NULL) {
  1707. return (EFI_OUT_OF_RESOURCES);
  1708. }
  1709. *CmdLine = NewCmdLine;
  1710. return (EFI_SUCCESS);
  1711. }
  1712. /**
  1713. Take the original command line, substitute any alias in the first group of space delimited characters, free
  1714. the original string, return the modified copy.
  1715. @param[in] CmdLine pointer to the command line to update.
  1716. @retval EFI_SUCCESS the function was successful.
  1717. @retval EFI_OUT_OF_RESOURCES a memory allocation failed.
  1718. **/
  1719. EFI_STATUS
  1720. ShellSubstituteAliases (
  1721. IN CHAR16 **CmdLine
  1722. )
  1723. {
  1724. CHAR16 *NewCmdLine;
  1725. CHAR16 *CommandName;
  1726. EFI_STATUS Status;
  1727. UINTN PostAliasSize;
  1728. ASSERT (CmdLine != NULL);
  1729. ASSERT (*CmdLine != NULL);
  1730. CommandName = NULL;
  1731. if (StrStr ((*CmdLine), L" ") == NULL) {
  1732. StrnCatGrow (&CommandName, NULL, (*CmdLine), 0);
  1733. } else {
  1734. StrnCatGrow (&CommandName, NULL, (*CmdLine), StrStr ((*CmdLine), L" ") - (*CmdLine));
  1735. }
  1736. //
  1737. // This cannot happen 'inline' since the CmdLine can need extra space.
  1738. //
  1739. NewCmdLine = NULL;
  1740. if (!ShellCommandIsCommandOnList (CommandName)) {
  1741. //
  1742. // Convert via alias
  1743. //
  1744. Status = ShellConvertAlias (&CommandName);
  1745. if (EFI_ERROR (Status)) {
  1746. return (Status);
  1747. }
  1748. PostAliasSize = 0;
  1749. NewCmdLine = StrnCatGrow (&NewCmdLine, &PostAliasSize, CommandName, 0);
  1750. if (NewCmdLine == NULL) {
  1751. SHELL_FREE_NON_NULL (CommandName);
  1752. SHELL_FREE_NON_NULL (*CmdLine);
  1753. return (EFI_OUT_OF_RESOURCES);
  1754. }
  1755. NewCmdLine = StrnCatGrow (&NewCmdLine, &PostAliasSize, StrStr ((*CmdLine), L" "), 0);
  1756. if (NewCmdLine == NULL) {
  1757. SHELL_FREE_NON_NULL (CommandName);
  1758. SHELL_FREE_NON_NULL (*CmdLine);
  1759. return (EFI_OUT_OF_RESOURCES);
  1760. }
  1761. } else {
  1762. NewCmdLine = StrnCatGrow (&NewCmdLine, NULL, (*CmdLine), 0);
  1763. }
  1764. SHELL_FREE_NON_NULL (*CmdLine);
  1765. SHELL_FREE_NON_NULL (CommandName);
  1766. //
  1767. // re-assign the passed in double pointer to point to our newly allocated buffer
  1768. //
  1769. *CmdLine = NewCmdLine;
  1770. return (EFI_SUCCESS);
  1771. }
  1772. /**
  1773. Takes the Argv[0] part of the command line and determine the meaning of it.
  1774. @param[in] CmdName pointer to the command line to update.
  1775. @retval Internal_Command The name is an internal command.
  1776. @retval File_Sys_Change the name is a file system change.
  1777. @retval Script_File_Name the name is a NSH script file.
  1778. @retval Unknown_Invalid the name is unknown.
  1779. @retval Efi_Application the name is an application (.EFI).
  1780. **/
  1781. SHELL_OPERATION_TYPES
  1782. GetOperationType (
  1783. IN CONST CHAR16 *CmdName
  1784. )
  1785. {
  1786. CHAR16 *FileWithPath;
  1787. CONST CHAR16 *TempLocation;
  1788. CONST CHAR16 *TempLocation2;
  1789. FileWithPath = NULL;
  1790. //
  1791. // test for an internal command.
  1792. //
  1793. if (ShellCommandIsCommandOnList (CmdName)) {
  1794. return (Internal_Command);
  1795. }
  1796. //
  1797. // Test for file system change request. anything ending with first : and cant have spaces.
  1798. //
  1799. if (CmdName[(StrLen (CmdName)-1)] == L':') {
  1800. if ( (StrStr (CmdName, L" ") != NULL)
  1801. || (StrLen (StrStr (CmdName, L":")) > 1)
  1802. )
  1803. {
  1804. return (Unknown_Invalid);
  1805. }
  1806. return (File_Sys_Change);
  1807. }
  1808. //
  1809. // Test for a file
  1810. //
  1811. if ((FileWithPath = ShellFindFilePathEx (CmdName, mExecutableExtensions)) != NULL) {
  1812. //
  1813. // See if that file has a script file extension
  1814. //
  1815. if (StrLen (FileWithPath) > 4) {
  1816. TempLocation = FileWithPath+StrLen (FileWithPath)-4;
  1817. TempLocation2 = mScriptExtension;
  1818. if (StringNoCaseCompare ((VOID *)(&TempLocation), (VOID *)(&TempLocation2)) == 0) {
  1819. SHELL_FREE_NON_NULL (FileWithPath);
  1820. return (Script_File_Name);
  1821. }
  1822. }
  1823. //
  1824. // Was a file, but not a script. we treat this as an application.
  1825. //
  1826. SHELL_FREE_NON_NULL (FileWithPath);
  1827. return (Efi_Application);
  1828. }
  1829. SHELL_FREE_NON_NULL (FileWithPath);
  1830. //
  1831. // No clue what this is... return invalid flag...
  1832. //
  1833. return (Unknown_Invalid);
  1834. }
  1835. /**
  1836. Determine if the first item in a command line is valid.
  1837. @param[in] CmdLine The command line to parse.
  1838. @retval EFI_SUCCESS The item is valid.
  1839. @retval EFI_OUT_OF_RESOURCES A memory allocation failed.
  1840. @retval EFI_NOT_FOUND The operation type is unknown or invalid.
  1841. **/
  1842. EFI_STATUS
  1843. IsValidSplit (
  1844. IN CONST CHAR16 *CmdLine
  1845. )
  1846. {
  1847. CHAR16 *Temp;
  1848. CHAR16 *FirstParameter;
  1849. CHAR16 *TempWalker;
  1850. EFI_STATUS Status;
  1851. Temp = NULL;
  1852. Temp = StrnCatGrow (&Temp, NULL, CmdLine, 0);
  1853. if (Temp == NULL) {
  1854. return (EFI_OUT_OF_RESOURCES);
  1855. }
  1856. FirstParameter = StrStr (Temp, L"|");
  1857. if (FirstParameter != NULL) {
  1858. *FirstParameter = CHAR_NULL;
  1859. }
  1860. FirstParameter = NULL;
  1861. //
  1862. // Process the command line
  1863. //
  1864. Status = ProcessCommandLineToFinal (&Temp);
  1865. if (!EFI_ERROR (Status)) {
  1866. FirstParameter = AllocateZeroPool (StrSize (CmdLine));
  1867. if (FirstParameter == NULL) {
  1868. SHELL_FREE_NON_NULL (Temp);
  1869. return (EFI_OUT_OF_RESOURCES);
  1870. }
  1871. TempWalker = (CHAR16 *)Temp;
  1872. if (!EFI_ERROR (GetNextParameter (&TempWalker, &FirstParameter, StrSize (CmdLine), TRUE))) {
  1873. if (GetOperationType (FirstParameter) == Unknown_Invalid) {
  1874. ShellPrintHiiEx (-1, -1, NULL, STRING_TOKEN (STR_SHELL_NOT_FOUND), ShellInfoObject.HiiHandle, FirstParameter);
  1875. SetLastError (SHELL_NOT_FOUND);
  1876. Status = EFI_NOT_FOUND;
  1877. }
  1878. }
  1879. }
  1880. SHELL_FREE_NON_NULL (Temp);
  1881. SHELL_FREE_NON_NULL (FirstParameter);
  1882. return Status;
  1883. }
  1884. /**
  1885. Determine if a command line contains with a split contains only valid commands.
  1886. @param[in] CmdLine The command line to parse.
  1887. @retval EFI_SUCCESS CmdLine has only valid commands, application, or has no split.
  1888. @retval EFI_ABORTED CmdLine has at least one invalid command or application.
  1889. **/
  1890. EFI_STATUS
  1891. VerifySplit (
  1892. IN CONST CHAR16 *CmdLine
  1893. )
  1894. {
  1895. CONST CHAR16 *TempSpot;
  1896. EFI_STATUS Status;
  1897. //
  1898. // If this was the only item, then get out
  1899. //
  1900. if (!ContainsSplit (CmdLine)) {
  1901. return (EFI_SUCCESS);
  1902. }
  1903. //
  1904. // Verify up to the pipe or end character
  1905. //
  1906. Status = IsValidSplit (CmdLine);
  1907. if (EFI_ERROR (Status)) {
  1908. return (Status);
  1909. }
  1910. //
  1911. // recurse to verify the next item
  1912. //
  1913. TempSpot = FindFirstCharacter (CmdLine, L"|", L'^') + 1;
  1914. if ((*TempSpot == L'a') &&
  1915. ((*(TempSpot + 1) == L' ') || (*(TempSpot + 1) == CHAR_NULL))
  1916. )
  1917. {
  1918. // If it's an ASCII pipe '|a'
  1919. TempSpot += 1;
  1920. }
  1921. return (VerifySplit (TempSpot));
  1922. }
  1923. /**
  1924. Process a split based operation.
  1925. @param[in] CmdLine pointer to the command line to process
  1926. @retval EFI_SUCCESS The operation was successful
  1927. @return an error occurred.
  1928. **/
  1929. EFI_STATUS
  1930. ProcessNewSplitCommandLine (
  1931. IN CONST CHAR16 *CmdLine
  1932. )
  1933. {
  1934. SPLIT_LIST *Split;
  1935. EFI_STATUS Status;
  1936. Status = VerifySplit (CmdLine);
  1937. if (EFI_ERROR (Status)) {
  1938. return (Status);
  1939. }
  1940. Split = NULL;
  1941. //
  1942. // are we in an existing split???
  1943. //
  1944. if (!IsListEmpty (&ShellInfoObject.SplitList.Link)) {
  1945. Split = (SPLIT_LIST *)GetFirstNode (&ShellInfoObject.SplitList.Link);
  1946. }
  1947. if (Split == NULL) {
  1948. Status = RunSplitCommand (CmdLine, NULL, NULL);
  1949. } else {
  1950. Status = RunSplitCommand (CmdLine, Split->SplitStdIn, Split->SplitStdOut);
  1951. }
  1952. if (EFI_ERROR (Status)) {
  1953. ShellPrintHiiEx (-1, -1, NULL, STRING_TOKEN (STR_SHELL_INVALID_SPLIT), ShellInfoObject.HiiHandle, CmdLine);
  1954. }
  1955. return (Status);
  1956. }
  1957. /**
  1958. Handle a request to change the current file system.
  1959. @param[in] CmdLine The passed in command line.
  1960. @retval EFI_SUCCESS The operation was successful.
  1961. **/
  1962. EFI_STATUS
  1963. ChangeMappedDrive (
  1964. IN CONST CHAR16 *CmdLine
  1965. )
  1966. {
  1967. EFI_STATUS Status;
  1968. Status = EFI_SUCCESS;
  1969. //
  1970. // make sure we are the right operation
  1971. //
  1972. ASSERT (CmdLine[(StrLen (CmdLine)-1)] == L':' && StrStr (CmdLine, L" ") == NULL);
  1973. //
  1974. // Call the protocol API to do the work
  1975. //
  1976. Status = ShellInfoObject.NewEfiShellProtocol->SetCurDir (NULL, CmdLine);
  1977. //
  1978. // Report any errors
  1979. //
  1980. if (EFI_ERROR (Status)) {
  1981. ShellPrintHiiEx (-1, -1, NULL, STRING_TOKEN (STR_SHELL_INVALID_MAPPING), ShellInfoObject.HiiHandle, CmdLine);
  1982. }
  1983. return (Status);
  1984. }
  1985. /**
  1986. Reprocess the command line to direct all -? to the help command.
  1987. if found, will add "help" as argv[0], and move the rest later.
  1988. @param[in,out] CmdLine pointer to the command line to update
  1989. **/
  1990. EFI_STATUS
  1991. DoHelpUpdate (
  1992. IN OUT CHAR16 **CmdLine
  1993. )
  1994. {
  1995. CHAR16 *CurrentParameter;
  1996. CHAR16 *Walker;
  1997. CHAR16 *NewCommandLine;
  1998. EFI_STATUS Status;
  1999. UINTN NewCmdLineSize;
  2000. Status = EFI_SUCCESS;
  2001. CurrentParameter = AllocateZeroPool (StrSize (*CmdLine));
  2002. if (CurrentParameter == NULL) {
  2003. return (EFI_OUT_OF_RESOURCES);
  2004. }
  2005. Walker = *CmdLine;
  2006. while (Walker != NULL && *Walker != CHAR_NULL) {
  2007. if (!EFI_ERROR (GetNextParameter (&Walker, &CurrentParameter, StrSize (*CmdLine), TRUE))) {
  2008. if (StrStr (CurrentParameter, L"-?") == CurrentParameter) {
  2009. CurrentParameter[0] = L' ';
  2010. CurrentParameter[1] = L' ';
  2011. NewCmdLineSize = StrSize (L"help ") + StrSize (*CmdLine);
  2012. NewCommandLine = AllocateZeroPool (NewCmdLineSize);
  2013. if (NewCommandLine == NULL) {
  2014. Status = EFI_OUT_OF_RESOURCES;
  2015. break;
  2016. }
  2017. //
  2018. // We know the space is sufficient since we just calculated it.
  2019. //
  2020. StrnCpyS (NewCommandLine, NewCmdLineSize/sizeof (CHAR16), L"help ", 5);
  2021. StrnCatS (NewCommandLine, NewCmdLineSize/sizeof (CHAR16), *CmdLine, StrLen (*CmdLine));
  2022. SHELL_FREE_NON_NULL (*CmdLine);
  2023. *CmdLine = NewCommandLine;
  2024. break;
  2025. }
  2026. }
  2027. }
  2028. SHELL_FREE_NON_NULL (CurrentParameter);
  2029. return (Status);
  2030. }
  2031. /**
  2032. Function to update the shell variable "lasterror".
  2033. @param[in] ErrorCode the error code to put into lasterror.
  2034. **/
  2035. EFI_STATUS
  2036. SetLastError (
  2037. IN CONST SHELL_STATUS ErrorCode
  2038. )
  2039. {
  2040. CHAR16 LeString[19];
  2041. if (sizeof (EFI_STATUS) == sizeof (UINT64)) {
  2042. UnicodeSPrint (LeString, sizeof (LeString), L"0x%Lx", ErrorCode);
  2043. } else {
  2044. UnicodeSPrint (LeString, sizeof (LeString), L"0x%x", ErrorCode);
  2045. }
  2046. DEBUG_CODE (
  2047. InternalEfiShellSetEnv (L"debuglasterror", LeString, TRUE);
  2048. );
  2049. InternalEfiShellSetEnv (L"lasterror", LeString, TRUE);
  2050. return (EFI_SUCCESS);
  2051. }
  2052. /**
  2053. Converts the command line to its post-processed form. this replaces variables and alias' per UEFI Shell spec.
  2054. @param[in,out] CmdLine pointer to the command line to update
  2055. @retval EFI_SUCCESS The operation was successful
  2056. @retval EFI_OUT_OF_RESOURCES A memory allocation failed.
  2057. @return some other error occurred
  2058. **/
  2059. EFI_STATUS
  2060. ProcessCommandLineToFinal (
  2061. IN OUT CHAR16 **CmdLine
  2062. )
  2063. {
  2064. EFI_STATUS Status;
  2065. TrimSpaces (CmdLine);
  2066. Status = ShellSubstituteAliases (CmdLine);
  2067. if (EFI_ERROR (Status)) {
  2068. return (Status);
  2069. }
  2070. TrimSpaces (CmdLine);
  2071. Status = ShellSubstituteVariables (CmdLine);
  2072. if (EFI_ERROR (Status)) {
  2073. return (Status);
  2074. }
  2075. ASSERT (*CmdLine != NULL);
  2076. TrimSpaces (CmdLine);
  2077. //
  2078. // update for help parsing
  2079. //
  2080. if (StrStr (*CmdLine, L"?") != NULL) {
  2081. //
  2082. // This may do nothing if the ? does not indicate help.
  2083. // Save all the details for in the API below.
  2084. //
  2085. Status = DoHelpUpdate (CmdLine);
  2086. }
  2087. TrimSpaces (CmdLine);
  2088. return (EFI_SUCCESS);
  2089. }
  2090. /**
  2091. Run an internal shell command.
  2092. This API will update the shell's environment since these commands are libraries.
  2093. @param[in] CmdLine the command line to run.
  2094. @param[in] FirstParameter the first parameter on the command line
  2095. @param[in] ParamProtocol the shell parameters protocol pointer
  2096. @param[out] CommandStatus the status from the command line.
  2097. @retval EFI_SUCCESS The command was completed.
  2098. @retval EFI_ABORTED The command's operation was aborted.
  2099. **/
  2100. EFI_STATUS
  2101. RunInternalCommand (
  2102. IN CONST CHAR16 *CmdLine,
  2103. IN CHAR16 *FirstParameter,
  2104. IN EFI_SHELL_PARAMETERS_PROTOCOL *ParamProtocol,
  2105. OUT EFI_STATUS *CommandStatus
  2106. )
  2107. {
  2108. EFI_STATUS Status;
  2109. UINTN Argc;
  2110. CHAR16 **Argv;
  2111. SHELL_STATUS CommandReturnedStatus;
  2112. BOOLEAN LastError;
  2113. CHAR16 *Walker;
  2114. CHAR16 *NewCmdLine;
  2115. NewCmdLine = AllocateCopyPool (StrSize (CmdLine), CmdLine);
  2116. if (NewCmdLine == NULL) {
  2117. return EFI_OUT_OF_RESOURCES;
  2118. }
  2119. for (Walker = NewCmdLine; Walker != NULL && *Walker != CHAR_NULL; Walker++) {
  2120. if ((*Walker == L'^') && (*(Walker+1) == L'#')) {
  2121. CopyMem (Walker, Walker+1, StrSize (Walker) - sizeof (Walker[0]));
  2122. }
  2123. }
  2124. //
  2125. // get the argc and argv updated for internal commands
  2126. //
  2127. Status = UpdateArgcArgv (ParamProtocol, NewCmdLine, Internal_Command, &Argv, &Argc);
  2128. if (!EFI_ERROR (Status)) {
  2129. //
  2130. // Run the internal command.
  2131. //
  2132. Status = ShellCommandRunCommandHandler (FirstParameter, &CommandReturnedStatus, &LastError);
  2133. if (!EFI_ERROR (Status)) {
  2134. if (CommandStatus != NULL) {
  2135. if (CommandReturnedStatus != SHELL_SUCCESS) {
  2136. *CommandStatus = (EFI_STATUS)(CommandReturnedStatus | MAX_BIT);
  2137. } else {
  2138. *CommandStatus = EFI_SUCCESS;
  2139. }
  2140. }
  2141. //
  2142. // Update last error status.
  2143. // some commands do not update last error.
  2144. //
  2145. if (LastError) {
  2146. SetLastError (CommandReturnedStatus);
  2147. }
  2148. //
  2149. // Pass thru the exitcode from the app.
  2150. //
  2151. if (ShellCommandGetExit ()) {
  2152. //
  2153. // An Exit was requested ("exit" command), pass its value up.
  2154. //
  2155. Status = CommandReturnedStatus;
  2156. } else if ((CommandReturnedStatus != SHELL_SUCCESS) && IsScriptOnlyCommand (FirstParameter)) {
  2157. //
  2158. // Always abort when a script only command fails for any reason
  2159. //
  2160. Status = EFI_ABORTED;
  2161. } else if ((ShellCommandGetCurrentScriptFile () != NULL) && (CommandReturnedStatus == SHELL_ABORTED)) {
  2162. //
  2163. // Abort when in a script and a command aborted
  2164. //
  2165. Status = EFI_ABORTED;
  2166. }
  2167. }
  2168. }
  2169. //
  2170. // This is guaranteed to be called after UpdateArgcArgv no matter what else happened.
  2171. // This is safe even if the update API failed. In this case, it may be a no-op.
  2172. //
  2173. RestoreArgcArgv (ParamProtocol, &Argv, &Argc);
  2174. //
  2175. // If a script is running and the command is not a script only command, then
  2176. // change return value to success so the script won't halt (unless aborted).
  2177. //
  2178. // Script only commands have to be able halt the script since the script will
  2179. // not operate if they are failing.
  2180. //
  2181. if ( (ShellCommandGetCurrentScriptFile () != NULL)
  2182. && !IsScriptOnlyCommand (FirstParameter)
  2183. && (Status != EFI_ABORTED)
  2184. )
  2185. {
  2186. Status = EFI_SUCCESS;
  2187. }
  2188. FreePool (NewCmdLine);
  2189. return (Status);
  2190. }
  2191. /**
  2192. Function to run the command or file.
  2193. @param[in] Type the type of operation being run.
  2194. @param[in] CmdLine the command line to run.
  2195. @param[in] FirstParameter the first parameter on the command line
  2196. @param[in] ParamProtocol the shell parameters protocol pointer
  2197. @param[out] CommandStatus the status from the command line.
  2198. @retval EFI_SUCCESS The command was completed.
  2199. @retval EFI_ABORTED The command's operation was aborted.
  2200. **/
  2201. EFI_STATUS
  2202. RunCommandOrFile (
  2203. IN SHELL_OPERATION_TYPES Type,
  2204. IN CONST CHAR16 *CmdLine,
  2205. IN CHAR16 *FirstParameter,
  2206. IN EFI_SHELL_PARAMETERS_PROTOCOL *ParamProtocol,
  2207. OUT EFI_STATUS *CommandStatus
  2208. )
  2209. {
  2210. EFI_STATUS Status;
  2211. EFI_STATUS StartStatus;
  2212. CHAR16 *CommandWithPath;
  2213. CHAR16 *FullCommandWithPath;
  2214. EFI_DEVICE_PATH_PROTOCOL *DevPath;
  2215. SHELL_STATUS CalleeExitStatus;
  2216. Status = EFI_SUCCESS;
  2217. CommandWithPath = NULL;
  2218. DevPath = NULL;
  2219. CalleeExitStatus = SHELL_INVALID_PARAMETER;
  2220. switch (Type) {
  2221. case Internal_Command:
  2222. Status = RunInternalCommand (CmdLine, FirstParameter, ParamProtocol, CommandStatus);
  2223. break;
  2224. case Script_File_Name:
  2225. case Efi_Application:
  2226. //
  2227. // Process a fully qualified path
  2228. //
  2229. if (StrStr (FirstParameter, L":") != NULL) {
  2230. ASSERT (CommandWithPath == NULL);
  2231. if (ShellIsFile (FirstParameter) == EFI_SUCCESS) {
  2232. CommandWithPath = StrnCatGrow (&CommandWithPath, NULL, FirstParameter, 0);
  2233. }
  2234. }
  2235. //
  2236. // Process a relative path and also check in the path environment variable
  2237. //
  2238. if (CommandWithPath == NULL) {
  2239. CommandWithPath = ShellFindFilePathEx (FirstParameter, mExecutableExtensions);
  2240. }
  2241. //
  2242. // This should be impossible now.
  2243. //
  2244. ASSERT (CommandWithPath != NULL);
  2245. //
  2246. // Make sure that path is not just a directory (or not found)
  2247. //
  2248. if (!EFI_ERROR (ShellIsDirectory (CommandWithPath))) {
  2249. ShellPrintHiiEx (-1, -1, NULL, STRING_TOKEN (STR_SHELL_NOT_FOUND), ShellInfoObject.HiiHandle, FirstParameter);
  2250. SetLastError (SHELL_NOT_FOUND);
  2251. }
  2252. switch (Type) {
  2253. case Script_File_Name:
  2254. FullCommandWithPath = FullyQualifyPath (CommandWithPath);
  2255. if (FullCommandWithPath == NULL) {
  2256. Status = RunScriptFile (CommandWithPath, NULL, CmdLine, ParamProtocol);
  2257. } else {
  2258. Status = RunScriptFile (FullCommandWithPath, NULL, CmdLine, ParamProtocol);
  2259. FreePool (FullCommandWithPath);
  2260. }
  2261. break;
  2262. case Efi_Application:
  2263. //
  2264. // Get the device path of the application image
  2265. //
  2266. DevPath = ShellInfoObject.NewEfiShellProtocol->GetDevicePathFromFilePath (CommandWithPath);
  2267. if (DevPath == NULL) {
  2268. Status = EFI_OUT_OF_RESOURCES;
  2269. break;
  2270. }
  2271. //
  2272. // Execute the device path
  2273. //
  2274. Status = InternalShellExecuteDevicePath (
  2275. &gImageHandle,
  2276. DevPath,
  2277. CmdLine,
  2278. NULL,
  2279. &StartStatus
  2280. );
  2281. SHELL_FREE_NON_NULL (DevPath);
  2282. if (EFI_ERROR (Status)) {
  2283. CalleeExitStatus = (SHELL_STATUS)(Status & (~MAX_BIT));
  2284. } else {
  2285. CalleeExitStatus = (SHELL_STATUS)StartStatus;
  2286. }
  2287. if (CommandStatus != NULL) {
  2288. *CommandStatus = CalleeExitStatus;
  2289. }
  2290. //
  2291. // Update last error status.
  2292. //
  2293. // Status is an EFI_STATUS. Clear top bit to convert to SHELL_STATUS
  2294. SetLastError (CalleeExitStatus);
  2295. break;
  2296. default:
  2297. //
  2298. // Do nothing.
  2299. //
  2300. break;
  2301. }
  2302. break;
  2303. default:
  2304. //
  2305. // Do nothing.
  2306. //
  2307. break;
  2308. }
  2309. SHELL_FREE_NON_NULL (CommandWithPath);
  2310. return (Status);
  2311. }
  2312. /**
  2313. Function to setup StdIn, StdErr, StdOut, and then run the command or file.
  2314. @param[in] Type the type of operation being run.
  2315. @param[in] CmdLine the command line to run.
  2316. @param[in] FirstParameter the first parameter on the command line.
  2317. @param[in] ParamProtocol the shell parameters protocol pointer
  2318. @param[out] CommandStatus the status from the command line.
  2319. @retval EFI_SUCCESS The command was completed.
  2320. @retval EFI_ABORTED The command's operation was aborted.
  2321. **/
  2322. EFI_STATUS
  2323. SetupAndRunCommandOrFile (
  2324. IN SHELL_OPERATION_TYPES Type,
  2325. IN CHAR16 *CmdLine,
  2326. IN CHAR16 *FirstParameter,
  2327. IN EFI_SHELL_PARAMETERS_PROTOCOL *ParamProtocol,
  2328. OUT EFI_STATUS *CommandStatus
  2329. )
  2330. {
  2331. EFI_STATUS Status;
  2332. SHELL_FILE_HANDLE OriginalStdIn;
  2333. SHELL_FILE_HANDLE OriginalStdOut;
  2334. SHELL_FILE_HANDLE OriginalStdErr;
  2335. SYSTEM_TABLE_INFO OriginalSystemTableInfo;
  2336. CONST SCRIPT_FILE *ConstScriptFile;
  2337. //
  2338. // Update the StdIn, StdOut, and StdErr for redirection to environment variables, files, etc... unicode and ASCII
  2339. //
  2340. Status = UpdateStdInStdOutStdErr (ParamProtocol, CmdLine, &OriginalStdIn, &OriginalStdOut, &OriginalStdErr, &OriginalSystemTableInfo);
  2341. //
  2342. // The StdIn, StdOut, and StdErr are set up.
  2343. // Now run the command, script, or application
  2344. //
  2345. if (!EFI_ERROR (Status)) {
  2346. TrimSpaces (&CmdLine);
  2347. Status = RunCommandOrFile (Type, CmdLine, FirstParameter, ParamProtocol, CommandStatus);
  2348. }
  2349. //
  2350. // Now print errors
  2351. //
  2352. if (EFI_ERROR (Status)) {
  2353. ConstScriptFile = ShellCommandGetCurrentScriptFile ();
  2354. if ((ConstScriptFile == NULL) || (ConstScriptFile->CurrentCommand == NULL)) {
  2355. ShellPrintHiiEx (-1, -1, NULL, STRING_TOKEN (STR_SHELL_ERROR), ShellInfoObject.HiiHandle, (VOID *)(Status));
  2356. } else {
  2357. ShellPrintHiiEx (-1, -1, NULL, STRING_TOKEN (STR_SHELL_ERROR_SCRIPT), ShellInfoObject.HiiHandle, (VOID *)(Status), ConstScriptFile->CurrentCommand->Line);
  2358. }
  2359. }
  2360. //
  2361. // put back the original StdIn, StdOut, and StdErr
  2362. //
  2363. RestoreStdInStdOutStdErr (ParamProtocol, &OriginalStdIn, &OriginalStdOut, &OriginalStdErr, &OriginalSystemTableInfo);
  2364. return (Status);
  2365. }
  2366. /**
  2367. Function will process and run a command line.
  2368. This will determine if the command line represents an internal shell
  2369. command or dispatch an external application.
  2370. @param[in] CmdLine The command line to parse.
  2371. @param[out] CommandStatus The status from the command line.
  2372. @retval EFI_SUCCESS The command was completed.
  2373. @retval EFI_ABORTED The command's operation was aborted.
  2374. **/
  2375. EFI_STATUS
  2376. RunShellCommand (
  2377. IN CONST CHAR16 *CmdLine,
  2378. OUT EFI_STATUS *CommandStatus
  2379. )
  2380. {
  2381. EFI_STATUS Status;
  2382. CHAR16 *CleanOriginal;
  2383. CHAR16 *FirstParameter;
  2384. CHAR16 *TempWalker;
  2385. SHELL_OPERATION_TYPES Type;
  2386. CONST CHAR16 *CurDir;
  2387. ASSERT (CmdLine != NULL);
  2388. if (StrLen (CmdLine) == 0) {
  2389. return (EFI_SUCCESS);
  2390. }
  2391. Status = EFI_SUCCESS;
  2392. CleanOriginal = NULL;
  2393. CleanOriginal = StrnCatGrow (&CleanOriginal, NULL, CmdLine, 0);
  2394. if (CleanOriginal == NULL) {
  2395. return (EFI_OUT_OF_RESOURCES);
  2396. }
  2397. TrimSpaces (&CleanOriginal);
  2398. //
  2399. // NULL out comments (leveraged from RunScriptFileHandle() ).
  2400. // The # character on a line is used to denote that all characters on the same line
  2401. // and to the right of the # are to be ignored by the shell.
  2402. // Afterwards, again remove spaces, in case any were between the last command-parameter and '#'.
  2403. //
  2404. for (TempWalker = CleanOriginal; TempWalker != NULL && *TempWalker != CHAR_NULL; TempWalker++) {
  2405. if (*TempWalker == L'^') {
  2406. if (*(TempWalker + 1) == L'#') {
  2407. TempWalker++;
  2408. }
  2409. } else if (*TempWalker == L'#') {
  2410. *TempWalker = CHAR_NULL;
  2411. }
  2412. }
  2413. TrimSpaces (&CleanOriginal);
  2414. //
  2415. // Handle case that passed in command line is just 1 or more " " characters.
  2416. //
  2417. if (StrLen (CleanOriginal) == 0) {
  2418. SHELL_FREE_NON_NULL (CleanOriginal);
  2419. return (EFI_SUCCESS);
  2420. }
  2421. Status = ProcessCommandLineToFinal (&CleanOriginal);
  2422. if (EFI_ERROR (Status)) {
  2423. SHELL_FREE_NON_NULL (CleanOriginal);
  2424. return (Status);
  2425. }
  2426. //
  2427. // We don't do normal processing with a split command line (output from one command input to another)
  2428. //
  2429. if (ContainsSplit (CleanOriginal)) {
  2430. Status = ProcessNewSplitCommandLine (CleanOriginal);
  2431. SHELL_FREE_NON_NULL (CleanOriginal);
  2432. return (Status);
  2433. }
  2434. //
  2435. // We need the first parameter information so we can determine the operation type
  2436. //
  2437. FirstParameter = AllocateZeroPool (StrSize (CleanOriginal));
  2438. if (FirstParameter == NULL) {
  2439. SHELL_FREE_NON_NULL (CleanOriginal);
  2440. return (EFI_OUT_OF_RESOURCES);
  2441. }
  2442. TempWalker = CleanOriginal;
  2443. if (!EFI_ERROR (GetNextParameter (&TempWalker, &FirstParameter, StrSize (CleanOriginal), TRUE))) {
  2444. //
  2445. // Depending on the first parameter we change the behavior
  2446. //
  2447. switch (Type = GetOperationType (FirstParameter)) {
  2448. case File_Sys_Change:
  2449. Status = ChangeMappedDrive (FirstParameter);
  2450. break;
  2451. case Internal_Command:
  2452. case Script_File_Name:
  2453. case Efi_Application:
  2454. Status = SetupAndRunCommandOrFile (Type, CleanOriginal, FirstParameter, ShellInfoObject.NewShellParametersProtocol, CommandStatus);
  2455. break;
  2456. default:
  2457. //
  2458. // Whatever was typed, it was invalid.
  2459. //
  2460. ShellPrintHiiEx (-1, -1, NULL, STRING_TOKEN (STR_SHELL_NOT_FOUND), ShellInfoObject.HiiHandle, FirstParameter);
  2461. SetLastError (SHELL_NOT_FOUND);
  2462. break;
  2463. }
  2464. } else {
  2465. ShellPrintHiiEx (-1, -1, NULL, STRING_TOKEN (STR_SHELL_NOT_FOUND), ShellInfoObject.HiiHandle, FirstParameter);
  2466. SetLastError (SHELL_NOT_FOUND);
  2467. }
  2468. //
  2469. // Check whether the current file system still exists. If not exist, we need update "cwd" and gShellCurMapping.
  2470. //
  2471. CurDir = EfiShellGetCurDir (NULL);
  2472. if (CurDir != NULL) {
  2473. if (EFI_ERROR (ShellFileExists (CurDir))) {
  2474. //
  2475. // EfiShellSetCurDir() cannot set current directory to NULL.
  2476. // EfiShellSetEnv() is not allowed to set the "cwd" variable.
  2477. // Only InternalEfiShellSetEnv () is allowed setting the "cwd" variable.
  2478. //
  2479. InternalEfiShellSetEnv (L"cwd", NULL, TRUE);
  2480. gShellCurMapping = NULL;
  2481. }
  2482. }
  2483. SHELL_FREE_NON_NULL (CleanOriginal);
  2484. SHELL_FREE_NON_NULL (FirstParameter);
  2485. return (Status);
  2486. }
  2487. /**
  2488. Function will process and run a command line.
  2489. This will determine if the command line represents an internal shell
  2490. command or dispatch an external application.
  2491. @param[in] CmdLine The command line to parse.
  2492. @retval EFI_SUCCESS The command was completed.
  2493. @retval EFI_ABORTED The command's operation was aborted.
  2494. **/
  2495. EFI_STATUS
  2496. RunCommand (
  2497. IN CONST CHAR16 *CmdLine
  2498. )
  2499. {
  2500. return (RunShellCommand (CmdLine, NULL));
  2501. }
  2502. /**
  2503. Function to process a NSH script file via SHELL_FILE_HANDLE.
  2504. @param[in] Handle The handle to the already opened file.
  2505. @param[in] Name The name of the script file.
  2506. @retval EFI_SUCCESS the script completed successfully
  2507. **/
  2508. EFI_STATUS
  2509. RunScriptFileHandle (
  2510. IN SHELL_FILE_HANDLE Handle,
  2511. IN CONST CHAR16 *Name
  2512. )
  2513. {
  2514. EFI_STATUS Status;
  2515. SCRIPT_FILE *NewScriptFile;
  2516. UINTN LoopVar;
  2517. UINTN PrintBuffSize;
  2518. CHAR16 *CommandLine;
  2519. CHAR16 *CommandLine2;
  2520. CHAR16 *CommandLine3;
  2521. SCRIPT_COMMAND_LIST *LastCommand;
  2522. BOOLEAN Ascii;
  2523. BOOLEAN PreScriptEchoState;
  2524. BOOLEAN PreCommandEchoState;
  2525. CONST CHAR16 *CurDir;
  2526. UINTN LineCount;
  2527. CHAR16 LeString[50];
  2528. LIST_ENTRY OldBufferList;
  2529. ASSERT (!ShellCommandGetScriptExit ());
  2530. PreScriptEchoState = ShellCommandGetEchoState ();
  2531. PrintBuffSize = PcdGet16 (PcdShellPrintBufferSize);
  2532. NewScriptFile = (SCRIPT_FILE *)AllocateZeroPool (sizeof (SCRIPT_FILE));
  2533. if (NewScriptFile == NULL) {
  2534. return (EFI_OUT_OF_RESOURCES);
  2535. }
  2536. //
  2537. // Set up the name
  2538. //
  2539. ASSERT (NewScriptFile->ScriptName == NULL);
  2540. NewScriptFile->ScriptName = StrnCatGrow (&NewScriptFile->ScriptName, NULL, Name, 0);
  2541. if (NewScriptFile->ScriptName == NULL) {
  2542. DeleteScriptFileStruct (NewScriptFile);
  2543. return (EFI_OUT_OF_RESOURCES);
  2544. }
  2545. //
  2546. // Save the parameters (used to replace %0 to %9 later on)
  2547. //
  2548. NewScriptFile->Argc = ShellInfoObject.NewShellParametersProtocol->Argc;
  2549. if (NewScriptFile->Argc != 0) {
  2550. NewScriptFile->Argv = (CHAR16 **)AllocateZeroPool (NewScriptFile->Argc * sizeof (CHAR16 *));
  2551. if (NewScriptFile->Argv == NULL) {
  2552. DeleteScriptFileStruct (NewScriptFile);
  2553. return (EFI_OUT_OF_RESOURCES);
  2554. }
  2555. //
  2556. // Put the full path of the script file into Argv[0] as required by section
  2557. // 3.6.2 of version 2.2 of the shell specification.
  2558. //
  2559. NewScriptFile->Argv[0] = StrnCatGrow (&NewScriptFile->Argv[0], NULL, NewScriptFile->ScriptName, 0);
  2560. for (LoopVar = 1; LoopVar < 10 && LoopVar < NewScriptFile->Argc; LoopVar++) {
  2561. ASSERT (NewScriptFile->Argv[LoopVar] == NULL);
  2562. NewScriptFile->Argv[LoopVar] = StrnCatGrow (&NewScriptFile->Argv[LoopVar], NULL, ShellInfoObject.NewShellParametersProtocol->Argv[LoopVar], 0);
  2563. if (NewScriptFile->Argv[LoopVar] == NULL) {
  2564. DeleteScriptFileStruct (NewScriptFile);
  2565. return (EFI_OUT_OF_RESOURCES);
  2566. }
  2567. }
  2568. } else {
  2569. NewScriptFile->Argv = NULL;
  2570. }
  2571. InitializeListHead (&NewScriptFile->CommandList);
  2572. InitializeListHead (&NewScriptFile->SubstList);
  2573. //
  2574. // Now build the list of all script commands.
  2575. //
  2576. LineCount = 0;
  2577. while (!ShellFileHandleEof (Handle)) {
  2578. CommandLine = ShellFileHandleReturnLine (Handle, &Ascii);
  2579. LineCount++;
  2580. if ((CommandLine == NULL) || (StrLen (CommandLine) == 0) || (CommandLine[0] == '#')) {
  2581. SHELL_FREE_NON_NULL (CommandLine);
  2582. continue;
  2583. }
  2584. NewScriptFile->CurrentCommand = AllocateZeroPool (sizeof (SCRIPT_COMMAND_LIST));
  2585. if (NewScriptFile->CurrentCommand == NULL) {
  2586. SHELL_FREE_NON_NULL (CommandLine);
  2587. DeleteScriptFileStruct (NewScriptFile);
  2588. return (EFI_OUT_OF_RESOURCES);
  2589. }
  2590. NewScriptFile->CurrentCommand->Cl = CommandLine;
  2591. NewScriptFile->CurrentCommand->Data = NULL;
  2592. NewScriptFile->CurrentCommand->Line = LineCount;
  2593. InsertTailList (&NewScriptFile->CommandList, &NewScriptFile->CurrentCommand->Link);
  2594. }
  2595. //
  2596. // Add this as the topmost script file
  2597. //
  2598. ShellCommandSetNewScript (NewScriptFile);
  2599. //
  2600. // Now enumerate through the commands and run each one.
  2601. //
  2602. CommandLine = AllocateZeroPool (PrintBuffSize);
  2603. if (CommandLine == NULL) {
  2604. DeleteScriptFileStruct (NewScriptFile);
  2605. return (EFI_OUT_OF_RESOURCES);
  2606. }
  2607. CommandLine2 = AllocateZeroPool (PrintBuffSize);
  2608. if (CommandLine2 == NULL) {
  2609. FreePool (CommandLine);
  2610. DeleteScriptFileStruct (NewScriptFile);
  2611. return (EFI_OUT_OF_RESOURCES);
  2612. }
  2613. for ( NewScriptFile->CurrentCommand = (SCRIPT_COMMAND_LIST *)GetFirstNode (&NewScriptFile->CommandList)
  2614. ; !IsNull (&NewScriptFile->CommandList, &NewScriptFile->CurrentCommand->Link)
  2615. ; // conditional increment in the body of the loop
  2616. )
  2617. {
  2618. ASSERT (CommandLine2 != NULL);
  2619. StrnCpyS (
  2620. CommandLine2,
  2621. PrintBuffSize/sizeof (CHAR16),
  2622. NewScriptFile->CurrentCommand->Cl,
  2623. PrintBuffSize/sizeof (CHAR16) - 1
  2624. );
  2625. SaveBufferList (&OldBufferList);
  2626. //
  2627. // NULL out comments
  2628. //
  2629. for (CommandLine3 = CommandLine2; CommandLine3 != NULL && *CommandLine3 != CHAR_NULL; CommandLine3++) {
  2630. if (*CommandLine3 == L'^') {
  2631. if ( *(CommandLine3+1) == L':') {
  2632. CopyMem (CommandLine3, CommandLine3+1, StrSize (CommandLine3) - sizeof (CommandLine3[0]));
  2633. } else if (*(CommandLine3+1) == L'#') {
  2634. CommandLine3++;
  2635. }
  2636. } else if (*CommandLine3 == L'#') {
  2637. *CommandLine3 = CHAR_NULL;
  2638. }
  2639. }
  2640. if ((CommandLine2 != NULL) && (StrLen (CommandLine2) >= 1)) {
  2641. //
  2642. // Due to variability in starting the find and replace action we need to have both buffers the same.
  2643. //
  2644. StrnCpyS (
  2645. CommandLine,
  2646. PrintBuffSize/sizeof (CHAR16),
  2647. CommandLine2,
  2648. PrintBuffSize/sizeof (CHAR16) - 1
  2649. );
  2650. //
  2651. // Remove the %0 to %9 from the command line (if we have some arguments)
  2652. //
  2653. if (NewScriptFile->Argv != NULL) {
  2654. switch (NewScriptFile->Argc) {
  2655. default:
  2656. Status = ShellCopySearchAndReplace (CommandLine2, CommandLine, PrintBuffSize, L"%9", NewScriptFile->Argv[9], FALSE, FALSE);
  2657. ASSERT_EFI_ERROR (Status);
  2658. case 9:
  2659. Status = ShellCopySearchAndReplace (CommandLine, CommandLine2, PrintBuffSize, L"%8", NewScriptFile->Argv[8], FALSE, FALSE);
  2660. ASSERT_EFI_ERROR (Status);
  2661. case 8:
  2662. Status = ShellCopySearchAndReplace (CommandLine2, CommandLine, PrintBuffSize, L"%7", NewScriptFile->Argv[7], FALSE, FALSE);
  2663. ASSERT_EFI_ERROR (Status);
  2664. case 7:
  2665. Status = ShellCopySearchAndReplace (CommandLine, CommandLine2, PrintBuffSize, L"%6", NewScriptFile->Argv[6], FALSE, FALSE);
  2666. ASSERT_EFI_ERROR (Status);
  2667. case 6:
  2668. Status = ShellCopySearchAndReplace (CommandLine2, CommandLine, PrintBuffSize, L"%5", NewScriptFile->Argv[5], FALSE, FALSE);
  2669. ASSERT_EFI_ERROR (Status);
  2670. case 5:
  2671. Status = ShellCopySearchAndReplace (CommandLine, CommandLine2, PrintBuffSize, L"%4", NewScriptFile->Argv[4], FALSE, FALSE);
  2672. ASSERT_EFI_ERROR (Status);
  2673. case 4:
  2674. Status = ShellCopySearchAndReplace (CommandLine2, CommandLine, PrintBuffSize, L"%3", NewScriptFile->Argv[3], FALSE, FALSE);
  2675. ASSERT_EFI_ERROR (Status);
  2676. case 3:
  2677. Status = ShellCopySearchAndReplace (CommandLine, CommandLine2, PrintBuffSize, L"%2", NewScriptFile->Argv[2], FALSE, FALSE);
  2678. ASSERT_EFI_ERROR (Status);
  2679. case 2:
  2680. Status = ShellCopySearchAndReplace (CommandLine2, CommandLine, PrintBuffSize, L"%1", NewScriptFile->Argv[1], FALSE, FALSE);
  2681. ASSERT_EFI_ERROR (Status);
  2682. case 1:
  2683. Status = ShellCopySearchAndReplace (CommandLine, CommandLine2, PrintBuffSize, L"%0", NewScriptFile->Argv[0], FALSE, FALSE);
  2684. ASSERT_EFI_ERROR (Status);
  2685. break;
  2686. case 0:
  2687. break;
  2688. }
  2689. }
  2690. Status = ShellCopySearchAndReplace (CommandLine2, CommandLine, PrintBuffSize, L"%1", L"\"\"", FALSE, FALSE);
  2691. Status = ShellCopySearchAndReplace (CommandLine, CommandLine2, PrintBuffSize, L"%2", L"\"\"", FALSE, FALSE);
  2692. Status = ShellCopySearchAndReplace (CommandLine2, CommandLine, PrintBuffSize, L"%3", L"\"\"", FALSE, FALSE);
  2693. Status = ShellCopySearchAndReplace (CommandLine, CommandLine2, PrintBuffSize, L"%4", L"\"\"", FALSE, FALSE);
  2694. Status = ShellCopySearchAndReplace (CommandLine2, CommandLine, PrintBuffSize, L"%5", L"\"\"", FALSE, FALSE);
  2695. Status = ShellCopySearchAndReplace (CommandLine, CommandLine2, PrintBuffSize, L"%6", L"\"\"", FALSE, FALSE);
  2696. Status = ShellCopySearchAndReplace (CommandLine2, CommandLine, PrintBuffSize, L"%7", L"\"\"", FALSE, FALSE);
  2697. Status = ShellCopySearchAndReplace (CommandLine, CommandLine2, PrintBuffSize, L"%8", L"\"\"", FALSE, FALSE);
  2698. Status = ShellCopySearchAndReplace (CommandLine2, CommandLine, PrintBuffSize, L"%9", L"\"\"", FALSE, FALSE);
  2699. StrnCpyS (
  2700. CommandLine2,
  2701. PrintBuffSize/sizeof (CHAR16),
  2702. CommandLine,
  2703. PrintBuffSize/sizeof (CHAR16) - 1
  2704. );
  2705. LastCommand = NewScriptFile->CurrentCommand;
  2706. for (CommandLine3 = CommandLine2; CommandLine3[0] == L' '; CommandLine3++) {
  2707. }
  2708. if ((CommandLine3 != NULL) && (CommandLine3[0] == L':')) {
  2709. //
  2710. // This line is a goto target / label
  2711. //
  2712. } else {
  2713. if ((CommandLine3 != NULL) && (StrLen (CommandLine3) > 0)) {
  2714. if (CommandLine3[0] == L'@') {
  2715. //
  2716. // We need to save the current echo state
  2717. // and disable echo for just this command.
  2718. //
  2719. PreCommandEchoState = ShellCommandGetEchoState ();
  2720. ShellCommandSetEchoState (FALSE);
  2721. Status = RunCommand (CommandLine3+1);
  2722. //
  2723. // If command was "@echo -off" or "@echo -on" then don't restore echo state
  2724. //
  2725. if ((StrCmp (L"@echo -off", CommandLine3) != 0) &&
  2726. (StrCmp (L"@echo -on", CommandLine3) != 0))
  2727. {
  2728. //
  2729. // Now restore the pre-'@' echo state.
  2730. //
  2731. ShellCommandSetEchoState (PreCommandEchoState);
  2732. }
  2733. } else {
  2734. if (ShellCommandGetEchoState ()) {
  2735. CurDir = ShellInfoObject.NewEfiShellProtocol->GetEnv (L"cwd");
  2736. if ((CurDir != NULL) && (StrLen (CurDir) > 1)) {
  2737. ShellPrintHiiEx (-1, -1, NULL, STRING_TOKEN (STR_SHELL_CURDIR), ShellInfoObject.HiiHandle, CurDir);
  2738. } else {
  2739. ShellPrintHiiEx (-1, -1, NULL, STRING_TOKEN (STR_SHELL_SHELL), ShellInfoObject.HiiHandle);
  2740. }
  2741. ShellPrintEx (-1, -1, L"%s\r\n", CommandLine2);
  2742. }
  2743. Status = RunCommand (CommandLine3);
  2744. }
  2745. }
  2746. if (ShellCommandGetScriptExit ()) {
  2747. //
  2748. // ShellCommandGetExitCode() always returns a UINT64
  2749. //
  2750. UnicodeSPrint (LeString, sizeof (LeString), L"0x%Lx", ShellCommandGetExitCode ());
  2751. DEBUG_CODE (
  2752. InternalEfiShellSetEnv (L"debuglasterror", LeString, TRUE);
  2753. );
  2754. InternalEfiShellSetEnv (L"lasterror", LeString, TRUE);
  2755. ShellCommandRegisterExit (FALSE, 0);
  2756. Status = EFI_SUCCESS;
  2757. RestoreBufferList (&OldBufferList);
  2758. break;
  2759. }
  2760. if (ShellGetExecutionBreakFlag ()) {
  2761. RestoreBufferList (&OldBufferList);
  2762. break;
  2763. }
  2764. if (EFI_ERROR (Status)) {
  2765. RestoreBufferList (&OldBufferList);
  2766. break;
  2767. }
  2768. if (ShellCommandGetExit ()) {
  2769. RestoreBufferList (&OldBufferList);
  2770. break;
  2771. }
  2772. }
  2773. //
  2774. // If that commend did not update the CurrentCommand then we need to advance it...
  2775. //
  2776. if (LastCommand == NewScriptFile->CurrentCommand) {
  2777. NewScriptFile->CurrentCommand = (SCRIPT_COMMAND_LIST *)GetNextNode (&NewScriptFile->CommandList, &NewScriptFile->CurrentCommand->Link);
  2778. if (!IsNull (&NewScriptFile->CommandList, &NewScriptFile->CurrentCommand->Link)) {
  2779. NewScriptFile->CurrentCommand->Reset = TRUE;
  2780. }
  2781. }
  2782. } else {
  2783. NewScriptFile->CurrentCommand = (SCRIPT_COMMAND_LIST *)GetNextNode (&NewScriptFile->CommandList, &NewScriptFile->CurrentCommand->Link);
  2784. if (!IsNull (&NewScriptFile->CommandList, &NewScriptFile->CurrentCommand->Link)) {
  2785. NewScriptFile->CurrentCommand->Reset = TRUE;
  2786. }
  2787. }
  2788. RestoreBufferList (&OldBufferList);
  2789. }
  2790. FreePool (CommandLine);
  2791. FreePool (CommandLine2);
  2792. ShellCommandSetNewScript (NULL);
  2793. //
  2794. // Only if this was the last script reset the state.
  2795. //
  2796. if (ShellCommandGetCurrentScriptFile () == NULL) {
  2797. ShellCommandSetEchoState (PreScriptEchoState);
  2798. }
  2799. return (EFI_SUCCESS);
  2800. }
  2801. /**
  2802. Function to process a NSH script file.
  2803. @param[in] ScriptPath Pointer to the script file name (including file system path).
  2804. @param[in] Handle the handle of the script file already opened.
  2805. @param[in] CmdLine the command line to run.
  2806. @param[in] ParamProtocol the shell parameters protocol pointer
  2807. @retval EFI_SUCCESS the script completed successfully
  2808. **/
  2809. EFI_STATUS
  2810. RunScriptFile (
  2811. IN CONST CHAR16 *ScriptPath,
  2812. IN SHELL_FILE_HANDLE Handle OPTIONAL,
  2813. IN CONST CHAR16 *CmdLine,
  2814. IN EFI_SHELL_PARAMETERS_PROTOCOL *ParamProtocol
  2815. )
  2816. {
  2817. EFI_STATUS Status;
  2818. SHELL_FILE_HANDLE FileHandle;
  2819. UINTN Argc;
  2820. CHAR16 **Argv;
  2821. if (ShellIsFile (ScriptPath) != EFI_SUCCESS) {
  2822. return (EFI_INVALID_PARAMETER);
  2823. }
  2824. //
  2825. // get the argc and argv updated for scripts
  2826. //
  2827. Status = UpdateArgcArgv (ParamProtocol, CmdLine, Script_File_Name, &Argv, &Argc);
  2828. if (!EFI_ERROR (Status)) {
  2829. if (Handle == NULL) {
  2830. //
  2831. // open the file
  2832. //
  2833. Status = ShellOpenFileByName (ScriptPath, &FileHandle, EFI_FILE_MODE_READ, 0);
  2834. if (!EFI_ERROR (Status)) {
  2835. //
  2836. // run it
  2837. //
  2838. Status = RunScriptFileHandle (FileHandle, ScriptPath);
  2839. //
  2840. // now close the file
  2841. //
  2842. ShellCloseFile (&FileHandle);
  2843. }
  2844. } else {
  2845. Status = RunScriptFileHandle (Handle, ScriptPath);
  2846. }
  2847. }
  2848. //
  2849. // This is guaranteed to be called after UpdateArgcArgv no matter what else happened.
  2850. // This is safe even if the update API failed. In this case, it may be a no-op.
  2851. //
  2852. RestoreArgcArgv (ParamProtocol, &Argv, &Argc);
  2853. return (Status);
  2854. }
  2855. /**
  2856. Return the pointer to the first occurrence of any character from a list of characters.
  2857. @param[in] String the string to parse
  2858. @param[in] CharacterList the list of character to look for
  2859. @param[in] EscapeCharacter An escape character to skip
  2860. @return the location of the first character in the string
  2861. @retval CHAR_NULL no instance of any character in CharacterList was found in String
  2862. **/
  2863. CONST CHAR16 *
  2864. FindFirstCharacter (
  2865. IN CONST CHAR16 *String,
  2866. IN CONST CHAR16 *CharacterList,
  2867. IN CONST CHAR16 EscapeCharacter
  2868. )
  2869. {
  2870. UINT32 WalkChar;
  2871. UINT32 WalkStr;
  2872. for (WalkStr = 0; WalkStr < StrLen (String); WalkStr++) {
  2873. if (String[WalkStr] == EscapeCharacter) {
  2874. WalkStr++;
  2875. continue;
  2876. }
  2877. for (WalkChar = 0; WalkChar < StrLen (CharacterList); WalkChar++) {
  2878. if (String[WalkStr] == CharacterList[WalkChar]) {
  2879. return (&String[WalkStr]);
  2880. }
  2881. }
  2882. }
  2883. return (String + StrLen (String));
  2884. }