3
0

hush.c 133 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * sh.c -- a prototype Bourne shell grammar parser
  4. * Intended to follow the original Thompson and Ritchie
  5. * "small and simple is beautiful" philosophy, which
  6. * incidentally is a good match to today's BusyBox.
  7. *
  8. * Copyright (C) 2000,2001 Larry Doolittle <larry@doolittle.boa.org>
  9. *
  10. * Credits:
  11. * The parser routines proper are all original material, first
  12. * written Dec 2000 and Jan 2001 by Larry Doolittle. The
  13. * execution engine, the builtins, and much of the underlying
  14. * support has been adapted from busybox-0.49pre's lash, which is
  15. * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
  16. * written by Erik Andersen <andersen@codepoet.org>. That, in turn,
  17. * is based in part on ladsh.c, by Michael K. Johnson and Erik W.
  18. * Troan, which they placed in the public domain. I don't know
  19. * how much of the Johnson/Troan code has survived the repeated
  20. * rewrites.
  21. *
  22. * Other credits:
  23. * o_addchr() derived from similar w_addchar function in glibc-2.2.
  24. * setup_redirect(), redirect_opt_num(), and big chunks of main()
  25. * and many builtins derived from contributions by Erik Andersen
  26. * miscellaneous bugfixes from Matt Kraai.
  27. *
  28. * There are two big (and related) architecture differences between
  29. * this parser and the lash parser. One is that this version is
  30. * actually designed from the ground up to understand nearly all
  31. * of the Bourne grammar. The second, consequential change is that
  32. * the parser and input reader have been turned inside out. Now,
  33. * the parser is in control, and asks for input as needed. The old
  34. * way had the input reader in control, and it asked for parsing to
  35. * take place as needed. The new way makes it much easier to properly
  36. * handle the recursion implicit in the various substitutions, especially
  37. * across continuation lines.
  38. *
  39. * Bash grammar not implemented: (how many of these were in original sh?)
  40. * $_
  41. * &> and >& redirection of stdout+stderr
  42. * Brace Expansion
  43. * Tilde Expansion
  44. * fancy forms of Parameter Expansion
  45. * aliases
  46. * Arithmetic Expansion
  47. * <(list) and >(list) Process Substitution
  48. * reserved words: select, function
  49. * Here Documents ( << word )
  50. * Functions
  51. * Major bugs:
  52. * job handling woefully incomplete and buggy (improved --vda)
  53. * to-do:
  54. * port selected bugfixes from post-0.49 busybox lash - done?
  55. * change { and } from special chars to reserved words
  56. * builtins: return, trap, ulimit
  57. * test magic exec with redirection only
  58. * check setting of global_argc and global_argv
  59. * follow IFS rules more precisely, including update semantics
  60. * figure out what to do with backslash-newline
  61. * propagate syntax errors, die on resource errors?
  62. * continuation lines, both explicit and implicit - done?
  63. * memory leak finding and plugging - done?
  64. * maybe change charmap[] to use 2-bit entries
  65. *
  66. * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
  67. */
  68. #include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
  69. #include <glob.h>
  70. /* #include <dmalloc.h> */
  71. #if ENABLE_HUSH_CASE
  72. #include <fnmatch.h>
  73. #endif
  74. #define HUSH_VER_STR "0.91"
  75. #if !BB_MMU && ENABLE_HUSH_TICK
  76. //#undef ENABLE_HUSH_TICK
  77. //#define ENABLE_HUSH_TICK 0
  78. #warning On NOMMU, hush command substitution is dangerous.
  79. #warning Dont use it for commands which produce lots of output.
  80. #warning For more info see shell/hush.c, generate_stream_from_list().
  81. #endif
  82. #if !BB_MMU && ENABLE_HUSH_JOB
  83. #undef ENABLE_HUSH_JOB
  84. #define ENABLE_HUSH_JOB 0
  85. #endif
  86. #if !ENABLE_HUSH_INTERACTIVE
  87. #undef ENABLE_FEATURE_EDITING
  88. #define ENABLE_FEATURE_EDITING 0
  89. #undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
  90. #define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
  91. #endif
  92. /* Keep unconditionally on for now */
  93. #define HUSH_DEBUG 1
  94. /* In progress... */
  95. #define ENABLE_HUSH_FUNCTIONS 0
  96. /* If you comment out one of these below, it will be #defined later
  97. * to perform debug printfs to stderr: */
  98. #define debug_printf(...) do {} while (0)
  99. /* Finer-grained debug switches */
  100. #define debug_printf_parse(...) do {} while (0)
  101. #define debug_print_tree(a, b) do {} while (0)
  102. #define debug_printf_exec(...) do {} while (0)
  103. #define debug_printf_env(...) do {} while (0)
  104. #define debug_printf_jobs(...) do {} while (0)
  105. #define debug_printf_expand(...) do {} while (0)
  106. #define debug_printf_glob(...) do {} while (0)
  107. #define debug_printf_list(...) do {} while (0)
  108. #define debug_printf_subst(...) do {} while (0)
  109. #define debug_printf_clean(...) do {} while (0)
  110. #ifndef debug_printf
  111. #define debug_printf(...) fprintf(stderr, __VA_ARGS__)
  112. #endif
  113. #ifndef debug_printf_parse
  114. #define debug_printf_parse(...) fprintf(stderr, __VA_ARGS__)
  115. #endif
  116. #ifndef debug_printf_exec
  117. #define debug_printf_exec(...) fprintf(stderr, __VA_ARGS__)
  118. #endif
  119. #ifndef debug_printf_env
  120. #define debug_printf_env(...) fprintf(stderr, __VA_ARGS__)
  121. #endif
  122. #ifndef debug_printf_jobs
  123. #define debug_printf_jobs(...) fprintf(stderr, __VA_ARGS__)
  124. #define DEBUG_JOBS 1
  125. #else
  126. #define DEBUG_JOBS 0
  127. #endif
  128. #ifndef debug_printf_expand
  129. #define debug_printf_expand(...) fprintf(stderr, __VA_ARGS__)
  130. #define DEBUG_EXPAND 1
  131. #else
  132. #define DEBUG_EXPAND 0
  133. #endif
  134. #ifndef debug_printf_glob
  135. #define debug_printf_glob(...) fprintf(stderr, __VA_ARGS__)
  136. #define DEBUG_GLOB 1
  137. #else
  138. #define DEBUG_GLOB 0
  139. #endif
  140. #ifndef debug_printf_list
  141. #define debug_printf_list(...) fprintf(stderr, __VA_ARGS__)
  142. #endif
  143. #ifndef debug_printf_subst
  144. #define debug_printf_subst(...) fprintf(stderr, __VA_ARGS__)
  145. #endif
  146. #ifndef debug_printf_clean
  147. /* broken, of course, but OK for testing */
  148. static const char *indenter(int i)
  149. {
  150. static const char blanks[] ALIGN1 =
  151. " ";
  152. return &blanks[sizeof(blanks) - i - 1];
  153. }
  154. #define debug_printf_clean(...) fprintf(stderr, __VA_ARGS__)
  155. #define DEBUG_CLEAN 1
  156. #endif
  157. #if DEBUG_EXPAND
  158. static void debug_print_strings(const char *prefix, char **vv)
  159. {
  160. fprintf(stderr, "%s:\n", prefix);
  161. while (*vv)
  162. fprintf(stderr, " '%s'\n", *vv++);
  163. }
  164. #else
  165. #define debug_print_strings(prefix, vv) ((void)0)
  166. #endif
  167. /*
  168. * Leak hunting. Use hush_leaktool.sh for post-processing.
  169. */
  170. #ifdef FOR_HUSH_LEAKTOOL
  171. /* suppress "warning: no previous prototype..." */
  172. void *xxmalloc(int lineno, size_t size);
  173. void *xxrealloc(int lineno, void *ptr, size_t size);
  174. char *xxstrdup(int lineno, const char *str);
  175. void xxfree(void *ptr);
  176. void *xxmalloc(int lineno, size_t size)
  177. {
  178. void *ptr = xmalloc((size + 0xff) & ~0xff);
  179. fprintf(stderr, "line %d: malloc %p\n", lineno, ptr);
  180. return ptr;
  181. }
  182. void *xxrealloc(int lineno, void *ptr, size_t size)
  183. {
  184. ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
  185. fprintf(stderr, "line %d: realloc %p\n", lineno, ptr);
  186. return ptr;
  187. }
  188. char *xxstrdup(int lineno, const char *str)
  189. {
  190. char *ptr = xstrdup(str);
  191. fprintf(stderr, "line %d: strdup %p\n", lineno, ptr);
  192. return ptr;
  193. }
  194. void xxfree(void *ptr)
  195. {
  196. fprintf(stderr, "free %p\n", ptr);
  197. free(ptr);
  198. }
  199. #define xmalloc(s) xxmalloc(__LINE__, s)
  200. #define xrealloc(p, s) xxrealloc(__LINE__, p, s)
  201. #define xstrdup(s) xxstrdup(__LINE__, s)
  202. #define free(p) xxfree(p)
  203. #endif
  204. /* Do we support ANY keywords? */
  205. #if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
  206. #define HAS_KEYWORDS 1
  207. #define IF_HAS_KEYWORDS(...) __VA_ARGS__
  208. #define IF_HAS_NO_KEYWORDS(...)
  209. #else
  210. #define HAS_KEYWORDS 0
  211. #define IF_HAS_KEYWORDS(...)
  212. #define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
  213. #endif
  214. #define SPECIAL_VAR_SYMBOL 3
  215. #define PARSEFLAG_EXIT_FROM_LOOP 1
  216. typedef enum redir_type {
  217. REDIRECT_INPUT = 1,
  218. REDIRECT_OVERWRITE = 2,
  219. REDIRECT_APPEND = 3,
  220. REDIRECT_HEREIS = 4,
  221. REDIRECT_IO = 5
  222. } redir_type;
  223. /* The descrip member of this structure is only used to make
  224. * debugging output pretty */
  225. static const struct {
  226. int mode;
  227. signed char default_fd;
  228. char descrip[3];
  229. } redir_table[] = {
  230. { 0, 0, "()" },
  231. { O_RDONLY, 0, "<" },
  232. { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
  233. { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
  234. { O_RDONLY, -1, "<<" },
  235. { O_RDWR, 1, "<>" }
  236. };
  237. typedef enum pipe_style {
  238. PIPE_SEQ = 1,
  239. PIPE_AND = 2,
  240. PIPE_OR = 3,
  241. PIPE_BG = 4,
  242. } pipe_style;
  243. typedef enum reserved_style {
  244. RES_NONE = 0,
  245. #if ENABLE_HUSH_IF
  246. RES_IF ,
  247. RES_THEN ,
  248. RES_ELIF ,
  249. RES_ELSE ,
  250. RES_FI ,
  251. #endif
  252. #if ENABLE_HUSH_LOOPS
  253. RES_FOR ,
  254. RES_WHILE ,
  255. RES_UNTIL ,
  256. RES_DO ,
  257. RES_DONE ,
  258. #endif
  259. #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
  260. RES_IN ,
  261. #endif
  262. #if ENABLE_HUSH_CASE
  263. RES_CASE ,
  264. /* two pseudo-keywords support contrived "case" syntax: */
  265. RES_MATCH , /* "word)" */
  266. RES_CASEI , /* "this command is inside CASE" */
  267. RES_ESAC ,
  268. #endif
  269. RES_XXXX ,
  270. RES_SNTX
  271. } reserved_style;
  272. struct redir_struct {
  273. struct redir_struct *next;
  274. char *rd_filename; /* filename */
  275. int fd; /* file descriptor being redirected */
  276. int dup; /* -1, or file descriptor being duplicated */
  277. smallint /*enum redir_type*/ rd_type;
  278. };
  279. struct command {
  280. pid_t pid; /* 0 if exited */
  281. int assignment_cnt; /* how many argv[i] are assignments? */
  282. smallint is_stopped; /* is the command currently running? */
  283. smallint grp_type;
  284. struct pipe *group; /* if non-NULL, this "prog" is {} group,
  285. * subshell, or a compound statement */
  286. char **argv; /* command name and arguments */
  287. struct redir_struct *redirects; /* I/O redirections */
  288. };
  289. /* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
  290. * and on execution these are substituted with their values.
  291. * Substitution can make _several_ words out of one argv[n]!
  292. * Example: argv[0]=='.^C*^C.' here: echo .$*.
  293. * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
  294. */
  295. #define GRP_NORMAL 0
  296. #define GRP_SUBSHELL 1
  297. #if ENABLE_HUSH_FUNCTIONS
  298. #define GRP_FUNCTION 2
  299. #endif
  300. struct pipe {
  301. struct pipe *next;
  302. int num_cmds; /* total number of commands in job */
  303. int alive_cmds; /* number of commands running (not exited) */
  304. int stopped_cmds; /* number of commands alive, but stopped */
  305. #if ENABLE_HUSH_JOB
  306. int jobid; /* job number */
  307. pid_t pgrp; /* process group ID for the job */
  308. char *cmdtext; /* name of job */
  309. #endif
  310. struct command *cmds; /* array of commands in pipe */
  311. smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
  312. IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
  313. IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
  314. };
  315. /* This holds pointers to the various results of parsing */
  316. struct parse_context {
  317. struct command *command;
  318. struct pipe *list_head;
  319. struct pipe *pipe;
  320. struct redir_struct *pending_redirect;
  321. #if HAS_KEYWORDS
  322. smallint ctx_res_w;
  323. smallint ctx_inverted; /* "! cmd | cmd" */
  324. #if ENABLE_HUSH_CASE
  325. smallint ctx_dsemicolon; /* ";;" seen */
  326. #endif
  327. int old_flag; /* bitmask of FLAG_xxx, for figuring out valid reserved words */
  328. struct parse_context *stack;
  329. #endif
  330. };
  331. /* On program start, environ points to initial environment.
  332. * putenv adds new pointers into it, unsetenv removes them.
  333. * Neither of these (de)allocates the strings.
  334. * setenv allocates new strings in malloc space and does putenv,
  335. * and thus setenv is unusable (leaky) for shell's purposes */
  336. #define setenv(...) setenv_is_leaky_dont_use()
  337. struct variable {
  338. struct variable *next;
  339. char *varstr; /* points to "name=" portion */
  340. int max_len; /* if > 0, name is part of initial env; else name is malloced */
  341. smallint flg_export; /* putenv should be done on this var */
  342. smallint flg_read_only;
  343. };
  344. typedef struct o_string {
  345. char *data;
  346. int length; /* position where data is appended */
  347. int maxlen;
  348. /* Misnomer! it's not "quoting", it's "protection against globbing"!
  349. * (by prepending \ to *, ?, [ and to \ too) */
  350. smallint o_quote;
  351. smallint o_glob;
  352. smallint nonnull;
  353. smallint has_empty_slot;
  354. smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
  355. } o_string;
  356. enum {
  357. MAYBE_ASSIGNMENT = 0,
  358. DEFINITELY_ASSIGNMENT = 1,
  359. NOT_ASSIGNMENT = 2,
  360. WORD_IS_KEYWORD = 3, /* not assigment, but next word may be: "if v=xyz cmd;" */
  361. };
  362. /* Used for initialization: o_string foo = NULL_O_STRING; */
  363. #define NULL_O_STRING { NULL }
  364. /* I can almost use ordinary FILE*. Is open_memstream() universally
  365. * available? Where is it documented? */
  366. typedef struct in_str {
  367. const char *p;
  368. /* eof_flag=1: last char in ->p is really an EOF */
  369. char eof_flag; /* meaningless if ->p == NULL */
  370. char peek_buf[2];
  371. #if ENABLE_HUSH_INTERACTIVE
  372. smallint promptme;
  373. smallint promptmode; /* 0: PS1, 1: PS2 */
  374. #endif
  375. FILE *file;
  376. int (*get) (struct in_str *);
  377. int (*peek) (struct in_str *);
  378. } in_str;
  379. #define i_getch(input) ((input)->get(input))
  380. #define i_peek(input) ((input)->peek(input))
  381. enum {
  382. CHAR_ORDINARY = 0,
  383. CHAR_ORDINARY_IF_QUOTED = 1, /* example: *, # */
  384. CHAR_IFS = 2, /* treated as ordinary if quoted */
  385. CHAR_SPECIAL = 3, /* example: $ */
  386. };
  387. enum {
  388. BC_BREAK = 1,
  389. BC_CONTINUE = 2,
  390. };
  391. /* "Globals" within this file */
  392. /* Sorted roughly by size (smaller offsets == smaller code) */
  393. struct globals {
  394. #if ENABLE_HUSH_INTERACTIVE
  395. /* 'interactive_fd' is a fd# open to ctty, if we have one
  396. * _AND_ if we decided to act interactively */
  397. int interactive_fd;
  398. const char *PS1;
  399. const char *PS2;
  400. #endif
  401. #if ENABLE_FEATURE_EDITING
  402. line_input_t *line_input_state;
  403. #endif
  404. pid_t root_pid;
  405. pid_t last_bg_pid;
  406. #if ENABLE_HUSH_JOB
  407. int run_list_level;
  408. pid_t saved_tty_pgrp;
  409. int last_jobid;
  410. struct pipe *job_list;
  411. struct pipe *toplevel_list;
  412. smallint ctrl_z_flag;
  413. #endif
  414. #if ENABLE_HUSH_LOOPS
  415. smallint flag_break_continue;
  416. #endif
  417. smallint fake_mode;
  418. /* these three support $?, $#, and $1 */
  419. smalluint last_return_code;
  420. /* is global_argv and global_argv[1..n] malloced? (note: not [0]) */
  421. smalluint global_args_malloced;
  422. /* how many non-NULL argv's we have. NB: $# + 1 */
  423. int global_argc;
  424. char **global_argv;
  425. #if ENABLE_HUSH_LOOPS
  426. unsigned depth_break_continue;
  427. unsigned depth_of_loop;
  428. #endif
  429. const char *ifs;
  430. const char *cwd;
  431. struct variable *top_var; /* = &G.shell_ver (set in main()) */
  432. struct variable shell_ver;
  433. #if ENABLE_FEATURE_SH_STANDALONE
  434. struct nofork_save_area nofork_save;
  435. #endif
  436. #if ENABLE_HUSH_JOB
  437. sigjmp_buf toplevel_jb;
  438. #endif
  439. unsigned char charmap[256];
  440. char user_input_buf[ENABLE_FEATURE_EDITING ? BUFSIZ : 2];
  441. };
  442. #define G (*ptr_to_globals)
  443. /* Not #defining name to G.name - this quickly gets unwieldy
  444. * (too many defines). Also, I actually prefer to see when a variable
  445. * is global, thus "G." prefix is a useful hint */
  446. #define INIT_G() do { \
  447. SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
  448. } while (0)
  449. #define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
  450. #if 1
  451. /* Normal */
  452. static void syntax(const char *msg)
  453. {
  454. #if ENABLE_HUSH_INTERACTIVE
  455. /* Was using fancy stuff:
  456. * (G.interactive_fd ? bb_error_msg : bb_error_msg_and_die)(...params...)
  457. * but it SEGVs. ?! Oh well... explicit temp ptr works around that */
  458. void FAST_FUNC (*fp)(const char *s, ...);
  459. fp = (G.interactive_fd ? bb_error_msg : bb_error_msg_and_die);
  460. fp(msg ? "%s: %s" : "syntax error", "syntax error", msg);
  461. #else
  462. bb_error_msg_and_die(msg ? "%s: %s" : "syntax error", "syntax error", msg);
  463. #endif
  464. }
  465. #else
  466. /* Debug */
  467. static void syntax_lineno(int line)
  468. {
  469. #if ENABLE_HUSH_INTERACTIVE
  470. void FAST_FUNC (*fp)(const char *s, ...);
  471. fp = (G.interactive_fd ? bb_error_msg : bb_error_msg_and_die);
  472. fp("syntax error hush.c:%d", line);
  473. #else
  474. bb_error_msg_and_die("syntax error hush.c:%d", line);
  475. #endif
  476. }
  477. #define syntax(str) syntax_lineno(__LINE__)
  478. #endif
  479. /* Index of subroutines: */
  480. /* in_str manipulations: */
  481. static int static_get(struct in_str *i);
  482. static int static_peek(struct in_str *i);
  483. static int file_get(struct in_str *i);
  484. static int file_peek(struct in_str *i);
  485. static void setup_file_in_str(struct in_str *i, FILE *f);
  486. static void setup_string_in_str(struct in_str *i, const char *s);
  487. /* "run" the final data structures: */
  488. #if !defined(DEBUG_CLEAN)
  489. #define free_pipe_list(head, indent) free_pipe_list(head)
  490. #define free_pipe(pi, indent) free_pipe(pi)
  491. #endif
  492. static int free_pipe_list(struct pipe *head, int indent);
  493. static int free_pipe(struct pipe *pi, int indent);
  494. /* really run the final data structures: */
  495. typedef struct nommu_save_t {
  496. char **new_env;
  497. char **old_env;
  498. char **argv;
  499. } nommu_save_t;
  500. #if BB_MMU
  501. #define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
  502. pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
  503. #define pseudo_exec(nommu_save, command, argv_expanded) \
  504. pseudo_exec(command, argv_expanded)
  505. #endif
  506. static void pseudo_exec_argv(nommu_save_t *nommu_save, char **argv, int assignment_cnt, char **argv_expanded) NORETURN;
  507. static void pseudo_exec(nommu_save_t *nommu_save, struct command *command, char **argv_expanded) NORETURN;
  508. static int setup_redirects(struct command *prog, int squirrel[]);
  509. static int run_list(struct pipe *pi);
  510. static int run_pipe(struct pipe *pi);
  511. /* data structure manipulation: */
  512. static int setup_redirect(struct parse_context *ctx, int fd, redir_type style, struct in_str *input);
  513. static void initialize_context(struct parse_context *ctx);
  514. static int done_word(o_string *dest, struct parse_context *ctx);
  515. static int done_command(struct parse_context *ctx);
  516. static void done_pipe(struct parse_context *ctx, pipe_style type);
  517. /* primary string parsing: */
  518. static int redirect_dup_num(struct in_str *input);
  519. static int redirect_opt_num(o_string *o);
  520. #if ENABLE_HUSH_TICK
  521. static int process_command_subs(o_string *dest,
  522. struct in_str *input, const char *subst_end);
  523. #endif
  524. static int parse_group(o_string *dest, struct parse_context *ctx, struct in_str *input, int ch);
  525. static const char *lookup_param(const char *src);
  526. static int handle_dollar(o_string *dest,
  527. struct in_str *input);
  528. static int parse_stream(o_string *dest, struct parse_context *ctx, struct in_str *input0, const char *end_trigger);
  529. /* setup: */
  530. static int parse_and_run_stream(struct in_str *inp, int parse_flag);
  531. static int parse_and_run_string(const char *s, int parse_flag);
  532. static int parse_and_run_file(FILE *f);
  533. /* job management: */
  534. static int checkjobs(struct pipe* fg_pipe);
  535. #if ENABLE_HUSH_JOB
  536. static int checkjobs_and_fg_shell(struct pipe* fg_pipe);
  537. static void insert_bg_job(struct pipe *pi);
  538. static void remove_bg_job(struct pipe *pi);
  539. static void delete_finished_bg_job(struct pipe *pi);
  540. #else
  541. int checkjobs_and_fg_shell(struct pipe* fg_pipe); /* never called */
  542. #endif
  543. /* local variable support */
  544. static char **expand_strvec_to_strvec(char **argv);
  545. /* used for eval */
  546. static char *expand_strvec_to_string(char **argv);
  547. /* used for expansion of right hand of assignments */
  548. static char *expand_string_to_string(const char *str);
  549. static struct variable *get_local_var(const char *name);
  550. static int set_local_var(char *str, int flg_export);
  551. static void unset_local_var(const char *name);
  552. static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="HUSH_VER_STR;
  553. static int glob_needed(const char *s)
  554. {
  555. while (*s) {
  556. if (*s == '\\')
  557. s++;
  558. if (*s == '*' || *s == '[' || *s == '?')
  559. return 1;
  560. s++;
  561. }
  562. return 0;
  563. }
  564. static int is_assignment(const char *s)
  565. {
  566. if (!s || !(isalpha(*s) || *s == '_'))
  567. return 0;
  568. s++;
  569. while (isalnum(*s) || *s == '_')
  570. s++;
  571. return *s == '=';
  572. }
  573. /* Replace each \x with x in place, return ptr past NUL. */
  574. static char *unbackslash(char *src)
  575. {
  576. char *dst = src;
  577. while (1) {
  578. if (*src == '\\')
  579. src++;
  580. if ((*dst++ = *src++) == '\0')
  581. break;
  582. }
  583. return dst;
  584. }
  585. static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
  586. {
  587. int i;
  588. unsigned count1;
  589. unsigned count2;
  590. char **v;
  591. v = strings;
  592. count1 = 0;
  593. if (v) {
  594. while (*v) {
  595. count1++;
  596. v++;
  597. }
  598. }
  599. count2 = 0;
  600. v = add;
  601. while (*v) {
  602. count2++;
  603. v++;
  604. }
  605. v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
  606. v[count1 + count2] = NULL;
  607. i = count2;
  608. while (--i >= 0)
  609. v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
  610. return v;
  611. }
  612. static char **add_string_to_strings(char **strings, char *add)
  613. {
  614. char *v[2];
  615. v[0] = add;
  616. v[1] = NULL;
  617. return add_strings_to_strings(strings, v, /*dup:*/ 0);
  618. }
  619. static void putenv_all(char **strings)
  620. {
  621. if (!strings)
  622. return;
  623. while (*strings) {
  624. debug_printf_env("putenv '%s'\n", *strings);
  625. putenv(*strings++);
  626. }
  627. }
  628. static char **putenv_all_and_save_old(char **strings)
  629. {
  630. char **old = NULL;
  631. char **s = strings;
  632. if (!strings)
  633. return old;
  634. while (*strings) {
  635. char *v, *eq;
  636. eq = strchr(*strings, '=');
  637. if (eq) {
  638. *eq = '\0';
  639. v = getenv(*strings);
  640. *eq = '=';
  641. if (v) {
  642. /* v points to VAL in VAR=VAL, go back to VAR */
  643. v -= (eq - *strings) + 1;
  644. old = add_string_to_strings(old, v);
  645. }
  646. }
  647. strings++;
  648. }
  649. putenv_all(s);
  650. return old;
  651. }
  652. static void free_strings_and_unsetenv(char **strings, int unset)
  653. {
  654. char **v;
  655. if (!strings)
  656. return;
  657. v = strings;
  658. while (*v) {
  659. if (unset) {
  660. char *copy;
  661. /* *strchrnul(*v, '=') = '\0'; -- BAD
  662. * In case *v was putenv'ed, we can't
  663. * unsetenv(*v) after taking out '=':
  664. * it won't work, env is modified by taking out!
  665. * horror :( */
  666. copy = xstrndup(*v, strchrnul(*v, '=') - *v);
  667. debug_printf_env("unsetenv '%s'\n", copy);
  668. unsetenv(copy);
  669. free(copy);
  670. }
  671. free(*v++);
  672. }
  673. free(strings);
  674. }
  675. static void free_strings(char **strings)
  676. {
  677. free_strings_and_unsetenv(strings, 0);
  678. }
  679. /* Function prototypes for builtins */
  680. static int builtin_cd(char **argv);
  681. static int builtin_echo(char **argv);
  682. static int builtin_eval(char **argv);
  683. static int builtin_exec(char **argv);
  684. static int builtin_exit(char **argv);
  685. static int builtin_export(char **argv);
  686. #if ENABLE_HUSH_JOB
  687. static int builtin_fg_bg(char **argv);
  688. static int builtin_jobs(char **argv);
  689. #endif
  690. #if ENABLE_HUSH_HELP
  691. static int builtin_help(char **argv);
  692. #endif
  693. static int builtin_pwd(char **argv);
  694. static int builtin_read(char **argv);
  695. static int builtin_test(char **argv);
  696. static int builtin_true(char **argv);
  697. static int builtin_set(char **argv);
  698. static int builtin_shift(char **argv);
  699. static int builtin_source(char **argv);
  700. static int builtin_umask(char **argv);
  701. static int builtin_unset(char **argv);
  702. #if ENABLE_HUSH_LOOPS
  703. static int builtin_break(char **argv);
  704. static int builtin_continue(char **argv);
  705. #endif
  706. //static int builtin_not_written(char **argv);
  707. /* Table of built-in functions. They can be forked or not, depending on
  708. * context: within pipes, they fork. As simple commands, they do not.
  709. * When used in non-forking context, they can change global variables
  710. * in the parent shell process. If forked, of course they cannot.
  711. * For example, 'unset foo | whatever' will parse and run, but foo will
  712. * still be set at the end. */
  713. struct built_in_command {
  714. const char *cmd;
  715. int (*function)(char **argv);
  716. #if ENABLE_HUSH_HELP
  717. const char *descr;
  718. #define BLTIN(cmd, func, help) { cmd, func, help }
  719. #else
  720. #define BLTIN(cmd, func, help) { cmd, func }
  721. #endif
  722. };
  723. /* For now, echo and test are unconditionally enabled.
  724. * Maybe make it configurable? */
  725. static const struct built_in_command bltins[] = {
  726. BLTIN("." , builtin_source, "Run commands in a file"),
  727. BLTIN(":" , builtin_true, "No-op"),
  728. BLTIN("[" , builtin_test, "Test condition"),
  729. BLTIN("[[" , builtin_test, "Test condition"),
  730. #if ENABLE_HUSH_JOB
  731. BLTIN("bg" , builtin_fg_bg, "Resume a job in the background"),
  732. #endif
  733. #if ENABLE_HUSH_LOOPS
  734. BLTIN("break" , builtin_break, "Exit from a loop"),
  735. #endif
  736. BLTIN("cd" , builtin_cd, "Change directory"),
  737. #if ENABLE_HUSH_LOOPS
  738. BLTIN("continue", builtin_continue, "Start new loop iteration"),
  739. #endif
  740. BLTIN("echo" , builtin_echo, "Write to stdout"),
  741. BLTIN("eval" , builtin_eval, "Construct and run shell command"),
  742. BLTIN("exec" , builtin_exec, "Execute command, don't return to shell"),
  743. BLTIN("exit" , builtin_exit, "Exit"),
  744. BLTIN("export", builtin_export, "Set environment variable"),
  745. #if ENABLE_HUSH_JOB
  746. BLTIN("fg" , builtin_fg_bg, "Bring job into the foreground"),
  747. BLTIN("jobs" , builtin_jobs, "List active jobs"),
  748. #endif
  749. BLTIN("pwd" , builtin_pwd, "Print current directory"),
  750. BLTIN("read" , builtin_read, "Input environment variable"),
  751. // BLTIN("return", builtin_not_written, "Return from a function"),
  752. BLTIN("set" , builtin_set, "Set/unset shell local variables"),
  753. BLTIN("shift" , builtin_shift, "Shift positional parameters"),
  754. // BLTIN("trap" , builtin_not_written, "Trap signals"),
  755. BLTIN("test" , builtin_test, "Test condition"),
  756. // BLTIN("ulimit", builtin_not_written, "Control resource limits"),
  757. BLTIN("umask" , builtin_umask, "Set file creation mask"),
  758. BLTIN("unset" , builtin_unset, "Unset environment variable"),
  759. #if ENABLE_HUSH_HELP
  760. BLTIN("help" , builtin_help, "List shell built-in commands"),
  761. #endif
  762. };
  763. /* Signals are grouped, we handle them in batches */
  764. static void set_misc_sighandler(void (*handler)(int))
  765. {
  766. bb_signals(0
  767. + (1 << SIGINT)
  768. + (1 << SIGQUIT)
  769. + (1 << SIGTERM)
  770. , handler);
  771. }
  772. #if ENABLE_HUSH_JOB
  773. static void set_fatal_sighandler(void (*handler)(int))
  774. {
  775. bb_signals(0
  776. + (1 << SIGILL)
  777. + (1 << SIGTRAP)
  778. + (1 << SIGABRT)
  779. + (1 << SIGFPE)
  780. + (1 << SIGBUS)
  781. + (1 << SIGSEGV)
  782. /* bash 3.2 seems to handle these just like 'fatal' ones */
  783. + (1 << SIGHUP)
  784. + (1 << SIGPIPE)
  785. + (1 << SIGALRM)
  786. , handler);
  787. }
  788. static void set_jobctrl_sighandler(void (*handler)(int))
  789. {
  790. bb_signals(0
  791. + (1 << SIGTSTP)
  792. + (1 << SIGTTIN)
  793. + (1 << SIGTTOU)
  794. , handler);
  795. }
  796. /* SIGCHLD is special and handled separately */
  797. static void set_every_sighandler(void (*handler)(int))
  798. {
  799. set_fatal_sighandler(handler);
  800. set_jobctrl_sighandler(handler);
  801. set_misc_sighandler(handler);
  802. signal(SIGCHLD, handler);
  803. }
  804. static void handler_ctrl_c(int sig UNUSED_PARAM)
  805. {
  806. debug_printf_jobs("got sig %d\n", sig);
  807. // as usual we can have all kinds of nasty problems with leaked malloc data here
  808. siglongjmp(G.toplevel_jb, 1);
  809. }
  810. static void handler_ctrl_z(int sig UNUSED_PARAM)
  811. {
  812. pid_t pid;
  813. debug_printf_jobs("got tty sig %d in pid %d\n", sig, getpid());
  814. pid = fork();
  815. if (pid < 0) /* can't fork. Pretend there was no ctrl-Z */
  816. return;
  817. G.ctrl_z_flag = 1;
  818. if (!pid) { /* child */
  819. if (ENABLE_HUSH_JOB)
  820. die_sleep = 0; /* let nofork's xfuncs die */
  821. bb_setpgrp();
  822. debug_printf_jobs("set pgrp for child %d ok\n", getpid());
  823. set_every_sighandler(SIG_DFL);
  824. raise(SIGTSTP); /* resend TSTP so that child will be stopped */
  825. debug_printf_jobs("returning in child\n");
  826. /* return to nofork, it will eventually exit now,
  827. * not return back to shell */
  828. return;
  829. }
  830. /* parent */
  831. /* finish filling up pipe info */
  832. G.toplevel_list->pgrp = pid; /* child is in its own pgrp */
  833. G.toplevel_list->cmds[0].pid = pid;
  834. /* parent needs to longjmp out of running nofork.
  835. * we will "return" exitcode 0, with child put in background */
  836. // as usual we can have all kinds of nasty problems with leaked malloc data here
  837. debug_printf_jobs("siglongjmp in parent\n");
  838. siglongjmp(G.toplevel_jb, 1);
  839. }
  840. /* Restores tty foreground process group, and exits.
  841. * May be called as signal handler for fatal signal
  842. * (will faithfully resend signal to itself, producing correct exit state)
  843. * or called directly with -EXITCODE.
  844. * We also call it if xfunc is exiting. */
  845. static void sigexit(int sig) NORETURN;
  846. static void sigexit(int sig)
  847. {
  848. /* Disable all signals: job control, SIGPIPE, etc. */
  849. sigprocmask_allsigs(SIG_BLOCK);
  850. #if ENABLE_HUSH_INTERACTIVE
  851. if (G.interactive_fd)
  852. tcsetpgrp(G.interactive_fd, G.saved_tty_pgrp);
  853. #endif
  854. /* Not a signal, just exit */
  855. if (sig <= 0)
  856. _exit(- sig);
  857. kill_myself_with_sig(sig); /* does not return */
  858. }
  859. /* Restores tty foreground process group, and exits. */
  860. static void hush_exit(int exitcode) NORETURN;
  861. static void hush_exit(int exitcode)
  862. {
  863. fflush(NULL); /* flush all streams */
  864. sigexit(- (exitcode & 0xff));
  865. }
  866. #else /* !JOB */
  867. #define set_fatal_sighandler(handler) ((void)0)
  868. #define set_jobctrl_sighandler(handler) ((void)0)
  869. #define hush_exit(e) exit(e)
  870. #endif /* JOB */
  871. static const char *set_cwd(void)
  872. {
  873. if (G.cwd == bb_msg_unknown)
  874. G.cwd = NULL; /* xrealloc_getcwd_or_warn(arg) calls free(arg)! */
  875. G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
  876. if (!G.cwd)
  877. G.cwd = bb_msg_unknown;
  878. return G.cwd;
  879. }
  880. /*
  881. * o_string support
  882. */
  883. #define B_CHUNK (32 * sizeof(char*))
  884. static void o_reset(o_string *o)
  885. {
  886. o->length = 0;
  887. o->nonnull = 0;
  888. if (o->data)
  889. o->data[0] = '\0';
  890. }
  891. static void o_free(o_string *o)
  892. {
  893. free(o->data);
  894. memset(o, 0, sizeof(*o));
  895. }
  896. static void o_grow_by(o_string *o, int len)
  897. {
  898. if (o->length + len > o->maxlen) {
  899. o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
  900. o->data = xrealloc(o->data, 1 + o->maxlen);
  901. }
  902. }
  903. static void o_addchr(o_string *o, int ch)
  904. {
  905. debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
  906. o_grow_by(o, 1);
  907. o->data[o->length] = ch;
  908. o->length++;
  909. o->data[o->length] = '\0';
  910. }
  911. static void o_addstr(o_string *o, const char *str, int len)
  912. {
  913. o_grow_by(o, len);
  914. memcpy(&o->data[o->length], str, len);
  915. o->length += len;
  916. o->data[o->length] = '\0';
  917. }
  918. static void o_addstr_duplicate_backslash(o_string *o, const char *str, int len)
  919. {
  920. while (len) {
  921. o_addchr(o, *str);
  922. if (*str++ == '\\'
  923. && (*str != '*' && *str != '?' && *str != '[')
  924. ) {
  925. o_addchr(o, '\\');
  926. }
  927. len--;
  928. }
  929. }
  930. /* My analysis of quoting semantics tells me that state information
  931. * is associated with a destination, not a source.
  932. */
  933. static void o_addqchr(o_string *o, int ch)
  934. {
  935. int sz = 1;
  936. char *found = strchr("*?[\\", ch);
  937. if (found)
  938. sz++;
  939. o_grow_by(o, sz);
  940. if (found) {
  941. o->data[o->length] = '\\';
  942. o->length++;
  943. }
  944. o->data[o->length] = ch;
  945. o->length++;
  946. o->data[o->length] = '\0';
  947. }
  948. static void o_addQchr(o_string *o, int ch)
  949. {
  950. int sz = 1;
  951. if (o->o_quote && strchr("*?[\\", ch)) {
  952. sz++;
  953. o->data[o->length] = '\\';
  954. o->length++;
  955. }
  956. o_grow_by(o, sz);
  957. o->data[o->length] = ch;
  958. o->length++;
  959. o->data[o->length] = '\0';
  960. }
  961. static void o_addQstr(o_string *o, const char *str, int len)
  962. {
  963. if (!o->o_quote) {
  964. o_addstr(o, str, len);
  965. return;
  966. }
  967. while (len) {
  968. char ch;
  969. int sz;
  970. int ordinary_cnt = strcspn(str, "*?[\\");
  971. if (ordinary_cnt > len) /* paranoia */
  972. ordinary_cnt = len;
  973. o_addstr(o, str, ordinary_cnt);
  974. if (ordinary_cnt == len)
  975. return;
  976. str += ordinary_cnt;
  977. len -= ordinary_cnt + 1; /* we are processing + 1 char below */
  978. ch = *str++;
  979. sz = 1;
  980. if (ch) { /* it is necessarily one of "*?[\\" */
  981. sz++;
  982. o->data[o->length] = '\\';
  983. o->length++;
  984. }
  985. o_grow_by(o, sz);
  986. o->data[o->length] = ch;
  987. o->length++;
  988. o->data[o->length] = '\0';
  989. }
  990. }
  991. /* A special kind of o_string for $VAR and `cmd` expansion.
  992. * It contains char* list[] at the beginning, which is grown in 16 element
  993. * increments. Actual string data starts at the next multiple of 16 * (char*).
  994. * list[i] contains an INDEX (int!) into this string data.
  995. * It means that if list[] needs to grow, data needs to be moved higher up
  996. * but list[i]'s need not be modified.
  997. * NB: remembering how many list[i]'s you have there is crucial.
  998. * o_finalize_list() operation post-processes this structure - calculates
  999. * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
  1000. */
  1001. #if DEBUG_EXPAND || DEBUG_GLOB
  1002. static void debug_print_list(const char *prefix, o_string *o, int n)
  1003. {
  1004. char **list = (char**)o->data;
  1005. int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
  1006. int i = 0;
  1007. fprintf(stderr, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d\n",
  1008. prefix, list, n, string_start, o->length, o->maxlen);
  1009. while (i < n) {
  1010. fprintf(stderr, " list[%d]=%d '%s' %p\n", i, (int)list[i],
  1011. o->data + (int)list[i] + string_start,
  1012. o->data + (int)list[i] + string_start);
  1013. i++;
  1014. }
  1015. if (n) {
  1016. const char *p = o->data + (int)list[n - 1] + string_start;
  1017. fprintf(stderr, " total_sz:%d\n", (p + strlen(p) + 1) - o->data);
  1018. }
  1019. }
  1020. #else
  1021. #define debug_print_list(prefix, o, n) ((void)0)
  1022. #endif
  1023. /* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
  1024. * in list[n] so that it points past last stored byte so far.
  1025. * It returns n+1. */
  1026. static int o_save_ptr_helper(o_string *o, int n)
  1027. {
  1028. char **list = (char**)o->data;
  1029. int string_start;
  1030. int string_len;
  1031. if (!o->has_empty_slot) {
  1032. string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
  1033. string_len = o->length - string_start;
  1034. if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
  1035. debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
  1036. /* list[n] points to string_start, make space for 16 more pointers */
  1037. o->maxlen += 0x10 * sizeof(list[0]);
  1038. o->data = xrealloc(o->data, o->maxlen + 1);
  1039. list = (char**)o->data;
  1040. memmove(list + n + 0x10, list + n, string_len);
  1041. o->length += 0x10 * sizeof(list[0]);
  1042. } else
  1043. debug_printf_list("list[%d]=%d string_start=%d\n", n, string_len, string_start);
  1044. } else {
  1045. /* We have empty slot at list[n], reuse without growth */
  1046. string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
  1047. string_len = o->length - string_start;
  1048. debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n", n, string_len, string_start);
  1049. o->has_empty_slot = 0;
  1050. }
  1051. list[n] = (char*)(ptrdiff_t)string_len;
  1052. return n + 1;
  1053. }
  1054. /* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
  1055. static int o_get_last_ptr(o_string *o, int n)
  1056. {
  1057. char **list = (char**)o->data;
  1058. int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
  1059. return ((int)(ptrdiff_t)list[n-1]) + string_start;
  1060. }
  1061. /* o_glob performs globbing on last list[], saving each result
  1062. * as a new list[]. */
  1063. static int o_glob(o_string *o, int n)
  1064. {
  1065. glob_t globdata;
  1066. int gr;
  1067. char *pattern;
  1068. debug_printf_glob("start o_glob: n:%d o->data:%p\n", n, o->data);
  1069. if (!o->data)
  1070. return o_save_ptr_helper(o, n);
  1071. pattern = o->data + o_get_last_ptr(o, n);
  1072. debug_printf_glob("glob pattern '%s'\n", pattern);
  1073. if (!glob_needed(pattern)) {
  1074. literal:
  1075. o->length = unbackslash(pattern) - o->data;
  1076. debug_printf_glob("glob pattern '%s' is literal\n", pattern);
  1077. return o_save_ptr_helper(o, n);
  1078. }
  1079. memset(&globdata, 0, sizeof(globdata));
  1080. gr = glob(pattern, 0, NULL, &globdata);
  1081. debug_printf_glob("glob('%s'):%d\n", pattern, gr);
  1082. if (gr == GLOB_NOSPACE)
  1083. bb_error_msg_and_die("out of memory during glob");
  1084. if (gr == GLOB_NOMATCH) {
  1085. globfree(&globdata);
  1086. goto literal;
  1087. }
  1088. if (gr != 0) { /* GLOB_ABORTED ? */
  1089. //TODO: testcase for bad glob pattern behavior
  1090. bb_error_msg("glob(3) error %d on '%s'", gr, pattern);
  1091. }
  1092. if (globdata.gl_pathv && globdata.gl_pathv[0]) {
  1093. char **argv = globdata.gl_pathv;
  1094. o->length = pattern - o->data; /* "forget" pattern */
  1095. while (1) {
  1096. o_addstr(o, *argv, strlen(*argv) + 1);
  1097. n = o_save_ptr_helper(o, n);
  1098. argv++;
  1099. if (!*argv)
  1100. break;
  1101. }
  1102. }
  1103. globfree(&globdata);
  1104. if (DEBUG_GLOB)
  1105. debug_print_list("o_glob returning", o, n);
  1106. return n;
  1107. }
  1108. /* If o->o_glob == 1, glob the string so far remembered.
  1109. * Otherwise, just finish current list[] and start new */
  1110. static int o_save_ptr(o_string *o, int n)
  1111. {
  1112. if (o->o_glob) { /* if globbing is requested */
  1113. /* If o->has_empty_slot, list[n] was already globbed
  1114. * (if it was requested back then when it was filled)
  1115. * so don't do that again! */
  1116. if (!o->has_empty_slot)
  1117. return o_glob(o, n); /* o_save_ptr_helper is inside */
  1118. }
  1119. return o_save_ptr_helper(o, n);
  1120. }
  1121. /* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
  1122. static char **o_finalize_list(o_string *o, int n)
  1123. {
  1124. char **list;
  1125. int string_start;
  1126. n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
  1127. if (DEBUG_EXPAND)
  1128. debug_print_list("finalized", o, n);
  1129. debug_printf_expand("finalized n:%d\n", n);
  1130. list = (char**)o->data;
  1131. string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
  1132. list[--n] = NULL;
  1133. while (n) {
  1134. n--;
  1135. list[n] = o->data + (int)(ptrdiff_t)list[n] + string_start;
  1136. }
  1137. return list;
  1138. }
  1139. /*
  1140. * in_str support
  1141. */
  1142. static int static_get(struct in_str *i)
  1143. {
  1144. int ch = *i->p++;
  1145. if (ch == '\0') return EOF;
  1146. return ch;
  1147. }
  1148. static int static_peek(struct in_str *i)
  1149. {
  1150. return *i->p;
  1151. }
  1152. #if ENABLE_HUSH_INTERACTIVE
  1153. #if ENABLE_FEATURE_EDITING
  1154. static void cmdedit_set_initial_prompt(void)
  1155. {
  1156. #if !ENABLE_FEATURE_EDITING_FANCY_PROMPT
  1157. G.PS1 = NULL;
  1158. #else
  1159. G.PS1 = getenv("PS1");
  1160. if (G.PS1 == NULL)
  1161. G.PS1 = "\\w \\$ ";
  1162. #endif
  1163. }
  1164. #endif /* EDITING */
  1165. static const char* setup_prompt_string(int promptmode)
  1166. {
  1167. const char *prompt_str;
  1168. debug_printf("setup_prompt_string %d ", promptmode);
  1169. #if !ENABLE_FEATURE_EDITING_FANCY_PROMPT
  1170. /* Set up the prompt */
  1171. if (promptmode == 0) { /* PS1 */
  1172. free((char*)G.PS1);
  1173. G.PS1 = xasprintf("%s %c ", G.cwd, (geteuid() != 0) ? '$' : '#');
  1174. prompt_str = G.PS1;
  1175. } else {
  1176. prompt_str = G.PS2;
  1177. }
  1178. #else
  1179. prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
  1180. #endif
  1181. debug_printf("result '%s'\n", prompt_str);
  1182. return prompt_str;
  1183. }
  1184. static void get_user_input(struct in_str *i)
  1185. {
  1186. int r;
  1187. const char *prompt_str;
  1188. prompt_str = setup_prompt_string(i->promptmode);
  1189. #if ENABLE_FEATURE_EDITING
  1190. /* Enable command line editing only while a command line
  1191. * is actually being read */
  1192. do {
  1193. r = read_line_input(prompt_str, G.user_input_buf, BUFSIZ-1, G.line_input_state);
  1194. } while (r == 0); /* repeat if Ctrl-C */
  1195. i->eof_flag = (r < 0);
  1196. if (i->eof_flag) { /* EOF/error detected */
  1197. G.user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
  1198. G.user_input_buf[1] = '\0';
  1199. }
  1200. #else
  1201. fputs(prompt_str, stdout);
  1202. fflush(stdout);
  1203. G.user_input_buf[0] = r = fgetc(i->file);
  1204. /*G.user_input_buf[1] = '\0'; - already is and never changed */
  1205. i->eof_flag = (r == EOF);
  1206. #endif
  1207. i->p = G.user_input_buf;
  1208. }
  1209. #endif /* INTERACTIVE */
  1210. /* This is the magic location that prints prompts
  1211. * and gets data back from the user */
  1212. static int file_get(struct in_str *i)
  1213. {
  1214. int ch;
  1215. /* If there is data waiting, eat it up */
  1216. if (i->p && *i->p) {
  1217. #if ENABLE_HUSH_INTERACTIVE
  1218. take_cached:
  1219. #endif
  1220. ch = *i->p++;
  1221. if (i->eof_flag && !*i->p)
  1222. ch = EOF;
  1223. } else {
  1224. /* need to double check i->file because we might be doing something
  1225. * more complicated by now, like sourcing or substituting. */
  1226. #if ENABLE_HUSH_INTERACTIVE
  1227. if (G.interactive_fd && i->promptme && i->file == stdin) {
  1228. do {
  1229. get_user_input(i);
  1230. } while (!*i->p); /* need non-empty line */
  1231. i->promptmode = 1; /* PS2 */
  1232. i->promptme = 0;
  1233. goto take_cached;
  1234. }
  1235. #endif
  1236. ch = fgetc(i->file);
  1237. }
  1238. debug_printf("file_get: got a '%c' %d\n", ch, ch);
  1239. #if ENABLE_HUSH_INTERACTIVE
  1240. if (ch == '\n')
  1241. i->promptme = 1;
  1242. #endif
  1243. return ch;
  1244. }
  1245. /* All the callers guarantee this routine will never be
  1246. * used right after a newline, so prompting is not needed.
  1247. */
  1248. static int file_peek(struct in_str *i)
  1249. {
  1250. int ch;
  1251. if (i->p && *i->p) {
  1252. if (i->eof_flag && !i->p[1])
  1253. return EOF;
  1254. return *i->p;
  1255. }
  1256. ch = fgetc(i->file);
  1257. i->eof_flag = (ch == EOF);
  1258. i->peek_buf[0] = ch;
  1259. i->peek_buf[1] = '\0';
  1260. i->p = i->peek_buf;
  1261. debug_printf("file_peek: got a '%c' %d\n", *i->p, *i->p);
  1262. return ch;
  1263. }
  1264. static void setup_file_in_str(struct in_str *i, FILE *f)
  1265. {
  1266. i->peek = file_peek;
  1267. i->get = file_get;
  1268. #if ENABLE_HUSH_INTERACTIVE
  1269. i->promptme = 1;
  1270. i->promptmode = 0; /* PS1 */
  1271. #endif
  1272. i->file = f;
  1273. i->p = NULL;
  1274. }
  1275. static void setup_string_in_str(struct in_str *i, const char *s)
  1276. {
  1277. i->peek = static_peek;
  1278. i->get = static_get;
  1279. #if ENABLE_HUSH_INTERACTIVE
  1280. i->promptme = 1;
  1281. i->promptmode = 0; /* PS1 */
  1282. #endif
  1283. i->p = s;
  1284. i->eof_flag = 0;
  1285. }
  1286. /* squirrel != NULL means we squirrel away copies of stdin, stdout,
  1287. * and stderr if they are redirected. */
  1288. static int setup_redirects(struct command *prog, int squirrel[])
  1289. {
  1290. int openfd, mode;
  1291. struct redir_struct *redir;
  1292. for (redir = prog->redirects; redir; redir = redir->next) {
  1293. if (redir->dup == -1 && redir->rd_filename == NULL) {
  1294. /* something went wrong in the parse. Pretend it didn't happen */
  1295. continue;
  1296. }
  1297. if (redir->dup == -1) {
  1298. char *p;
  1299. mode = redir_table[redir->rd_type].mode;
  1300. //TODO: check redir for names like '\\'
  1301. p = expand_string_to_string(redir->rd_filename);
  1302. openfd = open_or_warn(p, mode);
  1303. free(p);
  1304. if (openfd < 0) {
  1305. /* this could get lost if stderr has been redirected, but
  1306. bash and ash both lose it as well (though zsh doesn't!) */
  1307. return 1;
  1308. }
  1309. } else {
  1310. openfd = redir->dup;
  1311. }
  1312. if (openfd != redir->fd) {
  1313. if (squirrel && redir->fd < 3) {
  1314. squirrel[redir->fd] = dup(redir->fd);
  1315. }
  1316. if (openfd == -3) {
  1317. //close(openfd); // close(-3) ??!
  1318. } else {
  1319. dup2(openfd, redir->fd);
  1320. if (redir->dup == -1)
  1321. close(openfd);
  1322. }
  1323. }
  1324. }
  1325. return 0;
  1326. }
  1327. static void restore_redirects(int squirrel[])
  1328. {
  1329. int i, fd;
  1330. for (i = 0; i < 3; i++) {
  1331. fd = squirrel[i];
  1332. if (fd != -1) {
  1333. /* We simply die on error */
  1334. xmove_fd(fd, i);
  1335. }
  1336. }
  1337. }
  1338. static char **expand_assignments(char **argv, int count)
  1339. {
  1340. int i;
  1341. char **p = NULL;
  1342. /* Expand assignments into one string each */
  1343. for (i = 0; i < count; i++) {
  1344. p = add_string_to_strings(p, expand_string_to_string(argv[i]));
  1345. }
  1346. return p;
  1347. }
  1348. /* Called after [v]fork() in run_pipe(), or from builtin_exec().
  1349. * Never returns.
  1350. * XXX no exit() here. If you don't exec, use _exit instead.
  1351. * The at_exit handlers apparently confuse the calling process,
  1352. * in particular stdin handling. Not sure why? -- because of vfork! (vda) */
  1353. static void pseudo_exec_argv(nommu_save_t *nommu_save, char **argv, int assignment_cnt, char **argv_expanded)
  1354. {
  1355. int rcode;
  1356. char **new_env;
  1357. const struct built_in_command *x;
  1358. /* If a variable is assigned in a forest, and nobody listens,
  1359. * was it ever really set?
  1360. */
  1361. if (!argv[assignment_cnt])
  1362. _exit(EXIT_SUCCESS);
  1363. new_env = expand_assignments(argv, assignment_cnt);
  1364. #if BB_MMU
  1365. putenv_all(new_env);
  1366. free(new_env); /* optional */
  1367. #else
  1368. nommu_save->new_env = new_env;
  1369. nommu_save->old_env = putenv_all_and_save_old(new_env);
  1370. #endif
  1371. if (argv_expanded) {
  1372. argv = argv_expanded;
  1373. } else {
  1374. argv = expand_strvec_to_strvec(argv);
  1375. #if !BB_MMU
  1376. nommu_save->argv = argv;
  1377. #endif
  1378. }
  1379. /*
  1380. * Check if the command matches any of the builtins.
  1381. * Depending on context, this might be redundant. But it's
  1382. * easier to waste a few CPU cycles than it is to figure out
  1383. * if this is one of those cases.
  1384. */
  1385. for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
  1386. if (strcmp(argv[0], x->cmd) == 0) {
  1387. debug_printf_exec("running builtin '%s'\n", argv[0]);
  1388. rcode = x->function(argv);
  1389. fflush(stdout);
  1390. _exit(rcode);
  1391. }
  1392. }
  1393. /* Check if the command matches any busybox applets */
  1394. #if ENABLE_FEATURE_SH_STANDALONE
  1395. if (strchr(argv[0], '/') == NULL) {
  1396. int a = find_applet_by_name(argv[0]);
  1397. if (a >= 0) {
  1398. if (APPLET_IS_NOEXEC(a)) {
  1399. debug_printf_exec("running applet '%s'\n", argv[0]);
  1400. // is it ok that run_applet_no_and_exit() does exit(), not _exit()?
  1401. run_applet_no_and_exit(a, argv);
  1402. }
  1403. /* re-exec ourselves with the new arguments */
  1404. debug_printf_exec("re-execing applet '%s'\n", argv[0]);
  1405. execvp(bb_busybox_exec_path, argv);
  1406. /* If they called chroot or otherwise made the binary no longer
  1407. * executable, fall through */
  1408. }
  1409. }
  1410. #endif
  1411. debug_printf_exec("execing '%s'\n", argv[0]);
  1412. execvp(argv[0], argv);
  1413. bb_perror_msg("can't exec '%s'", argv[0]);
  1414. _exit(EXIT_FAILURE);
  1415. }
  1416. /* Called after [v]fork() in run_pipe()
  1417. */
  1418. static void pseudo_exec(nommu_save_t *nommu_save, struct command *command, char **argv_expanded)
  1419. {
  1420. if (command->argv)
  1421. pseudo_exec_argv(nommu_save, command->argv, command->assignment_cnt, argv_expanded);
  1422. if (command->group) {
  1423. #if !BB_MMU
  1424. bb_error_msg_and_die("nested lists are not supported on NOMMU");
  1425. #else
  1426. int rcode;
  1427. debug_printf_exec("pseudo_exec: run_list\n");
  1428. rcode = run_list(command->group);
  1429. /* OK to leak memory by not calling free_pipe_list,
  1430. * since this process is about to exit */
  1431. _exit(rcode);
  1432. #endif
  1433. }
  1434. /* Can happen. See what bash does with ">foo" by itself. */
  1435. debug_printf("trying to pseudo_exec null command\n");
  1436. _exit(EXIT_SUCCESS);
  1437. }
  1438. #if ENABLE_HUSH_JOB
  1439. static const char *get_cmdtext(struct pipe *pi)
  1440. {
  1441. char **argv;
  1442. char *p;
  1443. int len;
  1444. /* This is subtle. ->cmdtext is created only on first backgrounding.
  1445. * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
  1446. * On subsequent bg argv is trashed, but we won't use it */
  1447. if (pi->cmdtext)
  1448. return pi->cmdtext;
  1449. argv = pi->cmds[0].argv;
  1450. if (!argv || !argv[0]) {
  1451. pi->cmdtext = xzalloc(1);
  1452. return pi->cmdtext;
  1453. }
  1454. len = 0;
  1455. do len += strlen(*argv) + 1; while (*++argv);
  1456. pi->cmdtext = p = xmalloc(len);
  1457. argv = pi->cmds[0].argv;
  1458. do {
  1459. len = strlen(*argv);
  1460. memcpy(p, *argv, len);
  1461. p += len;
  1462. *p++ = ' ';
  1463. } while (*++argv);
  1464. p[-1] = '\0';
  1465. return pi->cmdtext;
  1466. }
  1467. static void insert_bg_job(struct pipe *pi)
  1468. {
  1469. struct pipe *thejob;
  1470. int i;
  1471. /* Linear search for the ID of the job to use */
  1472. pi->jobid = 1;
  1473. for (thejob = G.job_list; thejob; thejob = thejob->next)
  1474. if (thejob->jobid >= pi->jobid)
  1475. pi->jobid = thejob->jobid + 1;
  1476. /* Add thejob to the list of running jobs */
  1477. if (!G.job_list) {
  1478. thejob = G.job_list = xmalloc(sizeof(*thejob));
  1479. } else {
  1480. for (thejob = G.job_list; thejob->next; thejob = thejob->next)
  1481. continue;
  1482. thejob->next = xmalloc(sizeof(*thejob));
  1483. thejob = thejob->next;
  1484. }
  1485. /* Physically copy the struct job */
  1486. memcpy(thejob, pi, sizeof(struct pipe));
  1487. thejob->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
  1488. /* We cannot copy entire pi->cmds[] vector! Double free()s will happen */
  1489. for (i = 0; i < pi->num_cmds; i++) {
  1490. // TODO: do we really need to have so many fields which are just dead weight
  1491. // at execution stage?
  1492. thejob->cmds[i].pid = pi->cmds[i].pid;
  1493. /* all other fields are not used and stay zero */
  1494. }
  1495. thejob->next = NULL;
  1496. thejob->cmdtext = xstrdup(get_cmdtext(pi));
  1497. /* We don't wait for background thejobs to return -- append it
  1498. to the list of backgrounded thejobs and leave it alone */
  1499. printf("[%d] %d %s\n", thejob->jobid, thejob->cmds[0].pid, thejob->cmdtext);
  1500. G.last_bg_pid = thejob->cmds[0].pid;
  1501. G.last_jobid = thejob->jobid;
  1502. }
  1503. static void remove_bg_job(struct pipe *pi)
  1504. {
  1505. struct pipe *prev_pipe;
  1506. if (pi == G.job_list) {
  1507. G.job_list = pi->next;
  1508. } else {
  1509. prev_pipe = G.job_list;
  1510. while (prev_pipe->next != pi)
  1511. prev_pipe = prev_pipe->next;
  1512. prev_pipe->next = pi->next;
  1513. }
  1514. if (G.job_list)
  1515. G.last_jobid = G.job_list->jobid;
  1516. else
  1517. G.last_jobid = 0;
  1518. }
  1519. /* Remove a backgrounded job */
  1520. static void delete_finished_bg_job(struct pipe *pi)
  1521. {
  1522. remove_bg_job(pi);
  1523. pi->stopped_cmds = 0;
  1524. free_pipe(pi, 0);
  1525. free(pi);
  1526. }
  1527. #endif /* JOB */
  1528. /* Check to see if any processes have exited -- if they
  1529. * have, figure out why and see if a job has completed */
  1530. static int checkjobs(struct pipe* fg_pipe)
  1531. {
  1532. int attributes;
  1533. int status;
  1534. #if ENABLE_HUSH_JOB
  1535. struct pipe *pi;
  1536. #endif
  1537. pid_t childpid;
  1538. int rcode = 0;
  1539. attributes = WUNTRACED;
  1540. if (fg_pipe == NULL)
  1541. attributes |= WNOHANG;
  1542. /* Do we do this right?
  1543. * bash-3.00# sleep 20 | false
  1544. * <ctrl-Z pressed>
  1545. * [3]+ Stopped sleep 20 | false
  1546. * bash-3.00# echo $?
  1547. * 1 <========== bg pipe is not fully done, but exitcode is already known!
  1548. */
  1549. //FIXME: non-interactive bash does not continue even if all processes in fg pipe
  1550. //are stopped. Testcase: "cat | cat" in a script (not on command line)
  1551. // + killall -STOP cat
  1552. wait_more:
  1553. // TODO: safe_waitpid?
  1554. while ((childpid = waitpid(-1, &status, attributes)) > 0) {
  1555. int i;
  1556. const int dead = WIFEXITED(status) || WIFSIGNALED(status);
  1557. #if DEBUG_JOBS
  1558. if (WIFSTOPPED(status))
  1559. debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
  1560. childpid, WSTOPSIG(status), WEXITSTATUS(status));
  1561. if (WIFSIGNALED(status))
  1562. debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
  1563. childpid, WTERMSIG(status), WEXITSTATUS(status));
  1564. if (WIFEXITED(status))
  1565. debug_printf_jobs("pid %d exited, exitcode %d\n",
  1566. childpid, WEXITSTATUS(status));
  1567. #endif
  1568. /* Were we asked to wait for fg pipe? */
  1569. if (fg_pipe) {
  1570. for (i = 0; i < fg_pipe->num_cmds; i++) {
  1571. debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
  1572. if (fg_pipe->cmds[i].pid != childpid)
  1573. continue;
  1574. /* printf("process %d exit %d\n", i, WEXITSTATUS(status)); */
  1575. if (dead) {
  1576. fg_pipe->cmds[i].pid = 0;
  1577. fg_pipe->alive_cmds--;
  1578. if (i == fg_pipe->num_cmds - 1) {
  1579. /* last process gives overall exitstatus */
  1580. rcode = WEXITSTATUS(status);
  1581. IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
  1582. }
  1583. } else {
  1584. fg_pipe->cmds[i].is_stopped = 1;
  1585. fg_pipe->stopped_cmds++;
  1586. }
  1587. debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
  1588. fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
  1589. if (fg_pipe->alive_cmds - fg_pipe->stopped_cmds <= 0) {
  1590. /* All processes in fg pipe have exited/stopped */
  1591. #if ENABLE_HUSH_JOB
  1592. if (fg_pipe->alive_cmds)
  1593. insert_bg_job(fg_pipe);
  1594. #endif
  1595. return rcode;
  1596. }
  1597. /* There are still running processes in the fg pipe */
  1598. goto wait_more; /* do waitpid again */
  1599. }
  1600. /* it wasnt fg_pipe, look for process in bg pipes */
  1601. }
  1602. #if ENABLE_HUSH_JOB
  1603. /* We asked to wait for bg or orphaned children */
  1604. /* No need to remember exitcode in this case */
  1605. for (pi = G.job_list; pi; pi = pi->next) {
  1606. for (i = 0; i < pi->num_cmds; i++) {
  1607. if (pi->cmds[i].pid == childpid)
  1608. goto found_pi_and_prognum;
  1609. }
  1610. }
  1611. /* Happens when shell is used as init process (init=/bin/sh) */
  1612. debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
  1613. continue; /* do waitpid again */
  1614. found_pi_and_prognum:
  1615. if (dead) {
  1616. /* child exited */
  1617. pi->cmds[i].pid = 0;
  1618. pi->alive_cmds--;
  1619. if (!pi->alive_cmds) {
  1620. printf(JOB_STATUS_FORMAT, pi->jobid,
  1621. "Done", pi->cmdtext);
  1622. delete_finished_bg_job(pi);
  1623. }
  1624. } else {
  1625. /* child stopped */
  1626. pi->cmds[i].is_stopped = 1;
  1627. pi->stopped_cmds++;
  1628. }
  1629. #endif
  1630. } /* while (waitpid succeeds)... */
  1631. /* wait found no children or failed */
  1632. if (childpid && errno != ECHILD)
  1633. bb_perror_msg("waitpid");
  1634. return rcode;
  1635. }
  1636. #if ENABLE_HUSH_JOB
  1637. static int checkjobs_and_fg_shell(struct pipe* fg_pipe)
  1638. {
  1639. pid_t p;
  1640. int rcode = checkjobs(fg_pipe);
  1641. /* Job finished, move the shell to the foreground */
  1642. p = getpgid(0); /* pgid of our process */
  1643. debug_printf_jobs("fg'ing ourself: getpgid(0)=%d\n", (int)p);
  1644. tcsetpgrp(G.interactive_fd, p);
  1645. return rcode;
  1646. }
  1647. #endif
  1648. /* run_pipe() starts all the jobs, but doesn't wait for anything
  1649. * to finish. See checkjobs().
  1650. *
  1651. * return code is normally -1, when the caller has to wait for children
  1652. * to finish to determine the exit status of the pipe. If the pipe
  1653. * is a simple builtin command, however, the action is done by the
  1654. * time run_pipe returns, and the exit code is provided as the
  1655. * return value.
  1656. *
  1657. * The input of the pipe is always stdin, the output is always
  1658. * stdout. The outpipe[] mechanism in BusyBox-0.48 lash is bogus,
  1659. * because it tries to avoid running the command substitution in
  1660. * subshell, when that is in fact necessary. The subshell process
  1661. * now has its stdout directed to the input of the appropriate pipe,
  1662. * so this routine is noticeably simpler.
  1663. *
  1664. * Returns -1 only if started some children. IOW: we have to
  1665. * mask out retvals of builtins etc with 0xff!
  1666. */
  1667. static int run_pipe(struct pipe *pi)
  1668. {
  1669. int i;
  1670. int nextin;
  1671. int pipefds[2]; /* pipefds[0] is for reading */
  1672. struct command *command;
  1673. char **argv_expanded;
  1674. char **argv;
  1675. const struct built_in_command *x;
  1676. char *p;
  1677. /* it is not always needed, but we aim to smaller code */
  1678. int squirrel[] = { -1, -1, -1 };
  1679. int rcode;
  1680. const int single_and_fg = (pi->num_cmds == 1 && pi->followup != PIPE_BG);
  1681. debug_printf_exec("run_pipe start: single_and_fg=%d\n", single_and_fg);
  1682. #if ENABLE_HUSH_JOB
  1683. pi->pgrp = -1;
  1684. #endif
  1685. pi->alive_cmds = 1;
  1686. pi->stopped_cmds = 0;
  1687. /* Check if this is a simple builtin (not part of a pipe).
  1688. * Builtins within pipes have to fork anyway, and are handled in
  1689. * pseudo_exec. "echo foo | read bar" doesn't work on bash, either.
  1690. */
  1691. command = &(pi->cmds[0]);
  1692. #if ENABLE_HUSH_FUNCTIONS
  1693. if (single_and_fg && command->group && command->grp_type == GRP_FUNCTION) {
  1694. /* We "execute" function definition */
  1695. bb_error_msg("here we ought to remember function definition, and go on");
  1696. return EXIT_SUCCESS;
  1697. }
  1698. #endif
  1699. if (single_and_fg && command->group && command->grp_type == GRP_NORMAL) {
  1700. debug_printf("non-subshell grouping\n");
  1701. setup_redirects(command, squirrel);
  1702. debug_printf_exec(": run_list\n");
  1703. rcode = run_list(command->group) & 0xff;
  1704. restore_redirects(squirrel);
  1705. debug_printf_exec("run_pipe return %d\n", rcode);
  1706. IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
  1707. return rcode;
  1708. }
  1709. argv = command->argv;
  1710. argv_expanded = NULL;
  1711. if (single_and_fg && argv != NULL) {
  1712. char **new_env = NULL;
  1713. char **old_env = NULL;
  1714. i = command->assignment_cnt;
  1715. if (i != 0 && argv[i] == NULL) {
  1716. /* assignments, but no command: set local environment */
  1717. for (i = 0; argv[i] != NULL; i++) {
  1718. debug_printf("local environment set: %s\n", argv[i]);
  1719. p = expand_string_to_string(argv[i]);
  1720. set_local_var(p, 0);
  1721. }
  1722. return EXIT_SUCCESS; /* don't worry about errors in set_local_var() yet */
  1723. }
  1724. /* Expand the rest into (possibly) many strings each */
  1725. argv_expanded = expand_strvec_to_strvec(argv + i);
  1726. for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
  1727. if (strcmp(argv_expanded[0], x->cmd) != 0)
  1728. continue;
  1729. if (x->function == builtin_exec && argv_expanded[1] == NULL) {
  1730. debug_printf("exec with redirects only\n");
  1731. setup_redirects(command, NULL);
  1732. rcode = EXIT_SUCCESS;
  1733. goto clean_up_and_ret1;
  1734. }
  1735. debug_printf("builtin inline %s\n", argv_expanded[0]);
  1736. /* XXX setup_redirects acts on file descriptors, not FILEs.
  1737. * This is perfect for work that comes after exec().
  1738. * Is it really safe for inline use? Experimentally,
  1739. * things seem to work with glibc. */
  1740. setup_redirects(command, squirrel);
  1741. new_env = expand_assignments(argv, command->assignment_cnt);
  1742. old_env = putenv_all_and_save_old(new_env);
  1743. debug_printf_exec(": builtin '%s' '%s'...\n", x->cmd, argv_expanded[1]);
  1744. rcode = x->function(argv_expanded) & 0xff;
  1745. #if ENABLE_FEATURE_SH_STANDALONE
  1746. clean_up_and_ret:
  1747. #endif
  1748. restore_redirects(squirrel);
  1749. free_strings_and_unsetenv(new_env, 1);
  1750. putenv_all(old_env);
  1751. free(old_env); /* not free_strings()! */
  1752. clean_up_and_ret1:
  1753. free(argv_expanded);
  1754. IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
  1755. debug_printf_exec("run_pipe return %d\n", rcode);
  1756. return rcode;
  1757. }
  1758. #if ENABLE_FEATURE_SH_STANDALONE
  1759. i = find_applet_by_name(argv_expanded[0]);
  1760. if (i >= 0 && APPLET_IS_NOFORK(i)) {
  1761. setup_redirects(command, squirrel);
  1762. save_nofork_data(&G.nofork_save);
  1763. new_env = expand_assignments(argv, command->assignment_cnt);
  1764. old_env = putenv_all_and_save_old(new_env);
  1765. debug_printf_exec(": run_nofork_applet '%s' '%s'...\n", argv_expanded[0], argv_expanded[1]);
  1766. rcode = run_nofork_applet_prime(&G.nofork_save, i, argv_expanded);
  1767. goto clean_up_and_ret;
  1768. }
  1769. #endif
  1770. }
  1771. /* NB: argv_expanded may already be created, and that
  1772. * might include `cmd` runs! Do not rerun it! We *must*
  1773. * use argv_expanded if it's non-NULL */
  1774. /* Disable job control signals for shell (parent) and
  1775. * for initial child code after fork */
  1776. set_jobctrl_sighandler(SIG_IGN);
  1777. /* Going to fork a child per each pipe member */
  1778. pi->alive_cmds = 0;
  1779. nextin = 0;
  1780. for (i = 0; i < pi->num_cmds; i++) {
  1781. #if !BB_MMU
  1782. volatile nommu_save_t nommu_save;
  1783. nommu_save.new_env = NULL;
  1784. nommu_save.old_env = NULL;
  1785. nommu_save.argv = NULL;
  1786. #endif
  1787. command = &(pi->cmds[i]);
  1788. if (command->argv) {
  1789. debug_printf_exec(": pipe member '%s' '%s'...\n", command->argv[0], command->argv[1]);
  1790. } else
  1791. debug_printf_exec(": pipe member with no argv\n");
  1792. /* pipes are inserted between pairs of commands */
  1793. pipefds[0] = 0;
  1794. pipefds[1] = 1;
  1795. if ((i + 1) < pi->num_cmds)
  1796. xpipe(pipefds);
  1797. command->pid = BB_MMU ? fork() : vfork();
  1798. if (!command->pid) { /* child */
  1799. if (ENABLE_HUSH_JOB)
  1800. die_sleep = 0; /* let nofork's xfuncs die */
  1801. #if ENABLE_HUSH_JOB
  1802. /* Every child adds itself to new process group
  1803. * with pgid == pid_of_first_child_in_pipe */
  1804. if (G.run_list_level == 1 && G.interactive_fd) {
  1805. pid_t pgrp;
  1806. /* Don't do pgrp restore anymore on fatal signals */
  1807. set_fatal_sighandler(SIG_DFL);
  1808. pgrp = pi->pgrp;
  1809. if (pgrp < 0) /* true for 1st process only */
  1810. pgrp = getpid();
  1811. if (setpgid(0, pgrp) == 0 && pi->followup != PIPE_BG) {
  1812. /* We do it in *every* child, not just first,
  1813. * to avoid races */
  1814. tcsetpgrp(G.interactive_fd, pgrp);
  1815. }
  1816. }
  1817. #endif
  1818. xmove_fd(nextin, 0);
  1819. xmove_fd(pipefds[1], 1); /* write end */
  1820. if (pipefds[0] > 1)
  1821. close(pipefds[0]); /* read end */
  1822. /* Like bash, explicit redirects override pipes,
  1823. * and the pipe fd is available for dup'ing. */
  1824. setup_redirects(command, NULL);
  1825. /* Restore default handlers just prior to exec */
  1826. set_jobctrl_sighandler(SIG_DFL);
  1827. set_misc_sighandler(SIG_DFL);
  1828. signal(SIGCHLD, SIG_DFL);
  1829. /* Stores to nommu_save list of env vars putenv'ed
  1830. * (NOMMU, on MMU we don't need that) */
  1831. /* cast away volatility... */
  1832. pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
  1833. /* pseudo_exec() does not return */
  1834. }
  1835. /* parent */
  1836. #if !BB_MMU
  1837. /* Clean up after vforked child */
  1838. free(nommu_save.argv);
  1839. free_strings_and_unsetenv(nommu_save.new_env, 1);
  1840. putenv_all(nommu_save.old_env);
  1841. #endif
  1842. free(argv_expanded);
  1843. argv_expanded = NULL;
  1844. if (command->pid < 0) { /* [v]fork failed */
  1845. /* Clearly indicate, was it fork or vfork */
  1846. bb_perror_msg(BB_MMU ? "fork" : "vfork");
  1847. } else {
  1848. pi->alive_cmds++;
  1849. #if ENABLE_HUSH_JOB
  1850. /* Second and next children need to know pid of first one */
  1851. if (pi->pgrp < 0)
  1852. pi->pgrp = command->pid;
  1853. #endif
  1854. }
  1855. if (i)
  1856. close(nextin);
  1857. if ((i + 1) < pi->num_cmds)
  1858. close(pipefds[1]); /* write end */
  1859. /* Pass read (output) pipe end to next iteration */
  1860. nextin = pipefds[0];
  1861. }
  1862. if (!pi->alive_cmds) {
  1863. debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
  1864. return 1;
  1865. }
  1866. debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
  1867. return -1;
  1868. }
  1869. #ifndef debug_print_tree
  1870. static void debug_print_tree(struct pipe *pi, int lvl)
  1871. {
  1872. static const char *const PIPE[] = {
  1873. [PIPE_SEQ] = "SEQ",
  1874. [PIPE_AND] = "AND",
  1875. [PIPE_OR ] = "OR" ,
  1876. [PIPE_BG ] = "BG" ,
  1877. };
  1878. static const char *RES[] = {
  1879. [RES_NONE ] = "NONE" ,
  1880. #if ENABLE_HUSH_IF
  1881. [RES_IF ] = "IF" ,
  1882. [RES_THEN ] = "THEN" ,
  1883. [RES_ELIF ] = "ELIF" ,
  1884. [RES_ELSE ] = "ELSE" ,
  1885. [RES_FI ] = "FI" ,
  1886. #endif
  1887. #if ENABLE_HUSH_LOOPS
  1888. [RES_FOR ] = "FOR" ,
  1889. [RES_WHILE] = "WHILE",
  1890. [RES_UNTIL] = "UNTIL",
  1891. [RES_DO ] = "DO" ,
  1892. [RES_DONE ] = "DONE" ,
  1893. #endif
  1894. #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
  1895. [RES_IN ] = "IN" ,
  1896. #endif
  1897. #if ENABLE_HUSH_CASE
  1898. [RES_CASE ] = "CASE" ,
  1899. [RES_MATCH] = "MATCH",
  1900. [RES_CASEI] = "CASEI",
  1901. [RES_ESAC ] = "ESAC" ,
  1902. #endif
  1903. [RES_XXXX ] = "XXXX" ,
  1904. [RES_SNTX ] = "SNTX" ,
  1905. };
  1906. static const char *const GRPTYPE[] = {
  1907. "()",
  1908. "{}",
  1909. #if ENABLE_HUSH_FUNCTIONS
  1910. "func()",
  1911. #endif
  1912. };
  1913. int pin, prn;
  1914. pin = 0;
  1915. while (pi) {
  1916. fprintf(stderr, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
  1917. pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
  1918. prn = 0;
  1919. while (prn < pi->num_cmds) {
  1920. struct command *command = &pi->cmds[prn];
  1921. char **argv = command->argv;
  1922. fprintf(stderr, "%*s prog %d assignment_cnt:%d", lvl*2, "", prn, command->assignment_cnt);
  1923. if (command->group) {
  1924. fprintf(stderr, " group %s: (argv=%p)\n",
  1925. GRPTYPE[command->grp_type],
  1926. argv);
  1927. debug_print_tree(command->group, lvl+1);
  1928. prn++;
  1929. continue;
  1930. }
  1931. if (argv) while (*argv) {
  1932. fprintf(stderr, " '%s'", *argv);
  1933. argv++;
  1934. }
  1935. fprintf(stderr, "\n");
  1936. prn++;
  1937. }
  1938. pi = pi->next;
  1939. pin++;
  1940. }
  1941. }
  1942. #endif
  1943. /* NB: called by pseudo_exec, and therefore must not modify any
  1944. * global data until exec/_exit (we can be a child after vfork!) */
  1945. static int run_list(struct pipe *pi)
  1946. {
  1947. #if ENABLE_HUSH_CASE
  1948. char *case_word = NULL;
  1949. #endif
  1950. #if ENABLE_HUSH_LOOPS
  1951. struct pipe *loop_top = NULL;
  1952. char *for_varname = NULL;
  1953. char **for_lcur = NULL;
  1954. char **for_list = NULL;
  1955. #endif
  1956. smallint flag_skip = 1;
  1957. smalluint rcode = 0; /* probably just for compiler */
  1958. #if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
  1959. smalluint cond_code = 0;
  1960. #else
  1961. enum { cond_code = 0, };
  1962. #endif
  1963. /*enum reserved_style*/ smallint rword = RES_NONE;
  1964. /*enum reserved_style*/ smallint skip_more_for_this_rword = RES_XXXX;
  1965. debug_printf_exec("run_list start lvl %d\n", G.run_list_level + 1);
  1966. #if ENABLE_HUSH_LOOPS
  1967. /* Check syntax for "for" */
  1968. for (struct pipe *cpipe = pi; cpipe; cpipe = cpipe->next) {
  1969. if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
  1970. continue;
  1971. /* current word is FOR or IN (BOLD in comments below) */
  1972. if (cpipe->next == NULL) {
  1973. syntax("malformed for");
  1974. debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
  1975. return 1;
  1976. }
  1977. /* "FOR v; do ..." and "for v IN a b; do..." are ok */
  1978. if (cpipe->next->res_word == RES_DO)
  1979. continue;
  1980. /* next word is not "do". It must be "in" then ("FOR v in ...") */
  1981. if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
  1982. || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
  1983. ) {
  1984. syntax("malformed for");
  1985. debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
  1986. return 1;
  1987. }
  1988. }
  1989. #endif
  1990. /* Past this point, all code paths should jump to ret: label
  1991. * in order to return, no direct "return" statements please.
  1992. * This helps to ensure that no memory is leaked. */
  1993. #if ENABLE_HUSH_JOB
  1994. /* Example of nested list: "while true; do { sleep 1 | exit 2; } done".
  1995. * We are saving state before entering outermost list ("while...done")
  1996. * so that ctrl-Z will correctly background _entire_ outermost list,
  1997. * not just a part of it (like "sleep 1 | exit 2") */
  1998. if (++G.run_list_level == 1 && G.interactive_fd) {
  1999. if (sigsetjmp(G.toplevel_jb, 1)) {
  2000. /* ctrl-Z forked and we are parent; or ctrl-C.
  2001. * Sighandler has longjmped us here */
  2002. signal(SIGINT, SIG_IGN);
  2003. signal(SIGTSTP, SIG_IGN);
  2004. /* Restore level (we can be coming from deep inside
  2005. * nested levels) */
  2006. G.run_list_level = 1;
  2007. #if ENABLE_FEATURE_SH_STANDALONE
  2008. if (G.nofork_save.saved) { /* if save area is valid */
  2009. debug_printf_jobs("exiting nofork early\n");
  2010. restore_nofork_data(&G.nofork_save);
  2011. }
  2012. #endif
  2013. if (G.ctrl_z_flag) {
  2014. /* ctrl-Z has forked and stored pid of the child in pi->pid.
  2015. * Remember this child as background job */
  2016. insert_bg_job(pi);
  2017. } else {
  2018. /* ctrl-C. We just stop doing whatever we were doing */
  2019. bb_putchar('\n');
  2020. }
  2021. USE_HUSH_LOOPS(loop_top = NULL;)
  2022. USE_HUSH_LOOPS(G.depth_of_loop = 0;)
  2023. rcode = 0;
  2024. goto ret;
  2025. }
  2026. /* ctrl-Z handler will store pid etc in pi */
  2027. G.toplevel_list = pi;
  2028. G.ctrl_z_flag = 0;
  2029. #if ENABLE_FEATURE_SH_STANDALONE
  2030. G.nofork_save.saved = 0; /* in case we will run a nofork later */
  2031. #endif
  2032. signal_SA_RESTART_empty_mask(SIGTSTP, handler_ctrl_z);
  2033. signal(SIGINT, handler_ctrl_c);
  2034. }
  2035. #endif /* JOB */
  2036. /* Go through list of pipes, (maybe) executing them. */
  2037. for (; pi; pi = USE_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
  2038. IF_HAS_KEYWORDS(rword = pi->res_word;)
  2039. IF_HAS_NO_KEYWORDS(rword = RES_NONE;)
  2040. debug_printf_exec(": rword=%d cond_code=%d skip_more=%d\n",
  2041. rword, cond_code, skip_more_for_this_rword);
  2042. #if ENABLE_HUSH_LOOPS
  2043. if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
  2044. && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
  2045. ) {
  2046. /* start of a loop: remember where loop starts */
  2047. loop_top = pi;
  2048. G.depth_of_loop++;
  2049. }
  2050. #endif
  2051. if (rword == skip_more_for_this_rword && flag_skip) {
  2052. if (pi->followup == PIPE_SEQ)
  2053. flag_skip = 0;
  2054. /* it is "<false> && CMD" or "<true> || CMD"
  2055. * and we should not execute CMD */
  2056. continue;
  2057. }
  2058. flag_skip = 1;
  2059. skip_more_for_this_rword = RES_XXXX;
  2060. #if ENABLE_HUSH_IF
  2061. if (cond_code) {
  2062. if (rword == RES_THEN) {
  2063. /* "if <false> THEN cmd": skip cmd */
  2064. continue;
  2065. }
  2066. } else {
  2067. if (rword == RES_ELSE || rword == RES_ELIF) {
  2068. /* "if <true> then ... ELSE/ELIF cmd":
  2069. * skip cmd and all following ones */
  2070. break;
  2071. }
  2072. }
  2073. #endif
  2074. #if ENABLE_HUSH_LOOPS
  2075. if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
  2076. if (!for_lcur) {
  2077. /* first loop through for */
  2078. static const char encoded_dollar_at[] ALIGN1 = {
  2079. SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
  2080. }; /* encoded representation of "$@" */
  2081. static const char *const encoded_dollar_at_argv[] = {
  2082. encoded_dollar_at, NULL
  2083. }; /* argv list with one element: "$@" */
  2084. char **vals;
  2085. vals = (char**)encoded_dollar_at_argv;
  2086. if (pi->next->res_word == RES_IN) {
  2087. /* if no variable values after "in" we skip "for" */
  2088. if (!pi->next->cmds[0].argv)
  2089. break;
  2090. vals = pi->next->cmds[0].argv;
  2091. } /* else: "for var; do..." -> assume "$@" list */
  2092. /* create list of variable values */
  2093. debug_print_strings("for_list made from", vals);
  2094. for_list = expand_strvec_to_strvec(vals);
  2095. for_lcur = for_list;
  2096. debug_print_strings("for_list", for_list);
  2097. for_varname = pi->cmds[0].argv[0];
  2098. pi->cmds[0].argv[0] = NULL;
  2099. }
  2100. free(pi->cmds[0].argv[0]);
  2101. if (!*for_lcur) {
  2102. /* "for" loop is over, clean up */
  2103. free(for_list);
  2104. for_list = NULL;
  2105. for_lcur = NULL;
  2106. pi->cmds[0].argv[0] = for_varname;
  2107. break;
  2108. }
  2109. /* insert next value from for_lcur */
  2110. //TODO: does it need escaping?
  2111. pi->cmds[0].argv[0] = xasprintf("%s=%s", for_varname, *for_lcur++);
  2112. pi->cmds[0].assignment_cnt = 1;
  2113. }
  2114. if (rword == RES_IN) /* "for v IN list;..." - "in" has no cmds anyway */
  2115. continue;
  2116. if (rword == RES_DONE) {
  2117. continue; /* "done" has no cmds too */
  2118. }
  2119. #endif
  2120. #if ENABLE_HUSH_CASE
  2121. if (rword == RES_CASE) {
  2122. case_word = expand_strvec_to_string(pi->cmds->argv);
  2123. continue;
  2124. }
  2125. if (rword == RES_MATCH) {
  2126. char **argv;
  2127. if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
  2128. break;
  2129. /* all prev words didn't match, does this one match? */
  2130. argv = pi->cmds->argv;
  2131. while (*argv) {
  2132. char *pattern = expand_string_to_string(*argv);
  2133. /* TODO: which FNM_xxx flags to use? */
  2134. cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
  2135. free(pattern);
  2136. if (cond_code == 0) { /* match! we will execute this branch */
  2137. free(case_word); /* make future "word)" stop */
  2138. case_word = NULL;
  2139. break;
  2140. }
  2141. argv++;
  2142. }
  2143. continue;
  2144. }
  2145. if (rword == RES_CASEI) { /* inside of a case branch */
  2146. if (cond_code != 0)
  2147. continue; /* not matched yet, skip this pipe */
  2148. }
  2149. #endif
  2150. if (pi->num_cmds == 0)
  2151. continue;
  2152. /* After analyzing all keywords and conditions, we decided
  2153. * to execute this pipe. NB: has to do checkjobs(NULL)
  2154. * after run_pipe() to collect any background children,
  2155. * even if list execution is to be stopped. */
  2156. debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
  2157. {
  2158. int r;
  2159. #if ENABLE_HUSH_LOOPS
  2160. G.flag_break_continue = 0;
  2161. #endif
  2162. rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
  2163. if (r != -1) {
  2164. /* we only ran a builtin: rcode is already known
  2165. * and we don't need to wait for anything. */
  2166. #if ENABLE_HUSH_LOOPS
  2167. /* was it "break" or "continue"? */
  2168. if (G.flag_break_continue) {
  2169. smallint fbc = G.flag_break_continue;
  2170. /* we might fall into outer *loop*,
  2171. * don't want to break it too */
  2172. if (loop_top) {
  2173. G.depth_break_continue--;
  2174. if (G.depth_break_continue == 0)
  2175. G.flag_break_continue = 0;
  2176. /* else: e.g. "continue 2" should *break* once, *then* continue */
  2177. } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
  2178. if (G.depth_break_continue != 0 || fbc == BC_BREAK)
  2179. goto check_jobs_and_break;
  2180. /* "continue": simulate end of loop */
  2181. rword = RES_DONE;
  2182. continue;
  2183. }
  2184. #endif
  2185. } else if (pi->followup == PIPE_BG) {
  2186. /* what does bash do with attempts to background builtins? */
  2187. /* even bash 3.2 doesn't do that well with nested bg:
  2188. * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
  2189. * I'm NOT treating inner &'s as jobs */
  2190. #if ENABLE_HUSH_JOB
  2191. if (G.run_list_level == 1)
  2192. insert_bg_job(pi);
  2193. #endif
  2194. rcode = 0; /* EXIT_SUCCESS */
  2195. } else {
  2196. #if ENABLE_HUSH_JOB
  2197. if (G.run_list_level == 1 && G.interactive_fd) {
  2198. /* waits for completion, then fg's main shell */
  2199. rcode = checkjobs_and_fg_shell(pi);
  2200. debug_printf_exec(": checkjobs_and_fg_shell returned %d\n", rcode);
  2201. } else
  2202. #endif
  2203. { /* this one just waits for completion */
  2204. rcode = checkjobs(pi);
  2205. debug_printf_exec(": checkjobs returned %d\n", rcode);
  2206. }
  2207. }
  2208. }
  2209. debug_printf_exec(": setting last_return_code=%d\n", rcode);
  2210. G.last_return_code = rcode;
  2211. /* Analyze how result affects subsequent commands */
  2212. #if ENABLE_HUSH_IF
  2213. if (rword == RES_IF || rword == RES_ELIF)
  2214. cond_code = rcode;
  2215. #endif
  2216. #if ENABLE_HUSH_LOOPS
  2217. if (rword == RES_WHILE) {
  2218. if (rcode) {
  2219. rcode = 0; /* "while false; do...done" - exitcode 0 */
  2220. goto check_jobs_and_break;
  2221. }
  2222. }
  2223. if (rword == RES_UNTIL) {
  2224. if (!rcode) {
  2225. check_jobs_and_break:
  2226. checkjobs(NULL);
  2227. break;
  2228. }
  2229. }
  2230. #endif
  2231. if ((rcode == 0 && pi->followup == PIPE_OR)
  2232. || (rcode != 0 && pi->followup == PIPE_AND)
  2233. ) {
  2234. skip_more_for_this_rword = rword;
  2235. }
  2236. checkjobs(NULL);
  2237. } /* for (pi) */
  2238. #if ENABLE_HUSH_JOB
  2239. if (G.ctrl_z_flag) {
  2240. /* ctrl-Z forked somewhere in the past, we are the child,
  2241. * and now we completed running the list. Exit. */
  2242. //TODO: _exit?
  2243. exit(rcode);
  2244. }
  2245. ret:
  2246. if (!--G.run_list_level && G.interactive_fd) {
  2247. signal(SIGTSTP, SIG_IGN);
  2248. signal(SIGINT, SIG_IGN);
  2249. }
  2250. #endif
  2251. debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
  2252. #if ENABLE_HUSH_LOOPS
  2253. if (loop_top)
  2254. G.depth_of_loop--;
  2255. free(for_list);
  2256. #endif
  2257. #if ENABLE_HUSH_CASE
  2258. free(case_word);
  2259. #endif
  2260. return rcode;
  2261. }
  2262. /* return code is the exit status of the pipe */
  2263. static int free_pipe(struct pipe *pi, int indent)
  2264. {
  2265. char **p;
  2266. struct command *command;
  2267. struct redir_struct *r, *rnext;
  2268. int a, i, ret_code = 0;
  2269. if (pi->stopped_cmds > 0)
  2270. return ret_code;
  2271. debug_printf_clean("%s run pipe: (pid %d)\n", indenter(indent), getpid());
  2272. for (i = 0; i < pi->num_cmds; i++) {
  2273. command = &pi->cmds[i];
  2274. debug_printf_clean("%s command %d:\n", indenter(indent), i);
  2275. if (command->argv) {
  2276. for (a = 0, p = command->argv; *p; a++, p++) {
  2277. debug_printf_clean("%s argv[%d] = %s\n", indenter(indent), a, *p);
  2278. }
  2279. free_strings(command->argv);
  2280. command->argv = NULL;
  2281. } else if (command->group) {
  2282. debug_printf_clean("%s begin group (grp_type:%d)\n", indenter(indent), command->grp_type);
  2283. ret_code = free_pipe_list(command->group, indent+3);
  2284. debug_printf_clean("%s end group\n", indenter(indent));
  2285. } else {
  2286. debug_printf_clean("%s (nil)\n", indenter(indent));
  2287. }
  2288. for (r = command->redirects; r; r = rnext) {
  2289. debug_printf_clean("%s redirect %d%s", indenter(indent), r->fd, redir_table[r->rd_type].descrip);
  2290. if (r->dup == -1) {
  2291. /* guard against the case >$FOO, where foo is unset or blank */
  2292. if (r->rd_filename) {
  2293. debug_printf_clean(" %s\n", r->rd_filename);
  2294. free(r->rd_filename);
  2295. r->rd_filename = NULL;
  2296. }
  2297. } else {
  2298. debug_printf_clean("&%d\n", r->dup);
  2299. }
  2300. rnext = r->next;
  2301. free(r);
  2302. }
  2303. command->redirects = NULL;
  2304. }
  2305. free(pi->cmds); /* children are an array, they get freed all at once */
  2306. pi->cmds = NULL;
  2307. #if ENABLE_HUSH_JOB
  2308. free(pi->cmdtext);
  2309. pi->cmdtext = NULL;
  2310. #endif
  2311. return ret_code;
  2312. }
  2313. static int free_pipe_list(struct pipe *head, int indent)
  2314. {
  2315. int rcode = 0; /* if list has no members */
  2316. struct pipe *pi, *next;
  2317. for (pi = head; pi; pi = next) {
  2318. #if HAS_KEYWORDS
  2319. debug_printf_clean("%s pipe reserved mode %d\n", indenter(indent), pi->res_word);
  2320. #endif
  2321. rcode = free_pipe(pi, indent);
  2322. debug_printf_clean("%s pipe followup code %d\n", indenter(indent), pi->followup);
  2323. next = pi->next;
  2324. /*pi->next = NULL;*/
  2325. free(pi);
  2326. }
  2327. return rcode;
  2328. }
  2329. /* Select which version we will use */
  2330. static int run_and_free_list(struct pipe *pi)
  2331. {
  2332. int rcode = 0;
  2333. debug_printf_exec("run_and_free_list entered\n");
  2334. if (!G.fake_mode) {
  2335. debug_printf_exec(": run_list with %d members\n", pi->num_cmds);
  2336. rcode = run_list(pi);
  2337. }
  2338. /* free_pipe_list has the side effect of clearing memory.
  2339. * In the long run that function can be merged with run_list,
  2340. * but doing that now would hobble the debugging effort. */
  2341. free_pipe_list(pi, /* indent: */ 0);
  2342. debug_printf_exec("run_and_free_list return %d\n", rcode);
  2343. return rcode;
  2344. }
  2345. /* expand_strvec_to_strvec() takes a list of strings, expands
  2346. * all variable references within and returns a pointer to
  2347. * a list of expanded strings, possibly with larger number
  2348. * of strings. (Think VAR="a b"; echo $VAR).
  2349. * This new list is allocated as a single malloc block.
  2350. * NULL-terminated list of char* pointers is at the beginning of it,
  2351. * followed by strings themself.
  2352. * Caller can deallocate entire list by single free(list). */
  2353. /* Store given string, finalizing the word and starting new one whenever
  2354. * we encounter IFS char(s). This is used for expanding variable values.
  2355. * End-of-string does NOT finalize word: think about 'echo -$VAR-' */
  2356. static int expand_on_ifs(o_string *output, int n, const char *str)
  2357. {
  2358. while (1) {
  2359. int word_len = strcspn(str, G.ifs);
  2360. if (word_len) {
  2361. if (output->o_quote || !output->o_glob)
  2362. o_addQstr(output, str, word_len);
  2363. else /* protect backslashes against globbing up :) */
  2364. o_addstr_duplicate_backslash(output, str, word_len);
  2365. str += word_len;
  2366. }
  2367. if (!*str) /* EOL - do not finalize word */
  2368. break;
  2369. o_addchr(output, '\0');
  2370. debug_print_list("expand_on_ifs", output, n);
  2371. n = o_save_ptr(output, n);
  2372. str += strspn(str, G.ifs); /* skip ifs chars */
  2373. }
  2374. debug_print_list("expand_on_ifs[1]", output, n);
  2375. return n;
  2376. }
  2377. /* Expand all variable references in given string, adding words to list[]
  2378. * at n, n+1,... positions. Return updated n (so that list[n] is next one
  2379. * to be filled). This routine is extremely tricky: has to deal with
  2380. * variables/parameters with whitespace, $* and $@, and constructs like
  2381. * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
  2382. static int expand_vars_to_list(o_string *output, int n, char *arg, char or_mask)
  2383. {
  2384. /* or_mask is either 0 (normal case) or 0x80
  2385. * (expansion of right-hand side of assignment == 1-element expand.
  2386. * It will also do no globbing, and thus we must not backslash-quote!) */
  2387. char first_ch, ored_ch;
  2388. int i;
  2389. const char *val;
  2390. char *p;
  2391. ored_ch = 0;
  2392. debug_printf_expand("expand_vars_to_list: arg '%s'\n", arg);
  2393. debug_print_list("expand_vars_to_list", output, n);
  2394. n = o_save_ptr(output, n);
  2395. debug_print_list("expand_vars_to_list[0]", output, n);
  2396. while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
  2397. #if ENABLE_HUSH_TICK
  2398. o_string subst_result = NULL_O_STRING;
  2399. #endif
  2400. o_addstr(output, arg, p - arg);
  2401. debug_print_list("expand_vars_to_list[1]", output, n);
  2402. arg = ++p;
  2403. p = strchr(p, SPECIAL_VAR_SYMBOL);
  2404. first_ch = arg[0] | or_mask; /* forced to "quoted" if or_mask = 0x80 */
  2405. /* "$@" is special. Even if quoted, it can still
  2406. * expand to nothing (not even an empty string) */
  2407. if ((first_ch & 0x7f) != '@')
  2408. ored_ch |= first_ch;
  2409. val = NULL;
  2410. switch (first_ch & 0x7f) {
  2411. /* Highest bit in first_ch indicates that var is double-quoted */
  2412. case '$': /* pid */
  2413. val = utoa(G.root_pid);
  2414. break;
  2415. case '!': /* bg pid */
  2416. val = G.last_bg_pid ? utoa(G.last_bg_pid) : (char*)"";
  2417. break;
  2418. case '?': /* exitcode */
  2419. val = utoa(G.last_return_code);
  2420. break;
  2421. case '#': /* argc */
  2422. val = utoa(G.global_argc ? G.global_argc-1 : 0);
  2423. break;
  2424. case '*':
  2425. case '@':
  2426. i = 1;
  2427. if (!G.global_argv[i])
  2428. break;
  2429. ored_ch |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
  2430. if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
  2431. smallint sv = output->o_quote;
  2432. /* unquoted var's contents should be globbed, so don't quote */
  2433. output->o_quote = 0;
  2434. while (G.global_argv[i]) {
  2435. n = expand_on_ifs(output, n, G.global_argv[i]);
  2436. debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
  2437. if (G.global_argv[i++][0] && G.global_argv[i]) {
  2438. /* this argv[] is not empty and not last:
  2439. * put terminating NUL, start new word */
  2440. o_addchr(output, '\0');
  2441. debug_print_list("expand_vars_to_list[2]", output, n);
  2442. n = o_save_ptr(output, n);
  2443. debug_print_list("expand_vars_to_list[3]", output, n);
  2444. }
  2445. }
  2446. output->o_quote = sv;
  2447. } else
  2448. /* If or_mask is nonzero, we handle assignment 'a=....$@.....'
  2449. * and in this case should treat it like '$*' - see 'else...' below */
  2450. if (first_ch == ('@'|0x80) && !or_mask) { /* quoted $@ */
  2451. while (1) {
  2452. o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
  2453. if (++i >= G.global_argc)
  2454. break;
  2455. o_addchr(output, '\0');
  2456. debug_print_list("expand_vars_to_list[4]", output, n);
  2457. n = o_save_ptr(output, n);
  2458. }
  2459. } else { /* quoted $*: add as one word */
  2460. while (1) {
  2461. o_addQstr(output, G.global_argv[i], strlen(G.global_argv[i]));
  2462. if (!G.global_argv[++i])
  2463. break;
  2464. if (G.ifs[0])
  2465. o_addchr(output, G.ifs[0]);
  2466. }
  2467. }
  2468. break;
  2469. case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
  2470. /* "Empty variable", used to make "" etc to not disappear */
  2471. arg++;
  2472. ored_ch = 0x80;
  2473. break;
  2474. #if ENABLE_HUSH_TICK
  2475. case '`': { /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
  2476. struct in_str input;
  2477. *p = '\0';
  2478. arg++;
  2479. //TODO: can we just stuff it into "output" directly?
  2480. debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
  2481. setup_string_in_str(&input, arg);
  2482. process_command_subs(&subst_result, &input, NULL);
  2483. debug_printf_subst("SUBST RES '%s'\n", subst_result.data);
  2484. val = subst_result.data;
  2485. goto store_val;
  2486. }
  2487. #endif
  2488. default: /* <SPECIAL_VAR_SYMBOL>varname<SPECIAL_VAR_SYMBOL> */
  2489. *p = '\0';
  2490. arg[0] = first_ch & 0x7f;
  2491. if (isdigit(arg[0])) {
  2492. i = xatoi_u(arg);
  2493. if (i < G.global_argc)
  2494. val = G.global_argv[i];
  2495. /* else val remains NULL: $N with too big N */
  2496. } else
  2497. val = lookup_param(arg);
  2498. arg[0] = first_ch;
  2499. #if ENABLE_HUSH_TICK
  2500. store_val:
  2501. #endif
  2502. *p = SPECIAL_VAR_SYMBOL;
  2503. if (!(first_ch & 0x80)) { /* unquoted $VAR */
  2504. debug_printf_expand("unquoted '%s', output->o_quote:%d\n", val, output->o_quote);
  2505. if (val) {
  2506. /* unquoted var's contents should be globbed, so don't quote */
  2507. smallint sv = output->o_quote;
  2508. output->o_quote = 0;
  2509. n = expand_on_ifs(output, n, val);
  2510. val = NULL;
  2511. output->o_quote = sv;
  2512. }
  2513. } else { /* quoted $VAR, val will be appended below */
  2514. debug_printf_expand("quoted '%s', output->o_quote:%d\n", val, output->o_quote);
  2515. }
  2516. }
  2517. if (val) {
  2518. o_addQstr(output, val, strlen(val));
  2519. }
  2520. #if ENABLE_HUSH_TICK
  2521. o_free(&subst_result);
  2522. #endif
  2523. arg = ++p;
  2524. } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
  2525. if (arg[0]) {
  2526. debug_print_list("expand_vars_to_list[a]", output, n);
  2527. /* this part is literal, and it was already pre-quoted
  2528. * if needed (much earlier), do not use o_addQstr here! */
  2529. o_addstr(output, arg, strlen(arg) + 1);
  2530. debug_print_list("expand_vars_to_list[b]", output, n);
  2531. } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
  2532. && !(ored_ch & 0x80) /* and all vars were not quoted. */
  2533. ) {
  2534. n--;
  2535. /* allow to reuse list[n] later without re-growth */
  2536. output->has_empty_slot = 1;
  2537. } else {
  2538. o_addchr(output, '\0');
  2539. }
  2540. return n;
  2541. }
  2542. static char **expand_variables(char **argv, int or_mask)
  2543. {
  2544. int n;
  2545. char **list;
  2546. char **v;
  2547. o_string output = NULL_O_STRING;
  2548. if (or_mask & 0x100) {
  2549. output.o_quote = 1; /* protect against globbing for "$var" */
  2550. /* (unquoted $var will temporarily switch it off) */
  2551. output.o_glob = 1;
  2552. }
  2553. n = 0;
  2554. v = argv;
  2555. while (*v) {
  2556. n = expand_vars_to_list(&output, n, *v, (char)or_mask);
  2557. v++;
  2558. }
  2559. debug_print_list("expand_variables", &output, n);
  2560. /* output.data (malloced in one block) gets returned in "list" */
  2561. list = o_finalize_list(&output, n);
  2562. debug_print_strings("expand_variables[1]", list);
  2563. return list;
  2564. }
  2565. static char **expand_strvec_to_strvec(char **argv)
  2566. {
  2567. return expand_variables(argv, 0x100);
  2568. }
  2569. /* Used for expansion of right hand of assignments */
  2570. /* NB: should NOT do globbing! "export v=/bin/c*; env | grep ^v=" outputs
  2571. * "v=/bin/c*" */
  2572. static char *expand_string_to_string(const char *str)
  2573. {
  2574. char *argv[2], **list;
  2575. argv[0] = (char*)str;
  2576. argv[1] = NULL;
  2577. list = expand_variables(argv, 0x80); /* 0x80: make one-element expansion */
  2578. if (HUSH_DEBUG)
  2579. if (!list[0] || list[1])
  2580. bb_error_msg_and_die("BUG in varexp2");
  2581. /* actually, just move string 2*sizeof(char*) bytes back */
  2582. strcpy((char*)list, list[0]);
  2583. debug_printf_expand("string_to_string='%s'\n", (char*)list);
  2584. return (char*)list;
  2585. }
  2586. /* Used for "eval" builtin */
  2587. static char* expand_strvec_to_string(char **argv)
  2588. {
  2589. char **list;
  2590. list = expand_variables(argv, 0x80);
  2591. /* Convert all NULs to spaces */
  2592. if (list[0]) {
  2593. int n = 1;
  2594. while (list[n]) {
  2595. if (HUSH_DEBUG)
  2596. if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
  2597. bb_error_msg_and_die("BUG in varexp3");
  2598. list[n][-1] = ' '; /* TODO: or to G.ifs[0]? */
  2599. n++;
  2600. }
  2601. }
  2602. strcpy((char*)list, list[0]);
  2603. debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
  2604. return (char*)list;
  2605. }
  2606. /* Used to get/check local shell variables */
  2607. static struct variable *get_local_var(const char *name)
  2608. {
  2609. struct variable *cur;
  2610. int len;
  2611. if (!name)
  2612. return NULL;
  2613. len = strlen(name);
  2614. for (cur = G.top_var; cur; cur = cur->next) {
  2615. if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
  2616. return cur;
  2617. }
  2618. return NULL;
  2619. }
  2620. /* str holds "NAME=VAL" and is expected to be malloced.
  2621. * We take ownership of it. */
  2622. static int set_local_var(char *str, int flg_export)
  2623. {
  2624. struct variable *cur;
  2625. char *value;
  2626. int name_len;
  2627. value = strchr(str, '=');
  2628. if (!value) { /* not expected to ever happen? */
  2629. free(str);
  2630. return -1;
  2631. }
  2632. name_len = value - str + 1; /* including '=' */
  2633. cur = G.top_var; /* cannot be NULL (we have HUSH_VERSION and it's RO) */
  2634. while (1) {
  2635. if (strncmp(cur->varstr, str, name_len) != 0) {
  2636. if (!cur->next) {
  2637. /* Bail out. Note that now cur points
  2638. * to last var in linked list */
  2639. break;
  2640. }
  2641. cur = cur->next;
  2642. continue;
  2643. }
  2644. /* We found an existing var with this name */
  2645. *value = '\0';
  2646. if (cur->flg_read_only) {
  2647. bb_error_msg("%s: readonly variable", str);
  2648. free(str);
  2649. return -1;
  2650. }
  2651. debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
  2652. unsetenv(str); /* just in case */
  2653. *value = '=';
  2654. if (strcmp(cur->varstr, str) == 0) {
  2655. free_and_exp:
  2656. free(str);
  2657. goto exp;
  2658. }
  2659. if (cur->max_len >= strlen(str)) {
  2660. /* This one is from startup env, reuse space */
  2661. strcpy(cur->varstr, str);
  2662. goto free_and_exp;
  2663. }
  2664. /* max_len == 0 signifies "malloced" var, which we can
  2665. * (and has to) free */
  2666. if (!cur->max_len)
  2667. free(cur->varstr);
  2668. cur->max_len = 0;
  2669. goto set_str_and_exp;
  2670. }
  2671. /* Not found - create next variable struct */
  2672. cur->next = xzalloc(sizeof(*cur));
  2673. cur = cur->next;
  2674. set_str_and_exp:
  2675. cur->varstr = str;
  2676. exp:
  2677. if (flg_export)
  2678. cur->flg_export = 1;
  2679. if (cur->flg_export) {
  2680. debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
  2681. return putenv(cur->varstr);
  2682. }
  2683. return 0;
  2684. }
  2685. static void unset_local_var(const char *name)
  2686. {
  2687. struct variable *cur;
  2688. struct variable *prev = prev; /* for gcc */
  2689. int name_len;
  2690. if (!name)
  2691. return;
  2692. name_len = strlen(name);
  2693. cur = G.top_var;
  2694. while (cur) {
  2695. if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
  2696. if (cur->flg_read_only) {
  2697. bb_error_msg("%s: readonly variable", name);
  2698. return;
  2699. }
  2700. /* prev is ok to use here because 1st variable, HUSH_VERSION,
  2701. * is ro, and we cannot reach this code on the 1st pass */
  2702. prev->next = cur->next;
  2703. debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
  2704. unsetenv(cur->varstr);
  2705. if (!cur->max_len)
  2706. free(cur->varstr);
  2707. free(cur);
  2708. return;
  2709. }
  2710. prev = cur;
  2711. cur = cur->next;
  2712. }
  2713. }
  2714. /* The src parameter allows us to peek forward to a possible &n syntax
  2715. * for file descriptor duplication, e.g., "2>&1".
  2716. * Return code is 0 normally, 1 if a syntax error is detected in src.
  2717. * Resource errors (in xmalloc) cause the process to exit */
  2718. static int setup_redirect(struct parse_context *ctx, int fd, redir_type style,
  2719. struct in_str *input)
  2720. {
  2721. struct command *command = ctx->command;
  2722. struct redir_struct *redir = command->redirects;
  2723. struct redir_struct *last_redir = NULL;
  2724. /* Create a new redir_struct and drop it onto the end of the linked list */
  2725. while (redir) {
  2726. last_redir = redir;
  2727. redir = redir->next;
  2728. }
  2729. redir = xzalloc(sizeof(struct redir_struct));
  2730. /* redir->next = NULL; */
  2731. /* redir->rd_filename = NULL; */
  2732. if (last_redir) {
  2733. last_redir->next = redir;
  2734. } else {
  2735. command->redirects = redir;
  2736. }
  2737. redir->rd_type = style;
  2738. redir->fd = (fd == -1) ? redir_table[style].default_fd : fd;
  2739. debug_printf("Redirect type %d%s\n", redir->fd, redir_table[style].descrip);
  2740. /* Check for a '2>&1' type redirect */
  2741. redir->dup = redirect_dup_num(input);
  2742. if (redir->dup == -2)
  2743. return 1; /* syntax error */
  2744. if (redir->dup != -1) {
  2745. /* Erik had a check here that the file descriptor in question
  2746. * is legit; I postpone that to "run time"
  2747. * A "-" representation of "close me" shows up as a -3 here */
  2748. debug_printf("Duplicating redirect '%d>&%d'\n", redir->fd, redir->dup);
  2749. } else {
  2750. /* We do _not_ try to open the file that src points to,
  2751. * since we need to return and let src be expanded first.
  2752. * Set ctx->pending_redirect, so we know what to do at the
  2753. * end of the next parsed word. */
  2754. ctx->pending_redirect = redir;
  2755. }
  2756. return 0;
  2757. }
  2758. static struct pipe *new_pipe(void)
  2759. {
  2760. struct pipe *pi;
  2761. pi = xzalloc(sizeof(struct pipe));
  2762. /*pi->followup = 0; - deliberately invalid value */
  2763. /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
  2764. return pi;
  2765. }
  2766. static void initialize_context(struct parse_context *ctx)
  2767. {
  2768. memset(ctx, 0, sizeof(*ctx));
  2769. ctx->pipe = ctx->list_head = new_pipe();
  2770. /* Create the memory for command, roughly:
  2771. * ctx->pipe->cmds = new struct command;
  2772. * ctx->command = &ctx->pipe->cmds[0];
  2773. */
  2774. done_command(ctx);
  2775. }
  2776. /* If a reserved word is found and processed, parse context is modified
  2777. * and 1 is returned.
  2778. * Handles if, then, elif, else, fi, for, while, until, do, done.
  2779. * case, function, and select are obnoxious, save those for later.
  2780. */
  2781. #if HAS_KEYWORDS
  2782. struct reserved_combo {
  2783. char literal[6];
  2784. unsigned char res;
  2785. unsigned char assignment_flag;
  2786. int flag;
  2787. };
  2788. enum {
  2789. FLAG_END = (1 << RES_NONE ),
  2790. #if ENABLE_HUSH_IF
  2791. FLAG_IF = (1 << RES_IF ),
  2792. FLAG_THEN = (1 << RES_THEN ),
  2793. FLAG_ELIF = (1 << RES_ELIF ),
  2794. FLAG_ELSE = (1 << RES_ELSE ),
  2795. FLAG_FI = (1 << RES_FI ),
  2796. #endif
  2797. #if ENABLE_HUSH_LOOPS
  2798. FLAG_FOR = (1 << RES_FOR ),
  2799. FLAG_WHILE = (1 << RES_WHILE),
  2800. FLAG_UNTIL = (1 << RES_UNTIL),
  2801. FLAG_DO = (1 << RES_DO ),
  2802. FLAG_DONE = (1 << RES_DONE ),
  2803. FLAG_IN = (1 << RES_IN ),
  2804. #endif
  2805. #if ENABLE_HUSH_CASE
  2806. FLAG_MATCH = (1 << RES_MATCH),
  2807. FLAG_ESAC = (1 << RES_ESAC ),
  2808. #endif
  2809. FLAG_START = (1 << RES_XXXX ),
  2810. };
  2811. static const struct reserved_combo* match_reserved_word(o_string *word)
  2812. {
  2813. /* Mostly a list of accepted follow-up reserved words.
  2814. * FLAG_END means we are done with the sequence, and are ready
  2815. * to turn the compound list into a command.
  2816. * FLAG_START means the word must start a new compound list.
  2817. */
  2818. static const struct reserved_combo reserved_list[] = {
  2819. #if ENABLE_HUSH_IF
  2820. { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
  2821. { "if", RES_IF, WORD_IS_KEYWORD, FLAG_THEN | FLAG_START },
  2822. { "then", RES_THEN, WORD_IS_KEYWORD, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
  2823. { "elif", RES_ELIF, WORD_IS_KEYWORD, FLAG_THEN },
  2824. { "else", RES_ELSE, WORD_IS_KEYWORD, FLAG_FI },
  2825. { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
  2826. #endif
  2827. #if ENABLE_HUSH_LOOPS
  2828. { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
  2829. { "while", RES_WHILE, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
  2830. { "until", RES_UNTIL, WORD_IS_KEYWORD, FLAG_DO | FLAG_START },
  2831. { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
  2832. { "do", RES_DO, WORD_IS_KEYWORD, FLAG_DONE },
  2833. { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
  2834. #endif
  2835. #if ENABLE_HUSH_CASE
  2836. { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
  2837. { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
  2838. #endif
  2839. };
  2840. const struct reserved_combo *r;
  2841. for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
  2842. if (strcmp(word->data, r->literal) == 0)
  2843. return r;
  2844. }
  2845. return NULL;
  2846. }
  2847. static int reserved_word(o_string *word, struct parse_context *ctx)
  2848. {
  2849. #if ENABLE_HUSH_CASE
  2850. static const struct reserved_combo reserved_match = {
  2851. "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
  2852. };
  2853. #endif
  2854. const struct reserved_combo *r;
  2855. r = match_reserved_word(word);
  2856. if (!r)
  2857. return 0;
  2858. debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
  2859. #if ENABLE_HUSH_CASE
  2860. if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE)
  2861. /* "case word IN ..." - IN part starts first match part */
  2862. r = &reserved_match;
  2863. else
  2864. #endif
  2865. if (r->flag == 0) { /* '!' */
  2866. if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
  2867. syntax(NULL);
  2868. IF_HAS_KEYWORDS(ctx->ctx_res_w = RES_SNTX;)
  2869. }
  2870. ctx->ctx_inverted = 1;
  2871. return 1;
  2872. }
  2873. if (r->flag & FLAG_START) {
  2874. struct parse_context *new;
  2875. debug_printf("push stack\n");
  2876. new = xmalloc(sizeof(*new));
  2877. *new = *ctx; /* physical copy */
  2878. initialize_context(ctx);
  2879. ctx->stack = new;
  2880. } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
  2881. syntax(NULL);
  2882. ctx->ctx_res_w = RES_SNTX;
  2883. return 1;
  2884. }
  2885. ctx->ctx_res_w = r->res;
  2886. ctx->old_flag = r->flag;
  2887. if (ctx->old_flag & FLAG_END) {
  2888. struct parse_context *old;
  2889. debug_printf("pop stack\n");
  2890. done_pipe(ctx, PIPE_SEQ);
  2891. old = ctx->stack;
  2892. old->command->group = ctx->list_head;
  2893. old->command->grp_type = GRP_NORMAL;
  2894. *ctx = *old; /* physical copy */
  2895. free(old);
  2896. }
  2897. word->o_assignment = r->assignment_flag;
  2898. return 1;
  2899. }
  2900. #endif
  2901. //TODO: many, many callers don't check error from done_word()
  2902. /* Word is complete, look at it and update parsing context.
  2903. * Normal return is 0. Syntax errors return 1. */
  2904. static int done_word(o_string *word, struct parse_context *ctx)
  2905. {
  2906. struct command *command = ctx->command;
  2907. debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
  2908. if (word->length == 0 && word->nonnull == 0) {
  2909. debug_printf_parse("done_word return 0: true null, ignored\n");
  2910. return 0;
  2911. }
  2912. /* If this word wasn't an assignment, next ones definitely
  2913. * can't be assignments. Even if they look like ones. */
  2914. if (word->o_assignment != DEFINITELY_ASSIGNMENT
  2915. && word->o_assignment != WORD_IS_KEYWORD
  2916. ) {
  2917. word->o_assignment = NOT_ASSIGNMENT;
  2918. } else {
  2919. if (word->o_assignment == DEFINITELY_ASSIGNMENT)
  2920. command->assignment_cnt++;
  2921. word->o_assignment = MAYBE_ASSIGNMENT;
  2922. }
  2923. if (ctx->pending_redirect) {
  2924. /* We do not glob in e.g. >*.tmp case. bash seems to glob here
  2925. * only if run as "bash", not "sh" */
  2926. ctx->pending_redirect->rd_filename = xstrdup(word->data);
  2927. word->o_assignment = NOT_ASSIGNMENT;
  2928. debug_printf("word stored in rd_filename: '%s'\n", word->data);
  2929. } else {
  2930. /* "{ echo foo; } echo bar" - bad */
  2931. /* NB: bash allows e.g. "if true; then { echo foo; } fi". TODO? */
  2932. if (command->group) {
  2933. syntax(NULL);
  2934. debug_printf_parse("done_word return 1: syntax error, groups and arglists don't mix\n");
  2935. return 1;
  2936. }
  2937. #if HAS_KEYWORDS
  2938. #if ENABLE_HUSH_CASE
  2939. if (ctx->ctx_dsemicolon
  2940. && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
  2941. ) {
  2942. /* already done when ctx_dsemicolon was set to 1: */
  2943. /* ctx->ctx_res_w = RES_MATCH; */
  2944. ctx->ctx_dsemicolon = 0;
  2945. } else
  2946. #endif
  2947. if (!command->argv /* if it's the first word... */
  2948. #if ENABLE_HUSH_LOOPS
  2949. && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
  2950. && ctx->ctx_res_w != RES_IN
  2951. #endif
  2952. ) {
  2953. debug_printf_parse(": checking '%s' for reserved-ness\n", word->data);
  2954. if (reserved_word(word, ctx)) {
  2955. o_reset(word);
  2956. debug_printf_parse("done_word return %d\n", (ctx->ctx_res_w == RES_SNTX));
  2957. return (ctx->ctx_res_w == RES_SNTX);
  2958. }
  2959. }
  2960. #endif
  2961. if (word->nonnull /* word had "xx" or 'xx' at least as part of it. */
  2962. /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
  2963. && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
  2964. /* (otherwise it's known to be not empty and is already safe) */
  2965. ) {
  2966. /* exclude "$@" - it can expand to no word despite "" */
  2967. char *p = word->data;
  2968. while (p[0] == SPECIAL_VAR_SYMBOL
  2969. && (p[1] & 0x7f) == '@'
  2970. && p[2] == SPECIAL_VAR_SYMBOL
  2971. ) {
  2972. p += 3;
  2973. }
  2974. if (p == word->data || p[0] != '\0') {
  2975. /* saw no "$@", or not only "$@" but some
  2976. * real text is there too */
  2977. /* insert "empty variable" reference, this makes
  2978. * e.g. "", $empty"" etc to not disappear */
  2979. o_addchr(word, SPECIAL_VAR_SYMBOL);
  2980. o_addchr(word, SPECIAL_VAR_SYMBOL);
  2981. }
  2982. }
  2983. command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
  2984. debug_print_strings("word appended to argv", command->argv);
  2985. }
  2986. o_reset(word);
  2987. ctx->pending_redirect = NULL;
  2988. #if ENABLE_HUSH_LOOPS
  2989. /* Force FOR to have just one word (variable name) */
  2990. /* NB: basically, this makes hush see "for v in ..." syntax as if
  2991. * as it is "for v; in ...". FOR and IN become two pipe structs
  2992. * in parse tree. */
  2993. if (ctx->ctx_res_w == RES_FOR) {
  2994. //TODO: check that command->argv[0] is a valid variable name!
  2995. done_pipe(ctx, PIPE_SEQ);
  2996. }
  2997. #endif
  2998. #if ENABLE_HUSH_CASE
  2999. /* Force CASE to have just one word */
  3000. if (ctx->ctx_res_w == RES_CASE) {
  3001. done_pipe(ctx, PIPE_SEQ);
  3002. }
  3003. #endif
  3004. debug_printf_parse("done_word return 0\n");
  3005. return 0;
  3006. }
  3007. /* Command (member of a pipe) is complete. The only possible error here
  3008. * is out of memory, in which case xmalloc exits. */
  3009. static int done_command(struct parse_context *ctx)
  3010. {
  3011. /* The command is really already in the pipe structure, so
  3012. * advance the pipe counter and make a new, null command. */
  3013. struct pipe *pi = ctx->pipe;
  3014. struct command *command = ctx->command;
  3015. if (command) {
  3016. if (command->group == NULL
  3017. && command->argv == NULL
  3018. && command->redirects == NULL
  3019. ) {
  3020. debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
  3021. return pi->num_cmds;
  3022. }
  3023. pi->num_cmds++;
  3024. debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
  3025. } else {
  3026. debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
  3027. }
  3028. /* Only real trickiness here is that the uncommitted
  3029. * command structure is not counted in pi->num_cmds. */
  3030. pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
  3031. command = &pi->cmds[pi->num_cmds];
  3032. memset(command, 0, sizeof(*command));
  3033. ctx->command = command;
  3034. /* but ctx->pipe and ctx->list_head remain unchanged */
  3035. return pi->num_cmds; /* used only for 0/nonzero check */
  3036. }
  3037. static void done_pipe(struct parse_context *ctx, pipe_style type)
  3038. {
  3039. int not_null;
  3040. debug_printf_parse("done_pipe entered, followup %d\n", type);
  3041. /* Close previous command */
  3042. not_null = done_command(ctx);
  3043. ctx->pipe->followup = type;
  3044. IF_HAS_KEYWORDS(ctx->pipe->pi_inverted = ctx->ctx_inverted;)
  3045. IF_HAS_KEYWORDS(ctx->ctx_inverted = 0;)
  3046. IF_HAS_KEYWORDS(ctx->pipe->res_word = ctx->ctx_res_w;)
  3047. /* Without this check, even just <enter> on command line generates
  3048. * tree of three NOPs (!). Which is harmless but annoying.
  3049. * IOW: it is safe to do it unconditionally.
  3050. * RES_NONE case is for "for a in; do ..." (empty IN set)
  3051. * to work, possibly other cases too. */
  3052. if (not_null IF_HAS_KEYWORDS(|| ctx->ctx_res_w != RES_NONE)) {
  3053. struct pipe *new_p;
  3054. debug_printf_parse("done_pipe: adding new pipe: "
  3055. "not_null:%d ctx->ctx_res_w:%d\n",
  3056. not_null, ctx->ctx_res_w);
  3057. new_p = new_pipe();
  3058. ctx->pipe->next = new_p;
  3059. ctx->pipe = new_p;
  3060. ctx->command = NULL; /* needed! */
  3061. /* RES_THEN, RES_DO etc are "sticky" -
  3062. * they remain set for commands inside if/while.
  3063. * This is used to control execution.
  3064. * RES_FOR and RES_IN are NOT sticky (needed to support
  3065. * cases where variable or value happens to match a keyword):
  3066. */
  3067. #if ENABLE_HUSH_LOOPS
  3068. if (ctx->ctx_res_w == RES_FOR
  3069. || ctx->ctx_res_w == RES_IN)
  3070. ctx->ctx_res_w = RES_NONE;
  3071. #endif
  3072. #if ENABLE_HUSH_CASE
  3073. if (ctx->ctx_res_w == RES_MATCH)
  3074. ctx->ctx_res_w = RES_CASEI;
  3075. #endif
  3076. /* Create the memory for command, roughly:
  3077. * ctx->pipe->cmds = new struct command;
  3078. * ctx->command = &ctx->pipe->cmds[0];
  3079. */
  3080. done_command(ctx);
  3081. }
  3082. debug_printf_parse("done_pipe return\n");
  3083. }
  3084. /* Peek ahead in the in_str to find out if we have a "&n" construct,
  3085. * as in "2>&1", that represents duplicating a file descriptor.
  3086. * Return either -2 (syntax error), -1 (no &), or the number found.
  3087. */
  3088. static int redirect_dup_num(struct in_str *input)
  3089. {
  3090. int ch, d = 0, ok = 0;
  3091. ch = i_peek(input);
  3092. if (ch != '&') return -1;
  3093. i_getch(input); /* get the & */
  3094. ch = i_peek(input);
  3095. if (ch == '-') {
  3096. i_getch(input);
  3097. return -3; /* "-" represents "close me" */
  3098. }
  3099. while (isdigit(ch)) {
  3100. d = d*10 + (ch-'0');
  3101. ok = 1;
  3102. i_getch(input);
  3103. ch = i_peek(input);
  3104. }
  3105. if (ok) return d;
  3106. bb_error_msg("ambiguous redirect");
  3107. return -2;
  3108. }
  3109. /* If a redirect is immediately preceded by a number, that number is
  3110. * supposed to tell which file descriptor to redirect. This routine
  3111. * looks for such preceding numbers. In an ideal world this routine
  3112. * needs to handle all the following classes of redirects...
  3113. * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
  3114. * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
  3115. * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
  3116. * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
  3117. * A -1 output from this program means no valid number was found, so the
  3118. * caller should use the appropriate default for this redirection.
  3119. */
  3120. static int redirect_opt_num(o_string *o)
  3121. {
  3122. int num;
  3123. if (o->length == 0)
  3124. return -1;
  3125. for (num = 0; num < o->length; num++) {
  3126. if (!isdigit(o->data[num])) {
  3127. return -1;
  3128. }
  3129. }
  3130. num = atoi(o->data);
  3131. o_reset(o);
  3132. return num;
  3133. }
  3134. #if ENABLE_HUSH_TICK
  3135. static FILE *generate_stream_from_list(struct pipe *head)
  3136. {
  3137. FILE *pf;
  3138. int pid, channel[2];
  3139. xpipe(channel);
  3140. /* *** NOMMU WARNING *** */
  3141. /* By using vfork here, we suspend parent till child exits or execs.
  3142. * If child will not do it before it fills the pipe, it can block forever
  3143. * in write(STDOUT_FILENO), and parent (shell) will be also stuck.
  3144. * Try this script:
  3145. * yes "0123456789012345678901234567890" | dd bs=32 count=64k >TESTFILE
  3146. * huge=`cat TESTFILE` # will block here forever
  3147. * echo OK
  3148. */
  3149. pid = BB_MMU ? fork() : vfork();
  3150. if (pid < 0)
  3151. bb_perror_msg_and_die(BB_MMU ? "fork" : "vfork");
  3152. if (pid == 0) { /* child */
  3153. if (ENABLE_HUSH_JOB)
  3154. die_sleep = 0; /* let nofork's xfuncs die */
  3155. close(channel[0]); /* NB: close _first_, then move fd! */
  3156. xmove_fd(channel[1], 1);
  3157. /* Prevent it from trying to handle ctrl-z etc */
  3158. #if ENABLE_HUSH_JOB
  3159. G.run_list_level = 1;
  3160. #endif
  3161. /* Process substitution is not considered to be usual
  3162. * 'command execution'.
  3163. * SUSv3 says ctrl-Z should be ignored, ctrl-C should not. */
  3164. /* Not needed, we are relying on it being disabled
  3165. * everywhere outside actual command execution. */
  3166. /*set_jobctrl_sighandler(SIG_IGN);*/
  3167. set_misc_sighandler(SIG_DFL);
  3168. /* Freeing 'head' here would break NOMMU. */
  3169. _exit(run_list(head));
  3170. }
  3171. close(channel[1]);
  3172. pf = fdopen(channel[0], "r");
  3173. return pf;
  3174. /* 'head' is freed by the caller */
  3175. }
  3176. /* Return code is exit status of the process that is run. */
  3177. static int process_command_subs(o_string *dest,
  3178. struct in_str *input,
  3179. const char *subst_end)
  3180. {
  3181. int retcode, ch, eol_cnt;
  3182. o_string result = NULL_O_STRING;
  3183. struct parse_context inner;
  3184. FILE *p;
  3185. struct in_str pipe_str;
  3186. initialize_context(&inner);
  3187. /* Recursion to generate command */
  3188. retcode = parse_stream(&result, &inner, input, subst_end);
  3189. if (retcode != 0)
  3190. return retcode; /* syntax error or EOF */
  3191. done_word(&result, &inner);
  3192. done_pipe(&inner, PIPE_SEQ);
  3193. o_free(&result);
  3194. p = generate_stream_from_list(inner.list_head);
  3195. if (p == NULL)
  3196. return 1;
  3197. close_on_exec_on(fileno(p));
  3198. setup_file_in_str(&pipe_str, p);
  3199. /* Now send results of command back into original context */
  3200. eol_cnt = 0;
  3201. while ((ch = i_getch(&pipe_str)) != EOF) {
  3202. if (ch == '\n') {
  3203. eol_cnt++;
  3204. continue;
  3205. }
  3206. while (eol_cnt) {
  3207. o_addchr(dest, '\n');
  3208. eol_cnt--;
  3209. }
  3210. o_addQchr(dest, ch);
  3211. }
  3212. debug_printf("done reading from pipe, pclose()ing\n");
  3213. /* This is the step that wait()s for the child. Should be pretty
  3214. * safe, since we just read an EOF from its stdout. We could try
  3215. * to do better, by using wait(), and keeping track of background jobs
  3216. * at the same time. That would be a lot of work, and contrary
  3217. * to the KISS philosophy of this program. */
  3218. retcode = fclose(p);
  3219. free_pipe_list(inner.list_head, /* indent: */ 0);
  3220. debug_printf("closed FILE from child, retcode=%d\n", retcode);
  3221. return retcode;
  3222. }
  3223. #endif
  3224. static int parse_group(o_string *dest, struct parse_context *ctx,
  3225. struct in_str *input, int ch)
  3226. {
  3227. /* dest contains characters seen prior to ( or {.
  3228. * Typically it's empty, but for functions defs,
  3229. * it contains function name (without '()'). */
  3230. int rcode;
  3231. const char *endch = NULL;
  3232. struct parse_context sub;
  3233. struct command *command = ctx->command;
  3234. debug_printf_parse("parse_group entered\n");
  3235. #if ENABLE_HUSH_FUNCTIONS
  3236. if (ch == 'F') { /* function definition? */
  3237. bb_error_msg("aha '%s' is a function, parsing it...", dest->data);
  3238. //command->fname = dest->data;
  3239. command->grp_type = GRP_FUNCTION;
  3240. //TODO: review every o_reset() location... do they handle all o_string fields correctly?
  3241. memset(dest, 0, sizeof(*dest));
  3242. }
  3243. #endif
  3244. if (command->argv /* word [word](... */
  3245. || dest->length /* word(... */
  3246. || dest->nonnull /* ""(... */
  3247. ) {
  3248. syntax(NULL);
  3249. debug_printf_parse("parse_group return 1: syntax error, groups and arglists don't mix\n");
  3250. return 1;
  3251. }
  3252. initialize_context(&sub);
  3253. endch = "}";
  3254. if (ch == '(') {
  3255. endch = ")";
  3256. command->grp_type = GRP_SUBSHELL;
  3257. }
  3258. rcode = parse_stream(dest, &sub, input, endch);
  3259. if (rcode == 0) {
  3260. done_word(dest, &sub); /* finish off the final word in the subcontext */
  3261. done_pipe(&sub, PIPE_SEQ); /* and the final command there, too */
  3262. command->group = sub.list_head;
  3263. }
  3264. debug_printf_parse("parse_group return %d\n", rcode);
  3265. return rcode;
  3266. /* command remains "open", available for possible redirects */
  3267. }
  3268. /* Basically useful version until someone wants to get fancier,
  3269. * see the bash man page under "Parameter Expansion" */
  3270. static const char *lookup_param(const char *src)
  3271. {
  3272. struct variable *var = get_local_var(src);
  3273. if (var)
  3274. return strchr(var->varstr, '=') + 1;
  3275. return NULL;
  3276. }
  3277. #if ENABLE_HUSH_TICK
  3278. /* Subroutines for copying $(...) and `...` things */
  3279. static void add_till_backquote(o_string *dest, struct in_str *input);
  3280. /* '...' */
  3281. static void add_till_single_quote(o_string *dest, struct in_str *input)
  3282. {
  3283. while (1) {
  3284. int ch = i_getch(input);
  3285. if (ch == EOF)
  3286. break;
  3287. if (ch == '\'')
  3288. break;
  3289. o_addchr(dest, ch);
  3290. }
  3291. }
  3292. /* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
  3293. static void add_till_double_quote(o_string *dest, struct in_str *input)
  3294. {
  3295. while (1) {
  3296. int ch = i_getch(input);
  3297. if (ch == '"')
  3298. break;
  3299. if (ch == '\\') { /* \x. Copy both chars. */
  3300. o_addchr(dest, ch);
  3301. ch = i_getch(input);
  3302. }
  3303. if (ch == EOF)
  3304. break;
  3305. o_addchr(dest, ch);
  3306. if (ch == '`') {
  3307. add_till_backquote(dest, input);
  3308. o_addchr(dest, ch);
  3309. continue;
  3310. }
  3311. //if (ch == '$') ...
  3312. }
  3313. }
  3314. /* Process `cmd` - copy contents until "`" is seen. Complicated by
  3315. * \` quoting.
  3316. * "Within the backquoted style of command substitution, backslash
  3317. * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
  3318. * The search for the matching backquote shall be satisfied by the first
  3319. * backquote found without a preceding backslash; during this search,
  3320. * if a non-escaped backquote is encountered within a shell comment,
  3321. * a here-document, an embedded command substitution of the $(command)
  3322. * form, or a quoted string, undefined results occur. A single-quoted
  3323. * or double-quoted string that begins, but does not end, within the
  3324. * "`...`" sequence produces undefined results."
  3325. * Example Output
  3326. * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
  3327. */
  3328. static void add_till_backquote(o_string *dest, struct in_str *input)
  3329. {
  3330. while (1) {
  3331. int ch = i_getch(input);
  3332. if (ch == '`')
  3333. break;
  3334. if (ch == '\\') { /* \x. Copy both chars unless it is \` */
  3335. int ch2 = i_getch(input);
  3336. if (ch2 != '`' && ch2 != '$' && ch2 != '\\')
  3337. o_addchr(dest, ch);
  3338. ch = ch2;
  3339. }
  3340. if (ch == EOF)
  3341. break;
  3342. o_addchr(dest, ch);
  3343. }
  3344. }
  3345. /* Process $(cmd) - copy contents until ")" is seen. Complicated by
  3346. * quoting and nested ()s.
  3347. * "With the $(command) style of command substitution, all characters
  3348. * following the open parenthesis to the matching closing parenthesis
  3349. * constitute the command. Any valid shell script can be used for command,
  3350. * except a script consisting solely of redirections which produces
  3351. * unspecified results."
  3352. * Example Output
  3353. * echo $(echo '(TEST)' BEST) (TEST) BEST
  3354. * echo $(echo 'TEST)' BEST) TEST) BEST
  3355. * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
  3356. */
  3357. static void add_till_closing_curly_brace(o_string *dest, struct in_str *input)
  3358. {
  3359. int count = 0;
  3360. while (1) {
  3361. int ch = i_getch(input);
  3362. if (ch == EOF)
  3363. break;
  3364. if (ch == '(')
  3365. count++;
  3366. if (ch == ')')
  3367. if (--count < 0)
  3368. break;
  3369. o_addchr(dest, ch);
  3370. if (ch == '\'') {
  3371. add_till_single_quote(dest, input);
  3372. o_addchr(dest, ch);
  3373. continue;
  3374. }
  3375. if (ch == '"') {
  3376. add_till_double_quote(dest, input);
  3377. o_addchr(dest, ch);
  3378. continue;
  3379. }
  3380. if (ch == '\\') { /* \x. Copy verbatim. Important for \(, \) */
  3381. ch = i_getch(input);
  3382. if (ch == EOF)
  3383. break;
  3384. o_addchr(dest, ch);
  3385. continue;
  3386. }
  3387. }
  3388. }
  3389. #endif /* ENABLE_HUSH_TICK */
  3390. /* Return code: 0 for OK, 1 for syntax error */
  3391. static int handle_dollar(o_string *dest, struct in_str *input)
  3392. {
  3393. int ch = i_peek(input); /* first character after the $ */
  3394. unsigned char quote_mask = dest->o_quote ? 0x80 : 0;
  3395. debug_printf_parse("handle_dollar entered: ch='%c'\n", ch);
  3396. if (isalpha(ch)) {
  3397. i_getch(input);
  3398. make_var:
  3399. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  3400. while (1) {
  3401. debug_printf_parse(": '%c'\n", ch);
  3402. o_addchr(dest, ch | quote_mask);
  3403. quote_mask = 0;
  3404. ch = i_peek(input);
  3405. if (!isalnum(ch) && ch != '_')
  3406. break;
  3407. i_getch(input);
  3408. }
  3409. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  3410. } else if (isdigit(ch)) {
  3411. make_one_char_var:
  3412. i_getch(input);
  3413. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  3414. debug_printf_parse(": '%c'\n", ch);
  3415. o_addchr(dest, ch | quote_mask);
  3416. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  3417. } else switch (ch) {
  3418. case '$': /* pid */
  3419. case '!': /* last bg pid */
  3420. case '?': /* last exit code */
  3421. case '#': /* number of args */
  3422. case '*': /* args */
  3423. case '@': /* args */
  3424. goto make_one_char_var;
  3425. case '{':
  3426. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  3427. i_getch(input);
  3428. /* XXX maybe someone will try to escape the '}' */
  3429. while (1) {
  3430. ch = i_getch(input);
  3431. if (ch == '}')
  3432. break;
  3433. if (!isalnum(ch) && ch != '_') {
  3434. syntax("unterminated ${name}");
  3435. debug_printf_parse("handle_dollar return 1: unterminated ${name}\n");
  3436. return 1;
  3437. }
  3438. debug_printf_parse(": '%c'\n", ch);
  3439. o_addchr(dest, ch | quote_mask);
  3440. quote_mask = 0;
  3441. }
  3442. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  3443. break;
  3444. #if ENABLE_HUSH_TICK
  3445. case '(': {
  3446. //int pos = dest->length;
  3447. i_getch(input);
  3448. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  3449. o_addchr(dest, quote_mask | '`');
  3450. add_till_closing_curly_brace(dest, input);
  3451. //debug_printf_subst("SUBST RES2 '%s'\n", dest->data + pos);
  3452. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  3453. break;
  3454. }
  3455. #endif
  3456. case '_':
  3457. i_getch(input);
  3458. ch = i_peek(input);
  3459. if (isalnum(ch)) { /* it's $_name or $_123 */
  3460. ch = '_';
  3461. goto make_var;
  3462. }
  3463. /* else: it's $_ */
  3464. case '-':
  3465. /* still unhandled, but should be eventually */
  3466. bb_error_msg("unhandled syntax: $%c", ch);
  3467. return 1;
  3468. break;
  3469. default:
  3470. o_addQchr(dest, '$');
  3471. }
  3472. debug_printf_parse("handle_dollar return 0\n");
  3473. return 0;
  3474. }
  3475. /* Scan input, call done_word() whenever full IFS delimited word was seen.
  3476. * Call done_pipe if '\n' was seen (and end_trigger != NULL).
  3477. * Return code is 0 if end_trigger char is met,
  3478. * -1 on EOF (but if end_trigger == NULL then return 0),
  3479. * 1 for syntax error */
  3480. static int parse_stream(o_string *dest, struct parse_context *ctx,
  3481. struct in_str *input, const char *end_trigger)
  3482. {
  3483. int ch, m;
  3484. int redir_fd;
  3485. redir_type redir_style;
  3486. int shadow_quote = dest->o_quote;
  3487. int next;
  3488. /* Only double-quote state is handled in the state variable dest->o_quote.
  3489. * A single-quote triggers a bypass of the main loop until its mate is
  3490. * found. When recursing, quote state is passed in via dest->o_quote. */
  3491. debug_printf_parse("parse_stream entered, end_trigger='%s' dest->o_assignment:%d\n", end_trigger, dest->o_assignment);
  3492. while (1) {
  3493. m = CHAR_IFS;
  3494. next = '\0';
  3495. ch = i_getch(input);
  3496. if (ch != EOF) {
  3497. m = G.charmap[ch];
  3498. if (ch != '\n') {
  3499. next = i_peek(input);
  3500. }
  3501. }
  3502. debug_printf_parse(": ch=%c (%d) m=%d quote=%d\n",
  3503. ch, ch, m, dest->o_quote);
  3504. if (m == CHAR_ORDINARY
  3505. || (m != CHAR_SPECIAL && shadow_quote)
  3506. ) {
  3507. if (ch == EOF) {
  3508. syntax("unterminated \"");
  3509. debug_printf_parse("parse_stream return 1: unterminated \"\n");
  3510. return 1;
  3511. }
  3512. o_addQchr(dest, ch);
  3513. if ((dest->o_assignment == MAYBE_ASSIGNMENT
  3514. || dest->o_assignment == WORD_IS_KEYWORD)
  3515. && ch == '='
  3516. && is_assignment(dest->data)
  3517. ) {
  3518. dest->o_assignment = DEFINITELY_ASSIGNMENT;
  3519. }
  3520. continue;
  3521. }
  3522. if (m == CHAR_IFS) {
  3523. if (done_word(dest, ctx)) {
  3524. debug_printf_parse("parse_stream return 1: done_word!=0\n");
  3525. return 1;
  3526. }
  3527. if (ch == EOF)
  3528. break;
  3529. /* If we aren't performing a substitution, treat
  3530. * a newline as a command separator.
  3531. * [why we don't handle it exactly like ';'? --vda] */
  3532. if (end_trigger && ch == '\n') {
  3533. #if ENABLE_HUSH_CASE
  3534. /* "case ... in <newline> word) ..." -
  3535. * newlines are ignored (but ';' wouldn't be) */
  3536. if (dest->length == 0 // && argv[0] == NULL
  3537. && ctx->ctx_res_w == RES_MATCH
  3538. ) {
  3539. continue;
  3540. }
  3541. #endif
  3542. done_pipe(ctx, PIPE_SEQ);
  3543. dest->o_assignment = MAYBE_ASSIGNMENT;
  3544. }
  3545. }
  3546. if (end_trigger) {
  3547. if (!shadow_quote && strchr(end_trigger, ch)) {
  3548. /* Special case: (...word) makes last word terminate,
  3549. * as if ';' is seen */
  3550. if (ch == ')') {
  3551. done_word(dest, ctx);
  3552. //err chk?
  3553. done_pipe(ctx, PIPE_SEQ);
  3554. dest->o_assignment = MAYBE_ASSIGNMENT;
  3555. }
  3556. if (!HAS_KEYWORDS
  3557. IF_HAS_KEYWORDS(|| (ctx->ctx_res_w == RES_NONE && ctx->old_flag == 0))
  3558. ) {
  3559. debug_printf_parse("parse_stream return 0: end_trigger char found\n");
  3560. return 0;
  3561. }
  3562. }
  3563. }
  3564. if (m == CHAR_IFS)
  3565. continue;
  3566. if (dest->o_assignment == MAYBE_ASSIGNMENT) {
  3567. /* ch is a special char and thus this word
  3568. * cannot be an assignment: */
  3569. dest->o_assignment = NOT_ASSIGNMENT;
  3570. }
  3571. switch (ch) {
  3572. case '#':
  3573. if (dest->length == 0 && !shadow_quote) {
  3574. while (1) {
  3575. ch = i_peek(input);
  3576. if (ch == EOF || ch == '\n')
  3577. break;
  3578. i_getch(input);
  3579. }
  3580. } else {
  3581. o_addQchr(dest, ch);
  3582. }
  3583. break;
  3584. case '\\':
  3585. if (next == EOF) {
  3586. syntax("\\<eof>");
  3587. debug_printf_parse("parse_stream return 1: \\<eof>\n");
  3588. return 1;
  3589. }
  3590. /* bash:
  3591. * "The backslash retains its special meaning [in "..."]
  3592. * only when followed by one of the following characters:
  3593. * $, `, ", \, or <newline>. A double quote may be quoted
  3594. * within double quotes by preceding it with a backslash.
  3595. * If enabled, history expansion will be performed unless
  3596. * an ! appearing in double quotes is escaped using
  3597. * a backslash. The backslash preceding the ! is not removed."
  3598. */
  3599. if (shadow_quote) { //NOT SURE dest->o_quote) {
  3600. if (strchr("$`\"\\", next) != NULL) {
  3601. o_addqchr(dest, i_getch(input));
  3602. } else {
  3603. o_addqchr(dest, '\\');
  3604. }
  3605. } else {
  3606. o_addchr(dest, '\\');
  3607. o_addchr(dest, i_getch(input));
  3608. }
  3609. break;
  3610. case '$':
  3611. if (handle_dollar(dest, input) != 0) {
  3612. debug_printf_parse("parse_stream return 1: handle_dollar returned non-0\n");
  3613. return 1;
  3614. }
  3615. break;
  3616. case '\'':
  3617. dest->nonnull = 1;
  3618. while (1) {
  3619. ch = i_getch(input);
  3620. if (ch == EOF) {
  3621. syntax("unterminated '");
  3622. debug_printf_parse("parse_stream return 1: unterminated '\n");
  3623. return 1;
  3624. }
  3625. if (ch == '\'')
  3626. break;
  3627. if (dest->o_assignment == NOT_ASSIGNMENT)
  3628. o_addqchr(dest, ch);
  3629. else
  3630. o_addchr(dest, ch);
  3631. }
  3632. break;
  3633. case '"':
  3634. dest->nonnull = 1;
  3635. shadow_quote ^= 1; /* invert */
  3636. if (dest->o_assignment == NOT_ASSIGNMENT)
  3637. dest->o_quote ^= 1;
  3638. break;
  3639. #if ENABLE_HUSH_TICK
  3640. case '`': {
  3641. //int pos = dest->length;
  3642. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  3643. o_addchr(dest, shadow_quote /*or dest->o_quote??*/ ? 0x80 | '`' : '`');
  3644. add_till_backquote(dest, input);
  3645. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  3646. //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
  3647. break;
  3648. }
  3649. #endif
  3650. case '>':
  3651. redir_fd = redirect_opt_num(dest);
  3652. done_word(dest, ctx);
  3653. redir_style = REDIRECT_OVERWRITE;
  3654. if (next == '>') {
  3655. redir_style = REDIRECT_APPEND;
  3656. i_getch(input);
  3657. }
  3658. #if 0
  3659. else if (next == '(') {
  3660. syntax(">(process) not supported");
  3661. debug_printf_parse("parse_stream return 1: >(process) not supported\n");
  3662. return 1;
  3663. }
  3664. #endif
  3665. setup_redirect(ctx, redir_fd, redir_style, input);
  3666. break;
  3667. case '<':
  3668. redir_fd = redirect_opt_num(dest);
  3669. done_word(dest, ctx);
  3670. redir_style = REDIRECT_INPUT;
  3671. if (next == '<') {
  3672. redir_style = REDIRECT_HEREIS;
  3673. i_getch(input);
  3674. } else if (next == '>') {
  3675. redir_style = REDIRECT_IO;
  3676. i_getch(input);
  3677. }
  3678. #if 0
  3679. else if (next == '(') {
  3680. syntax("<(process) not supported");
  3681. debug_printf_parse("parse_stream return 1: <(process) not supported\n");
  3682. return 1;
  3683. }
  3684. #endif
  3685. setup_redirect(ctx, redir_fd, redir_style, input);
  3686. break;
  3687. case ';':
  3688. #if ENABLE_HUSH_CASE
  3689. case_semi:
  3690. #endif
  3691. done_word(dest, ctx);
  3692. done_pipe(ctx, PIPE_SEQ);
  3693. #if ENABLE_HUSH_CASE
  3694. /* Eat multiple semicolons, detect
  3695. * whether it means something special */
  3696. while (1) {
  3697. ch = i_peek(input);
  3698. if (ch != ';')
  3699. break;
  3700. i_getch(input);
  3701. if (ctx->ctx_res_w == RES_CASEI) {
  3702. ctx->ctx_dsemicolon = 1;
  3703. ctx->ctx_res_w = RES_MATCH;
  3704. break;
  3705. }
  3706. }
  3707. #endif
  3708. new_cmd:
  3709. /* We just finished a cmd. New one may start
  3710. * with an assignment */
  3711. dest->o_assignment = MAYBE_ASSIGNMENT;
  3712. break;
  3713. case '&':
  3714. done_word(dest, ctx);
  3715. if (next == '&') {
  3716. i_getch(input);
  3717. done_pipe(ctx, PIPE_AND);
  3718. } else {
  3719. done_pipe(ctx, PIPE_BG);
  3720. }
  3721. goto new_cmd;
  3722. case '|':
  3723. done_word(dest, ctx);
  3724. #if ENABLE_HUSH_CASE
  3725. if (ctx->ctx_res_w == RES_MATCH)
  3726. break; /* we are in case's "word | word)" */
  3727. #endif
  3728. if (next == '|') { /* || */
  3729. i_getch(input);
  3730. done_pipe(ctx, PIPE_OR);
  3731. } else {
  3732. /* we could pick up a file descriptor choice here
  3733. * with redirect_opt_num(), but bash doesn't do it.
  3734. * "echo foo 2| cat" yields "foo 2". */
  3735. done_command(ctx);
  3736. }
  3737. goto new_cmd;
  3738. case '(':
  3739. #if ENABLE_HUSH_CASE
  3740. /* "case... in [(]word)..." - skip '(' */
  3741. if (ctx->ctx_res_w == RES_MATCH
  3742. && ctx->command->argv == NULL /* not (word|(... */
  3743. && dest->length == 0 /* not word(... */
  3744. && dest->nonnull == 0 /* not ""(... */
  3745. ) {
  3746. continue;
  3747. }
  3748. #endif
  3749. #if ENABLE_HUSH_FUNCTIONS
  3750. if (dest->length != 0 /* not just () but word() */
  3751. && dest->nonnull == 0 /* not a"b"c() */
  3752. && ctx->command->argv == NULL /* it's the first word */
  3753. //TODO: "func ( ) {...}" - note spaces - is valid format too in bash
  3754. && i_peek(input) == ')'
  3755. && !match_reserved_word(dest)
  3756. ) {
  3757. bb_error_msg("seems like a function definition");
  3758. i_getch(input);
  3759. do {
  3760. //TODO: do it properly.
  3761. ch = i_getch(input);
  3762. } while (ch == ' ' || ch == '\n');
  3763. if (ch != '{') {
  3764. syntax("was expecting {");
  3765. debug_printf_parse("parse_stream return 1\n");
  3766. return 1;
  3767. }
  3768. ch = 'F'; /* magic value */
  3769. }
  3770. #endif
  3771. case '{':
  3772. if (parse_group(dest, ctx, input, ch) != 0) {
  3773. debug_printf_parse("parse_stream return 1: parse_group returned non-0\n");
  3774. return 1;
  3775. }
  3776. goto new_cmd;
  3777. case ')':
  3778. #if ENABLE_HUSH_CASE
  3779. if (ctx->ctx_res_w == RES_MATCH)
  3780. goto case_semi;
  3781. #endif
  3782. case '}':
  3783. /* proper use of this character is caught by end_trigger:
  3784. * if we see {, we call parse_group(..., end_trigger='}')
  3785. * and it will match } earlier (not here). */
  3786. syntax("unexpected } or )");
  3787. debug_printf_parse("parse_stream return 1: unexpected '}'\n");
  3788. return 1;
  3789. default:
  3790. if (HUSH_DEBUG)
  3791. bb_error_msg_and_die("BUG: unexpected %c\n", ch);
  3792. }
  3793. } /* while (1) */
  3794. debug_printf_parse("parse_stream return %d\n", -(end_trigger != NULL));
  3795. if (end_trigger)
  3796. return -1;
  3797. return 0;
  3798. }
  3799. static void set_in_charmap(const char *set, int code)
  3800. {
  3801. while (*set)
  3802. G.charmap[(unsigned char)*set++] = code;
  3803. }
  3804. static void update_charmap(void)
  3805. {
  3806. G.ifs = getenv("IFS");
  3807. if (G.ifs == NULL)
  3808. G.ifs = " \t\n";
  3809. /* Precompute a list of 'flow through' behavior so it can be treated
  3810. * quickly up front. Computation is necessary because of IFS.
  3811. * Special case handling of IFS == " \t\n" is not implemented.
  3812. * The charmap[] array only really needs two bits each,
  3813. * and on most machines that would be faster (reduced L1 cache use).
  3814. */
  3815. memset(G.charmap, CHAR_ORDINARY, sizeof(G.charmap));
  3816. #if ENABLE_HUSH_TICK
  3817. set_in_charmap("\\$\"`", CHAR_SPECIAL);
  3818. #else
  3819. set_in_charmap("\\$\"", CHAR_SPECIAL);
  3820. #endif
  3821. set_in_charmap("<>;&|(){}#'", CHAR_ORDINARY_IF_QUOTED);
  3822. set_in_charmap(G.ifs, CHAR_IFS); /* are ordinary if quoted */
  3823. }
  3824. /* Most recursion does not come through here, the exception is
  3825. * from builtin_source() and builtin_eval() */
  3826. static int parse_and_run_stream(struct in_str *inp, int parse_flag)
  3827. {
  3828. struct parse_context ctx;
  3829. o_string temp = NULL_O_STRING;
  3830. int rcode;
  3831. do {
  3832. initialize_context(&ctx);
  3833. update_charmap();
  3834. #if ENABLE_HUSH_INTERACTIVE
  3835. inp->promptmode = 0; /* PS1 */
  3836. #endif
  3837. /* We will stop & execute after each ';' or '\n'.
  3838. * Example: "sleep 9999; echo TEST" + ctrl-C:
  3839. * TEST should be printed */
  3840. temp.o_assignment = MAYBE_ASSIGNMENT;
  3841. rcode = parse_stream(&temp, &ctx, inp, ";\n");
  3842. #if HAS_KEYWORDS
  3843. if (rcode != 1 && ctx.old_flag != 0) {
  3844. syntax(NULL);
  3845. }
  3846. #endif
  3847. if (rcode != 1 IF_HAS_KEYWORDS(&& ctx.old_flag == 0)) {
  3848. done_word(&temp, &ctx);
  3849. done_pipe(&ctx, PIPE_SEQ);
  3850. debug_print_tree(ctx.list_head, 0);
  3851. debug_printf_exec("parse_stream_outer: run_and_free_list\n");
  3852. run_and_free_list(ctx.list_head);
  3853. } else {
  3854. /* We arrive here also if rcode == 1 (error in parse_stream) */
  3855. #if HAS_KEYWORDS
  3856. if (ctx.old_flag != 0) {
  3857. free(ctx.stack);
  3858. o_reset(&temp);
  3859. }
  3860. #endif
  3861. /*temp.nonnull = 0; - o_free does it below */
  3862. /*temp.o_quote = 0; - o_free does it below */
  3863. free_pipe_list(ctx.list_head, /* indent: */ 0);
  3864. /* Discard all unprocessed line input, force prompt on */
  3865. inp->p = NULL;
  3866. #if ENABLE_HUSH_INTERACTIVE
  3867. inp->promptme = 1;
  3868. #endif
  3869. }
  3870. o_free(&temp);
  3871. /* loop on syntax errors, return on EOF: */
  3872. } while (rcode != -1 && !(parse_flag & PARSEFLAG_EXIT_FROM_LOOP));
  3873. return 0;
  3874. }
  3875. static int parse_and_run_string(const char *s, int parse_flag)
  3876. {
  3877. struct in_str input;
  3878. setup_string_in_str(&input, s);
  3879. return parse_and_run_stream(&input, parse_flag);
  3880. }
  3881. static int parse_and_run_file(FILE *f)
  3882. {
  3883. int rcode;
  3884. struct in_str input;
  3885. setup_file_in_str(&input, f);
  3886. rcode = parse_and_run_stream(&input, 0 /* parse_flag */);
  3887. return rcode;
  3888. }
  3889. #if ENABLE_HUSH_JOB
  3890. /* Make sure we have a controlling tty. If we get started under a job
  3891. * aware app (like bash for example), make sure we are now in charge so
  3892. * we don't fight over who gets the foreground */
  3893. static void setup_job_control(void)
  3894. {
  3895. pid_t shell_pgrp;
  3896. shell_pgrp = getpgrp();
  3897. close_on_exec_on(G.interactive_fd);
  3898. /* If we were ran as 'hush &',
  3899. * sleep until we are in the foreground. */
  3900. while (tcgetpgrp(G.interactive_fd) != shell_pgrp) {
  3901. /* Send TTIN to ourself (should stop us) */
  3902. kill(- shell_pgrp, SIGTTIN);
  3903. shell_pgrp = getpgrp();
  3904. }
  3905. /* Ignore job-control and misc signals. */
  3906. set_jobctrl_sighandler(SIG_IGN);
  3907. set_misc_sighandler(SIG_IGN);
  3908. //huh? signal(SIGCHLD, SIG_IGN);
  3909. /* We _must_ restore tty pgrp on fatal signals */
  3910. set_fatal_sighandler(sigexit);
  3911. /* Put ourselves in our own process group. */
  3912. bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
  3913. /* Grab control of the terminal. */
  3914. tcsetpgrp(G.interactive_fd, getpid());
  3915. }
  3916. #endif
  3917. int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  3918. int hush_main(int argc, char **argv)
  3919. {
  3920. static const struct variable const_shell_ver = {
  3921. .next = NULL,
  3922. .varstr = (char*)hush_version_str,
  3923. .max_len = 1, /* 0 can provoke free(name) */
  3924. .flg_export = 1,
  3925. .flg_read_only = 1,
  3926. };
  3927. int opt;
  3928. FILE *input;
  3929. char **e;
  3930. struct variable *cur_var;
  3931. INIT_G();
  3932. G.root_pid = getpid();
  3933. /* Deal with HUSH_VERSION */
  3934. G.shell_ver = const_shell_ver; /* copying struct here */
  3935. G.top_var = &G.shell_ver;
  3936. debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
  3937. unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
  3938. /* Initialize our shell local variables with the values
  3939. * currently living in the environment */
  3940. cur_var = G.top_var;
  3941. e = environ;
  3942. if (e) while (*e) {
  3943. char *value = strchr(*e, '=');
  3944. if (value) { /* paranoia */
  3945. cur_var->next = xzalloc(sizeof(*cur_var));
  3946. cur_var = cur_var->next;
  3947. cur_var->varstr = *e;
  3948. cur_var->max_len = strlen(*e);
  3949. cur_var->flg_export = 1;
  3950. }
  3951. e++;
  3952. }
  3953. debug_printf_env("putenv '%s'\n", hush_version_str);
  3954. putenv((char *)hush_version_str); /* reinstate HUSH_VERSION */
  3955. #if ENABLE_FEATURE_EDITING
  3956. G.line_input_state = new_line_input_t(FOR_SHELL);
  3957. #endif
  3958. /* XXX what should these be while sourcing /etc/profile? */
  3959. G.global_argc = argc;
  3960. G.global_argv = argv;
  3961. /* Initialize some more globals to non-zero values */
  3962. set_cwd();
  3963. #if ENABLE_HUSH_INTERACTIVE
  3964. #if ENABLE_FEATURE_EDITING
  3965. cmdedit_set_initial_prompt();
  3966. #endif
  3967. G.PS2 = "> ";
  3968. #endif
  3969. if (EXIT_SUCCESS) /* otherwise is already done */
  3970. G.last_return_code = EXIT_SUCCESS;
  3971. if (argv[0] && argv[0][0] == '-') {
  3972. debug_printf("sourcing /etc/profile\n");
  3973. input = fopen_for_read("/etc/profile");
  3974. if (input != NULL) {
  3975. close_on_exec_on(fileno(input));
  3976. parse_and_run_file(input);
  3977. fclose(input);
  3978. }
  3979. }
  3980. input = stdin;
  3981. while ((opt = getopt(argc, argv, "c:xif")) > 0) {
  3982. switch (opt) {
  3983. case 'c':
  3984. G.global_argv = argv + optind;
  3985. if (!argv[optind]) {
  3986. /* -c 'script' (no params): prevent empty $0 */
  3987. *--G.global_argv = argv[0];
  3988. optind--;
  3989. } /* else -c 'script' PAR0 PAR1: $0 is PAR0 */
  3990. G.global_argc = argc - optind;
  3991. opt = parse_and_run_string(optarg, 0 /* parse_flag */);
  3992. goto final_return;
  3993. case 'i':
  3994. /* Well, we cannot just declare interactiveness,
  3995. * we have to have some stuff (ctty, etc) */
  3996. /* G.interactive_fd++; */
  3997. break;
  3998. case 'f':
  3999. G.fake_mode = 1;
  4000. break;
  4001. default:
  4002. #ifndef BB_VER
  4003. fprintf(stderr, "Usage: sh [FILE]...\n"
  4004. " or: sh -c command [args]...\n\n");
  4005. exit(EXIT_FAILURE);
  4006. #else
  4007. bb_show_usage();
  4008. #endif
  4009. }
  4010. }
  4011. #if ENABLE_HUSH_JOB
  4012. /* A shell is interactive if the '-i' flag was given, or if all of
  4013. * the following conditions are met:
  4014. * no -c command
  4015. * no arguments remaining or the -s flag given
  4016. * standard input is a terminal
  4017. * standard output is a terminal
  4018. * Refer to Posix.2, the description of the 'sh' utility. */
  4019. if (argv[optind] == NULL && input == stdin
  4020. && isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)
  4021. ) {
  4022. G.saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
  4023. debug_printf("saved_tty_pgrp=%d\n", G.saved_tty_pgrp);
  4024. if (G.saved_tty_pgrp >= 0) {
  4025. /* try to dup to high fd#, >= 255 */
  4026. G.interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
  4027. if (G.interactive_fd < 0) {
  4028. /* try to dup to any fd */
  4029. G.interactive_fd = dup(STDIN_FILENO);
  4030. if (G.interactive_fd < 0)
  4031. /* give up */
  4032. G.interactive_fd = 0;
  4033. }
  4034. // TODO: track & disallow any attempts of user
  4035. // to (inadvertently) close/redirect it
  4036. }
  4037. }
  4038. debug_printf("G.interactive_fd=%d\n", G.interactive_fd);
  4039. if (G.interactive_fd) {
  4040. fcntl(G.interactive_fd, F_SETFD, FD_CLOEXEC);
  4041. /* Looks like they want an interactive shell */
  4042. setup_job_control();
  4043. /* -1 is special - makes xfuncs longjmp, not exit
  4044. * (we reset die_sleep = 0 whereever we [v]fork) */
  4045. die_sleep = -1;
  4046. if (setjmp(die_jmp)) {
  4047. /* xfunc has failed! die die die */
  4048. hush_exit(xfunc_error_retval);
  4049. }
  4050. #if !ENABLE_FEATURE_SH_EXTRA_QUIET
  4051. printf("\n\n%s hush - the humble shell v"HUSH_VER_STR"\n", bb_banner);
  4052. printf("Enter 'help' for a list of built-in commands.\n\n");
  4053. #endif
  4054. }
  4055. #elif ENABLE_HUSH_INTERACTIVE
  4056. /* no job control compiled, only prompt/line editing */
  4057. if (argv[optind] == NULL && input == stdin
  4058. && isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)
  4059. ) {
  4060. G.interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
  4061. if (G.interactive_fd < 0) {
  4062. /* try to dup to any fd */
  4063. G.interactive_fd = dup(STDIN_FILENO);
  4064. if (G.interactive_fd < 0)
  4065. /* give up */
  4066. G.interactive_fd = 0;
  4067. }
  4068. if (G.interactive_fd) {
  4069. fcntl(G.interactive_fd, F_SETFD, FD_CLOEXEC);
  4070. set_misc_sighandler(SIG_IGN);
  4071. }
  4072. }
  4073. #endif
  4074. if (argv[optind] == NULL) {
  4075. opt = parse_and_run_file(stdin);
  4076. } else {
  4077. debug_printf("\nrunning script '%s'\n", argv[optind]);
  4078. G.global_argv = argv + optind;
  4079. G.global_argc = argc - optind;
  4080. input = xfopen_for_read(argv[optind]);
  4081. fcntl(fileno(input), F_SETFD, FD_CLOEXEC);
  4082. opt = parse_and_run_file(input);
  4083. }
  4084. final_return:
  4085. #if ENABLE_FEATURE_CLEAN_UP
  4086. fclose(input);
  4087. if (G.cwd != bb_msg_unknown)
  4088. free((char*)G.cwd);
  4089. cur_var = G.top_var->next;
  4090. while (cur_var) {
  4091. struct variable *tmp = cur_var;
  4092. if (!cur_var->max_len)
  4093. free(cur_var->varstr);
  4094. cur_var = cur_var->next;
  4095. free(tmp);
  4096. }
  4097. #endif
  4098. hush_exit(opt ? opt : G.last_return_code);
  4099. }
  4100. #if ENABLE_LASH
  4101. int lash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  4102. int lash_main(int argc, char **argv)
  4103. {
  4104. //bb_error_msg("lash is deprecated, please use hush instead");
  4105. return hush_main(argc, argv);
  4106. }
  4107. #endif
  4108. /*
  4109. * Built-ins
  4110. */
  4111. static int builtin_true(char **argv UNUSED_PARAM)
  4112. {
  4113. return 0;
  4114. }
  4115. static int builtin_test(char **argv)
  4116. {
  4117. int argc = 0;
  4118. while (*argv) {
  4119. argc++;
  4120. argv++;
  4121. }
  4122. return test_main(argc, argv - argc);
  4123. }
  4124. static int builtin_echo(char **argv)
  4125. {
  4126. int argc = 0;
  4127. while (*argv) {
  4128. argc++;
  4129. argv++;
  4130. }
  4131. return echo_main(argc, argv - argc);
  4132. }
  4133. static int builtin_eval(char **argv)
  4134. {
  4135. int rcode = EXIT_SUCCESS;
  4136. if (argv[1]) {
  4137. char *str = expand_strvec_to_string(argv + 1);
  4138. parse_and_run_string(str, PARSEFLAG_EXIT_FROM_LOOP);
  4139. free(str);
  4140. rcode = G.last_return_code;
  4141. }
  4142. return rcode;
  4143. }
  4144. static int builtin_cd(char **argv)
  4145. {
  4146. const char *newdir;
  4147. if (argv[1] == NULL) {
  4148. // bash does nothing (exitcode 0) if HOME is ""; if it's unset,
  4149. // bash says "bash: cd: HOME not set" and does nothing (exitcode 1)
  4150. newdir = getenv("HOME") ? : "/";
  4151. } else
  4152. newdir = argv[1];
  4153. if (chdir(newdir)) {
  4154. printf("cd: %s: %s\n", newdir, strerror(errno));
  4155. return EXIT_FAILURE;
  4156. }
  4157. set_cwd();
  4158. return EXIT_SUCCESS;
  4159. }
  4160. static int builtin_exec(char **argv)
  4161. {
  4162. if (argv[1] == NULL)
  4163. return EXIT_SUCCESS; /* bash does this */
  4164. {
  4165. #if !BB_MMU
  4166. nommu_save_t dummy;
  4167. #endif
  4168. // FIXME: if exec fails, bash does NOT exit! We do...
  4169. pseudo_exec_argv(&dummy, argv + 1, 0, NULL);
  4170. /* never returns */
  4171. }
  4172. }
  4173. static int builtin_exit(char **argv)
  4174. {
  4175. // TODO: bash does it ONLY on top-level sh exit (+interacive only?)
  4176. //puts("exit"); /* bash does it */
  4177. // TODO: warn if we have background jobs: "There are stopped jobs"
  4178. // On second consecutive 'exit', exit anyway.
  4179. if (argv[1] == NULL)
  4180. hush_exit(G.last_return_code);
  4181. /* mimic bash: exit 123abc == exit 255 + error msg */
  4182. xfunc_error_retval = 255;
  4183. /* bash: exit -2 == exit 254, no error msg */
  4184. hush_exit(xatoi(argv[1]) & 0xff);
  4185. }
  4186. static int builtin_export(char **argv)
  4187. {
  4188. const char *value;
  4189. char *name = argv[1];
  4190. if (name == NULL) {
  4191. // TODO:
  4192. // ash emits: export VAR='VAL'
  4193. // bash: declare -x VAR="VAL"
  4194. // (both also escape as needed (quotes, $, etc))
  4195. char **e = environ;
  4196. if (e)
  4197. while (*e)
  4198. puts(*e++);
  4199. return EXIT_SUCCESS;
  4200. }
  4201. value = strchr(name, '=');
  4202. if (!value) {
  4203. /* They are exporting something without a =VALUE */
  4204. struct variable *var;
  4205. var = get_local_var(name);
  4206. if (var) {
  4207. var->flg_export = 1;
  4208. debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
  4209. putenv(var->varstr);
  4210. }
  4211. /* bash does not return an error when trying to export
  4212. * an undefined variable. Do likewise. */
  4213. return EXIT_SUCCESS;
  4214. }
  4215. set_local_var(xstrdup(name), 1);
  4216. return EXIT_SUCCESS;
  4217. }
  4218. #if ENABLE_HUSH_JOB
  4219. /* built-in 'fg' and 'bg' handler */
  4220. static int builtin_fg_bg(char **argv)
  4221. {
  4222. int i, jobnum;
  4223. struct pipe *pi;
  4224. if (!G.interactive_fd)
  4225. return EXIT_FAILURE;
  4226. /* If they gave us no args, assume they want the last backgrounded task */
  4227. if (!argv[1]) {
  4228. for (pi = G.job_list; pi; pi = pi->next) {
  4229. if (pi->jobid == G.last_jobid) {
  4230. goto found;
  4231. }
  4232. }
  4233. bb_error_msg("%s: no current job", argv[0]);
  4234. return EXIT_FAILURE;
  4235. }
  4236. if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
  4237. bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
  4238. return EXIT_FAILURE;
  4239. }
  4240. for (pi = G.job_list; pi; pi = pi->next) {
  4241. if (pi->jobid == jobnum) {
  4242. goto found;
  4243. }
  4244. }
  4245. bb_error_msg("%s: %d: no such job", argv[0], jobnum);
  4246. return EXIT_FAILURE;
  4247. found:
  4248. // TODO: bash prints a string representation
  4249. // of job being foregrounded (like "sleep 1 | cat")
  4250. if (*argv[0] == 'f') {
  4251. /* Put the job into the foreground. */
  4252. tcsetpgrp(G.interactive_fd, pi->pgrp);
  4253. }
  4254. /* Restart the processes in the job */
  4255. debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
  4256. for (i = 0; i < pi->num_cmds; i++) {
  4257. debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
  4258. pi->cmds[i].is_stopped = 0;
  4259. }
  4260. pi->stopped_cmds = 0;
  4261. i = kill(- pi->pgrp, SIGCONT);
  4262. if (i < 0) {
  4263. if (errno == ESRCH) {
  4264. delete_finished_bg_job(pi);
  4265. return EXIT_SUCCESS;
  4266. } else {
  4267. bb_perror_msg("kill (SIGCONT)");
  4268. }
  4269. }
  4270. if (*argv[0] == 'f') {
  4271. remove_bg_job(pi);
  4272. return checkjobs_and_fg_shell(pi);
  4273. }
  4274. return EXIT_SUCCESS;
  4275. }
  4276. #endif
  4277. #if ENABLE_HUSH_HELP
  4278. static int builtin_help(char **argv UNUSED_PARAM)
  4279. {
  4280. const struct built_in_command *x;
  4281. printf("\nBuilt-in commands:\n");
  4282. printf("-------------------\n");
  4283. for (x = bltins; x != &bltins[ARRAY_SIZE(bltins)]; x++) {
  4284. printf("%s\t%s\n", x->cmd, x->descr);
  4285. }
  4286. printf("\n\n");
  4287. return EXIT_SUCCESS;
  4288. }
  4289. #endif
  4290. #if ENABLE_HUSH_JOB
  4291. static int builtin_jobs(char **argv UNUSED_PARAM)
  4292. {
  4293. struct pipe *job;
  4294. const char *status_string;
  4295. for (job = G.job_list; job; job = job->next) {
  4296. if (job->alive_cmds == job->stopped_cmds)
  4297. status_string = "Stopped";
  4298. else
  4299. status_string = "Running";
  4300. printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
  4301. }
  4302. return EXIT_SUCCESS;
  4303. }
  4304. #endif
  4305. static int builtin_pwd(char **argv UNUSED_PARAM)
  4306. {
  4307. puts(set_cwd());
  4308. return EXIT_SUCCESS;
  4309. }
  4310. static int builtin_read(char **argv)
  4311. {
  4312. char *string;
  4313. const char *name = argv[1] ? argv[1] : "REPLY";
  4314. string = xmalloc_reads(STDIN_FILENO, xasprintf("%s=", name), NULL);
  4315. return set_local_var(string, 0);
  4316. }
  4317. /* built-in 'set' handler
  4318. * SUSv3 says:
  4319. * set [-abCefmnuvx] [-h] [-o option] [argument...]
  4320. * set [+abCefmnuvx] [+h] [+o option] [argument...]
  4321. * set -- [argument...]
  4322. * set -o
  4323. * set +o
  4324. * Implementations shall support the options in both their hyphen and
  4325. * plus-sign forms. These options can also be specified as options to sh.
  4326. * Examples:
  4327. * Write out all variables and their values: set
  4328. * Set $1, $2, and $3 and set "$#" to 3: set c a b
  4329. * Turn on the -x and -v options: set -xv
  4330. * Unset all positional parameters: set --
  4331. * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
  4332. * Set the positional parameters to the expansion of x, even if x expands
  4333. * with a leading '-' or '+': set -- $x
  4334. *
  4335. * So far, we only support "set -- [argument...]" by ignoring all options
  4336. * (also, "-o option" will be mishandled by taking "option" as parameter #1).
  4337. */
  4338. static int builtin_set(char **argv)
  4339. {
  4340. struct variable *e;
  4341. char **pp;
  4342. char *arg = *++argv;
  4343. if (arg == NULL) {
  4344. for (e = G.top_var; e; e = e->next)
  4345. puts(e->varstr);
  4346. } else {
  4347. /* NB: G.global_argv[0] ($0) is never freed/changed */
  4348. if (G.global_args_malloced) {
  4349. pp = G.global_argv;
  4350. while (*++pp)
  4351. free(*pp);
  4352. G.global_argv[1] = NULL;
  4353. } else {
  4354. G.global_args_malloced = 1;
  4355. pp = xzalloc(sizeof(pp[0]) * 2);
  4356. pp[0] = G.global_argv[0]; /* retain $0 */
  4357. G.global_argv = pp;
  4358. }
  4359. do {
  4360. if (arg[0] == '+')
  4361. continue;
  4362. if (arg[0] != '-')
  4363. break;
  4364. if (arg[1] == '-' && arg[2] == '\0') {
  4365. argv++;
  4366. break;
  4367. }
  4368. } while ((arg = *++argv) != NULL);
  4369. /* Now argv[0] is 1st argument */
  4370. /* This realloc's G.global_argv */
  4371. G.global_argv = pp = add_strings_to_strings(G.global_argv, argv, /*dup:*/ 1);
  4372. G.global_argc = 1;
  4373. while (*++pp)
  4374. G.global_argc++;
  4375. }
  4376. return EXIT_SUCCESS;
  4377. }
  4378. static int builtin_shift(char **argv)
  4379. {
  4380. int n = 1;
  4381. if (argv[1]) {
  4382. n = atoi(argv[1]);
  4383. }
  4384. if (n >= 0 && n < G.global_argc) {
  4385. if (G.global_args_malloced) {
  4386. int m = 1;
  4387. while (m <= n)
  4388. free(G.global_argv[m++]);
  4389. }
  4390. G.global_argc -= n;
  4391. memmove(&G.global_argv[1], &G.global_argv[n+1],
  4392. G.global_argc * sizeof(G.global_argv[0]));
  4393. return EXIT_SUCCESS;
  4394. }
  4395. return EXIT_FAILURE;
  4396. }
  4397. static int builtin_source(char **argv)
  4398. {
  4399. FILE *input;
  4400. int status;
  4401. if (argv[1] == NULL)
  4402. return EXIT_FAILURE;
  4403. /* XXX search through $PATH is missing */
  4404. input = fopen_for_read(argv[1]);
  4405. if (!input) {
  4406. bb_error_msg("can't open '%s'", argv[1]);
  4407. return EXIT_FAILURE;
  4408. }
  4409. close_on_exec_on(fileno(input));
  4410. /* Now run the file */
  4411. /* XXX argv and argc are broken; need to save old G.global_argv
  4412. * (pointer only is OK!) on this stack frame,
  4413. * set G.global_argv=argv+1, recurse, and restore. */
  4414. status = parse_and_run_file(input);
  4415. fclose(input);
  4416. return status;
  4417. }
  4418. static int builtin_umask(char **argv)
  4419. {
  4420. mode_t new_umask;
  4421. const char *arg = argv[1];
  4422. char *end;
  4423. if (arg) {
  4424. new_umask = strtoul(arg, &end, 8);
  4425. if (*end != '\0' || end == arg) {
  4426. return EXIT_FAILURE;
  4427. }
  4428. } else {
  4429. new_umask = umask(0);
  4430. printf("%.3o\n", (unsigned) new_umask);
  4431. }
  4432. umask(new_umask);
  4433. return EXIT_SUCCESS;
  4434. }
  4435. static int builtin_unset(char **argv)
  4436. {
  4437. /* bash always returns true */
  4438. unset_local_var(argv[1]);
  4439. return EXIT_SUCCESS;
  4440. }
  4441. #if ENABLE_HUSH_LOOPS
  4442. static int builtin_break(char **argv)
  4443. {
  4444. if (G.depth_of_loop == 0) {
  4445. bb_error_msg("%s: only meaningful in a loop", argv[0]);
  4446. return EXIT_SUCCESS; /* bash compat */
  4447. }
  4448. G.flag_break_continue++; /* BC_BREAK = 1 */
  4449. G.depth_break_continue = 1;
  4450. if (argv[1]) {
  4451. G.depth_break_continue = bb_strtou(argv[1], NULL, 10);
  4452. if (errno || !G.depth_break_continue || argv[2]) {
  4453. bb_error_msg("%s: bad arguments", argv[0]);
  4454. G.flag_break_continue = BC_BREAK;
  4455. G.depth_break_continue = UINT_MAX;
  4456. }
  4457. }
  4458. if (G.depth_of_loop < G.depth_break_continue)
  4459. G.depth_break_continue = G.depth_of_loop;
  4460. return EXIT_SUCCESS;
  4461. }
  4462. static int builtin_continue(char **argv)
  4463. {
  4464. G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
  4465. return builtin_break(argv);
  4466. }
  4467. #endif