3
0

hush.c 330 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * 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. * Copyright (C) 2008,2009 Denys Vlasenko <vda.linux@googlemail.com>
  10. *
  11. * Licensed under GPLv2 or later, see file LICENSE in this source tree.
  12. *
  13. * Credits:
  14. * The parser routines proper are all original material, first
  15. * written Dec 2000 and Jan 2001 by Larry Doolittle. The
  16. * execution engine, the builtins, and much of the underlying
  17. * support has been adapted from busybox-0.49pre's lash, which is
  18. * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
  19. * written by Erik Andersen <andersen@codepoet.org>. That, in turn,
  20. * is based in part on ladsh.c, by Michael K. Johnson and Erik W.
  21. * Troan, which they placed in the public domain. I don't know
  22. * how much of the Johnson/Troan code has survived the repeated
  23. * rewrites.
  24. *
  25. * Other credits:
  26. * o_addchr derived from similar w_addchar function in glibc-2.2.
  27. * parse_redirect, redirect_opt_num, and big chunks of main
  28. * and many builtins derived from contributions by Erik Andersen.
  29. * Miscellaneous bugfixes from Matt Kraai.
  30. *
  31. * There are two big (and related) architecture differences between
  32. * this parser and the lash parser. One is that this version is
  33. * actually designed from the ground up to understand nearly all
  34. * of the Bourne grammar. The second, consequential change is that
  35. * the parser and input reader have been turned inside out. Now,
  36. * the parser is in control, and asks for input as needed. The old
  37. * way had the input reader in control, and it asked for parsing to
  38. * take place as needed. The new way makes it much easier to properly
  39. * handle the recursion implicit in the various substitutions, especially
  40. * across continuation lines.
  41. *
  42. * TODOs:
  43. * grep for "TODO" and fix (some of them are easy)
  44. * make complex ${var%...} constructs support optional
  45. * make here documents optional
  46. * special variables (done: PWD, PPID, RANDOM)
  47. * follow IFS rules more precisely, including update semantics
  48. * tilde expansion
  49. * aliases
  50. * "command" missing features:
  51. * command -p CMD: run CMD using default $PATH
  52. * (can use this to override standalone shell as well?)
  53. * command BLTIN: disables special-ness (e.g. errors do not abort)
  54. * command -V CMD1 CMD2 CMD3 (multiple args) (not in standard)
  55. * builtins mandated by standards we don't support:
  56. * [un]alias, fc:
  57. * fc -l[nr] [BEG] [END]: list range of commands in history
  58. * fc [-e EDITOR] [BEG] [END]: edit/rerun range of commands
  59. * fc -s [PAT=REP] [CMD]: rerun CMD, replacing PAT with REP
  60. *
  61. * Bash compat TODO:
  62. * redirection of stdout+stderr: &> and >&
  63. * reserved words: function select
  64. * advanced test: [[ ]]
  65. * process substitution: <(list) and >(list)
  66. * let EXPR [EXPR...]
  67. * Each EXPR is an arithmetic expression (ARITHMETIC EVALUATION)
  68. * If the last arg evaluates to 0, let returns 1; 0 otherwise.
  69. * NB: let `echo 'a=a + 1'` - error (IOW: multi-word expansion is used)
  70. * ((EXPR))
  71. * The EXPR is evaluated according to ARITHMETIC EVALUATION.
  72. * This is exactly equivalent to let "EXPR".
  73. * $[EXPR]: synonym for $((EXPR))
  74. * indirect expansion: ${!VAR}
  75. * substring op on @: ${@:n:m}
  76. *
  77. * Won't do:
  78. * Some builtins mandated by standards:
  79. * newgrp [GRP]: not a builtin in bash but a suid binary
  80. * which spawns a new shell with new group ID
  81. *
  82. * Status of [[ support:
  83. * [[ args ]] are CMD_SINGLEWORD_NOGLOB:
  84. * v='a b'; [[ $v = 'a b' ]]; echo 0:$?
  85. * [[ /bin/n* ]]; echo 0:$?
  86. * = is glob match operator, not equality operator: STR = GLOB
  87. * == same as =
  88. * =~ is regex match operator: STR =~ REGEX
  89. * TODO:
  90. * quoting needs to be considered (-f is an operator, "-f" and ""-f are not; etc)
  91. * in word = GLOB, quoting should be significant on char-by-char basis: a*cd"*"
  92. */
  93. //config:config HUSH
  94. //config: bool "hush (68 kb)"
  95. //config: default y
  96. //config: select SHELL_HUSH
  97. //config: help
  98. //config: hush is a small shell. It handles the normal flow control
  99. //config: constructs such as if/then/elif/else/fi, for/in/do/done, while loops,
  100. //config: case/esac. Redirections, here documents, $((arithmetic))
  101. //config: and functions are supported.
  102. //config:
  103. //config: It will compile and work on no-mmu systems.
  104. //config:
  105. //config: It does not handle select, aliases, tilde expansion,
  106. //config: &>file and >&file redirection of stdout+stderr.
  107. //config:
  108. // This option is visible (has a description) to make it possible to select
  109. // a "scripted" applet (such as NOLOGIN) but avoid selecting any shells:
  110. //config:config SHELL_HUSH
  111. //config: bool "Internal shell for embedded script support"
  112. //config: default n
  113. //config:
  114. //config:# hush options
  115. //config:# It's only needed to get "nice" menuconfig indenting.
  116. //config:if SHELL_HUSH || HUSH || SH_IS_HUSH || BASH_IS_HUSH
  117. //config:
  118. //config:config HUSH_BASH_COMPAT
  119. //config: bool "bash-compatible extensions"
  120. //config: default y
  121. //config: depends on SHELL_HUSH
  122. //config:
  123. //config:config HUSH_BRACE_EXPANSION
  124. //config: bool "Brace expansion"
  125. //config: default y
  126. //config: depends on HUSH_BASH_COMPAT
  127. //config: help
  128. //config: Enable {abc,def} extension.
  129. //config:
  130. //config:config HUSH_LINENO_VAR
  131. //config: bool "$LINENO variable"
  132. //config: default y
  133. //config: depends on HUSH_BASH_COMPAT
  134. //config:
  135. //config:config HUSH_BASH_SOURCE_CURDIR
  136. //config: bool "'source' and '.' builtins search current directory after $PATH"
  137. //config: default n # do not encourage non-standard behavior
  138. //config: depends on HUSH_BASH_COMPAT
  139. //config: help
  140. //config: This is not compliant with standards. Avoid if possible.
  141. //config:
  142. //config:config HUSH_INTERACTIVE
  143. //config: bool "Interactive mode"
  144. //config: default y
  145. //config: depends on SHELL_HUSH
  146. //config: help
  147. //config: Enable interactive mode (prompt and command editing).
  148. //config: Without this, hush simply reads and executes commands
  149. //config: from stdin just like a shell script from a file.
  150. //config: No prompt, no PS1/PS2 magic shell variables.
  151. //config:
  152. //config:config HUSH_SAVEHISTORY
  153. //config: bool "Save command history to .hush_history"
  154. //config: default y
  155. //config: depends on HUSH_INTERACTIVE && FEATURE_EDITING_SAVEHISTORY
  156. //config:
  157. //config:config HUSH_JOB
  158. //config: bool "Job control"
  159. //config: default y
  160. //config: depends on HUSH_INTERACTIVE
  161. //config: help
  162. //config: Enable job control: Ctrl-Z backgrounds, Ctrl-C interrupts current
  163. //config: command (not entire shell), fg/bg builtins work. Without this option,
  164. //config: "cmd &" still works by simply spawning a process and immediately
  165. //config: prompting for next command (or executing next command in a script),
  166. //config: but no separate process group is formed.
  167. //config:
  168. //config:config HUSH_TICK
  169. //config: bool "Support command substitution"
  170. //config: default y
  171. //config: depends on SHELL_HUSH
  172. //config: help
  173. //config: Enable `command` and $(command).
  174. //config:
  175. //config:config HUSH_IF
  176. //config: bool "Support if/then/elif/else/fi"
  177. //config: default y
  178. //config: depends on SHELL_HUSH
  179. //config:
  180. //config:config HUSH_LOOPS
  181. //config: bool "Support for, while and until loops"
  182. //config: default y
  183. //config: depends on SHELL_HUSH
  184. //config:
  185. //config:config HUSH_CASE
  186. //config: bool "Support case ... esac statement"
  187. //config: default y
  188. //config: depends on SHELL_HUSH
  189. //config: help
  190. //config: Enable case ... esac statement. +400 bytes.
  191. //config:
  192. //config:config HUSH_FUNCTIONS
  193. //config: bool "Support funcname() { commands; } syntax"
  194. //config: default y
  195. //config: depends on SHELL_HUSH
  196. //config: help
  197. //config: Enable support for shell functions. +800 bytes.
  198. //config:
  199. //config:config HUSH_LOCAL
  200. //config: bool "local builtin"
  201. //config: default y
  202. //config: depends on HUSH_FUNCTIONS
  203. //config: help
  204. //config: Enable support for local variables in functions.
  205. //config:
  206. //config:config HUSH_RANDOM_SUPPORT
  207. //config: bool "Pseudorandom generator and $RANDOM variable"
  208. //config: default y
  209. //config: depends on SHELL_HUSH
  210. //config: help
  211. //config: Enable pseudorandom generator and dynamic variable "$RANDOM".
  212. //config: Each read of "$RANDOM" will generate a new pseudorandom value.
  213. //config:
  214. //config:config HUSH_MODE_X
  215. //config: bool "Support 'hush -x' option and 'set -x' command"
  216. //config: default y
  217. //config: depends on SHELL_HUSH
  218. //config: help
  219. //config: This instructs hush to print commands before execution.
  220. //config: Adds ~300 bytes.
  221. //config:
  222. //config:config HUSH_ECHO
  223. //config: bool "echo builtin"
  224. //config: default y
  225. //config: depends on SHELL_HUSH
  226. //config:
  227. //config:config HUSH_PRINTF
  228. //config: bool "printf builtin"
  229. //config: default y
  230. //config: depends on SHELL_HUSH
  231. //config:
  232. //config:config HUSH_TEST
  233. //config: bool "test builtin"
  234. //config: default y
  235. //config: depends on SHELL_HUSH
  236. //config:
  237. //config:config HUSH_HELP
  238. //config: bool "help builtin"
  239. //config: default y
  240. //config: depends on SHELL_HUSH
  241. //config:
  242. //config:config HUSH_EXPORT
  243. //config: bool "export builtin"
  244. //config: default y
  245. //config: depends on SHELL_HUSH
  246. //config:
  247. //config:config HUSH_EXPORT_N
  248. //config: bool "Support 'export -n' option"
  249. //config: default y
  250. //config: depends on HUSH_EXPORT
  251. //config: help
  252. //config: export -n unexports variables. It is a bash extension.
  253. //config:
  254. //config:config HUSH_READONLY
  255. //config: bool "readonly builtin"
  256. //config: default y
  257. //config: depends on SHELL_HUSH
  258. //config: help
  259. //config: Enable support for read-only variables.
  260. //config:
  261. //config:config HUSH_KILL
  262. //config: bool "kill builtin (supports kill %jobspec)"
  263. //config: default y
  264. //config: depends on SHELL_HUSH
  265. //config:
  266. //config:config HUSH_WAIT
  267. //config: bool "wait builtin"
  268. //config: default y
  269. //config: depends on SHELL_HUSH
  270. //config:
  271. //config:config HUSH_COMMAND
  272. //config: bool "command builtin"
  273. //config: default y
  274. //config: depends on SHELL_HUSH
  275. //config:
  276. //config:config HUSH_TRAP
  277. //config: bool "trap builtin"
  278. //config: default y
  279. //config: depends on SHELL_HUSH
  280. //config:
  281. //config:config HUSH_TYPE
  282. //config: bool "type builtin"
  283. //config: default y
  284. //config: depends on SHELL_HUSH
  285. //config:
  286. //config:config HUSH_TIMES
  287. //config: bool "times builtin"
  288. //config: default y
  289. //config: depends on SHELL_HUSH
  290. //config:
  291. //config:config HUSH_READ
  292. //config: bool "read builtin"
  293. //config: default y
  294. //config: depends on SHELL_HUSH
  295. //config:
  296. //config:config HUSH_SET
  297. //config: bool "set builtin"
  298. //config: default y
  299. //config: depends on SHELL_HUSH
  300. //config:
  301. //config:config HUSH_UNSET
  302. //config: bool "unset builtin"
  303. //config: default y
  304. //config: depends on SHELL_HUSH
  305. //config:
  306. //config:config HUSH_ULIMIT
  307. //config: bool "ulimit builtin"
  308. //config: default y
  309. //config: depends on SHELL_HUSH
  310. //config:
  311. //config:config HUSH_UMASK
  312. //config: bool "umask builtin"
  313. //config: default y
  314. //config: depends on SHELL_HUSH
  315. //config:
  316. //config:config HUSH_GETOPTS
  317. //config: bool "getopts builtin"
  318. //config: default y
  319. //config: depends on SHELL_HUSH
  320. //config:
  321. //config:config HUSH_MEMLEAK
  322. //config: bool "memleak builtin (debugging)"
  323. //config: default n
  324. //config: depends on SHELL_HUSH
  325. //config:
  326. //config:endif # hush options
  327. //applet:IF_HUSH(APPLET(hush, BB_DIR_BIN, BB_SUID_DROP))
  328. // APPLET_ODDNAME:name main location suid_type help
  329. //applet:IF_SH_IS_HUSH( APPLET_ODDNAME(sh, hush, BB_DIR_BIN, BB_SUID_DROP, hush))
  330. //applet:IF_BASH_IS_HUSH(APPLET_ODDNAME(bash, hush, BB_DIR_BIN, BB_SUID_DROP, hush))
  331. //kbuild:lib-$(CONFIG_SHELL_HUSH) += hush.o match.o shell_common.o
  332. //kbuild:lib-$(CONFIG_HUSH_RANDOM_SUPPORT) += random.o
  333. /* -i (interactive) is also accepted,
  334. * but does nothing, therefore not shown in help.
  335. * NOMMU-specific options are not meant to be used by users,
  336. * therefore we don't show them either.
  337. */
  338. //usage:#define hush_trivial_usage
  339. //usage: "[-enxl] [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS] / -s [ARGS]]"
  340. //usage:#define hush_full_usage "\n\n"
  341. //usage: "Unix shell interpreter"
  342. #if !(defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) \
  343. || defined(__APPLE__) \
  344. )
  345. # include <malloc.h> /* for malloc_trim */
  346. #endif
  347. #include <glob.h>
  348. /* #include <dmalloc.h> */
  349. #if ENABLE_HUSH_CASE
  350. # include <fnmatch.h>
  351. #endif
  352. #include <sys/times.h>
  353. #include <sys/utsname.h> /* for setting $HOSTNAME */
  354. #include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
  355. #include "unicode.h"
  356. #include "shell_common.h"
  357. #include "math.h"
  358. #include "match.h"
  359. #if ENABLE_HUSH_RANDOM_SUPPORT
  360. # include "random.h"
  361. #else
  362. # define CLEAR_RANDOM_T(rnd) ((void)0)
  363. #endif
  364. #ifndef O_CLOEXEC
  365. # define O_CLOEXEC 0
  366. #endif
  367. #ifndef F_DUPFD_CLOEXEC
  368. # define F_DUPFD_CLOEXEC F_DUPFD
  369. #endif
  370. #if ENABLE_FEATURE_SH_EMBEDDED_SCRIPTS && !(ENABLE_ASH || ENABLE_SH_IS_ASH || ENABLE_BASH_IS_ASH)
  371. # include "embedded_scripts.h"
  372. #else
  373. # define NUM_SCRIPTS 0
  374. #endif
  375. /* So far, all bash compat is controlled by one config option */
  376. /* Separate defines document which part of code implements what */
  377. #define BASH_PATTERN_SUBST ENABLE_HUSH_BASH_COMPAT
  378. #define BASH_SUBSTR ENABLE_HUSH_BASH_COMPAT
  379. #define BASH_SOURCE ENABLE_HUSH_BASH_COMPAT
  380. #define BASH_HOSTNAME_VAR ENABLE_HUSH_BASH_COMPAT
  381. #define BASH_EPOCH_VARS ENABLE_HUSH_BASH_COMPAT
  382. #define BASH_TEST2 (ENABLE_HUSH_BASH_COMPAT && ENABLE_HUSH_TEST)
  383. #define BASH_READ_D ENABLE_HUSH_BASH_COMPAT
  384. /* Build knobs */
  385. #define LEAK_HUNTING 0
  386. #define BUILD_AS_NOMMU 0
  387. /* Enable/disable sanity checks. Ok to enable in production,
  388. * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
  389. * Keeping 1 for now even in released versions.
  390. */
  391. #define HUSH_DEBUG 1
  392. /* Slightly bigger (+200 bytes), but faster hush.
  393. * So far it only enables a trick with counting SIGCHLDs and forks,
  394. * which allows us to do fewer waitpid's.
  395. * (we can detect a case where neither forks were done nor SIGCHLDs happened
  396. * and therefore waitpid will return the same result as last time)
  397. */
  398. #define ENABLE_HUSH_FAST 0
  399. /* TODO: implement simplified code for users which do not need ${var%...} ops
  400. * So far ${var%...} ops are always enabled:
  401. */
  402. #define ENABLE_HUSH_DOLLAR_OPS 1
  403. #if BUILD_AS_NOMMU
  404. # undef BB_MMU
  405. # undef USE_FOR_NOMMU
  406. # undef USE_FOR_MMU
  407. # define BB_MMU 0
  408. # define USE_FOR_NOMMU(...) __VA_ARGS__
  409. # define USE_FOR_MMU(...)
  410. #endif
  411. #include "NUM_APPLETS.h"
  412. #if NUM_APPLETS == 1
  413. /* STANDALONE does not make sense, and won't compile */
  414. # undef CONFIG_FEATURE_SH_STANDALONE
  415. # undef ENABLE_FEATURE_SH_STANDALONE
  416. # undef IF_FEATURE_SH_STANDALONE
  417. # undef IF_NOT_FEATURE_SH_STANDALONE
  418. # define ENABLE_FEATURE_SH_STANDALONE 0
  419. # define IF_FEATURE_SH_STANDALONE(...)
  420. # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
  421. #endif
  422. #if !ENABLE_HUSH_INTERACTIVE
  423. # undef ENABLE_FEATURE_EDITING
  424. # define ENABLE_FEATURE_EDITING 0
  425. # undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
  426. # define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
  427. # undef ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
  428. # define ENABLE_FEATURE_EDITING_SAVE_ON_EXIT 0
  429. #endif
  430. /* Do we support ANY keywords? */
  431. #if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
  432. # define HAS_KEYWORDS 1
  433. # define IF_HAS_KEYWORDS(...) __VA_ARGS__
  434. # define IF_HAS_NO_KEYWORDS(...)
  435. #else
  436. # define HAS_KEYWORDS 0
  437. # define IF_HAS_KEYWORDS(...)
  438. # define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
  439. #endif
  440. /* If you comment out one of these below, it will be #defined later
  441. * to perform debug printfs to stderr: */
  442. #define debug_printf(...) do {} while (0)
  443. /* Finer-grained debug switches */
  444. #define debug_printf_parse(...) do {} while (0)
  445. #define debug_printf_heredoc(...) do {} while (0)
  446. #define debug_print_tree(a, b) do {} while (0)
  447. #define debug_printf_exec(...) do {} while (0)
  448. #define debug_printf_env(...) do {} while (0)
  449. #define debug_printf_jobs(...) do {} while (0)
  450. #define debug_printf_expand(...) do {} while (0)
  451. #define debug_printf_varexp(...) do {} while (0)
  452. #define debug_printf_glob(...) do {} while (0)
  453. #define debug_printf_redir(...) do {} while (0)
  454. #define debug_printf_list(...) do {} while (0)
  455. #define debug_printf_subst(...) do {} while (0)
  456. #define debug_printf_prompt(...) do {} while (0)
  457. #define debug_printf_clean(...) do {} while (0)
  458. #define ERR_PTR ((void*)(long)1)
  459. #define JOB_STATUS_FORMAT "[%u] %-22s %.40s\n"
  460. #define _SPECIAL_VARS_STR "_*@$!?#-"
  461. #define SPECIAL_VARS_STR ("_*@$!?#-" + 1)
  462. #define NUMERIC_SPECVARS_STR ("_*@$!?#-" + 3)
  463. #if BASH_PATTERN_SUBST
  464. /* Support / and // replace ops */
  465. /* Note that // is stored as \ in "encoded" string representation */
  466. # define VAR_ENCODED_SUBST_OPS "\\/%#:-=+?"
  467. # define VAR_SUBST_OPS ("\\/%#:-=+?" + 1)
  468. # define MINUS_PLUS_EQUAL_QUESTION ("\\/%#:-=+?" + 5)
  469. #else
  470. # define VAR_ENCODED_SUBST_OPS "%#:-=+?"
  471. # define VAR_SUBST_OPS "%#:-=+?"
  472. # define MINUS_PLUS_EQUAL_QUESTION ("%#:-=+?" + 3)
  473. #endif
  474. #define SPECIAL_VAR_SYMBOL_STR "\3"
  475. #define SPECIAL_VAR_SYMBOL 3
  476. /* The "variable" with name "\1" emits string "\3". Testcase: "echo ^C" */
  477. #define SPECIAL_VAR_QUOTED_SVS 1
  478. struct variable;
  479. static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
  480. /* This supports saving pointers malloced in vfork child,
  481. * to be freed in the parent.
  482. */
  483. #if !BB_MMU
  484. typedef struct nommu_save_t {
  485. struct variable *old_vars;
  486. char **argv;
  487. char **argv_from_re_execing;
  488. } nommu_save_t;
  489. #endif
  490. enum {
  491. RES_NONE = 0,
  492. #if ENABLE_HUSH_IF
  493. RES_IF ,
  494. RES_THEN ,
  495. RES_ELIF ,
  496. RES_ELSE ,
  497. RES_FI ,
  498. #endif
  499. #if ENABLE_HUSH_LOOPS
  500. RES_FOR ,
  501. RES_WHILE ,
  502. RES_UNTIL ,
  503. RES_DO ,
  504. RES_DONE ,
  505. #endif
  506. #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
  507. RES_IN ,
  508. #endif
  509. #if ENABLE_HUSH_CASE
  510. RES_CASE ,
  511. /* three pseudo-keywords support contrived "case" syntax: */
  512. RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
  513. RES_MATCH , /* "word)" */
  514. RES_CASE_BODY, /* "this command is inside CASE" */
  515. RES_ESAC ,
  516. #endif
  517. RES_XXXX ,
  518. RES_SNTX
  519. };
  520. typedef struct o_string {
  521. char *data;
  522. int length; /* position where data is appended */
  523. int maxlen;
  524. int o_expflags;
  525. /* At least some part of the string was inside '' or "",
  526. * possibly empty one: word"", wo''rd etc. */
  527. smallint has_quoted_part;
  528. smallint has_empty_slot;
  529. smallint ended_in_ifs;
  530. } o_string;
  531. enum {
  532. EXP_FLAG_SINGLEWORD = 0x80, /* must be 0x80 */
  533. EXP_FLAG_GLOB = 0x2,
  534. /* Protect newly added chars against globbing
  535. * by prepending \ to *, ?, [, \ */
  536. EXP_FLAG_ESC_GLOB_CHARS = 0x1,
  537. };
  538. /* Used for initialization: o_string foo = NULL_O_STRING; */
  539. #define NULL_O_STRING { NULL }
  540. #ifndef debug_printf_parse
  541. static const char *const assignment_flag[] = {
  542. "MAYBE_ASSIGNMENT",
  543. "DEFINITELY_ASSIGNMENT",
  544. "NOT_ASSIGNMENT",
  545. "WORD_IS_KEYWORD",
  546. };
  547. #endif
  548. /* We almost can use standard FILE api, but we need an ability to move
  549. * its fd when redirects coincide with it. No api exists for that
  550. * (RFE for it at https://sourceware.org/bugzilla/show_bug.cgi?id=21902).
  551. * HFILE is our internal alternative. Only supports reading.
  552. * Since we now can, we incorporate linked list of all opened HFILEs
  553. * into the struct (used to be a separate mini-list).
  554. */
  555. typedef struct HFILE {
  556. char *cur;
  557. char *end;
  558. struct HFILE *next_hfile;
  559. int fd;
  560. char buf[1024];
  561. } HFILE;
  562. typedef struct in_str {
  563. const char *p;
  564. int peek_buf[2];
  565. int last_char;
  566. HFILE *file;
  567. } in_str;
  568. /* The descrip member of this structure is only used to make
  569. * debugging output pretty */
  570. static const struct {
  571. int32_t mode;
  572. signed char default_fd;
  573. char descrip[3];
  574. } redir_table[] ALIGN4 = {
  575. { O_RDONLY, 0, "<" },
  576. { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
  577. { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
  578. { O_CREAT|O_RDWR, 1, "<>" },
  579. { O_RDONLY, 0, "<<" },
  580. /* Should not be needed. Bogus default_fd helps in debugging */
  581. /* { O_RDONLY, 77, "<<" }, */
  582. };
  583. struct redir_struct {
  584. struct redir_struct *next;
  585. char *rd_filename; /* filename */
  586. int rd_fd; /* fd to redirect */
  587. /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
  588. int rd_dup;
  589. smallint rd_type; /* (enum redir_type) */
  590. /* note: for heredocs, rd_filename contains heredoc delimiter,
  591. * and subsequently heredoc itself; and rd_dup is a bitmask:
  592. * bit 0: do we need to trim leading tabs?
  593. * bit 1: is heredoc quoted (<<'delim' syntax) ?
  594. */
  595. };
  596. typedef enum redir_type {
  597. REDIRECT_INPUT = 0,
  598. REDIRECT_OVERWRITE = 1,
  599. REDIRECT_APPEND = 2,
  600. REDIRECT_IO = 3,
  601. REDIRECT_HEREDOC = 4,
  602. REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
  603. REDIRFD_CLOSE = -3,
  604. REDIRFD_SYNTAX_ERR = -2,
  605. REDIRFD_TO_FILE = -1,
  606. /* otherwise, rd_fd is redirected to rd_dup */
  607. HEREDOC_SKIPTABS = 1,
  608. HEREDOC_QUOTED = 2,
  609. } redir_type;
  610. struct command {
  611. pid_t pid; /* 0 if exited */
  612. unsigned assignment_cnt; /* how many argv[i] are assignments? */
  613. #if ENABLE_HUSH_LINENO_VAR
  614. unsigned lineno;
  615. #endif
  616. smallint cmd_type; /* CMD_xxx */
  617. #define CMD_NORMAL 0
  618. #define CMD_SUBSHELL 1
  619. #if BASH_TEST2
  620. /* used for "[[ EXPR ]]" */
  621. # define CMD_TEST2_SINGLEWORD_NOGLOB 2
  622. #endif
  623. #if BASH_TEST2 || ENABLE_HUSH_LOCAL || ENABLE_HUSH_EXPORT || ENABLE_HUSH_READONLY
  624. /* used to prevent word splitting and globbing in "export v=t*" */
  625. # define CMD_SINGLEWORD_NOGLOB 3
  626. #endif
  627. #if ENABLE_HUSH_FUNCTIONS
  628. # define CMD_FUNCDEF 4
  629. #endif
  630. smalluint cmd_exitcode;
  631. /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
  632. struct pipe *group;
  633. #if !BB_MMU
  634. char *group_as_string;
  635. #endif
  636. #if ENABLE_HUSH_FUNCTIONS
  637. struct function *child_func;
  638. /* This field is used to prevent a bug here:
  639. * while...do f1() {a;}; f1; f1() {b;}; f1; done
  640. * When we execute "f1() {a;}" cmd, we create new function and clear
  641. * cmd->group, cmd->group_as_string, cmd->argv[0].
  642. * When we execute "f1() {b;}", we notice that f1 exists,
  643. * and that its "parent cmd" struct is still "alive",
  644. * we put those fields back into cmd->xxx
  645. * (struct function has ->parent_cmd ptr to facilitate that).
  646. * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
  647. * Without this trick, loop would execute a;b;b;b;...
  648. * instead of correct sequence a;b;a;b;...
  649. * When command is freed, it severs the link
  650. * (sets ->child_func->parent_cmd to NULL).
  651. */
  652. #endif
  653. char **argv; /* command name and arguments */
  654. /* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
  655. * and on execution these are substituted with their values.
  656. * Substitution can make _several_ words out of one argv[n]!
  657. * Example: argv[0]=='.^C*^C.' here: echo .$*.
  658. * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
  659. */
  660. struct redir_struct *redirects; /* I/O redirections */
  661. };
  662. /* Is there anything in this command at all? */
  663. #define IS_NULL_CMD(cmd) \
  664. (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
  665. struct pipe {
  666. struct pipe *next;
  667. int num_cmds; /* total number of commands in pipe */
  668. int alive_cmds; /* number of commands running (not exited) */
  669. int stopped_cmds; /* number of commands alive, but stopped */
  670. #if ENABLE_HUSH_JOB
  671. unsigned jobid; /* job number */
  672. pid_t pgrp; /* process group ID for the job */
  673. char *cmdtext; /* name of job */
  674. #endif
  675. struct command *cmds; /* array of commands in pipe */
  676. smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
  677. IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
  678. IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
  679. };
  680. typedef enum pipe_style {
  681. PIPE_SEQ = 0,
  682. PIPE_AND = 1,
  683. PIPE_OR = 2,
  684. PIPE_BG = 3,
  685. } pipe_style;
  686. /* Is there anything in this pipe at all? */
  687. #define IS_NULL_PIPE(pi) \
  688. ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
  689. /* This holds pointers to the various results of parsing */
  690. struct parse_context {
  691. /* linked list of pipes */
  692. struct pipe *list_head;
  693. /* last pipe (being constructed right now) */
  694. struct pipe *pipe;
  695. /* last command in pipe (being constructed right now) */
  696. struct command *command;
  697. /* last redirect in command->redirects list */
  698. struct redir_struct *pending_redirect;
  699. o_string word;
  700. #if !BB_MMU
  701. o_string as_string;
  702. #endif
  703. smallint is_assignment; /* 0:maybe, 1:yes, 2:no, 3:keyword */
  704. #if HAS_KEYWORDS
  705. smallint ctx_res_w;
  706. smallint ctx_inverted; /* "! cmd | cmd" */
  707. #if ENABLE_HUSH_CASE
  708. smallint ctx_dsemicolon; /* ";;" seen */
  709. #endif
  710. /* bitmask of FLAG_xxx, for figuring out valid reserved words */
  711. int old_flag;
  712. /* group we are enclosed in:
  713. * example: "if pipe1; pipe2; then pipe3; fi"
  714. * when we see "if" or "then", we malloc and copy current context,
  715. * and make ->stack point to it. then we parse pipeN.
  716. * when closing "then" / fi" / whatever is found,
  717. * we move list_head into ->stack->command->group,
  718. * copy ->stack into current context, and delete ->stack.
  719. * (parsing of { list } and ( list ) doesn't use this method)
  720. */
  721. struct parse_context *stack;
  722. #endif
  723. };
  724. enum {
  725. MAYBE_ASSIGNMENT = 0,
  726. DEFINITELY_ASSIGNMENT = 1,
  727. NOT_ASSIGNMENT = 2,
  728. /* Not an assignment, but next word may be: "if v=xyz cmd;" */
  729. WORD_IS_KEYWORD = 3,
  730. };
  731. /* On program start, environ points to initial environment.
  732. * putenv adds new pointers into it, unsetenv removes them.
  733. * Neither of these (de)allocates the strings.
  734. * setenv allocates new strings in malloc space and does putenv,
  735. * and thus setenv is unusable (leaky) for shell's purposes */
  736. #define setenv(...) setenv_is_leaky_dont_use()
  737. struct variable {
  738. struct variable *next;
  739. char *varstr; /* points to "name=" portion */
  740. int max_len; /* if > 0, name is part of initial env; else name is malloced */
  741. uint16_t var_nest_level;
  742. smallint flg_export; /* putenv should be done on this var */
  743. smallint flg_read_only;
  744. };
  745. enum {
  746. BC_BREAK = 1,
  747. BC_CONTINUE = 2,
  748. };
  749. #if ENABLE_HUSH_FUNCTIONS
  750. struct function {
  751. struct function *next;
  752. char *name;
  753. struct command *parent_cmd;
  754. struct pipe *body;
  755. # if !BB_MMU
  756. char *body_as_string;
  757. # endif
  758. };
  759. #endif
  760. /* set -/+o OPT support. (TODO: make it optional)
  761. * bash supports the following opts:
  762. * allexport off
  763. * braceexpand on
  764. * emacs on
  765. * errexit off
  766. * errtrace off
  767. * functrace off
  768. * hashall on
  769. * histexpand off
  770. * history on
  771. * ignoreeof off
  772. * interactive-comments on
  773. * keyword off
  774. * monitor on
  775. * noclobber off
  776. * noexec off
  777. * noglob off
  778. * nolog off
  779. * notify off
  780. * nounset off
  781. * onecmd off
  782. * physical off
  783. * pipefail off
  784. * posix off
  785. * privileged off
  786. * verbose off
  787. * vi off
  788. * xtrace off
  789. */
  790. static const char o_opt_strings[] ALIGN1 =
  791. "pipefail\0"
  792. "noexec\0"
  793. "errexit\0"
  794. #if ENABLE_HUSH_MODE_X
  795. "xtrace\0"
  796. #endif
  797. ;
  798. enum {
  799. OPT_O_PIPEFAIL,
  800. OPT_O_NOEXEC,
  801. OPT_O_ERREXIT,
  802. #if ENABLE_HUSH_MODE_X
  803. OPT_O_XTRACE,
  804. #endif
  805. NUM_OPT_O
  806. };
  807. /* "Globals" within this file */
  808. /* Sorted roughly by size (smaller offsets == smaller code) */
  809. struct globals {
  810. /* interactive_fd != 0 means we are an interactive shell.
  811. * If we are, then saved_tty_pgrp can also be != 0, meaning
  812. * that controlling tty is available. With saved_tty_pgrp == 0,
  813. * job control still works, but terminal signals
  814. * (^C, ^Z, ^Y, ^\) won't work at all, and background
  815. * process groups can only be created with "cmd &".
  816. * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
  817. * to give tty to the foreground process group,
  818. * and will take it back when the group is stopped (^Z)
  819. * or killed (^C).
  820. */
  821. #if ENABLE_HUSH_INTERACTIVE
  822. /* 'interactive_fd' is a fd# open to ctty, if we have one
  823. * _AND_ if we decided to act interactively */
  824. int interactive_fd;
  825. IF_NOT_FEATURE_EDITING_FANCY_PROMPT(char *PS1;)
  826. # define G_interactive_fd (G.interactive_fd)
  827. #else
  828. # define G_interactive_fd 0
  829. #endif
  830. #if ENABLE_FEATURE_EDITING
  831. line_input_t *line_input_state;
  832. #endif
  833. pid_t root_pid;
  834. pid_t root_ppid;
  835. pid_t last_bg_pid;
  836. #if ENABLE_HUSH_RANDOM_SUPPORT
  837. random_t random_gen;
  838. #endif
  839. #if ENABLE_HUSH_JOB
  840. int run_list_level;
  841. unsigned last_jobid;
  842. pid_t saved_tty_pgrp;
  843. struct pipe *job_list;
  844. # define G_saved_tty_pgrp (G.saved_tty_pgrp)
  845. #else
  846. # define G_saved_tty_pgrp 0
  847. #endif
  848. /* How deeply are we in context where "set -e" is ignored */
  849. int errexit_depth;
  850. /* "set -e" rules (do we follow them correctly?):
  851. * Exit if pipe, list, or compound command exits with a non-zero status.
  852. * Shell does not exit if failed command is part of condition in
  853. * if/while, part of && or || list except the last command, any command
  854. * in a pipe but the last, or if the command's return value is being
  855. * inverted with !. If a compound command other than a subshell returns a
  856. * non-zero status because a command failed while -e was being ignored, the
  857. * shell does not exit. A trap on ERR, if set, is executed before the shell
  858. * exits [ERR is a bashism].
  859. *
  860. * If a compound command or function executes in a context where -e is
  861. * ignored, none of the commands executed within are affected by the -e
  862. * setting. If a compound command or function sets -e while executing in a
  863. * context where -e is ignored, that setting does not have any effect until
  864. * the compound command or the command containing the function call completes.
  865. */
  866. char o_opt[NUM_OPT_O];
  867. #if ENABLE_HUSH_MODE_X
  868. # define G_x_mode (G.o_opt[OPT_O_XTRACE])
  869. #else
  870. # define G_x_mode 0
  871. #endif
  872. char opt_s;
  873. char opt_c;
  874. #if ENABLE_HUSH_INTERACTIVE
  875. smallint promptmode; /* 0: PS1, 1: PS2 */
  876. #endif
  877. smallint flag_SIGINT;
  878. #if ENABLE_HUSH_LOOPS
  879. smallint flag_break_continue;
  880. #endif
  881. #if ENABLE_HUSH_FUNCTIONS
  882. /* 0: outside of a function (or sourced file)
  883. * -1: inside of a function, ok to use return builtin
  884. * 1: return is invoked, skip all till end of func
  885. */
  886. smallint flag_return_in_progress;
  887. # define G_flag_return_in_progress (G.flag_return_in_progress)
  888. #else
  889. # define G_flag_return_in_progress 0
  890. #endif
  891. smallint exiting; /* used to prevent EXIT trap recursion */
  892. /* These support $? */
  893. smalluint last_exitcode;
  894. smalluint expand_exitcode;
  895. smalluint last_bg_pid_exitcode;
  896. #if ENABLE_HUSH_SET
  897. /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
  898. smalluint global_args_malloced;
  899. # define G_global_args_malloced (G.global_args_malloced)
  900. #else
  901. # define G_global_args_malloced 0
  902. #endif
  903. #if ENABLE_HUSH_BASH_COMPAT
  904. int dead_job_exitcode; /* for "wait -n" */
  905. #endif
  906. /* how many non-NULL argv's we have. NB: $# + 1 */
  907. int global_argc;
  908. char **global_argv;
  909. #if !BB_MMU
  910. char *argv0_for_re_execing;
  911. #endif
  912. #if ENABLE_HUSH_LOOPS
  913. unsigned depth_break_continue;
  914. unsigned depth_of_loop;
  915. #endif
  916. #if ENABLE_HUSH_GETOPTS
  917. unsigned getopt_count;
  918. #endif
  919. const char *ifs;
  920. char *ifs_whitespace; /* = G.ifs or malloced */
  921. const char *cwd;
  922. struct variable *top_var;
  923. char **expanded_assignments;
  924. struct variable **shadowed_vars_pp;
  925. unsigned var_nest_level;
  926. #if ENABLE_HUSH_FUNCTIONS
  927. # if ENABLE_HUSH_LOCAL
  928. unsigned func_nest_level; /* solely to prevent "local v" in non-functions */
  929. # endif
  930. struct function *top_func;
  931. #endif
  932. /* Signal and trap handling */
  933. #if ENABLE_HUSH_FAST
  934. unsigned count_SIGCHLD;
  935. unsigned handled_SIGCHLD;
  936. smallint we_have_children;
  937. #endif
  938. #if ENABLE_HUSH_LINENO_VAR
  939. unsigned parse_lineno;
  940. unsigned execute_lineno;
  941. #endif
  942. HFILE *HFILE_list;
  943. HFILE *HFILE_stdin;
  944. /* Which signals have non-DFL handler (even with no traps set)?
  945. * Set at the start to:
  946. * (SIGQUIT + maybe SPECIAL_INTERACTIVE_SIGS + maybe SPECIAL_JOBSTOP_SIGS)
  947. * SPECIAL_INTERACTIVE_SIGS are cleared after fork.
  948. * The rest is cleared right before execv syscalls.
  949. * Other than these two times, never modified.
  950. */
  951. unsigned special_sig_mask;
  952. #if ENABLE_HUSH_JOB
  953. unsigned fatal_sig_mask;
  954. # define G_fatal_sig_mask (G.fatal_sig_mask)
  955. #else
  956. # define G_fatal_sig_mask 0
  957. #endif
  958. #if ENABLE_HUSH_TRAP
  959. int pre_trap_exitcode;
  960. # if ENABLE_HUSH_FUNCTIONS
  961. int return_exitcode;
  962. # endif
  963. char **traps; /* char *traps[NSIG] */
  964. # define G_traps G.traps
  965. #else
  966. # define G_traps ((char**)NULL)
  967. #endif
  968. sigset_t pending_set;
  969. #if ENABLE_HUSH_MEMLEAK
  970. unsigned long memleak_value;
  971. #endif
  972. #if ENABLE_HUSH_MODE_X
  973. unsigned x_mode_depth;
  974. /* "set -x" output should not be redirectable with subsequent 2>FILE.
  975. * We dup fd#2 to x_mode_fd when "set -x" is executed, and use it
  976. * for all subsequent output.
  977. */
  978. int x_mode_fd;
  979. o_string x_mode_buf;
  980. #endif
  981. #if HUSH_DEBUG >= 2
  982. int debug_indent;
  983. #endif
  984. struct sigaction sa;
  985. char optstring_buf[sizeof("eixcs")];
  986. #if BASH_EPOCH_VARS
  987. char epoch_buf[sizeof("%lu.nnnnnn") + sizeof(long)*3];
  988. #endif
  989. #if ENABLE_FEATURE_EDITING
  990. char user_input_buf[CONFIG_FEATURE_EDITING_MAX_LEN];
  991. #endif
  992. };
  993. #define G (*ptr_to_globals)
  994. /* Not #defining name to G.name - this quickly gets unwieldy
  995. * (too many defines). Also, I actually prefer to see when a variable
  996. * is global, thus "G." prefix is a useful hint */
  997. #define INIT_G() do { \
  998. SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
  999. /* memset(&G.sa, 0, sizeof(G.sa)); */ \
  1000. sigfillset(&G.sa.sa_mask); \
  1001. G.sa.sa_flags = SA_RESTART; \
  1002. } while (0)
  1003. /* Function prototypes for builtins */
  1004. static int builtin_cd(char **argv) FAST_FUNC;
  1005. #if ENABLE_HUSH_ECHO
  1006. static int builtin_echo(char **argv) FAST_FUNC;
  1007. #endif
  1008. static int builtin_eval(char **argv) FAST_FUNC;
  1009. static int builtin_exec(char **argv) FAST_FUNC;
  1010. static int builtin_exit(char **argv) FAST_FUNC;
  1011. #if ENABLE_HUSH_EXPORT
  1012. static int builtin_export(char **argv) FAST_FUNC;
  1013. #endif
  1014. #if ENABLE_HUSH_READONLY
  1015. static int builtin_readonly(char **argv) FAST_FUNC;
  1016. #endif
  1017. #if ENABLE_HUSH_JOB
  1018. static int builtin_fg_bg(char **argv) FAST_FUNC;
  1019. static int builtin_jobs(char **argv) FAST_FUNC;
  1020. #endif
  1021. #if ENABLE_HUSH_GETOPTS
  1022. static int builtin_getopts(char **argv) FAST_FUNC;
  1023. #endif
  1024. #if ENABLE_HUSH_HELP
  1025. static int builtin_help(char **argv) FAST_FUNC;
  1026. #endif
  1027. #if MAX_HISTORY && ENABLE_FEATURE_EDITING
  1028. static int builtin_history(char **argv) FAST_FUNC;
  1029. #endif
  1030. #if ENABLE_HUSH_LOCAL
  1031. static int builtin_local(char **argv) FAST_FUNC;
  1032. #endif
  1033. #if ENABLE_HUSH_MEMLEAK
  1034. static int builtin_memleak(char **argv) FAST_FUNC;
  1035. #endif
  1036. #if ENABLE_HUSH_PRINTF
  1037. static int builtin_printf(char **argv) FAST_FUNC;
  1038. #endif
  1039. static int builtin_pwd(char **argv) FAST_FUNC;
  1040. #if ENABLE_HUSH_READ
  1041. static int builtin_read(char **argv) FAST_FUNC;
  1042. #endif
  1043. #if ENABLE_HUSH_SET
  1044. static int builtin_set(char **argv) FAST_FUNC;
  1045. #endif
  1046. static int builtin_shift(char **argv) FAST_FUNC;
  1047. static int builtin_source(char **argv) FAST_FUNC;
  1048. #if ENABLE_HUSH_TEST || BASH_TEST2
  1049. static int builtin_test(char **argv) FAST_FUNC;
  1050. #endif
  1051. #if ENABLE_HUSH_TRAP
  1052. static int builtin_trap(char **argv) FAST_FUNC;
  1053. #endif
  1054. #if ENABLE_HUSH_TYPE
  1055. static int builtin_type(char **argv) FAST_FUNC;
  1056. #endif
  1057. #if ENABLE_HUSH_TIMES
  1058. static int builtin_times(char **argv) FAST_FUNC;
  1059. #endif
  1060. static int builtin_true(char **argv) FAST_FUNC;
  1061. #if ENABLE_HUSH_UMASK
  1062. static int builtin_umask(char **argv) FAST_FUNC;
  1063. #endif
  1064. #if ENABLE_HUSH_UNSET
  1065. static int builtin_unset(char **argv) FAST_FUNC;
  1066. #endif
  1067. #if ENABLE_HUSH_KILL
  1068. static int builtin_kill(char **argv) FAST_FUNC;
  1069. #endif
  1070. #if ENABLE_HUSH_WAIT
  1071. static int builtin_wait(char **argv) FAST_FUNC;
  1072. #endif
  1073. #if ENABLE_HUSH_LOOPS
  1074. static int builtin_break(char **argv) FAST_FUNC;
  1075. static int builtin_continue(char **argv) FAST_FUNC;
  1076. #endif
  1077. #if ENABLE_HUSH_FUNCTIONS
  1078. static int builtin_return(char **argv) FAST_FUNC;
  1079. #endif
  1080. /* Table of built-in functions. They can be forked or not, depending on
  1081. * context: within pipes, they fork. As simple commands, they do not.
  1082. * When used in non-forking context, they can change global variables
  1083. * in the parent shell process. If forked, of course they cannot.
  1084. * For example, 'unset foo | whatever' will parse and run, but foo will
  1085. * still be set at the end. */
  1086. struct built_in_command {
  1087. const char *b_cmd;
  1088. int (*b_function)(char **argv) FAST_FUNC;
  1089. #if ENABLE_HUSH_HELP
  1090. const char *b_descr;
  1091. # define BLTIN(cmd, func, help) { cmd, func, help }
  1092. #else
  1093. # define BLTIN(cmd, func, help) { cmd, func }
  1094. #endif
  1095. };
  1096. static const struct built_in_command bltins1[] ALIGN_PTR = {
  1097. BLTIN("." , builtin_source , "Run commands in file"),
  1098. BLTIN(":" , builtin_true , NULL),
  1099. #if ENABLE_HUSH_JOB
  1100. BLTIN("bg" , builtin_fg_bg , "Resume job in background"),
  1101. #endif
  1102. #if ENABLE_HUSH_LOOPS
  1103. BLTIN("break" , builtin_break , "Exit loop"),
  1104. #endif
  1105. BLTIN("cd" , builtin_cd , "Change directory"),
  1106. #if ENABLE_HUSH_LOOPS
  1107. BLTIN("continue" , builtin_continue, "Start new loop iteration"),
  1108. #endif
  1109. BLTIN("eval" , builtin_eval , "Construct and run shell command"),
  1110. BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
  1111. BLTIN("exit" , builtin_exit , NULL),
  1112. #if ENABLE_HUSH_EXPORT
  1113. BLTIN("export" , builtin_export , "Set environment variables"),
  1114. #endif
  1115. #if ENABLE_HUSH_JOB
  1116. BLTIN("fg" , builtin_fg_bg , "Bring job to foreground"),
  1117. #endif
  1118. #if ENABLE_HUSH_GETOPTS
  1119. BLTIN("getopts" , builtin_getopts , NULL),
  1120. #endif
  1121. #if ENABLE_HUSH_HELP
  1122. BLTIN("help" , builtin_help , NULL),
  1123. #endif
  1124. #if MAX_HISTORY && ENABLE_FEATURE_EDITING
  1125. BLTIN("history" , builtin_history , "Show history"),
  1126. #endif
  1127. #if ENABLE_HUSH_JOB
  1128. BLTIN("jobs" , builtin_jobs , "List jobs"),
  1129. #endif
  1130. #if ENABLE_HUSH_KILL
  1131. BLTIN("kill" , builtin_kill , "Send signals to processes"),
  1132. #endif
  1133. #if ENABLE_HUSH_LOCAL
  1134. BLTIN("local" , builtin_local , "Set local variables"),
  1135. #endif
  1136. #if ENABLE_HUSH_MEMLEAK
  1137. BLTIN("memleak" , builtin_memleak , NULL),
  1138. #endif
  1139. #if ENABLE_HUSH_READ
  1140. BLTIN("read" , builtin_read , "Input into variable"),
  1141. #endif
  1142. #if ENABLE_HUSH_READONLY
  1143. BLTIN("readonly" , builtin_readonly, "Make variables read-only"),
  1144. #endif
  1145. #if ENABLE_HUSH_FUNCTIONS
  1146. BLTIN("return" , builtin_return , "Return from function"),
  1147. #endif
  1148. #if ENABLE_HUSH_SET
  1149. BLTIN("set" , builtin_set , "Set positional parameters"),
  1150. #endif
  1151. BLTIN("shift" , builtin_shift , "Shift positional parameters"),
  1152. #if BASH_SOURCE
  1153. BLTIN("source" , builtin_source , NULL),
  1154. #endif
  1155. #if ENABLE_HUSH_TIMES
  1156. BLTIN("times" , builtin_times , NULL),
  1157. #endif
  1158. #if ENABLE_HUSH_TRAP
  1159. BLTIN("trap" , builtin_trap , "Trap signals"),
  1160. #endif
  1161. BLTIN("true" , builtin_true , NULL),
  1162. #if ENABLE_HUSH_TYPE
  1163. BLTIN("type" , builtin_type , "Show command type"),
  1164. #endif
  1165. #if ENABLE_HUSH_ULIMIT
  1166. BLTIN("ulimit" , shell_builtin_ulimit, "Control resource limits"),
  1167. #endif
  1168. #if ENABLE_HUSH_UMASK
  1169. BLTIN("umask" , builtin_umask , "Set file creation mask"),
  1170. #endif
  1171. #if ENABLE_HUSH_UNSET
  1172. BLTIN("unset" , builtin_unset , "Unset variables"),
  1173. #endif
  1174. #if ENABLE_HUSH_WAIT
  1175. BLTIN("wait" , builtin_wait , "Wait for process to finish"),
  1176. #endif
  1177. };
  1178. /* These builtins won't be used if we are on NOMMU and need to re-exec
  1179. * (it's cheaper to run an external program in this case):
  1180. */
  1181. static const struct built_in_command bltins2[] ALIGN_PTR = {
  1182. #if ENABLE_HUSH_TEST
  1183. BLTIN("[" , builtin_test , NULL),
  1184. #endif
  1185. #if BASH_TEST2
  1186. BLTIN("[[" , builtin_test , NULL),
  1187. #endif
  1188. #if ENABLE_HUSH_ECHO
  1189. BLTIN("echo" , builtin_echo , NULL),
  1190. #endif
  1191. #if ENABLE_HUSH_PRINTF
  1192. BLTIN("printf" , builtin_printf , NULL),
  1193. #endif
  1194. BLTIN("pwd" , builtin_pwd , NULL),
  1195. #if ENABLE_HUSH_TEST
  1196. BLTIN("test" , builtin_test , NULL),
  1197. #endif
  1198. };
  1199. /* Debug printouts.
  1200. */
  1201. #if HUSH_DEBUG >= 2
  1202. /* prevent disasters with G.debug_indent < 0 */
  1203. # define indent() fdprintf(2, "%*s", (G.debug_indent * 2) & 0xff, "")
  1204. # define debug_enter() (G.debug_indent++)
  1205. # define debug_leave() (G.debug_indent--)
  1206. #else
  1207. # define indent() ((void)0)
  1208. # define debug_enter() ((void)0)
  1209. # define debug_leave() ((void)0)
  1210. #endif
  1211. #ifndef debug_printf
  1212. # define debug_printf(...) (indent(), fdprintf(2, __VA_ARGS__))
  1213. #endif
  1214. #ifndef debug_printf_parse
  1215. # define debug_printf_parse(...) (indent(), fdprintf(2, __VA_ARGS__))
  1216. #endif
  1217. #ifndef debug_printf_heredoc
  1218. # define debug_printf_heredoc(...) (indent(), fdprintf(2, __VA_ARGS__))
  1219. #endif
  1220. #ifndef debug_printf_exec
  1221. #define debug_printf_exec(...) (indent(), fdprintf(2, __VA_ARGS__))
  1222. #endif
  1223. #ifndef debug_printf_env
  1224. # define debug_printf_env(...) (indent(), fdprintf(2, __VA_ARGS__))
  1225. #endif
  1226. #ifndef debug_printf_jobs
  1227. # define debug_printf_jobs(...) (indent(), fdprintf(2, __VA_ARGS__))
  1228. # define DEBUG_JOBS 1
  1229. #else
  1230. # define DEBUG_JOBS 0
  1231. #endif
  1232. #ifndef debug_printf_expand
  1233. # define debug_printf_expand(...) (indent(), fdprintf(2, __VA_ARGS__))
  1234. # define DEBUG_EXPAND 1
  1235. #else
  1236. # define DEBUG_EXPAND 0
  1237. #endif
  1238. #ifndef debug_printf_varexp
  1239. # define debug_printf_varexp(...) (indent(), fdprintf(2, __VA_ARGS__))
  1240. #endif
  1241. #ifndef debug_printf_glob
  1242. # define debug_printf_glob(...) (indent(), fdprintf(2, __VA_ARGS__))
  1243. # define DEBUG_GLOB 1
  1244. #else
  1245. # define DEBUG_GLOB 0
  1246. #endif
  1247. #ifndef debug_printf_redir
  1248. # define debug_printf_redir(...) (indent(), fdprintf(2, __VA_ARGS__))
  1249. #endif
  1250. #ifndef debug_printf_list
  1251. # define debug_printf_list(...) (indent(), fdprintf(2, __VA_ARGS__))
  1252. #endif
  1253. #ifndef debug_printf_subst
  1254. # define debug_printf_subst(...) (indent(), fdprintf(2, __VA_ARGS__))
  1255. #endif
  1256. #ifndef debug_printf_prompt
  1257. # define debug_printf_prompt(...) (indent(), fdprintf(2, __VA_ARGS__))
  1258. #endif
  1259. #ifndef debug_printf_clean
  1260. # define debug_printf_clean(...) (indent(), fdprintf(2, __VA_ARGS__))
  1261. # define DEBUG_CLEAN 1
  1262. #else
  1263. # define DEBUG_CLEAN 0
  1264. #endif
  1265. #if DEBUG_EXPAND
  1266. static void debug_print_strings(const char *prefix, char **vv)
  1267. {
  1268. indent();
  1269. fdprintf(2, "%s:\n", prefix);
  1270. while (*vv)
  1271. fdprintf(2, " '%s'\n", *vv++);
  1272. }
  1273. #else
  1274. # define debug_print_strings(prefix, vv) ((void)0)
  1275. #endif
  1276. /* Leak hunting. Use hush_leaktool.sh for post-processing.
  1277. */
  1278. #if LEAK_HUNTING
  1279. static void *xxmalloc(int lineno, size_t size)
  1280. {
  1281. void *ptr = xmalloc((size + 0xff) & ~0xff);
  1282. fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
  1283. return ptr;
  1284. }
  1285. static void *xxrealloc(int lineno, void *ptr, size_t size)
  1286. {
  1287. ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
  1288. fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
  1289. return ptr;
  1290. }
  1291. static char *xxstrdup(int lineno, const char *str)
  1292. {
  1293. char *ptr = xstrdup(str);
  1294. fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
  1295. return ptr;
  1296. }
  1297. static void xxfree(void *ptr)
  1298. {
  1299. fdprintf(2, "free %p\n", ptr);
  1300. free(ptr);
  1301. }
  1302. # define xmalloc(s) xxmalloc(__LINE__, s)
  1303. # define xrealloc(p, s) xxrealloc(__LINE__, p, s)
  1304. # define xstrdup(s) xxstrdup(__LINE__, s)
  1305. # define free(p) xxfree(p)
  1306. #endif
  1307. /* Syntax and runtime errors. They always abort scripts.
  1308. * In interactive use they usually discard unparsed and/or unexecuted commands
  1309. * and return to the prompt.
  1310. * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
  1311. */
  1312. #if HUSH_DEBUG < 2
  1313. # define msg_and_die_if_script(lineno, ...) msg_and_die_if_script(__VA_ARGS__)
  1314. # define syntax_error(lineno, msg) syntax_error(msg)
  1315. # define syntax_error_at(lineno, msg) syntax_error_at(msg)
  1316. # define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
  1317. # define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
  1318. # define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
  1319. #endif
  1320. static void die_if_script(void)
  1321. {
  1322. if (!G_interactive_fd) {
  1323. if (G.last_exitcode) /* sometines it's 2, not 1 (bash compat) */
  1324. xfunc_error_retval = G.last_exitcode;
  1325. xfunc_die();
  1326. }
  1327. }
  1328. static void msg_and_die_if_script(unsigned lineno, const char *fmt, ...)
  1329. {
  1330. va_list p;
  1331. #if HUSH_DEBUG >= 2
  1332. bb_error_msg("hush.c:%u", lineno);
  1333. #endif
  1334. va_start(p, fmt);
  1335. bb_verror_msg(fmt, p, NULL);
  1336. va_end(p);
  1337. die_if_script();
  1338. }
  1339. static void syntax_error(unsigned lineno UNUSED_PARAM, const char *msg)
  1340. {
  1341. if (msg)
  1342. bb_error_msg("syntax error: %s", msg);
  1343. else
  1344. bb_simple_error_msg("syntax error");
  1345. die_if_script();
  1346. }
  1347. static void syntax_error_at(unsigned lineno UNUSED_PARAM, const char *msg)
  1348. {
  1349. bb_error_msg("syntax error at '%s'", msg);
  1350. die_if_script();
  1351. }
  1352. static void syntax_error_unterm_str(unsigned lineno UNUSED_PARAM, const char *s)
  1353. {
  1354. bb_error_msg("syntax error: unterminated %s", s);
  1355. //? source4.tests fails: in bash, echo ${^} in script does not terminate the script
  1356. // die_if_script();
  1357. }
  1358. static void syntax_error_unterm_ch(unsigned lineno, char ch)
  1359. {
  1360. char msg[2] = { ch, '\0' };
  1361. syntax_error_unterm_str(lineno, msg);
  1362. }
  1363. static void syntax_error_unexpected_ch(unsigned lineno UNUSED_PARAM, int ch)
  1364. {
  1365. char msg[2];
  1366. msg[0] = ch;
  1367. msg[1] = '\0';
  1368. #if HUSH_DEBUG >= 2
  1369. bb_error_msg("hush.c:%u", lineno);
  1370. #endif
  1371. bb_error_msg("syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
  1372. die_if_script();
  1373. }
  1374. #if HUSH_DEBUG < 2
  1375. # undef msg_and_die_if_script
  1376. # undef syntax_error
  1377. # undef syntax_error_at
  1378. # undef syntax_error_unterm_ch
  1379. # undef syntax_error_unterm_str
  1380. # undef syntax_error_unexpected_ch
  1381. #else
  1382. # define msg_and_die_if_script(...) msg_and_die_if_script(__LINE__, __VA_ARGS__)
  1383. # define syntax_error(msg) syntax_error(__LINE__, msg)
  1384. # define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
  1385. # define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
  1386. # define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
  1387. # define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
  1388. #endif
  1389. /* Utility functions
  1390. */
  1391. /* Replace each \x with x in place, return ptr past NUL. */
  1392. static char *unbackslash(char *src)
  1393. {
  1394. char *dst = src = strchrnul(src, '\\');
  1395. while (1) {
  1396. if (*src == '\\') {
  1397. src++;
  1398. if (*src != '\0') {
  1399. /* \x -> x */
  1400. *dst++ = *src++;
  1401. continue;
  1402. }
  1403. /* else: "\<nul>". Do not delete this backslash.
  1404. * Testcase: eval 'echo ok\'
  1405. */
  1406. *dst++ = '\\';
  1407. /* fallthrough */
  1408. }
  1409. if ((*dst++ = *src++) == '\0')
  1410. break;
  1411. }
  1412. return dst;
  1413. }
  1414. static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
  1415. {
  1416. int i;
  1417. unsigned count1;
  1418. unsigned count2;
  1419. char **v;
  1420. v = strings;
  1421. count1 = 0;
  1422. if (v) {
  1423. while (*v) {
  1424. count1++;
  1425. v++;
  1426. }
  1427. }
  1428. count2 = 0;
  1429. v = add;
  1430. while (*v) {
  1431. count2++;
  1432. v++;
  1433. }
  1434. v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
  1435. v[count1 + count2] = NULL;
  1436. i = count2;
  1437. while (--i >= 0)
  1438. v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
  1439. return v;
  1440. }
  1441. #if LEAK_HUNTING
  1442. static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
  1443. {
  1444. char **ptr = add_strings_to_strings(strings, add, need_to_dup);
  1445. fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
  1446. return ptr;
  1447. }
  1448. #define add_strings_to_strings(strings, add, need_to_dup) \
  1449. xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
  1450. #endif
  1451. /* Note: takes ownership of "add" ptr (it is not strdup'ed) */
  1452. static char **add_string_to_strings(char **strings, char *add)
  1453. {
  1454. char *v[2];
  1455. v[0] = add;
  1456. v[1] = NULL;
  1457. return add_strings_to_strings(strings, v, /*dup:*/ 0);
  1458. }
  1459. #if LEAK_HUNTING
  1460. static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
  1461. {
  1462. char **ptr = add_string_to_strings(strings, add);
  1463. fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
  1464. return ptr;
  1465. }
  1466. #define add_string_to_strings(strings, add) \
  1467. xx_add_string_to_strings(__LINE__, strings, add)
  1468. #endif
  1469. static void free_strings(char **strings)
  1470. {
  1471. char **v;
  1472. if (!strings)
  1473. return;
  1474. v = strings;
  1475. while (*v) {
  1476. free(*v);
  1477. v++;
  1478. }
  1479. free(strings);
  1480. }
  1481. static int dup_CLOEXEC(int fd, int avoid_fd)
  1482. {
  1483. int newfd;
  1484. repeat:
  1485. newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
  1486. if (newfd >= 0) {
  1487. if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
  1488. fcntl(newfd, F_SETFD, FD_CLOEXEC);
  1489. } else { /* newfd < 0 */
  1490. if (errno == EBUSY)
  1491. goto repeat;
  1492. if (errno == EINTR)
  1493. goto repeat;
  1494. }
  1495. return newfd;
  1496. }
  1497. static int xdup_CLOEXEC_and_close(int fd, int avoid_fd)
  1498. {
  1499. int newfd;
  1500. repeat:
  1501. newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
  1502. if (newfd < 0) {
  1503. if (errno == EBUSY)
  1504. goto repeat;
  1505. if (errno == EINTR)
  1506. goto repeat;
  1507. /* fd was not open? */
  1508. if (errno == EBADF)
  1509. return fd;
  1510. xfunc_die();
  1511. }
  1512. if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
  1513. fcntl(newfd, F_SETFD, FD_CLOEXEC);
  1514. close(fd);
  1515. return newfd;
  1516. }
  1517. /* Manipulating HFILEs */
  1518. static HFILE *hfopen(const char *name)
  1519. {
  1520. HFILE *fp;
  1521. int fd;
  1522. fd = STDIN_FILENO;
  1523. if (name) {
  1524. fd = open(name, O_RDONLY | O_CLOEXEC);
  1525. if (fd < 0)
  1526. return NULL;
  1527. if (O_CLOEXEC == 0) /* ancient libc */
  1528. close_on_exec_on(fd);
  1529. }
  1530. fp = xmalloc(sizeof(*fp));
  1531. if (name == NULL)
  1532. G.HFILE_stdin = fp;
  1533. fp->fd = fd;
  1534. fp->cur = fp->end = fp->buf;
  1535. fp->next_hfile = G.HFILE_list;
  1536. G.HFILE_list = fp;
  1537. return fp;
  1538. }
  1539. static void hfclose(HFILE *fp)
  1540. {
  1541. HFILE **pp = &G.HFILE_list;
  1542. while (*pp) {
  1543. HFILE *cur = *pp;
  1544. if (cur == fp) {
  1545. *pp = cur->next_hfile;
  1546. break;
  1547. }
  1548. pp = &cur->next_hfile;
  1549. }
  1550. if (fp->fd >= 0)
  1551. close(fp->fd);
  1552. free(fp);
  1553. }
  1554. static int refill_HFILE_and_getc(HFILE *fp)
  1555. {
  1556. int n;
  1557. if (fp->fd < 0) {
  1558. /* Already saw EOF */
  1559. return EOF;
  1560. }
  1561. #if ENABLE_HUSH_INTERACTIVE && !ENABLE_FEATURE_EDITING
  1562. /* If user presses ^C, read() restarts after SIGINT (we use SA_RESTART).
  1563. * IOW: ^C will not immediately stop line input.
  1564. * But poll() is different: it does NOT restart after signals.
  1565. */
  1566. if (fp == G.HFILE_stdin) {
  1567. struct pollfd pfd[1];
  1568. pfd[0].fd = fp->fd;
  1569. pfd[0].events = POLLIN;
  1570. n = poll(pfd, 1, -1);
  1571. if (n < 0
  1572. /*&& errno == EINTR - assumed true */
  1573. && sigismember(&G.pending_set, SIGINT)
  1574. ) {
  1575. return '\0';
  1576. }
  1577. }
  1578. #else
  1579. /* if FEATURE_EDITING=y, we do not use this routine for interactive input */
  1580. #endif
  1581. /* Try to buffer more input */
  1582. n = safe_read(fp->fd, fp->buf, sizeof(fp->buf));
  1583. if (n < 0) {
  1584. bb_simple_perror_msg("read error");
  1585. n = 0;
  1586. }
  1587. fp->cur = fp->buf;
  1588. fp->end = fp->buf + n;
  1589. if (n == 0) {
  1590. /* EOF/error */
  1591. close(fp->fd);
  1592. fp->fd = -1;
  1593. return EOF;
  1594. }
  1595. return (unsigned char)(*fp->cur++);
  1596. }
  1597. /* Inlined for common case of non-empty buffer.
  1598. */
  1599. static ALWAYS_INLINE int hfgetc(HFILE *fp)
  1600. {
  1601. if (fp->cur < fp->end)
  1602. return (unsigned char)(*fp->cur++);
  1603. /* Buffer empty */
  1604. return refill_HFILE_and_getc(fp);
  1605. }
  1606. static int move_HFILEs_on_redirect(int fd, int avoid_fd)
  1607. {
  1608. HFILE *fl = G.HFILE_list;
  1609. while (fl) {
  1610. if (fd == fl->fd) {
  1611. /* We use it only on script files, they are all CLOEXEC */
  1612. fl->fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
  1613. debug_printf_redir("redirect_fd %d: matches a script fd, moving it to %d\n", fd, fl->fd);
  1614. return 1; /* "found and moved" */
  1615. }
  1616. fl = fl->next_hfile;
  1617. }
  1618. #if ENABLE_HUSH_MODE_X
  1619. if (G.x_mode_fd > 0 && fd == G.x_mode_fd) {
  1620. G.x_mode_fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
  1621. return 1; /* "found and moved" */
  1622. }
  1623. #endif
  1624. return 0; /* "not in the list" */
  1625. }
  1626. #if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
  1627. static void close_all_HFILE_list(void)
  1628. {
  1629. HFILE *fl = G.HFILE_list;
  1630. while (fl) {
  1631. /* hfclose would also free HFILE object.
  1632. * It is disastrous if we share memory with a vforked parent.
  1633. * I'm not sure we never come here after vfork.
  1634. * Therefore just close fd, nothing more.
  1635. *
  1636. * ">" instead of ">=": we don't close fd#0,
  1637. * interactive shell uses hfopen(NULL) as stdin input
  1638. * which has fl->fd == 0, but fd#0 gets redirected in pipes.
  1639. * If we'd close it here, then e.g. interactive "set | sort"
  1640. * with NOFORKed sort, would have sort's input fd closed.
  1641. */
  1642. if (fl->fd > 0)
  1643. /*hfclose(fl); - unsafe */
  1644. close(fl->fd);
  1645. fl = fl->next_hfile;
  1646. }
  1647. }
  1648. #endif
  1649. static int fd_in_HFILEs(int fd)
  1650. {
  1651. HFILE *fl = G.HFILE_list;
  1652. while (fl) {
  1653. if (fl->fd == fd)
  1654. return 1;
  1655. fl = fl->next_hfile;
  1656. }
  1657. return 0;
  1658. }
  1659. /* Helpers for setting new $n and restoring them back
  1660. */
  1661. typedef struct save_arg_t {
  1662. char *sv_argv0;
  1663. char **sv_g_argv;
  1664. int sv_g_argc;
  1665. IF_HUSH_SET(smallint sv_g_malloced;)
  1666. } save_arg_t;
  1667. static void save_and_replace_G_args(save_arg_t *sv, char **argv)
  1668. {
  1669. sv->sv_argv0 = argv[0];
  1670. sv->sv_g_argv = G.global_argv;
  1671. sv->sv_g_argc = G.global_argc;
  1672. IF_HUSH_SET(sv->sv_g_malloced = G.global_args_malloced;)
  1673. argv[0] = G.global_argv[0]; /* retain $0 */
  1674. G.global_argv = argv;
  1675. IF_HUSH_SET(G.global_args_malloced = 0;)
  1676. G.global_argc = 1 + string_array_len(argv + 1);
  1677. }
  1678. static void restore_G_args(save_arg_t *sv, char **argv)
  1679. {
  1680. #if ENABLE_HUSH_SET
  1681. if (G.global_args_malloced) {
  1682. /* someone ran "set -- arg1 arg2 ...", undo */
  1683. char **pp = G.global_argv;
  1684. while (*++pp) /* note: does not free $0 */
  1685. free(*pp);
  1686. free(G.global_argv);
  1687. }
  1688. #endif
  1689. argv[0] = sv->sv_argv0;
  1690. G.global_argv = sv->sv_g_argv;
  1691. G.global_argc = sv->sv_g_argc;
  1692. IF_HUSH_SET(G.global_args_malloced = sv->sv_g_malloced;)
  1693. }
  1694. /* Basic theory of signal handling in shell
  1695. * ========================================
  1696. * This does not describe what hush does, rather, it is current understanding
  1697. * what it _should_ do. If it doesn't, it's a bug.
  1698. * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
  1699. *
  1700. * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
  1701. * is finished or backgrounded. It is the same in interactive and
  1702. * non-interactive shells, and is the same regardless of whether
  1703. * a user trap handler is installed or a shell special one is in effect.
  1704. * ^C or ^Z from keyboard seems to execute "at once" because it usually
  1705. * backgrounds (i.e. stops) or kills all members of currently running
  1706. * pipe.
  1707. *
  1708. * Wait builtin is interruptible by signals for which user trap is set
  1709. * or by SIGINT in interactive shell.
  1710. *
  1711. * Trap handlers will execute even within trap handlers. (right?)
  1712. *
  1713. * User trap handlers are forgotten when subshell ("(cmd)") is entered,
  1714. * except for handlers set to '' (empty string).
  1715. *
  1716. * If job control is off, backgrounded commands ("cmd &")
  1717. * have SIGINT, SIGQUIT set to SIG_IGN.
  1718. *
  1719. * Commands which are run in command substitution ("`cmd`")
  1720. * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
  1721. *
  1722. * Ordinary commands have signals set to SIG_IGN/DFL as inherited
  1723. * by the shell from its parent.
  1724. *
  1725. * Signals which differ from SIG_DFL action
  1726. * (note: child (i.e., [v]forked) shell is not an interactive shell):
  1727. *
  1728. * SIGQUIT: ignore
  1729. * SIGTERM (interactive): ignore
  1730. * SIGHUP (interactive):
  1731. * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
  1732. * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
  1733. * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
  1734. * that all pipe members are stopped. Try this in bash:
  1735. * while :; do :; done - ^Z does not background it
  1736. * (while :; do :; done) - ^Z backgrounds it
  1737. * SIGINT (interactive): wait for last pipe, ignore the rest
  1738. * of the command line, show prompt. NB: ^C does not send SIGINT
  1739. * to interactive shell while shell is waiting for a pipe,
  1740. * since shell is bg'ed (is not in foreground process group).
  1741. * Example 1: this waits 5 sec, but does not execute ls:
  1742. * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
  1743. * Example 2: this does not wait and does not execute ls:
  1744. * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
  1745. * Example 3: this does not wait 5 sec, but executes ls:
  1746. * "sleep 5; ls -l" + press ^C
  1747. * Example 4: this does not wait and does not execute ls:
  1748. * "sleep 5 & wait; ls -l" + press ^C
  1749. *
  1750. * (What happens to signals which are IGN on shell start?)
  1751. * (What happens with signal mask on shell start?)
  1752. *
  1753. * Old implementation
  1754. * ==================
  1755. * We use in-kernel pending signal mask to determine which signals were sent.
  1756. * We block all signals which we don't want to take action immediately,
  1757. * i.e. we block all signals which need to have special handling as described
  1758. * above, and all signals which have traps set.
  1759. * After each pipe execution, we extract any pending signals via sigtimedwait()
  1760. * and act on them.
  1761. *
  1762. * unsigned special_sig_mask: a mask of such "special" signals
  1763. * sigset_t blocked_set: current blocked signal set
  1764. *
  1765. * "trap - SIGxxx":
  1766. * clear bit in blocked_set unless it is also in special_sig_mask
  1767. * "trap 'cmd' SIGxxx":
  1768. * set bit in blocked_set (even if 'cmd' is '')
  1769. * after [v]fork, if we plan to be a shell:
  1770. * unblock signals with special interactive handling
  1771. * (child shell is not interactive),
  1772. * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
  1773. * after [v]fork, if we plan to exec:
  1774. * POSIX says fork clears pending signal mask in child - no need to clear it.
  1775. * Restore blocked signal set to one inherited by shell just prior to exec.
  1776. *
  1777. * Note: as a result, we do not use signal handlers much. The only uses
  1778. * are to count SIGCHLDs
  1779. * and to restore tty pgrp on signal-induced exit.
  1780. *
  1781. * Note 2 (compat):
  1782. * Standard says "When a subshell is entered, traps that are not being ignored
  1783. * are set to the default actions". bash interprets it so that traps which
  1784. * are set to '' (ignore) are NOT reset to defaults. We do the same.
  1785. *
  1786. * Problem: the above approach makes it unwieldy to catch signals while
  1787. * we are in read builtin, or while we read commands from stdin:
  1788. * masked signals are not visible!
  1789. *
  1790. * New implementation
  1791. * ==================
  1792. * We record each signal we are interested in by installing signal handler
  1793. * for them - a bit like emulating kernel pending signal mask in userspace.
  1794. * We are interested in: signals which need to have special handling
  1795. * as described above, and all signals which have traps set.
  1796. * Signals are recorded in pending_set.
  1797. * After each pipe execution, we extract any pending signals
  1798. * and act on them.
  1799. *
  1800. * unsigned special_sig_mask: a mask of shell-special signals.
  1801. * unsigned fatal_sig_mask: a mask of signals on which we restore tty pgrp.
  1802. * char *traps[sig] if trap for sig is set (even if it's '').
  1803. * sigset_t pending_set: set of sigs we received.
  1804. *
  1805. * "trap - SIGxxx":
  1806. * if sig is in special_sig_mask, set handler back to:
  1807. * record_pending_signo, or to IGN if it's a tty stop signal
  1808. * if sig is in fatal_sig_mask, set handler back to sigexit.
  1809. * else: set handler back to SIG_DFL
  1810. * "trap 'cmd' SIGxxx":
  1811. * set handler to record_pending_signo.
  1812. * "trap '' SIGxxx":
  1813. * set handler to SIG_IGN.
  1814. * after [v]fork, if we plan to be a shell:
  1815. * set signals with special interactive handling to SIG_DFL
  1816. * (because child shell is not interactive),
  1817. * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
  1818. * after [v]fork, if we plan to exec:
  1819. * POSIX says fork clears pending signal mask in child - no need to clear it.
  1820. *
  1821. * To make wait builtin interruptible, we handle SIGCHLD as special signal,
  1822. * otherwise (if we leave it SIG_DFL) sigsuspend in wait builtin will not wake up on it.
  1823. *
  1824. * Note (compat):
  1825. * Standard says "When a subshell is entered, traps that are not being ignored
  1826. * are set to the default actions". bash interprets it so that traps which
  1827. * are set to '' (ignore) are NOT reset to defaults. We do the same.
  1828. */
  1829. enum {
  1830. SPECIAL_INTERACTIVE_SIGS = 0
  1831. | (1 << SIGTERM)
  1832. | (1 << SIGINT)
  1833. | (1 << SIGHUP)
  1834. ,
  1835. SPECIAL_JOBSTOP_SIGS = 0
  1836. #if ENABLE_HUSH_JOB
  1837. | (1 << SIGTTIN)
  1838. | (1 << SIGTTOU)
  1839. | (1 << SIGTSTP)
  1840. #endif
  1841. ,
  1842. };
  1843. static void record_pending_signo(int sig)
  1844. {
  1845. sigaddset(&G.pending_set, sig);
  1846. #if ENABLE_HUSH_FAST
  1847. if (sig == SIGCHLD) {
  1848. G.count_SIGCHLD++;
  1849. //bb_error_msg("[%d] SIGCHLD_handler: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
  1850. }
  1851. #endif
  1852. }
  1853. static sighandler_t install_sighandler(int sig, sighandler_t handler)
  1854. {
  1855. struct sigaction old_sa;
  1856. /* We could use signal() to install handlers... almost:
  1857. * except that we need to mask ALL signals while handlers run.
  1858. * I saw signal nesting in strace, race window isn't small.
  1859. * SA_RESTART is also needed, but in Linux, signal()
  1860. * sets SA_RESTART too.
  1861. */
  1862. /* memset(&G.sa, 0, sizeof(G.sa)); - already done */
  1863. /* sigfillset(&G.sa.sa_mask); - already done */
  1864. /* G.sa.sa_flags = SA_RESTART; - already done */
  1865. G.sa.sa_handler = handler;
  1866. sigaction(sig, &G.sa, &old_sa);
  1867. return old_sa.sa_handler;
  1868. }
  1869. static void hush_exit(int exitcode) NORETURN;
  1870. static void restore_ttypgrp_and__exit(void) NORETURN;
  1871. static void restore_ttypgrp_and__exit(void)
  1872. {
  1873. /* xfunc has failed! die die die */
  1874. /* no EXIT traps, this is an escape hatch! */
  1875. G.exiting = 1;
  1876. hush_exit(xfunc_error_retval);
  1877. }
  1878. #if ENABLE_HUSH_JOB
  1879. /* Needed only on some libc:
  1880. * It was observed that on exit(), fgetc'ed buffered data
  1881. * gets "unwound" via lseek(fd, -NUM, SEEK_CUR).
  1882. * With the net effect that even after fork(), not vfork(),
  1883. * exit() in NOEXECed applet in "sh SCRIPT":
  1884. * noexec_applet_here
  1885. * echo END_OF_SCRIPT
  1886. * lseeks fd in input FILE object from EOF to "e" in "echo END_OF_SCRIPT".
  1887. * This makes "echo END_OF_SCRIPT" executed twice.
  1888. * Similar problems can be seen with msg_and_die_if_script() -> xfunc_die()
  1889. * and in `cmd` handling.
  1890. * If set as die_func(), this makes xfunc_die() exit via _exit(), not exit():
  1891. */
  1892. static void fflush_and__exit(void) NORETURN;
  1893. static void fflush_and__exit(void)
  1894. {
  1895. fflush_all();
  1896. _exit(xfunc_error_retval);
  1897. }
  1898. /* After [v]fork, in child: do not restore tty pgrp on xfunc death */
  1899. # define disable_restore_tty_pgrp_on_exit() (die_func = fflush_and__exit)
  1900. /* After [v]fork, in parent: restore tty pgrp on xfunc death */
  1901. # define enable_restore_tty_pgrp_on_exit() (die_func = restore_ttypgrp_and__exit)
  1902. /* Restores tty foreground process group, and exits.
  1903. * May be called as signal handler for fatal signal
  1904. * (will resend signal to itself, producing correct exit state)
  1905. * or called directly with -EXITCODE.
  1906. * We also call it if xfunc is exiting.
  1907. */
  1908. static void sigexit(int sig) NORETURN;
  1909. static void sigexit(int sig)
  1910. {
  1911. /* Careful: we can end up here after [v]fork. Do not restore
  1912. * tty pgrp then, only top-level shell process does that */
  1913. if (G_saved_tty_pgrp && getpid() == G.root_pid) {
  1914. /* Disable all signals: job control, SIGPIPE, etc.
  1915. * Mostly paranoid measure, to prevent infinite SIGTTOU.
  1916. */
  1917. sigprocmask_allsigs(SIG_BLOCK);
  1918. tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
  1919. }
  1920. /* Not a signal, just exit */
  1921. if (sig <= 0)
  1922. _exit(- sig);
  1923. kill_myself_with_sig(sig); /* does not return */
  1924. }
  1925. #else
  1926. # define disable_restore_tty_pgrp_on_exit() ((void)0)
  1927. # define enable_restore_tty_pgrp_on_exit() ((void)0)
  1928. #endif
  1929. static sighandler_t pick_sighandler(unsigned sig)
  1930. {
  1931. sighandler_t handler = SIG_DFL;
  1932. if (sig < sizeof(unsigned)*8) {
  1933. unsigned sigmask = (1 << sig);
  1934. #if ENABLE_HUSH_JOB
  1935. /* is sig fatal? */
  1936. if (G_fatal_sig_mask & sigmask)
  1937. handler = sigexit;
  1938. else
  1939. #endif
  1940. /* sig has special handling? */
  1941. if (G.special_sig_mask & sigmask) {
  1942. handler = record_pending_signo;
  1943. /* TTIN/TTOU/TSTP can't be set to record_pending_signo
  1944. * in order to ignore them: they will be raised
  1945. * in an endless loop when we try to do some
  1946. * terminal ioctls! We do have to _ignore_ these.
  1947. */
  1948. if (SPECIAL_JOBSTOP_SIGS & sigmask)
  1949. handler = SIG_IGN;
  1950. }
  1951. }
  1952. return handler;
  1953. }
  1954. /* Restores tty foreground process group, and exits. */
  1955. static void hush_exit(int exitcode)
  1956. {
  1957. #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
  1958. save_history(G.line_input_state); /* may be NULL */
  1959. #endif
  1960. fflush_all();
  1961. if (G.exiting <= 0 && G_traps && G_traps[0] && G_traps[0][0]) {
  1962. char *argv[3];
  1963. /* argv[0] is unused */
  1964. argv[1] = xstrdup(G_traps[0]); /* copy, since EXIT trap handler may modify G_traps[0] */
  1965. argv[2] = NULL;
  1966. G.exiting = 1; /* prevent EXIT trap recursion */
  1967. /* Note: G_traps[0] is not cleared!
  1968. * "trap" will still show it, if executed
  1969. * in the handler */
  1970. builtin_eval(argv);
  1971. }
  1972. #if ENABLE_FEATURE_CLEAN_UP
  1973. {
  1974. struct variable *cur_var;
  1975. if (G.cwd != bb_msg_unknown)
  1976. free((char*)G.cwd);
  1977. cur_var = G.top_var;
  1978. while (cur_var) {
  1979. struct variable *tmp = cur_var;
  1980. if (!cur_var->max_len)
  1981. free(cur_var->varstr);
  1982. cur_var = cur_var->next;
  1983. free(tmp);
  1984. }
  1985. }
  1986. #endif
  1987. fflush_all();
  1988. #if ENABLE_HUSH_JOB
  1989. sigexit(- (exitcode & 0xff));
  1990. #else
  1991. _exit(exitcode);
  1992. #endif
  1993. }
  1994. //TODO: return a mask of ALL handled sigs?
  1995. static int check_and_run_traps(void)
  1996. {
  1997. int last_sig = 0;
  1998. while (1) {
  1999. int sig;
  2000. if (sigisemptyset(&G.pending_set))
  2001. break;
  2002. sig = 0;
  2003. do {
  2004. sig++;
  2005. if (sigismember(&G.pending_set, sig)) {
  2006. sigdelset(&G.pending_set, sig);
  2007. goto got_sig;
  2008. }
  2009. } while (sig < NSIG);
  2010. break;
  2011. got_sig:
  2012. #if ENABLE_HUSH_TRAP
  2013. if (G_traps && G_traps[sig]) {
  2014. debug_printf_exec("%s: sig:%d handler:'%s'\n", __func__, sig, G.traps[sig]);
  2015. if (G_traps[sig][0]) {
  2016. /* We have user-defined handler */
  2017. smalluint save_rcode;
  2018. int save_pre;
  2019. char *argv[3];
  2020. /* argv[0] is unused */
  2021. argv[1] = xstrdup(G_traps[sig]);
  2022. /* why strdup? trap can modify itself: trap 'trap "echo oops" INT' INT */
  2023. argv[2] = NULL;
  2024. save_pre = G.pre_trap_exitcode;
  2025. G.pre_trap_exitcode = save_rcode = G.last_exitcode;
  2026. builtin_eval(argv);
  2027. free(argv[1]);
  2028. G.pre_trap_exitcode = save_pre;
  2029. G.last_exitcode = save_rcode;
  2030. # if ENABLE_HUSH_FUNCTIONS
  2031. if (G.return_exitcode >= 0) {
  2032. debug_printf_exec("trap exitcode:%d\n", G.return_exitcode);
  2033. G.last_exitcode = G.return_exitcode;
  2034. }
  2035. # endif
  2036. last_sig = sig;
  2037. } /* else: "" trap, ignoring signal */
  2038. continue;
  2039. }
  2040. #endif
  2041. /* not a trap: special action */
  2042. switch (sig) {
  2043. case SIGINT:
  2044. debug_printf_exec("%s: sig:%d default SIGINT handler\n", __func__, sig);
  2045. G.flag_SIGINT = 1;
  2046. last_sig = sig;
  2047. break;
  2048. #if ENABLE_HUSH_JOB
  2049. case SIGHUP: {
  2050. //TODO: why are we doing this? ash and dash don't do this,
  2051. //they have no handler for SIGHUP at all,
  2052. //they rely on kernel to send SIGHUP+SIGCONT to orphaned process groups
  2053. struct pipe *job;
  2054. debug_printf_exec("%s: sig:%d default SIGHUP handler\n", __func__, sig);
  2055. /* bash is observed to signal whole process groups,
  2056. * not individual processes */
  2057. for (job = G.job_list; job; job = job->next) {
  2058. if (job->pgrp <= 0)
  2059. continue;
  2060. debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
  2061. if (kill(- job->pgrp, SIGHUP) == 0)
  2062. kill(- job->pgrp, SIGCONT);
  2063. }
  2064. sigexit(SIGHUP);
  2065. }
  2066. #endif
  2067. #if ENABLE_HUSH_FAST
  2068. case SIGCHLD:
  2069. debug_printf_exec("%s: sig:%d default SIGCHLD handler\n", __func__, sig);
  2070. G.count_SIGCHLD++;
  2071. //bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
  2072. /* Note:
  2073. * We don't do 'last_sig = sig' here -> NOT returning this sig.
  2074. * This simplifies wait builtin a bit.
  2075. */
  2076. break;
  2077. #endif
  2078. default: /* ignored: */
  2079. debug_printf_exec("%s: sig:%d default handling is to ignore\n", __func__, sig);
  2080. /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
  2081. /* Note:
  2082. * We don't do 'last_sig = sig' here -> NOT returning this sig.
  2083. * Example: wait is not interrupted by TERM
  2084. * in interactive shell, because TERM is ignored.
  2085. */
  2086. break;
  2087. }
  2088. }
  2089. return last_sig;
  2090. }
  2091. static const char *get_cwd(int force)
  2092. {
  2093. if (force || G.cwd == NULL) {
  2094. /* xrealloc_getcwd_or_warn(arg) calls free(arg),
  2095. * we must not try to free(bb_msg_unknown) */
  2096. if (G.cwd == bb_msg_unknown)
  2097. G.cwd = NULL;
  2098. G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
  2099. if (!G.cwd)
  2100. G.cwd = bb_msg_unknown;
  2101. }
  2102. return G.cwd;
  2103. }
  2104. /*
  2105. * Shell and environment variable support
  2106. */
  2107. static struct variable **get_ptr_to_local_var(const char *name, unsigned len)
  2108. {
  2109. struct variable **pp;
  2110. struct variable *cur;
  2111. pp = &G.top_var;
  2112. while ((cur = *pp) != NULL) {
  2113. if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
  2114. return pp;
  2115. pp = &cur->next;
  2116. }
  2117. return NULL;
  2118. }
  2119. static const char* FAST_FUNC get_local_var_value(const char *name)
  2120. {
  2121. struct variable **vpp;
  2122. unsigned len = strlen(name);
  2123. if (G.expanded_assignments) {
  2124. char **cpp = G.expanded_assignments;
  2125. while (*cpp) {
  2126. char *cp = *cpp;
  2127. if (strncmp(cp, name, len) == 0 && cp[len] == '=')
  2128. return cp + len + 1;
  2129. cpp++;
  2130. }
  2131. }
  2132. vpp = get_ptr_to_local_var(name, len);
  2133. if (vpp)
  2134. return (*vpp)->varstr + len + 1;
  2135. if (strcmp(name, "PPID") == 0)
  2136. return utoa(G.root_ppid);
  2137. // bash compat: UID? EUID?
  2138. #if ENABLE_HUSH_RANDOM_SUPPORT
  2139. if (strcmp(name, "RANDOM") == 0)
  2140. return utoa(next_random(&G.random_gen));
  2141. #endif
  2142. #if ENABLE_HUSH_LINENO_VAR
  2143. if (strcmp(name, "LINENO") == 0)
  2144. return utoa(G.execute_lineno);
  2145. #endif
  2146. #if BASH_EPOCH_VARS
  2147. {
  2148. const char *fmt = NULL;
  2149. if (strcmp(name, "EPOCHSECONDS") == 0)
  2150. fmt = "%lu";
  2151. else if (strcmp(name, "EPOCHREALTIME") == 0)
  2152. fmt = "%lu.%06u";
  2153. if (fmt) {
  2154. struct timeval tv;
  2155. gettimeofday(&tv, NULL);
  2156. sprintf(G.epoch_buf, fmt, (unsigned long)tv.tv_sec,
  2157. (unsigned)tv.tv_usec);
  2158. return G.epoch_buf;
  2159. }
  2160. }
  2161. #endif
  2162. return NULL;
  2163. }
  2164. #if ENABLE_HUSH_GETOPTS
  2165. static void handle_changed_special_names(const char *name, unsigned name_len)
  2166. {
  2167. if (name_len == 6) {
  2168. if (strncmp(name, "OPTIND", 6) == 0) {
  2169. G.getopt_count = 0;
  2170. return;
  2171. }
  2172. }
  2173. }
  2174. #else
  2175. /* Do not even bother evaluating arguments */
  2176. # define handle_changed_special_names(...) ((void)0)
  2177. #endif
  2178. /* str holds "NAME=VAL" and is expected to be malloced.
  2179. * We take ownership of it.
  2180. */
  2181. #define SETFLAG_EXPORT (1 << 0)
  2182. #define SETFLAG_UNEXPORT (1 << 1)
  2183. #define SETFLAG_MAKE_RO (1 << 2)
  2184. #define SETFLAG_VARLVL_SHIFT 3
  2185. static int set_local_var(char *str, unsigned flags)
  2186. {
  2187. struct variable **cur_pp;
  2188. struct variable *cur;
  2189. char *free_me = NULL;
  2190. char *eq_sign;
  2191. int name_len;
  2192. int retval;
  2193. unsigned local_lvl = (flags >> SETFLAG_VARLVL_SHIFT);
  2194. eq_sign = strchr(str, '=');
  2195. if (HUSH_DEBUG && !eq_sign)
  2196. bb_simple_error_msg_and_die("BUG in setvar");
  2197. name_len = eq_sign - str + 1; /* including '=' */
  2198. cur_pp = &G.top_var;
  2199. while ((cur = *cur_pp) != NULL) {
  2200. if (strncmp(cur->varstr, str, name_len) != 0) {
  2201. cur_pp = &cur->next;
  2202. continue;
  2203. }
  2204. /* We found an existing var with this name */
  2205. if (cur->flg_read_only) {
  2206. bb_error_msg("%s: readonly variable", str);
  2207. free(str);
  2208. //NOTE: in bash, assignment in "export READONLY_VAR=Z" fails, and sets $?=1,
  2209. //but export per se succeeds (does put the var in env). We don't mimic that.
  2210. return -1;
  2211. }
  2212. if (flags & SETFLAG_UNEXPORT) { // && cur->flg_export ?
  2213. debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
  2214. *eq_sign = '\0';
  2215. unsetenv(str);
  2216. *eq_sign = '=';
  2217. }
  2218. if (cur->var_nest_level < local_lvl) {
  2219. /* bash 3.2.33(1) and exported vars:
  2220. * # export z=z
  2221. * # f() { local z=a; env | grep ^z; }
  2222. * # f
  2223. * z=a
  2224. * # env | grep ^z
  2225. * z=z
  2226. */
  2227. if (cur->flg_export)
  2228. flags |= SETFLAG_EXPORT;
  2229. /* New variable is local ("local VAR=VAL" or
  2230. * "VAR=VAL cmd")
  2231. * and existing one is global, or local
  2232. * on a lower level that new one.
  2233. * Remove it from global variable list:
  2234. */
  2235. *cur_pp = cur->next;
  2236. if (G.shadowed_vars_pp) {
  2237. /* Save in "shadowed" list */
  2238. debug_printf_env("shadowing %s'%s'/%u by '%s'/%u\n",
  2239. cur->flg_export ? "exported " : "",
  2240. cur->varstr, cur->var_nest_level, str, local_lvl
  2241. );
  2242. cur->next = *G.shadowed_vars_pp;
  2243. *G.shadowed_vars_pp = cur;
  2244. } else {
  2245. /* Came from pseudo_exec_argv(), no need to save: delete it */
  2246. debug_printf_env("shadow-deleting %s'%s'/%u by '%s'/%u\n",
  2247. cur->flg_export ? "exported " : "",
  2248. cur->varstr, cur->var_nest_level, str, local_lvl
  2249. );
  2250. if (cur->max_len == 0) /* allocated "VAR=VAL"? */
  2251. free_me = cur->varstr; /* then free it later */
  2252. free(cur);
  2253. }
  2254. break;
  2255. }
  2256. if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
  2257. debug_printf_env("assignement '%s' does not change anything\n", str);
  2258. free_and_exp:
  2259. free(str);
  2260. goto exp;
  2261. }
  2262. /* Replace the value in the found "struct variable" */
  2263. if (cur->max_len != 0) {
  2264. if (cur->max_len >= strnlen(str, cur->max_len + 1)) {
  2265. /* This one is from startup env, reuse space */
  2266. debug_printf_env("reusing startup env for '%s'\n", str);
  2267. strcpy(cur->varstr, str);
  2268. goto free_and_exp;
  2269. }
  2270. /* Can't reuse */
  2271. cur->max_len = 0;
  2272. goto set_str_and_exp;
  2273. }
  2274. /* max_len == 0 signifies "malloced" var, which we can
  2275. * (and have to) free. But we can't free(cur->varstr) here:
  2276. * if cur->flg_export is 1, it is in the environment.
  2277. * We should either unsetenv+free, or wait until putenv,
  2278. * then putenv(new)+free(old).
  2279. */
  2280. free_me = cur->varstr;
  2281. goto set_str_and_exp;
  2282. }
  2283. /* Not found or shadowed - create new variable struct */
  2284. debug_printf_env("%s: alloc new var '%s'/%u\n", __func__, str, local_lvl);
  2285. cur = xzalloc(sizeof(*cur));
  2286. cur->var_nest_level = local_lvl;
  2287. cur->next = *cur_pp;
  2288. *cur_pp = cur;
  2289. set_str_and_exp:
  2290. cur->varstr = str;
  2291. exp:
  2292. #if !BB_MMU || ENABLE_HUSH_READONLY
  2293. if (flags & SETFLAG_MAKE_RO) {
  2294. cur->flg_read_only = 1;
  2295. }
  2296. #endif
  2297. if (flags & SETFLAG_EXPORT)
  2298. cur->flg_export = 1;
  2299. retval = 0;
  2300. if (cur->flg_export) {
  2301. if (flags & SETFLAG_UNEXPORT) {
  2302. cur->flg_export = 0;
  2303. /* unsetenv was already done */
  2304. } else {
  2305. debug_printf_env("%s: putenv '%s'/%u\n", __func__, cur->varstr, cur->var_nest_level);
  2306. retval = putenv(cur->varstr);
  2307. /* fall through to "free(free_me)" -
  2308. * only now we can free old exported malloced string
  2309. */
  2310. }
  2311. }
  2312. free(free_me);
  2313. handle_changed_special_names(cur->varstr, name_len - 1);
  2314. return retval;
  2315. }
  2316. static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
  2317. {
  2318. char *var = xasprintf("%s=%s", name, val);
  2319. set_local_var(var, /*flag:*/ 0);
  2320. }
  2321. /* Used at startup and after each cd */
  2322. static void set_pwd_var(unsigned flag)
  2323. {
  2324. set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)), flag);
  2325. }
  2326. #if ENABLE_HUSH_UNSET || ENABLE_HUSH_GETOPTS
  2327. static int unset_local_var_len(const char *name, int name_len)
  2328. {
  2329. struct variable *cur;
  2330. struct variable **cur_pp;
  2331. cur_pp = &G.top_var;
  2332. while ((cur = *cur_pp) != NULL) {
  2333. if (strncmp(cur->varstr, name, name_len) == 0
  2334. && cur->varstr[name_len] == '='
  2335. ) {
  2336. if (cur->flg_read_only) {
  2337. bb_error_msg("%s: readonly variable", name);
  2338. return EXIT_FAILURE;
  2339. }
  2340. *cur_pp = cur->next;
  2341. debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
  2342. bb_unsetenv(cur->varstr);
  2343. if (!cur->max_len)
  2344. free(cur->varstr);
  2345. free(cur);
  2346. break;
  2347. }
  2348. cur_pp = &cur->next;
  2349. }
  2350. /* Handle "unset LINENO" et al even if did not find the variable to unset */
  2351. handle_changed_special_names(name, name_len);
  2352. return EXIT_SUCCESS;
  2353. }
  2354. static int unset_local_var(const char *name)
  2355. {
  2356. return unset_local_var_len(name, strlen(name));
  2357. }
  2358. #endif
  2359. /*
  2360. * Helpers for "var1=val1 var2=val2 cmd" feature
  2361. */
  2362. static void add_vars(struct variable *var)
  2363. {
  2364. struct variable *next;
  2365. while (var) {
  2366. next = var->next;
  2367. var->next = G.top_var;
  2368. G.top_var = var;
  2369. if (var->flg_export) {
  2370. debug_printf_env("%s: restoring exported '%s'/%u\n", __func__, var->varstr, var->var_nest_level);
  2371. putenv(var->varstr);
  2372. } else {
  2373. debug_printf_env("%s: restoring variable '%s'/%u\n", __func__, var->varstr, var->var_nest_level);
  2374. }
  2375. var = next;
  2376. }
  2377. }
  2378. /* We put strings[i] into variable table and possibly putenv them.
  2379. * If variable is read only, we can free the strings[i]
  2380. * which attempts to overwrite it.
  2381. * The strings[] vector itself is freed.
  2382. */
  2383. static void set_vars_and_save_old(char **strings)
  2384. {
  2385. char **s;
  2386. if (!strings)
  2387. return;
  2388. s = strings;
  2389. while (*s) {
  2390. struct variable *var_p;
  2391. struct variable **var_pp;
  2392. char *eq;
  2393. eq = strchr(*s, '=');
  2394. if (HUSH_DEBUG && !eq)
  2395. bb_simple_error_msg_and_die("BUG in varexp4");
  2396. var_pp = get_ptr_to_local_var(*s, eq - *s);
  2397. if (var_pp) {
  2398. var_p = *var_pp;
  2399. if (var_p->flg_read_only) {
  2400. char **p;
  2401. bb_error_msg("%s: readonly variable", *s);
  2402. /*
  2403. * "VAR=V BLTIN" unsets VARs after BLTIN completes.
  2404. * If VAR is readonly, leaving it in the list
  2405. * after asssignment error (msg above)
  2406. * causes doubled error message later, on unset.
  2407. */
  2408. debug_printf_env("removing/freeing '%s' element\n", *s);
  2409. free(*s);
  2410. p = s;
  2411. do { *p = p[1]; p++; } while (*p);
  2412. goto next;
  2413. }
  2414. /* below, set_local_var() with nest level will
  2415. * "shadow" (remove) this variable from
  2416. * global linked list.
  2417. */
  2418. }
  2419. debug_printf_env("%s: env override '%s'/%u\n", __func__, *s, G.var_nest_level);
  2420. set_local_var(*s, (G.var_nest_level << SETFLAG_VARLVL_SHIFT) | SETFLAG_EXPORT);
  2421. s++;
  2422. next: ;
  2423. }
  2424. free(strings);
  2425. }
  2426. /*
  2427. * Unicode helper
  2428. */
  2429. static void reinit_unicode_for_hush(void)
  2430. {
  2431. /* Unicode support should be activated even if LANG is set
  2432. * _during_ shell execution, not only if it was set when
  2433. * shell was started. Therefore, re-check LANG every time:
  2434. */
  2435. if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
  2436. || ENABLE_UNICODE_USING_LOCALE
  2437. ) {
  2438. const char *s = get_local_var_value("LC_ALL");
  2439. if (!s) s = get_local_var_value("LC_CTYPE");
  2440. if (!s) s = get_local_var_value("LANG");
  2441. reinit_unicode(s);
  2442. }
  2443. }
  2444. /*
  2445. * in_str support (strings, and "strings" read from files).
  2446. */
  2447. #if ENABLE_HUSH_INTERACTIVE
  2448. /* To test correct lineedit/interactive behavior, type from command line:
  2449. * echo $P\
  2450. * \
  2451. * AT\
  2452. * H\
  2453. * \
  2454. * It exercises a lot of corner cases.
  2455. */
  2456. static const char *setup_prompt_string(void)
  2457. {
  2458. const char *prompt_str;
  2459. debug_printf_prompt("%s promptmode:%d\n", __func__, G.promptmode);
  2460. # if ENABLE_FEATURE_EDITING_FANCY_PROMPT
  2461. prompt_str = get_local_var_value(G.promptmode == 0 ? "PS1" : "PS2");
  2462. if (!prompt_str)
  2463. prompt_str = "";
  2464. # else
  2465. prompt_str = "> "; /* if PS2, else... */
  2466. if (G.promptmode == 0) { /* PS1 */
  2467. /* No fancy prompts supported, (re)generate "CURDIR $ " by hand */
  2468. free(G.PS1);
  2469. /* bash uses $PWD value, even if it is set by user.
  2470. * It uses current dir only if PWD is unset.
  2471. * We always use current dir. */
  2472. prompt_str = G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
  2473. }
  2474. # endif
  2475. debug_printf("prompt_str '%s'\n", prompt_str);
  2476. return prompt_str;
  2477. }
  2478. static int get_user_input(struct in_str *i)
  2479. {
  2480. # if ENABLE_FEATURE_EDITING
  2481. /* In EDITING case, this function reads next input line,
  2482. * saves it in i->p, then returns 1st char of it.
  2483. */
  2484. int r;
  2485. const char *prompt_str;
  2486. prompt_str = setup_prompt_string();
  2487. for (;;) {
  2488. reinit_unicode_for_hush();
  2489. G.flag_SIGINT = 0;
  2490. /* buglet: SIGINT will not make new prompt to appear _at once_,
  2491. * only after <Enter>. (^C works immediately) */
  2492. r = read_line_input(G.line_input_state, prompt_str,
  2493. G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1
  2494. );
  2495. /* read_line_input intercepts ^C, "convert" it to SIGINT */
  2496. if (r == 0) {
  2497. raise(SIGINT);
  2498. }
  2499. check_and_run_traps();
  2500. if (r != 0 && !G.flag_SIGINT)
  2501. break;
  2502. /* ^C or SIGINT: repeat */
  2503. /* bash prints ^C even on real SIGINT (non-kbd generated) */
  2504. write(STDOUT_FILENO, "^C\n", 3);
  2505. G.last_exitcode = 128 | SIGINT;
  2506. }
  2507. if (r < 0) {
  2508. /* EOF/error detected */
  2509. i->p = NULL;
  2510. i->peek_buf[0] = r = EOF;
  2511. return r;
  2512. }
  2513. i->p = G.user_input_buf;
  2514. return (unsigned char)*i->p++;
  2515. # else
  2516. /* In !EDITING case, this function gets called for every char.
  2517. * Buffering happens deeper in the call chain, in hfgetc(i->file).
  2518. */
  2519. int r;
  2520. for (;;) {
  2521. G.flag_SIGINT = 0;
  2522. if (i->last_char == '\0' || i->last_char == '\n') {
  2523. const char *prompt_str = setup_prompt_string();
  2524. /* Why check_and_run_traps here? Try this interactively:
  2525. * $ trap 'echo INT' INT; (sleep 2; kill -INT $$) &
  2526. * $ <[enter], repeatedly...>
  2527. * Without check_and_run_traps, handler never runs.
  2528. */
  2529. check_and_run_traps();
  2530. fputs(prompt_str, stdout);
  2531. fflush_all();
  2532. }
  2533. r = hfgetc(i->file);
  2534. /* In !ENABLE_FEATURE_EDITING we don't use read_line_input,
  2535. * no ^C masking happens during fgetc, no special code for ^C:
  2536. * it generates SIGINT as usual.
  2537. */
  2538. check_and_run_traps();
  2539. if (r != '\0' && !G.flag_SIGINT)
  2540. break;
  2541. if (G.flag_SIGINT) {
  2542. /* ^C or SIGINT: repeat */
  2543. /* bash prints ^C even on real SIGINT (non-kbd generated) */
  2544. /* kernel prints "^C" itself, just print newline: */
  2545. write(STDOUT_FILENO, "\n", 1);
  2546. G.last_exitcode = 128 | SIGINT;
  2547. }
  2548. }
  2549. return r;
  2550. # endif
  2551. }
  2552. /* This is the magic location that prints prompts
  2553. * and gets data back from the user */
  2554. static int fgetc_interactive(struct in_str *i)
  2555. {
  2556. int ch;
  2557. /* If it's interactive stdin, get new line. */
  2558. if (G_interactive_fd && i->file == G.HFILE_stdin) {
  2559. /* Returns first char (or EOF), the rest is in i->p[] */
  2560. ch = get_user_input(i);
  2561. G.promptmode = 1; /* PS2 */
  2562. debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
  2563. } else {
  2564. /* Not stdin: script file, sourced file, etc */
  2565. do ch = hfgetc(i->file); while (ch == '\0');
  2566. }
  2567. return ch;
  2568. }
  2569. #else /* !INTERACTIVE */
  2570. static ALWAYS_INLINE int fgetc_interactive(struct in_str *i)
  2571. {
  2572. int ch;
  2573. do ch = hfgetc(i->file); while (ch == '\0');
  2574. return ch;
  2575. }
  2576. #endif /* !INTERACTIVE */
  2577. static int i_getch(struct in_str *i)
  2578. {
  2579. int ch;
  2580. if (!i->file) {
  2581. /* string-based in_str */
  2582. ch = (unsigned char)*i->p;
  2583. if (ch != '\0') {
  2584. i->p++;
  2585. i->last_char = ch;
  2586. return ch;
  2587. }
  2588. return EOF;
  2589. }
  2590. /* FILE-based in_str */
  2591. #if ENABLE_FEATURE_EDITING
  2592. /* This can be stdin, check line editing char[] buffer */
  2593. if (i->p && *i->p != '\0') {
  2594. ch = (unsigned char)*i->p++;
  2595. goto out;
  2596. }
  2597. #endif
  2598. /* peek_buf[] is an int array, not char. Can contain EOF. */
  2599. ch = i->peek_buf[0];
  2600. if (ch != 0) {
  2601. int ch2 = i->peek_buf[1];
  2602. i->peek_buf[0] = ch2;
  2603. if (ch2 == 0) /* very likely, avoid redundant write */
  2604. goto out;
  2605. i->peek_buf[1] = 0;
  2606. goto out;
  2607. }
  2608. ch = fgetc_interactive(i);
  2609. out:
  2610. debug_printf("file_get: got '%c' %d\n", ch, ch);
  2611. i->last_char = ch;
  2612. #if ENABLE_HUSH_LINENO_VAR
  2613. if (ch == '\n') {
  2614. G.parse_lineno++;
  2615. debug_printf_parse("G.parse_lineno++ = %u\n", G.parse_lineno);
  2616. }
  2617. #endif
  2618. return ch;
  2619. }
  2620. static int i_peek(struct in_str *i)
  2621. {
  2622. int ch;
  2623. if (!i->file) {
  2624. /* string-based in_str */
  2625. /* Doesn't report EOF on NUL. None of the callers care. */
  2626. return (unsigned char)*i->p;
  2627. }
  2628. /* FILE-based in_str */
  2629. #if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
  2630. /* This can be stdin, check line editing char[] buffer */
  2631. if (i->p && *i->p != '\0')
  2632. return (unsigned char)*i->p;
  2633. #endif
  2634. /* peek_buf[] is an int array, not char. Can contain EOF. */
  2635. ch = i->peek_buf[0];
  2636. if (ch != 0)
  2637. return ch;
  2638. /* Need to get a new char */
  2639. ch = fgetc_interactive(i);
  2640. debug_printf("file_peek: got '%c' %d\n", ch, ch);
  2641. /* Save it by either rolling back line editing buffer, or in i->peek_buf[0] */
  2642. #if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
  2643. if (i->p) {
  2644. i->p -= 1;
  2645. return ch;
  2646. }
  2647. #endif
  2648. i->peek_buf[0] = ch;
  2649. /*i->peek_buf[1] = 0; - already is */
  2650. return ch;
  2651. }
  2652. /* Only ever called if i_peek() was called, and did not return EOF.
  2653. * IOW: we know the previous peek saw an ordinary char, not EOF, not NUL,
  2654. * not end-of-line. Therefore we never need to read a new editing line here.
  2655. */
  2656. static int i_peek2(struct in_str *i)
  2657. {
  2658. int ch;
  2659. /* There are two cases when i->p[] buffer exists.
  2660. * (1) it's a string in_str.
  2661. * (2) It's a file, and we have a saved line editing buffer.
  2662. * In both cases, we know that i->p[0] exists and not NUL, and
  2663. * the peek2 result is in i->p[1].
  2664. */
  2665. if (i->p)
  2666. return (unsigned char)i->p[1];
  2667. /* Now we know it is a file-based in_str. */
  2668. /* peek_buf[] is an int array, not char. Can contain EOF. */
  2669. /* Is there 2nd char? */
  2670. ch = i->peek_buf[1];
  2671. if (ch == 0) {
  2672. /* We did not read it yet, get it now */
  2673. do ch = hfgetc(i->file); while (ch == '\0');
  2674. i->peek_buf[1] = ch;
  2675. }
  2676. debug_printf("file_peek2: got '%c' %d\n", ch, ch);
  2677. return ch;
  2678. }
  2679. static int i_getch_and_eat_bkslash_nl(struct in_str *input)
  2680. {
  2681. for (;;) {
  2682. int ch, ch2;
  2683. ch = i_getch(input);
  2684. if (ch != '\\')
  2685. return ch;
  2686. ch2 = i_peek(input);
  2687. if (ch2 != '\n')
  2688. return ch;
  2689. /* backslash+newline, skip it */
  2690. i_getch(input);
  2691. }
  2692. }
  2693. /* Note: this function _eats_ \<newline> pairs, safe to use plain
  2694. * i_getch() after it instead of i_getch_and_eat_bkslash_nl().
  2695. */
  2696. static int i_peek_and_eat_bkslash_nl(struct in_str *input)
  2697. {
  2698. for (;;) {
  2699. int ch, ch2;
  2700. ch = i_peek(input);
  2701. if (ch != '\\')
  2702. return ch;
  2703. ch2 = i_peek2(input);
  2704. if (ch2 != '\n')
  2705. return ch;
  2706. /* backslash+newline, skip it */
  2707. i_getch(input);
  2708. i_getch(input);
  2709. }
  2710. }
  2711. static void setup_file_in_str(struct in_str *i, HFILE *fp)
  2712. {
  2713. memset(i, 0, sizeof(*i));
  2714. i->file = fp;
  2715. /* i->p = NULL; */
  2716. }
  2717. static void setup_string_in_str(struct in_str *i, const char *s)
  2718. {
  2719. memset(i, 0, sizeof(*i));
  2720. /*i->file = NULL */;
  2721. i->p = s;
  2722. }
  2723. /*
  2724. * o_string support
  2725. */
  2726. #define B_CHUNK (32 * sizeof(char*))
  2727. static void o_reset_to_empty_unquoted(o_string *o)
  2728. {
  2729. o->length = 0;
  2730. o->has_quoted_part = 0;
  2731. if (o->data)
  2732. o->data[0] = '\0';
  2733. }
  2734. static void o_free_and_set_NULL(o_string *o)
  2735. {
  2736. free(o->data);
  2737. memset(o, 0, sizeof(*o));
  2738. }
  2739. static ALWAYS_INLINE void o_free(o_string *o)
  2740. {
  2741. free(o->data);
  2742. }
  2743. static void o_grow_by(o_string *o, int len)
  2744. {
  2745. if (o->length + len > o->maxlen) {
  2746. o->maxlen += (2 * len) | (B_CHUNK-1);
  2747. o->data = xrealloc(o->data, 1 + o->maxlen);
  2748. }
  2749. }
  2750. static void o_addchr(o_string *o, int ch)
  2751. {
  2752. debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
  2753. if (o->length < o->maxlen) {
  2754. /* likely. avoid o_grow_by() call */
  2755. add:
  2756. o->data[o->length] = ch;
  2757. o->length++;
  2758. o->data[o->length] = '\0';
  2759. return;
  2760. }
  2761. o_grow_by(o, 1);
  2762. goto add;
  2763. }
  2764. #if 0
  2765. /* Valid only if we know o_string is not empty */
  2766. static void o_delchr(o_string *o)
  2767. {
  2768. o->length--;
  2769. o->data[o->length] = '\0';
  2770. }
  2771. #endif
  2772. static void o_addblock(o_string *o, const char *str, int len)
  2773. {
  2774. o_grow_by(o, len);
  2775. ((char*)mempcpy(&o->data[o->length], str, len))[0] = '\0';
  2776. o->length += len;
  2777. }
  2778. static void o_addstr(o_string *o, const char *str)
  2779. {
  2780. o_addblock(o, str, strlen(str));
  2781. }
  2782. static void o_addstr_with_NUL(o_string *o, const char *str)
  2783. {
  2784. o_addblock(o, str, strlen(str) + 1);
  2785. }
  2786. #if !BB_MMU
  2787. static void nommu_addchr(o_string *o, int ch)
  2788. {
  2789. if (o)
  2790. o_addchr(o, ch);
  2791. }
  2792. #else
  2793. # define nommu_addchr(o, str) ((void)0)
  2794. #endif
  2795. #if ENABLE_HUSH_MODE_X
  2796. static void x_mode_addchr(int ch)
  2797. {
  2798. o_addchr(&G.x_mode_buf, ch);
  2799. }
  2800. static void x_mode_addstr(const char *str)
  2801. {
  2802. o_addstr(&G.x_mode_buf, str);
  2803. }
  2804. static void x_mode_addblock(const char *str, int len)
  2805. {
  2806. o_addblock(&G.x_mode_buf, str, len);
  2807. }
  2808. static void x_mode_prefix(void)
  2809. {
  2810. int n = G.x_mode_depth;
  2811. do x_mode_addchr('+'); while (--n >= 0);
  2812. }
  2813. static void x_mode_flush(void)
  2814. {
  2815. int len = G.x_mode_buf.length;
  2816. if (len <= 0)
  2817. return;
  2818. if (G.x_mode_fd > 0) {
  2819. G.x_mode_buf.data[len] = '\n';
  2820. full_write(G.x_mode_fd, G.x_mode_buf.data, len + 1);
  2821. }
  2822. G.x_mode_buf.length = 0;
  2823. }
  2824. #endif
  2825. /*
  2826. * HUSH_BRACE_EXPANSION code needs corresponding quoting on variable expansion side.
  2827. * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
  2828. * Apparently, on unquoted $v bash still does globbing
  2829. * ("v='*.txt'; echo $v" prints all .txt files),
  2830. * but NOT brace expansion! Thus, there should be TWO independent
  2831. * quoting mechanisms on $v expansion side: one protects
  2832. * $v from brace expansion, and other additionally protects "$v" against globbing.
  2833. * We have only second one.
  2834. */
  2835. #if ENABLE_HUSH_BRACE_EXPANSION
  2836. # define MAYBE_BRACES "{}"
  2837. #else
  2838. # define MAYBE_BRACES ""
  2839. #endif
  2840. /* My analysis of quoting semantics tells me that state information
  2841. * is associated with a destination, not a source.
  2842. */
  2843. static void o_addqchr(o_string *o, int ch)
  2844. {
  2845. int sz = 1;
  2846. /* '-' is included because of this case:
  2847. * >filename0 >filename1 >filename9; v='-'; echo filename[0"$v"9]
  2848. */
  2849. char *found = strchr("*?[-\\" MAYBE_BRACES, ch);
  2850. if (found)
  2851. sz++;
  2852. o_grow_by(o, sz);
  2853. if (found) {
  2854. o->data[o->length] = '\\';
  2855. o->length++;
  2856. }
  2857. o->data[o->length] = ch;
  2858. o->length++;
  2859. o->data[o->length] = '\0';
  2860. }
  2861. static void o_addQchr(o_string *o, int ch)
  2862. {
  2863. int sz = 1;
  2864. if ((o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)
  2865. && strchr("*?[-\\" MAYBE_BRACES, ch)
  2866. ) {
  2867. sz++;
  2868. o->data[o->length] = '\\';
  2869. o->length++;
  2870. }
  2871. o_grow_by(o, sz);
  2872. o->data[o->length] = ch;
  2873. o->length++;
  2874. o->data[o->length] = '\0';
  2875. }
  2876. static void o_addqblock(o_string *o, const char *str, int len)
  2877. {
  2878. while (len) {
  2879. char ch;
  2880. int sz;
  2881. int ordinary_cnt = strcspn(str, "*?[-\\" MAYBE_BRACES);
  2882. if (ordinary_cnt > len) /* paranoia */
  2883. ordinary_cnt = len;
  2884. o_addblock(o, str, ordinary_cnt);
  2885. if (ordinary_cnt == len)
  2886. return; /* NUL is already added by o_addblock */
  2887. str += ordinary_cnt;
  2888. len -= ordinary_cnt + 1; /* we are processing + 1 char below */
  2889. ch = *str++;
  2890. sz = 1;
  2891. if (ch) { /* it is necessarily one of "*?[-\\" MAYBE_BRACES */
  2892. sz++;
  2893. o->data[o->length] = '\\';
  2894. o->length++;
  2895. }
  2896. o_grow_by(o, sz);
  2897. o->data[o->length] = ch;
  2898. o->length++;
  2899. }
  2900. o->data[o->length] = '\0';
  2901. }
  2902. static void o_addQblock(o_string *o, const char *str, int len)
  2903. {
  2904. if (!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)) {
  2905. o_addblock(o, str, len);
  2906. return;
  2907. }
  2908. o_addqblock(o, str, len);
  2909. }
  2910. static void o_addQstr(o_string *o, const char *str)
  2911. {
  2912. o_addQblock(o, str, strlen(str));
  2913. }
  2914. /* A special kind of o_string for $VAR and `cmd` expansion.
  2915. * It contains char* list[] at the beginning, which is grown in 16 element
  2916. * increments. Actual string data starts at the next multiple of 16 * (char*).
  2917. * list[i] contains an INDEX (int!) into this string data.
  2918. * It means that if list[] needs to grow, data needs to be moved higher up
  2919. * but list[i]'s need not be modified.
  2920. * NB: remembering how many list[i]'s you have there is crucial.
  2921. * o_finalize_list() operation post-processes this structure - calculates
  2922. * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
  2923. */
  2924. #if DEBUG_EXPAND || DEBUG_GLOB
  2925. static void debug_print_list(const char *prefix, o_string *o, int n)
  2926. {
  2927. char **list = (char**)o->data;
  2928. int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
  2929. int i = 0;
  2930. indent();
  2931. fdprintf(2, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d glob:%d quoted:%d escape:%d\n",
  2932. prefix, list, n, string_start, o->length, o->maxlen,
  2933. !!(o->o_expflags & EXP_FLAG_GLOB),
  2934. o->has_quoted_part,
  2935. !!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
  2936. while (i < n) {
  2937. indent();
  2938. fdprintf(2, " list[%d]=%d '%s' %p\n", i, (int)(uintptr_t)list[i],
  2939. o->data + (int)(uintptr_t)list[i] + string_start,
  2940. o->data + (int)(uintptr_t)list[i] + string_start);
  2941. i++;
  2942. }
  2943. if (n) {
  2944. const char *p = o->data + (int)(uintptr_t)list[n - 1] + string_start;
  2945. indent();
  2946. fdprintf(2, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
  2947. }
  2948. }
  2949. #else
  2950. # define debug_print_list(prefix, o, n) ((void)0)
  2951. #endif
  2952. /* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
  2953. * in list[n] so that it points past last stored byte so far.
  2954. * It returns n+1. */
  2955. static int o_save_ptr_helper(o_string *o, int n)
  2956. {
  2957. char **list = (char**)o->data;
  2958. int string_start;
  2959. int string_len;
  2960. if (!o->has_empty_slot) {
  2961. string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
  2962. string_len = o->length - string_start;
  2963. if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
  2964. debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
  2965. /* list[n] points to string_start, make space for 16 more pointers */
  2966. o->maxlen += 0x10 * sizeof(list[0]);
  2967. o->data = xrealloc(o->data, o->maxlen + 1);
  2968. list = (char**)o->data;
  2969. memmove(list + n + 0x10, list + n, string_len);
  2970. /*
  2971. * expand_on_ifs() has a "previous argv[] ends in IFS?"
  2972. * check. (grep for -prev-ifs-check-).
  2973. * Ensure that argv[-1][last] is not garbage
  2974. * but zero bytes, to save index check there.
  2975. */
  2976. list[n + 0x10 - 1] = 0;
  2977. o->length += 0x10 * sizeof(list[0]);
  2978. } else {
  2979. debug_printf_list("list[%d]=%d string_start=%d\n",
  2980. n, string_len, string_start);
  2981. }
  2982. } else {
  2983. /* We have empty slot at list[n], reuse without growth */
  2984. string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
  2985. string_len = o->length - string_start;
  2986. debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
  2987. n, string_len, string_start);
  2988. o->has_empty_slot = 0;
  2989. }
  2990. o->has_quoted_part = 0;
  2991. list[n] = (char*)(uintptr_t)string_len;
  2992. return n + 1;
  2993. }
  2994. /* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
  2995. static int o_get_last_ptr(o_string *o, int n)
  2996. {
  2997. char **list = (char**)o->data;
  2998. int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
  2999. return ((int)(uintptr_t)list[n-1]) + string_start;
  3000. }
  3001. /*
  3002. * Globbing routines.
  3003. *
  3004. * Most words in commands need to be globbed, even ones which are
  3005. * (single or double) quoted. This stems from the possiblity of
  3006. * constructs like "abc"* and 'abc'* - these should be globbed.
  3007. * Having a different code path for fully-quoted strings ("abc",
  3008. * 'abc') would only help performance-wise, but we still need
  3009. * code for partially-quoted strings.
  3010. *
  3011. * Unfortunately, if we want to match bash and ash behavior in all cases,
  3012. * the logic can't be "shell-syntax argument is first transformed
  3013. * to a string, then globbed, and if globbing does not match anything,
  3014. * it is used verbatim". Here are two examples where it fails:
  3015. *
  3016. * echo 'b\*'?
  3017. *
  3018. * The globbing can't be avoided (because of '?' at the end).
  3019. * The glob pattern is: b\\\*? - IOW, both \ and * are literals
  3020. * and are glob-escaped. If this does not match, bash/ash print b\*?
  3021. * - IOW: they "unbackslash" the glob pattern.
  3022. * Now, look at this:
  3023. *
  3024. * v='\\\*'; echo b$v?
  3025. *
  3026. * The glob pattern is the same here: b\\\*? - the unquoted $v expansion
  3027. * should be used as glob pattern with no changes. However, if glob
  3028. * does not match, bash/ash print b\\\*? - NOT THE SAME as first example!
  3029. *
  3030. * ash implements this by having an encoded representation of the word
  3031. * to glob, which IS NOT THE SAME as the glob pattern - it has more data.
  3032. * Glob pattern is derived from it. If glob fails, the decision what result
  3033. * should be is made using that encoded representation. Not glob pattern.
  3034. */
  3035. #if ENABLE_HUSH_BRACE_EXPANSION
  3036. /* There in a GNU extension, GLOB_BRACE, but it is not usable:
  3037. * first, it processes even {a} (no commas), second,
  3038. * I didn't manage to make it return strings when they don't match
  3039. * existing files. Need to re-implement it.
  3040. */
  3041. /* Helper */
  3042. static int glob_needed(const char *s)
  3043. {
  3044. while (*s) {
  3045. if (*s == '\\') {
  3046. if (!s[1])
  3047. return 0;
  3048. s += 2;
  3049. continue;
  3050. }
  3051. if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
  3052. return 1;
  3053. s++;
  3054. }
  3055. return 0;
  3056. }
  3057. /* Return pointer to next closing brace or to comma */
  3058. static const char *next_brace_sub(const char *cp)
  3059. {
  3060. unsigned depth = 0;
  3061. cp++;
  3062. while (*cp != '\0') {
  3063. if (*cp == '\\') {
  3064. if (*++cp == '\0')
  3065. break;
  3066. cp++;
  3067. continue;
  3068. }
  3069. if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
  3070. break;
  3071. if (*cp++ == '{')
  3072. depth++;
  3073. }
  3074. return *cp != '\0' ? cp : NULL;
  3075. }
  3076. /* Recursive brace globber. Note: may garble pattern[]. */
  3077. static int glob_brace(char *pattern, o_string *o, int n)
  3078. {
  3079. char *new_pattern_buf;
  3080. const char *begin;
  3081. const char *next;
  3082. const char *rest;
  3083. const char *p;
  3084. size_t rest_len;
  3085. debug_printf_glob("glob_brace('%s')\n", pattern);
  3086. begin = pattern;
  3087. while (1) {
  3088. if (*begin == '\0')
  3089. goto simple_glob;
  3090. if (*begin == '{') {
  3091. /* Find the first sub-pattern and at the same time
  3092. * find the rest after the closing brace */
  3093. next = next_brace_sub(begin);
  3094. if (next == NULL) {
  3095. /* An illegal expression */
  3096. goto simple_glob;
  3097. }
  3098. if (*next == '}') {
  3099. /* "{abc}" with no commas - illegal
  3100. * brace expr, disregard and skip it */
  3101. begin = next + 1;
  3102. continue;
  3103. }
  3104. break;
  3105. }
  3106. if (*begin == '\\' && begin[1] != '\0')
  3107. begin++;
  3108. begin++;
  3109. }
  3110. debug_printf_glob("begin:%s\n", begin);
  3111. debug_printf_glob("next:%s\n", next);
  3112. /* Now find the end of the whole brace expression */
  3113. rest = next;
  3114. while (*rest != '}') {
  3115. rest = next_brace_sub(rest);
  3116. if (rest == NULL) {
  3117. /* An illegal expression */
  3118. goto simple_glob;
  3119. }
  3120. debug_printf_glob("rest:%s\n", rest);
  3121. }
  3122. rest_len = strlen(++rest) + 1;
  3123. /* We are sure the brace expression is well-formed */
  3124. /* Allocate working buffer large enough for our work */
  3125. new_pattern_buf = xmalloc(strlen(pattern));
  3126. /* We have a brace expression. BEGIN points to the opening {,
  3127. * NEXT points past the terminator of the first element, and REST
  3128. * points past the final }. We will accumulate result names from
  3129. * recursive runs for each brace alternative in the buffer using
  3130. * GLOB_APPEND. */
  3131. p = begin + 1;
  3132. while (1) {
  3133. /* Construct the new glob expression */
  3134. memcpy(
  3135. mempcpy(
  3136. mempcpy(new_pattern_buf,
  3137. /* We know the prefix for all sub-patterns */
  3138. pattern, begin - pattern),
  3139. p, next - p),
  3140. rest, rest_len);
  3141. /* Note: glob_brace() may garble new_pattern_buf[].
  3142. * That's why we re-copy prefix every time (1st memcpy above).
  3143. */
  3144. n = glob_brace(new_pattern_buf, o, n);
  3145. if (*next == '}') {
  3146. /* We saw the last entry */
  3147. break;
  3148. }
  3149. p = next + 1;
  3150. next = next_brace_sub(next);
  3151. }
  3152. free(new_pattern_buf);
  3153. return n;
  3154. simple_glob:
  3155. {
  3156. int gr;
  3157. glob_t globdata;
  3158. memset(&globdata, 0, sizeof(globdata));
  3159. gr = glob(pattern, 0, NULL, &globdata);
  3160. debug_printf_glob("glob('%s'):%d\n", pattern, gr);
  3161. if (gr != 0) {
  3162. if (gr == GLOB_NOMATCH) {
  3163. globfree(&globdata);
  3164. /* NB: garbles parameter */
  3165. unbackslash(pattern);
  3166. o_addstr_with_NUL(o, pattern);
  3167. debug_printf_glob("glob pattern '%s' is literal\n", pattern);
  3168. return o_save_ptr_helper(o, n);
  3169. }
  3170. if (gr == GLOB_NOSPACE)
  3171. bb_die_memory_exhausted();
  3172. /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
  3173. * but we didn't specify it. Paranoia again. */
  3174. bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
  3175. }
  3176. if (globdata.gl_pathv && globdata.gl_pathv[0]) {
  3177. char **argv = globdata.gl_pathv;
  3178. while (1) {
  3179. o_addstr_with_NUL(o, *argv);
  3180. n = o_save_ptr_helper(o, n);
  3181. argv++;
  3182. if (!*argv)
  3183. break;
  3184. }
  3185. }
  3186. globfree(&globdata);
  3187. }
  3188. return n;
  3189. }
  3190. /* Performs globbing on last list[],
  3191. * saving each result as a new list[].
  3192. */
  3193. static int perform_glob(o_string *o, int n)
  3194. {
  3195. char *pattern, *copy;
  3196. debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
  3197. if (!o->data)
  3198. return o_save_ptr_helper(o, n);
  3199. pattern = o->data + o_get_last_ptr(o, n);
  3200. debug_printf_glob("glob pattern '%s'\n", pattern);
  3201. if (!glob_needed(pattern)) {
  3202. /* unbackslash last string in o in place, fix length */
  3203. o->length = unbackslash(pattern) - o->data;
  3204. debug_printf_glob("glob pattern '%s' is literal\n", pattern);
  3205. return o_save_ptr_helper(o, n);
  3206. }
  3207. copy = xstrdup(pattern);
  3208. /* "forget" pattern in o */
  3209. o->length = pattern - o->data;
  3210. n = glob_brace(copy, o, n);
  3211. free(copy);
  3212. if (DEBUG_GLOB)
  3213. debug_print_list("perform_glob returning", o, n);
  3214. return n;
  3215. }
  3216. #else /* !HUSH_BRACE_EXPANSION */
  3217. /* Helper */
  3218. static int glob_needed(const char *s)
  3219. {
  3220. while (*s) {
  3221. if (*s == '\\') {
  3222. if (!s[1])
  3223. return 0;
  3224. s += 2;
  3225. continue;
  3226. }
  3227. if (*s == '*' || *s == '[' || *s == '?')
  3228. return 1;
  3229. s++;
  3230. }
  3231. return 0;
  3232. }
  3233. /* Performs globbing on last list[],
  3234. * saving each result as a new list[].
  3235. */
  3236. static int perform_glob(o_string *o, int n)
  3237. {
  3238. glob_t globdata;
  3239. int gr;
  3240. char *pattern;
  3241. debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
  3242. if (!o->data)
  3243. return o_save_ptr_helper(o, n);
  3244. pattern = o->data + o_get_last_ptr(o, n);
  3245. debug_printf_glob("glob pattern '%s'\n", pattern);
  3246. if (!glob_needed(pattern)) {
  3247. literal:
  3248. /* unbackslash last string in o in place, fix length */
  3249. o->length = unbackslash(pattern) - o->data;
  3250. debug_printf_glob("glob pattern '%s' is literal\n", pattern);
  3251. return o_save_ptr_helper(o, n);
  3252. }
  3253. memset(&globdata, 0, sizeof(globdata));
  3254. /* Can't use GLOB_NOCHECK: it does not unescape the string.
  3255. * If we glob "*.\*" and don't find anything, we need
  3256. * to fall back to using literal "*.*", but GLOB_NOCHECK
  3257. * will return "*.\*"!
  3258. */
  3259. gr = glob(pattern, 0, NULL, &globdata);
  3260. debug_printf_glob("glob('%s'):%d\n", pattern, gr);
  3261. if (gr != 0) {
  3262. if (gr == GLOB_NOMATCH) {
  3263. globfree(&globdata);
  3264. goto literal;
  3265. }
  3266. if (gr == GLOB_NOSPACE)
  3267. bb_die_memory_exhausted();
  3268. /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
  3269. * but we didn't specify it. Paranoia again. */
  3270. bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
  3271. }
  3272. if (globdata.gl_pathv && globdata.gl_pathv[0]) {
  3273. char **argv = globdata.gl_pathv;
  3274. /* "forget" pattern in o */
  3275. o->length = pattern - o->data;
  3276. while (1) {
  3277. o_addstr_with_NUL(o, *argv);
  3278. n = o_save_ptr_helper(o, n);
  3279. argv++;
  3280. if (!*argv)
  3281. break;
  3282. }
  3283. }
  3284. globfree(&globdata);
  3285. if (DEBUG_GLOB)
  3286. debug_print_list("perform_glob returning", o, n);
  3287. return n;
  3288. }
  3289. #endif /* !HUSH_BRACE_EXPANSION */
  3290. /* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered.
  3291. * Otherwise, just finish current list[] and start new */
  3292. static int o_save_ptr(o_string *o, int n)
  3293. {
  3294. if (o->o_expflags & EXP_FLAG_GLOB) {
  3295. /* If o->has_empty_slot, list[n] was already globbed
  3296. * (if it was requested back then when it was filled)
  3297. * so don't do that again! */
  3298. if (!o->has_empty_slot)
  3299. return perform_glob(o, n); /* o_save_ptr_helper is inside */
  3300. }
  3301. return o_save_ptr_helper(o, n);
  3302. }
  3303. /* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
  3304. static char **o_finalize_list(o_string *o, int n)
  3305. {
  3306. char **list;
  3307. int string_start;
  3308. if (DEBUG_EXPAND)
  3309. debug_print_list("finalized", o, n);
  3310. debug_printf_expand("finalized n:%d\n", n);
  3311. list = (char**)o->data;
  3312. string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
  3313. list[--n] = NULL;
  3314. while (n) {
  3315. n--;
  3316. list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
  3317. }
  3318. return list;
  3319. }
  3320. static void free_pipe_list(struct pipe *pi);
  3321. /* Returns pi->next - next pipe in the list */
  3322. static struct pipe *free_pipe(struct pipe *pi)
  3323. {
  3324. struct pipe *next;
  3325. int i;
  3326. debug_printf_clean("free_pipe (pid %d)\n", getpid());
  3327. for (i = 0; i < pi->num_cmds; i++) {
  3328. struct command *command;
  3329. struct redir_struct *r, *rnext;
  3330. command = &pi->cmds[i];
  3331. debug_printf_clean(" command %d:\n", i);
  3332. if (command->argv) {
  3333. if (DEBUG_CLEAN) {
  3334. int a;
  3335. char **p;
  3336. for (a = 0, p = command->argv; *p; a++, p++) {
  3337. debug_printf_clean(" argv[%d] = %s\n", a, *p);
  3338. }
  3339. }
  3340. free_strings(command->argv);
  3341. //command->argv = NULL;
  3342. }
  3343. /* not "else if": on syntax error, we may have both! */
  3344. if (command->group) {
  3345. debug_printf_clean(" begin group (cmd_type:%d)\n",
  3346. command->cmd_type);
  3347. free_pipe_list(command->group);
  3348. debug_printf_clean(" end group\n");
  3349. //command->group = NULL;
  3350. }
  3351. /* else is crucial here.
  3352. * If group != NULL, child_func is meaningless */
  3353. #if ENABLE_HUSH_FUNCTIONS
  3354. else if (command->child_func) {
  3355. debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
  3356. command->child_func->parent_cmd = NULL;
  3357. }
  3358. #endif
  3359. #if !BB_MMU
  3360. free(command->group_as_string);
  3361. //command->group_as_string = NULL;
  3362. #endif
  3363. for (r = command->redirects; r; r = rnext) {
  3364. debug_printf_clean(" redirect %d%s",
  3365. r->rd_fd, redir_table[r->rd_type].descrip);
  3366. /* guard against the case >$FOO, where foo is unset or blank */
  3367. if (r->rd_filename) {
  3368. debug_printf_clean(" fname:'%s'\n", r->rd_filename);
  3369. free(r->rd_filename);
  3370. //r->rd_filename = NULL;
  3371. }
  3372. debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
  3373. rnext = r->next;
  3374. free(r);
  3375. }
  3376. //command->redirects = NULL;
  3377. }
  3378. free(pi->cmds); /* children are an array, they get freed all at once */
  3379. //pi->cmds = NULL;
  3380. #if ENABLE_HUSH_JOB
  3381. free(pi->cmdtext);
  3382. //pi->cmdtext = NULL;
  3383. #endif
  3384. next = pi->next;
  3385. free(pi);
  3386. return next;
  3387. }
  3388. static void free_pipe_list(struct pipe *pi)
  3389. {
  3390. while (pi) {
  3391. #if HAS_KEYWORDS
  3392. debug_printf_clean("pipe reserved word %d\n", pi->res_word);
  3393. #endif
  3394. debug_printf_clean("pipe followup code %d\n", pi->followup);
  3395. pi = free_pipe(pi);
  3396. }
  3397. }
  3398. /*** Parsing routines ***/
  3399. #ifndef debug_print_tree
  3400. static void debug_print_tree(struct pipe *pi, int lvl)
  3401. {
  3402. static const char *const PIPE[] = {
  3403. [PIPE_SEQ] = "SEQ",
  3404. [PIPE_AND] = "AND",
  3405. [PIPE_OR ] = "OR" ,
  3406. [PIPE_BG ] = "BG" ,
  3407. };
  3408. static const char *RES[] = {
  3409. [RES_NONE ] = "NONE" ,
  3410. # if ENABLE_HUSH_IF
  3411. [RES_IF ] = "IF" ,
  3412. [RES_THEN ] = "THEN" ,
  3413. [RES_ELIF ] = "ELIF" ,
  3414. [RES_ELSE ] = "ELSE" ,
  3415. [RES_FI ] = "FI" ,
  3416. # endif
  3417. # if ENABLE_HUSH_LOOPS
  3418. [RES_FOR ] = "FOR" ,
  3419. [RES_WHILE] = "WHILE",
  3420. [RES_UNTIL] = "UNTIL",
  3421. [RES_DO ] = "DO" ,
  3422. [RES_DONE ] = "DONE" ,
  3423. # endif
  3424. # if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
  3425. [RES_IN ] = "IN" ,
  3426. # endif
  3427. # if ENABLE_HUSH_CASE
  3428. [RES_CASE ] = "CASE" ,
  3429. [RES_CASE_IN ] = "CASE_IN" ,
  3430. [RES_MATCH] = "MATCH",
  3431. [RES_CASE_BODY] = "CASE_BODY",
  3432. [RES_ESAC ] = "ESAC" ,
  3433. # endif
  3434. [RES_XXXX ] = "XXXX" ,
  3435. [RES_SNTX ] = "SNTX" ,
  3436. };
  3437. static const char *const CMDTYPE[] = {
  3438. "{}",
  3439. "()",
  3440. "[noglob]",
  3441. # if ENABLE_HUSH_FUNCTIONS
  3442. "func()",
  3443. # endif
  3444. };
  3445. int pin, prn;
  3446. pin = 0;
  3447. while (pi) {
  3448. fdprintf(2, "%*spipe %d #cmds:%d %sres_word=%s followup=%d %s\n",
  3449. lvl*2, "",
  3450. pin,
  3451. pi->num_cmds,
  3452. (IF_HAS_KEYWORDS(pi->pi_inverted ? "! " :) ""),
  3453. RES[pi->res_word],
  3454. pi->followup, PIPE[pi->followup]
  3455. );
  3456. prn = 0;
  3457. while (prn < pi->num_cmds) {
  3458. struct command *command = &pi->cmds[prn];
  3459. char **argv = command->argv;
  3460. fdprintf(2, "%*s cmd %d assignment_cnt:%d",
  3461. lvl*2, "", prn,
  3462. command->assignment_cnt);
  3463. # if ENABLE_HUSH_LINENO_VAR
  3464. fdprintf(2, " LINENO:%u", command->lineno);
  3465. # endif
  3466. if (command->group) {
  3467. fdprintf(2, " group %s: (argv=%p)%s%s\n",
  3468. CMDTYPE[command->cmd_type],
  3469. argv
  3470. # if !BB_MMU
  3471. , " group_as_string:", command->group_as_string
  3472. # else
  3473. , "", ""
  3474. # endif
  3475. );
  3476. debug_print_tree(command->group, lvl+1);
  3477. prn++;
  3478. continue;
  3479. }
  3480. if (argv) while (*argv) {
  3481. fdprintf(2, " '%s'", *argv);
  3482. argv++;
  3483. }
  3484. if (command->redirects)
  3485. fdprintf(2, " {redir}");
  3486. fdprintf(2, "\n");
  3487. prn++;
  3488. }
  3489. pi = pi->next;
  3490. pin++;
  3491. }
  3492. }
  3493. #endif /* debug_print_tree */
  3494. static struct pipe *new_pipe(void)
  3495. {
  3496. struct pipe *pi;
  3497. pi = xzalloc(sizeof(struct pipe));
  3498. /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
  3499. return pi;
  3500. }
  3501. /* Command (member of a pipe) is complete, or we start a new pipe
  3502. * if ctx->command is NULL.
  3503. * No errors possible here.
  3504. */
  3505. static int done_command(struct parse_context *ctx)
  3506. {
  3507. /* The command is really already in the pipe structure, so
  3508. * advance the pipe counter and make a new, null command. */
  3509. struct pipe *pi = ctx->pipe;
  3510. struct command *command = ctx->command;
  3511. #if 0 /* Instead we emit error message at run time */
  3512. if (ctx->pending_redirect) {
  3513. /* For example, "cmd >" (no filename to redirect to) */
  3514. syntax_error("invalid redirect");
  3515. ctx->pending_redirect = NULL;
  3516. }
  3517. #endif
  3518. if (command) {
  3519. if (IS_NULL_CMD(command)) {
  3520. debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
  3521. goto clear_and_ret;
  3522. }
  3523. pi->num_cmds++;
  3524. debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
  3525. //debug_print_tree(ctx->list_head, 20);
  3526. } else {
  3527. debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
  3528. }
  3529. /* Only real trickiness here is that the uncommitted
  3530. * command structure is not counted in pi->num_cmds. */
  3531. pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
  3532. ctx->command = command = &pi->cmds[pi->num_cmds];
  3533. clear_and_ret:
  3534. memset(command, 0, sizeof(*command));
  3535. #if ENABLE_HUSH_LINENO_VAR
  3536. command->lineno = G.parse_lineno;
  3537. debug_printf_parse("command->lineno = G.parse_lineno (%u)\n", G.parse_lineno);
  3538. #endif
  3539. return pi->num_cmds; /* used only for 0/nonzero check */
  3540. }
  3541. static void done_pipe(struct parse_context *ctx, pipe_style type)
  3542. {
  3543. int not_null;
  3544. debug_printf_parse("done_pipe entered, followup %d\n", type);
  3545. /* Close previous command */
  3546. not_null = done_command(ctx);
  3547. #if HAS_KEYWORDS
  3548. ctx->pipe->pi_inverted = ctx->ctx_inverted;
  3549. ctx->ctx_inverted = 0;
  3550. ctx->pipe->res_word = ctx->ctx_res_w;
  3551. #endif
  3552. if (type == PIPE_BG && ctx->list_head != ctx->pipe) {
  3553. /* Necessary since && and || have precedence over &:
  3554. * "cmd1 && cmd2 &" must spawn both cmds, not only cmd2,
  3555. * in a backgrounded subshell.
  3556. */
  3557. struct pipe *pi;
  3558. struct command *command;
  3559. /* Is this actually this construct, all pipes end with && or ||? */
  3560. pi = ctx->list_head;
  3561. while (pi != ctx->pipe) {
  3562. if (pi->followup != PIPE_AND && pi->followup != PIPE_OR)
  3563. goto no_conv;
  3564. pi = pi->next;
  3565. }
  3566. debug_printf_parse("BG with more than one pipe, converting to { p1 &&...pN; } &\n");
  3567. pi->followup = PIPE_SEQ; /* close pN _not_ with "&"! */
  3568. pi = xzalloc(sizeof(*pi));
  3569. pi->followup = PIPE_BG;
  3570. pi->num_cmds = 1;
  3571. pi->cmds = xzalloc(sizeof(pi->cmds[0]));
  3572. command = &pi->cmds[0];
  3573. if (CMD_NORMAL != 0) /* "if xzalloc didn't do that already" */
  3574. command->cmd_type = CMD_NORMAL;
  3575. command->group = ctx->list_head;
  3576. #if !BB_MMU
  3577. command->group_as_string = xstrndup(
  3578. ctx->as_string.data,
  3579. ctx->as_string.length - 1 /* do not copy last char, "&" */
  3580. );
  3581. #endif
  3582. /* Replace all pipes in ctx with one newly created */
  3583. ctx->list_head = ctx->pipe = pi;
  3584. /* for cases like "cmd && &", do not be tricked by last command
  3585. * being null - the entire {...} & is NOT null! */
  3586. not_null = 1;
  3587. } else {
  3588. no_conv:
  3589. ctx->pipe->followup = type;
  3590. }
  3591. /* Without this check, even just <enter> on command line generates
  3592. * tree of three NOPs (!). Which is harmless but annoying.
  3593. * IOW: it is safe to do it unconditionally. */
  3594. if (not_null
  3595. #if ENABLE_HUSH_IF
  3596. || ctx->ctx_res_w == RES_FI
  3597. #endif
  3598. #if ENABLE_HUSH_LOOPS
  3599. || ctx->ctx_res_w == RES_DONE
  3600. || ctx->ctx_res_w == RES_FOR
  3601. || ctx->ctx_res_w == RES_IN
  3602. #endif
  3603. #if ENABLE_HUSH_CASE
  3604. || ctx->ctx_res_w == RES_ESAC
  3605. #endif
  3606. ) {
  3607. struct pipe *new_p;
  3608. debug_printf_parse("done_pipe: adding new pipe: "
  3609. "not_null:%d ctx->ctx_res_w:%d\n",
  3610. not_null, ctx->ctx_res_w);
  3611. new_p = new_pipe();
  3612. ctx->pipe->next = new_p;
  3613. ctx->pipe = new_p;
  3614. /* RES_THEN, RES_DO etc are "sticky" -
  3615. * they remain set for pipes inside if/while.
  3616. * This is used to control execution.
  3617. * RES_FOR and RES_IN are NOT sticky (needed to support
  3618. * cases where variable or value happens to match a keyword):
  3619. */
  3620. #if ENABLE_HUSH_LOOPS
  3621. if (ctx->ctx_res_w == RES_FOR
  3622. || ctx->ctx_res_w == RES_IN)
  3623. ctx->ctx_res_w = RES_NONE;
  3624. #endif
  3625. #if ENABLE_HUSH_CASE
  3626. if (ctx->ctx_res_w == RES_MATCH)
  3627. ctx->ctx_res_w = RES_CASE_BODY;
  3628. if (ctx->ctx_res_w == RES_CASE)
  3629. ctx->ctx_res_w = RES_CASE_IN;
  3630. #endif
  3631. ctx->command = NULL; /* trick done_command below */
  3632. /* Create the memory for command, roughly:
  3633. * ctx->pipe->cmds = new struct command;
  3634. * ctx->command = &ctx->pipe->cmds[0];
  3635. */
  3636. done_command(ctx);
  3637. //debug_print_tree(ctx->list_head, 10);
  3638. }
  3639. debug_printf_parse("done_pipe return\n");
  3640. }
  3641. static void initialize_context(struct parse_context *ctx)
  3642. {
  3643. memset(ctx, 0, sizeof(*ctx));
  3644. if (MAYBE_ASSIGNMENT != 0)
  3645. ctx->is_assignment = MAYBE_ASSIGNMENT;
  3646. ctx->pipe = ctx->list_head = new_pipe();
  3647. /* Create the memory for command, roughly:
  3648. * ctx->pipe->cmds = new struct command;
  3649. * ctx->command = &ctx->pipe->cmds[0];
  3650. */
  3651. done_command(ctx);
  3652. }
  3653. /* If a reserved word is found and processed, parse context is modified
  3654. * and 1 is returned.
  3655. */
  3656. #if HAS_KEYWORDS
  3657. struct reserved_combo {
  3658. char literal[6];
  3659. unsigned char res;
  3660. unsigned char assignment_flag;
  3661. uint32_t flag;
  3662. };
  3663. enum {
  3664. FLAG_END = (1 << RES_NONE ),
  3665. # if ENABLE_HUSH_IF
  3666. FLAG_IF = (1 << RES_IF ),
  3667. FLAG_THEN = (1 << RES_THEN ),
  3668. FLAG_ELIF = (1 << RES_ELIF ),
  3669. FLAG_ELSE = (1 << RES_ELSE ),
  3670. FLAG_FI = (1 << RES_FI ),
  3671. # endif
  3672. # if ENABLE_HUSH_LOOPS
  3673. FLAG_FOR = (1 << RES_FOR ),
  3674. FLAG_WHILE = (1 << RES_WHILE),
  3675. FLAG_UNTIL = (1 << RES_UNTIL),
  3676. FLAG_DO = (1 << RES_DO ),
  3677. FLAG_DONE = (1 << RES_DONE ),
  3678. FLAG_IN = (1 << RES_IN ),
  3679. # endif
  3680. # if ENABLE_HUSH_CASE
  3681. FLAG_MATCH = (1 << RES_MATCH),
  3682. FLAG_ESAC = (1 << RES_ESAC ),
  3683. # endif
  3684. FLAG_START = (1 << RES_XXXX ),
  3685. };
  3686. static const struct reserved_combo* match_reserved_word(o_string *word)
  3687. {
  3688. /* Mostly a list of accepted follow-up reserved words.
  3689. * FLAG_END means we are done with the sequence, and are ready
  3690. * to turn the compound list into a command.
  3691. * FLAG_START means the word must start a new compound list.
  3692. */
  3693. static const struct reserved_combo reserved_list[] ALIGN4 = {
  3694. # if ENABLE_HUSH_IF
  3695. { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
  3696. { "if", RES_IF, MAYBE_ASSIGNMENT, FLAG_THEN | FLAG_START },
  3697. { "then", RES_THEN, MAYBE_ASSIGNMENT, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
  3698. { "elif", RES_ELIF, MAYBE_ASSIGNMENT, FLAG_THEN },
  3699. { "else", RES_ELSE, MAYBE_ASSIGNMENT, FLAG_FI },
  3700. { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
  3701. # endif
  3702. # if ENABLE_HUSH_LOOPS
  3703. { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
  3704. { "while", RES_WHILE, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
  3705. { "until", RES_UNTIL, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
  3706. { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
  3707. { "do", RES_DO, MAYBE_ASSIGNMENT, FLAG_DONE },
  3708. { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
  3709. # endif
  3710. # if ENABLE_HUSH_CASE
  3711. { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
  3712. { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
  3713. # endif
  3714. };
  3715. const struct reserved_combo *r;
  3716. for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
  3717. if (strcmp(word->data, r->literal) == 0)
  3718. return r;
  3719. }
  3720. return NULL;
  3721. }
  3722. /* Return NULL: not a keyword, else: keyword
  3723. */
  3724. static const struct reserved_combo* reserved_word(struct parse_context *ctx)
  3725. {
  3726. # if ENABLE_HUSH_CASE
  3727. static const struct reserved_combo reserved_match = {
  3728. "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
  3729. };
  3730. # endif
  3731. const struct reserved_combo *r;
  3732. if (ctx->word.has_quoted_part)
  3733. return 0;
  3734. r = match_reserved_word(&ctx->word);
  3735. if (!r)
  3736. return r; /* NULL */
  3737. debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
  3738. # if ENABLE_HUSH_CASE
  3739. if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
  3740. /* "case word IN ..." - IN part starts first MATCH part */
  3741. r = &reserved_match;
  3742. } else
  3743. # endif
  3744. if (r->flag == 0) { /* '!' */
  3745. if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
  3746. syntax_error("! ! command");
  3747. ctx->ctx_res_w = RES_SNTX;
  3748. }
  3749. ctx->ctx_inverted = 1;
  3750. return r;
  3751. }
  3752. if (r->flag & FLAG_START) {
  3753. struct parse_context *old;
  3754. old = xmemdup(ctx, sizeof(*ctx));
  3755. debug_printf_parse("push stack %p\n", old);
  3756. initialize_context(ctx);
  3757. ctx->stack = old;
  3758. } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
  3759. syntax_error_at(ctx->word.data);
  3760. ctx->ctx_res_w = RES_SNTX;
  3761. return r;
  3762. } else {
  3763. /* "{...} fi" is ok. "{...} if" is not
  3764. * Example:
  3765. * if { echo foo; } then { echo bar; } fi */
  3766. if (ctx->command->group)
  3767. done_pipe(ctx, PIPE_SEQ);
  3768. }
  3769. ctx->ctx_res_w = r->res;
  3770. ctx->old_flag = r->flag;
  3771. ctx->is_assignment = r->assignment_flag;
  3772. debug_printf_parse("ctx->is_assignment='%s'\n", assignment_flag[ctx->is_assignment]);
  3773. if (ctx->old_flag & FLAG_END) {
  3774. struct parse_context *old;
  3775. done_pipe(ctx, PIPE_SEQ);
  3776. debug_printf_parse("pop stack %p\n", ctx->stack);
  3777. old = ctx->stack;
  3778. old->command->group = ctx->list_head;
  3779. old->command->cmd_type = CMD_NORMAL;
  3780. # if !BB_MMU
  3781. /* At this point, the compound command's string is in
  3782. * ctx->as_string... except for the leading keyword!
  3783. * Consider this example: "echo a | if true; then echo a; fi"
  3784. * ctx->as_string will contain "true; then echo a; fi",
  3785. * with "if " remaining in old->as_string!
  3786. */
  3787. {
  3788. char *str;
  3789. int len = old->as_string.length;
  3790. /* Concatenate halves */
  3791. o_addstr(&old->as_string, ctx->as_string.data);
  3792. o_free(&ctx->as_string);
  3793. /* Find where leading keyword starts in first half */
  3794. str = old->as_string.data + len;
  3795. if (str > old->as_string.data)
  3796. str--; /* skip whitespace after keyword */
  3797. while (str > old->as_string.data && isalpha(str[-1]))
  3798. str--;
  3799. /* Ugh, we're done with this horrid hack */
  3800. old->command->group_as_string = xstrdup(str);
  3801. debug_printf_parse("pop, remembering as:'%s'\n",
  3802. old->command->group_as_string);
  3803. }
  3804. # endif
  3805. *ctx = *old; /* physical copy */
  3806. free(old);
  3807. }
  3808. return r;
  3809. }
  3810. #endif /* HAS_KEYWORDS */
  3811. /* Word is complete, look at it and update parsing context.
  3812. * Normal return is 0. Syntax errors return 1.
  3813. * Note: on return, word is reset, but not o_free'd!
  3814. */
  3815. static int done_word(struct parse_context *ctx)
  3816. {
  3817. struct command *command = ctx->command;
  3818. debug_printf_parse("done_word entered: '%s' %p\n", ctx->word.data, command);
  3819. if (ctx->word.length == 0 && !ctx->word.has_quoted_part) {
  3820. debug_printf_parse("done_word return 0: true null, ignored\n");
  3821. return 0;
  3822. }
  3823. if (ctx->pending_redirect) {
  3824. /* We do not glob in e.g. >*.tmp case. bash seems to glob here
  3825. * only if run as "bash", not "sh" */
  3826. /* http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
  3827. * "2.7 Redirection
  3828. * If the redirection operator is "<<" or "<<-", the word
  3829. * that follows the redirection operator shall be
  3830. * subjected to quote removal; it is unspecified whether
  3831. * any of the other expansions occur. For the other
  3832. * redirection operators, the word that follows the
  3833. * redirection operator shall be subjected to tilde
  3834. * expansion, parameter expansion, command substitution,
  3835. * arithmetic expansion, and quote removal.
  3836. * Pathname expansion shall not be performed
  3837. * on the word by a non-interactive shell; an interactive
  3838. * shell may perform it, but shall do so only when
  3839. * the expansion would result in one word."
  3840. */
  3841. //bash does not do parameter/command substitution or arithmetic expansion
  3842. //for _heredoc_ redirection word: these constructs look for exact eof marker
  3843. // as written:
  3844. // <<EOF$t
  3845. // <<EOF$((1))
  3846. // <<EOF`true` [this case also makes heredoc "quoted", a-la <<"EOF". Probably bash-4.3.43 bug]
  3847. ctx->pending_redirect->rd_filename = xstrdup(ctx->word.data);
  3848. /* Cater for >\file case:
  3849. * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
  3850. * Same with heredocs:
  3851. * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
  3852. */
  3853. if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
  3854. unbackslash(ctx->pending_redirect->rd_filename);
  3855. /* Is it <<"HEREDOC"? */
  3856. if (ctx->word.has_quoted_part) {
  3857. ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
  3858. }
  3859. }
  3860. debug_printf_parse("word stored in rd_filename: '%s'\n", ctx->word.data);
  3861. ctx->pending_redirect = NULL;
  3862. } else {
  3863. #if HAS_KEYWORDS
  3864. # if ENABLE_HUSH_CASE
  3865. if (ctx->ctx_dsemicolon
  3866. && strcmp(ctx->word.data, "esac") != 0 /* not "... pattern) cmd;; esac" */
  3867. ) {
  3868. /* already done when ctx_dsemicolon was set to 1: */
  3869. /* ctx->ctx_res_w = RES_MATCH; */
  3870. ctx->ctx_dsemicolon = 0;
  3871. } else
  3872. # endif
  3873. # if defined(CMD_TEST2_SINGLEWORD_NOGLOB)
  3874. if (command->cmd_type == CMD_TEST2_SINGLEWORD_NOGLOB
  3875. && strcmp(ctx->word.data, "]]") == 0
  3876. ) {
  3877. /* allow "[[ ]] >file" etc */
  3878. command->cmd_type = CMD_SINGLEWORD_NOGLOB;
  3879. } else
  3880. # endif
  3881. if (!command->argv /* if it's the first word... */
  3882. # if ENABLE_HUSH_LOOPS
  3883. && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
  3884. && ctx->ctx_res_w != RES_IN
  3885. # endif
  3886. # if ENABLE_HUSH_CASE
  3887. && ctx->ctx_res_w != RES_CASE
  3888. # endif
  3889. ) {
  3890. const struct reserved_combo *reserved;
  3891. reserved = reserved_word(ctx);
  3892. debug_printf_parse("checking for reserved-ness: %d\n", !!reserved);
  3893. if (reserved) {
  3894. # if ENABLE_HUSH_LINENO_VAR
  3895. /* Case:
  3896. * "while ...; do
  3897. * cmd ..."
  3898. * If we don't close the pipe _now_, immediately after "do", lineno logic
  3899. * sees "cmd" as starting at "do" - i.e., at the previous line.
  3900. */
  3901. if (0
  3902. IF_HUSH_IF(|| reserved->res == RES_THEN)
  3903. IF_HUSH_IF(|| reserved->res == RES_ELIF)
  3904. IF_HUSH_IF(|| reserved->res == RES_ELSE)
  3905. IF_HUSH_LOOPS(|| reserved->res == RES_DO)
  3906. ) {
  3907. done_pipe(ctx, PIPE_SEQ);
  3908. }
  3909. # endif
  3910. o_reset_to_empty_unquoted(&ctx->word);
  3911. debug_printf_parse("done_word return %d\n",
  3912. (ctx->ctx_res_w == RES_SNTX));
  3913. return (ctx->ctx_res_w == RES_SNTX);
  3914. }
  3915. # if defined(CMD_TEST2_SINGLEWORD_NOGLOB)
  3916. if (strcmp(ctx->word.data, "[[") == 0) {
  3917. command->cmd_type = CMD_TEST2_SINGLEWORD_NOGLOB;
  3918. } else
  3919. # endif
  3920. # if defined(CMD_SINGLEWORD_NOGLOB)
  3921. if (0
  3922. /* In bash, local/export/readonly are special, args
  3923. * are assignments and therefore expansion of them
  3924. * should be "one-word" expansion:
  3925. * $ export i=`echo 'a b'` # one arg: "i=a b"
  3926. * compare with:
  3927. * $ ls i=`echo 'a b'` # two args: "i=a" and "b"
  3928. * ls: cannot access i=a: No such file or directory
  3929. * ls: cannot access b: No such file or directory
  3930. * Note: bash 3.2.33(1) does this only if export word
  3931. * itself is not quoted:
  3932. * $ export i=`echo 'aaa bbb'`; echo "$i"
  3933. * aaa bbb
  3934. * $ "export" i=`echo 'aaa bbb'`; echo "$i"
  3935. * aaa
  3936. */
  3937. IF_HUSH_LOCAL( || strcmp(ctx->word.data, "local") == 0)
  3938. IF_HUSH_EXPORT( || strcmp(ctx->word.data, "export") == 0)
  3939. IF_HUSH_READONLY(|| strcmp(ctx->word.data, "readonly") == 0)
  3940. ) {
  3941. command->cmd_type = CMD_SINGLEWORD_NOGLOB;
  3942. }
  3943. # else
  3944. { /* empty block to pair "if ... else" */ }
  3945. # endif
  3946. }
  3947. #endif /* HAS_KEYWORDS */
  3948. if (command->group) {
  3949. /* "{ echo foo; } echo bar" - bad */
  3950. syntax_error_at(ctx->word.data);
  3951. debug_printf_parse("done_word return 1: syntax error, "
  3952. "groups and arglists don't mix\n");
  3953. return 1;
  3954. }
  3955. /* If this word wasn't an assignment, next ones definitely
  3956. * can't be assignments. Even if they look like ones. */
  3957. if (ctx->is_assignment != DEFINITELY_ASSIGNMENT
  3958. && ctx->is_assignment != WORD_IS_KEYWORD
  3959. ) {
  3960. ctx->is_assignment = NOT_ASSIGNMENT;
  3961. } else {
  3962. if (ctx->is_assignment == DEFINITELY_ASSIGNMENT) {
  3963. command->assignment_cnt++;
  3964. debug_printf_parse("++assignment_cnt=%d\n", command->assignment_cnt);
  3965. }
  3966. debug_printf_parse("ctx->is_assignment was:'%s'\n", assignment_flag[ctx->is_assignment]);
  3967. ctx->is_assignment = MAYBE_ASSIGNMENT;
  3968. }
  3969. debug_printf_parse("ctx->is_assignment='%s'\n", assignment_flag[ctx->is_assignment]);
  3970. command->argv = add_string_to_strings(command->argv, xstrdup(ctx->word.data));
  3971. debug_print_strings("word appended to argv", command->argv);
  3972. }
  3973. #if ENABLE_HUSH_LOOPS
  3974. if (ctx->ctx_res_w == RES_FOR) {
  3975. if (ctx->word.has_quoted_part
  3976. || endofname(command->argv[0])[0] != '\0'
  3977. ) {
  3978. /* bash says just "not a valid identifier" */
  3979. syntax_error("not a valid identifier in for");
  3980. return 1;
  3981. }
  3982. /* Force FOR to have just one word (variable name) */
  3983. /* NB: basically, this makes hush see "for v in ..."
  3984. * syntax as if it is "for v; in ...". FOR and IN become
  3985. * two pipe structs in parse tree. */
  3986. done_pipe(ctx, PIPE_SEQ);
  3987. }
  3988. #endif
  3989. #if ENABLE_HUSH_CASE
  3990. /* Force CASE to have just one word */
  3991. if (ctx->ctx_res_w == RES_CASE) {
  3992. done_pipe(ctx, PIPE_SEQ);
  3993. }
  3994. #endif
  3995. o_reset_to_empty_unquoted(&ctx->word);
  3996. debug_printf_parse("done_word return 0\n");
  3997. return 0;
  3998. }
  3999. /* Peek ahead in the input to find out if we have a "&n" construct,
  4000. * as in "2>&1", that represents duplicating a file descriptor.
  4001. * Return:
  4002. * REDIRFD_CLOSE if >&- "close fd" construct is seen,
  4003. * REDIRFD_SYNTAX_ERR if syntax error,
  4004. * REDIRFD_TO_FILE if no & was seen,
  4005. * or the number found.
  4006. */
  4007. #if BB_MMU
  4008. #define parse_redir_right_fd(as_string, input) \
  4009. parse_redir_right_fd(input)
  4010. #endif
  4011. static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
  4012. {
  4013. int ch, d, ok;
  4014. ch = i_peek(input);
  4015. if (ch != '&')
  4016. return REDIRFD_TO_FILE;
  4017. ch = i_getch(input); /* get the & */
  4018. nommu_addchr(as_string, ch);
  4019. ch = i_peek(input);
  4020. if (ch == '-') {
  4021. ch = i_getch(input);
  4022. nommu_addchr(as_string, ch);
  4023. return REDIRFD_CLOSE;
  4024. }
  4025. d = 0;
  4026. ok = 0;
  4027. while (ch != EOF && isdigit(ch)) {
  4028. d = d*10 + (ch-'0');
  4029. ok = 1;
  4030. ch = i_getch(input);
  4031. nommu_addchr(as_string, ch);
  4032. ch = i_peek(input);
  4033. }
  4034. if (ok) return d;
  4035. //TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
  4036. bb_simple_error_msg("ambiguous redirect");
  4037. return REDIRFD_SYNTAX_ERR;
  4038. }
  4039. /* Return code is 0 normal, 1 if a syntax error is detected
  4040. */
  4041. static int parse_redirect(struct parse_context *ctx,
  4042. int fd,
  4043. redir_type style,
  4044. struct in_str *input)
  4045. {
  4046. struct command *command = ctx->command;
  4047. struct redir_struct *redir;
  4048. struct redir_struct **redirp;
  4049. int dup_num;
  4050. dup_num = REDIRFD_TO_FILE;
  4051. if (style != REDIRECT_HEREDOC) {
  4052. /* Check for a '>&1' type redirect */
  4053. dup_num = parse_redir_right_fd(&ctx->as_string, input);
  4054. if (dup_num == REDIRFD_SYNTAX_ERR)
  4055. return 1;
  4056. } else {
  4057. int ch = i_peek_and_eat_bkslash_nl(input);
  4058. dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
  4059. if (dup_num) { /* <<-... */
  4060. ch = i_getch(input);
  4061. nommu_addchr(&ctx->as_string, ch);
  4062. ch = i_peek(input);
  4063. }
  4064. }
  4065. if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
  4066. int ch = i_peek_and_eat_bkslash_nl(input);
  4067. if (ch == '|') {
  4068. /* >|FILE redirect ("clobbering" >).
  4069. * Since we do not support "set -o noclobber" yet,
  4070. * >| and > are the same for now. Just eat |.
  4071. */
  4072. ch = i_getch(input);
  4073. nommu_addchr(&ctx->as_string, ch);
  4074. }
  4075. }
  4076. /* Create a new redir_struct and append it to the linked list */
  4077. redirp = &command->redirects;
  4078. while ((redir = *redirp) != NULL) {
  4079. redirp = &(redir->next);
  4080. }
  4081. *redirp = redir = xzalloc(sizeof(*redir));
  4082. /* redir->next = NULL; */
  4083. /* redir->rd_filename = NULL; */
  4084. redir->rd_type = style;
  4085. redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
  4086. debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
  4087. redir_table[style].descrip);
  4088. redir->rd_dup = dup_num;
  4089. if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
  4090. /* Erik had a check here that the file descriptor in question
  4091. * is legit; I postpone that to "run time"
  4092. * A "-" representation of "close me" shows up as a -3 here */
  4093. debug_printf_parse("duplicating redirect '%d>&%d'\n",
  4094. redir->rd_fd, redir->rd_dup);
  4095. } else {
  4096. #if 0 /* Instead we emit error message at run time */
  4097. if (ctx->pending_redirect) {
  4098. /* For example, "cmd > <file" */
  4099. syntax_error("invalid redirect");
  4100. }
  4101. #endif
  4102. /* Set ctx->pending_redirect, so we know what to do at the
  4103. * end of the next parsed word. */
  4104. ctx->pending_redirect = redir;
  4105. }
  4106. return 0;
  4107. }
  4108. /* If a redirect is immediately preceded by a number, that number is
  4109. * supposed to tell which file descriptor to redirect. This routine
  4110. * looks for such preceding numbers. In an ideal world this routine
  4111. * needs to handle all the following classes of redirects...
  4112. * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
  4113. * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
  4114. * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
  4115. * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
  4116. *
  4117. * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
  4118. * "2.7 Redirection
  4119. * ... If n is quoted, the number shall not be recognized as part of
  4120. * the redirection expression. For example:
  4121. * echo \2>a
  4122. * writes the character 2 into file a"
  4123. * We are getting it right by setting ->has_quoted_part on any \<char>
  4124. *
  4125. * A -1 return means no valid number was found,
  4126. * the caller should use the appropriate default for this redirection.
  4127. */
  4128. static int redirect_opt_num(o_string *o)
  4129. {
  4130. int num;
  4131. if (o->data == NULL)
  4132. return -1;
  4133. num = bb_strtou(o->data, NULL, 10);
  4134. if (errno || num < 0)
  4135. return -1;
  4136. o_reset_to_empty_unquoted(o);
  4137. return num;
  4138. }
  4139. #if BB_MMU
  4140. #define fetch_till_str(as_string, input, word, skip_tabs) \
  4141. fetch_till_str(input, word, skip_tabs)
  4142. #endif
  4143. static char *fetch_till_str(o_string *as_string,
  4144. struct in_str *input,
  4145. const char *word,
  4146. int heredoc_flags)
  4147. {
  4148. o_string heredoc = NULL_O_STRING;
  4149. unsigned past_EOL;
  4150. int prev = 0; /* not \ */
  4151. int ch;
  4152. /* Starting with "" is necessary for this case:
  4153. * cat <<EOF
  4154. *
  4155. * xxx
  4156. * EOF
  4157. */
  4158. heredoc.data = xzalloc(1); /* start as "", not as NULL */
  4159. goto jump_in;
  4160. while (1) {
  4161. ch = i_getch(input);
  4162. if (ch != EOF)
  4163. nommu_addchr(as_string, ch);
  4164. if (ch == '\n' || ch == EOF) {
  4165. check_heredoc_end:
  4166. if ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\') {
  4167. /* End-of-line, and not a line continuation */
  4168. if (strcmp(heredoc.data + past_EOL, word) == 0) {
  4169. heredoc.data[past_EOL] = '\0';
  4170. debug_printf_heredoc("parsed '%s' heredoc '%s'\n", word, heredoc.data);
  4171. return heredoc.data;
  4172. }
  4173. if (ch == '\n') {
  4174. /* This is a new line.
  4175. * Remember position and backslash-escaping status.
  4176. */
  4177. o_addchr(&heredoc, ch);
  4178. prev = ch;
  4179. jump_in:
  4180. past_EOL = heredoc.length;
  4181. /* Get 1st char of next line, possibly skipping leading tabs */
  4182. do {
  4183. ch = i_getch(input);
  4184. if (ch != EOF)
  4185. nommu_addchr(as_string, ch);
  4186. } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
  4187. /* If this immediately ended the line,
  4188. * go back to end-of-line checks.
  4189. */
  4190. if (ch == '\n')
  4191. goto check_heredoc_end;
  4192. }
  4193. } else {
  4194. /* Backslash-line continuation in an unquoted
  4195. * heredoc. This does not need special handling
  4196. * for heredoc body (unquoted heredocs are
  4197. * expanded on "execution" and that would take
  4198. * care of this case too), but not the case
  4199. * of line continuation *in terminator*:
  4200. * cat <<EOF
  4201. * Ok1
  4202. * EO\
  4203. * F
  4204. */
  4205. heredoc.data[--heredoc.length] = '\0';
  4206. prev = 0; /* not '\' */
  4207. continue;
  4208. }
  4209. }
  4210. if (ch == EOF) {
  4211. o_free(&heredoc);
  4212. return NULL; /* error */
  4213. }
  4214. o_addchr(&heredoc, ch);
  4215. nommu_addchr(as_string, ch);
  4216. if (prev == '\\' && ch == '\\')
  4217. /* Correctly handle foo\\<eol> (not a line cont.) */
  4218. prev = 0; /* not '\' */
  4219. else
  4220. prev = ch;
  4221. }
  4222. }
  4223. /* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
  4224. * and load them all. There should be exactly heredoc_cnt of them.
  4225. */
  4226. #if BB_MMU
  4227. #define fetch_heredocs(as_string, pi, heredoc_cnt, input) \
  4228. fetch_heredocs(pi, heredoc_cnt, input)
  4229. #endif
  4230. static int fetch_heredocs(o_string *as_string, struct pipe *pi, int heredoc_cnt, struct in_str *input)
  4231. {
  4232. while (pi && heredoc_cnt) {
  4233. int i;
  4234. struct command *cmd = pi->cmds;
  4235. debug_printf_heredoc("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
  4236. pi->num_cmds,
  4237. cmd->argv ? cmd->argv[0] : "NONE"
  4238. );
  4239. for (i = 0; i < pi->num_cmds; i++) {
  4240. struct redir_struct *redir = cmd->redirects;
  4241. debug_printf_heredoc("fetch_heredocs: %d cmd argv0:'%s'\n",
  4242. i, cmd->argv ? cmd->argv[0] : "NONE");
  4243. while (redir) {
  4244. if (redir->rd_type == REDIRECT_HEREDOC) {
  4245. char *p;
  4246. redir->rd_type = REDIRECT_HEREDOC2;
  4247. /* redir->rd_dup is (ab)used to indicate <<- */
  4248. p = fetch_till_str(as_string, input,
  4249. redir->rd_filename, redir->rd_dup);
  4250. if (!p) {
  4251. syntax_error("unexpected EOF in here document");
  4252. return -1;
  4253. }
  4254. free(redir->rd_filename);
  4255. redir->rd_filename = p;
  4256. heredoc_cnt--;
  4257. }
  4258. redir = redir->next;
  4259. }
  4260. if (cmd->group) {
  4261. //bb_error_msg("%s:%u heredoc_cnt:%d", __func__, __LINE__, heredoc_cnt);
  4262. heredoc_cnt = fetch_heredocs(as_string, cmd->group, heredoc_cnt, input);
  4263. //bb_error_msg("%s:%u heredoc_cnt:%d", __func__, __LINE__, heredoc_cnt);
  4264. if (heredoc_cnt < 0)
  4265. return heredoc_cnt; /* error */
  4266. }
  4267. cmd++;
  4268. }
  4269. pi = pi->next;
  4270. }
  4271. return heredoc_cnt;
  4272. }
  4273. static int run_list(struct pipe *pi);
  4274. #if BB_MMU
  4275. #define parse_stream(pstring, heredoc_cnt_ptr, input, end_trigger) \
  4276. parse_stream(heredoc_cnt_ptr, input, end_trigger)
  4277. #endif
  4278. static struct pipe *parse_stream(char **pstring,
  4279. int *heredoc_cnt_ptr,
  4280. struct in_str *input,
  4281. int end_trigger);
  4282. /* Returns number of heredocs not yet consumed,
  4283. * or -1 on error.
  4284. */
  4285. static int parse_group(struct parse_context *ctx,
  4286. struct in_str *input, int ch)
  4287. {
  4288. /* ctx->word contains characters seen prior to ( or {.
  4289. * Typically it's empty, but for function defs,
  4290. * it contains function name (without '()'). */
  4291. #if BB_MMU
  4292. # define as_string NULL
  4293. #else
  4294. char *as_string = NULL;
  4295. #endif
  4296. struct pipe *pipe_list;
  4297. int heredoc_cnt = 0;
  4298. int endch;
  4299. struct command *command = ctx->command;
  4300. debug_printf_parse("parse_group entered\n");
  4301. #if ENABLE_HUSH_FUNCTIONS
  4302. if (ch == '(' && !ctx->word.has_quoted_part) {
  4303. if (ctx->word.length)
  4304. if (done_word(ctx))
  4305. return -1;
  4306. if (!command->argv)
  4307. goto skip; /* (... */
  4308. if (command->argv[1]) { /* word word ... (... */
  4309. syntax_error_unexpected_ch('(');
  4310. return -1;
  4311. }
  4312. /* it is "word(..." or "word (..." */
  4313. do
  4314. ch = i_getch(input);
  4315. while (ch == ' ' || ch == '\t');
  4316. if (ch != ')') {
  4317. syntax_error_unexpected_ch(ch);
  4318. return -1;
  4319. }
  4320. nommu_addchr(&ctx->as_string, ch);
  4321. do
  4322. ch = i_getch(input);
  4323. while (ch == ' ' || ch == '\t' || ch == '\n');
  4324. if (ch != '{' && ch != '(') {
  4325. syntax_error_unexpected_ch(ch);
  4326. return -1;
  4327. }
  4328. nommu_addchr(&ctx->as_string, ch);
  4329. command->cmd_type = CMD_FUNCDEF;
  4330. goto skip;
  4331. }
  4332. #endif
  4333. #if 0 /* Prevented by caller */
  4334. if (command->argv /* word [word]{... */
  4335. || ctx->word.length /* word{... */
  4336. || ctx->word.has_quoted_part /* ""{... */
  4337. ) {
  4338. syntax_error(NULL);
  4339. debug_printf_parse("parse_group return -1: "
  4340. "syntax error, groups and arglists don't mix\n");
  4341. return -1;
  4342. }
  4343. #endif
  4344. IF_HUSH_FUNCTIONS(skip:)
  4345. endch = '}';
  4346. if (ch == '(') {
  4347. endch = ')';
  4348. IF_HUSH_FUNCTIONS(if (command->cmd_type != CMD_FUNCDEF))
  4349. command->cmd_type = CMD_SUBSHELL;
  4350. } else {
  4351. /* bash does not allow "{echo...", requires whitespace */
  4352. ch = i_peek(input);
  4353. if (ch != ' ' && ch != '\t' && ch != '\n'
  4354. && ch != '(' /* but "{(..." is allowed (without whitespace) */
  4355. ) {
  4356. syntax_error_unexpected_ch(ch);
  4357. return -1;
  4358. }
  4359. if (ch != '(') {
  4360. ch = i_getch(input);
  4361. nommu_addchr(&ctx->as_string, ch);
  4362. }
  4363. }
  4364. debug_printf_heredoc("calling parse_stream, heredoc_cnt:%d\n", heredoc_cnt);
  4365. pipe_list = parse_stream(&as_string, &heredoc_cnt, input, endch);
  4366. debug_printf_heredoc("parse_stream returned: heredoc_cnt:%d\n", heredoc_cnt);
  4367. #if !BB_MMU
  4368. if (as_string)
  4369. o_addstr(&ctx->as_string, as_string);
  4370. #endif
  4371. /* empty ()/{} or parse error? */
  4372. if (!pipe_list || pipe_list == ERR_PTR) {
  4373. /* parse_stream already emitted error msg */
  4374. if (!BB_MMU)
  4375. free(as_string);
  4376. debug_printf_parse("parse_group return -1: "
  4377. "parse_stream returned %p\n", pipe_list);
  4378. return -1;
  4379. }
  4380. #if !BB_MMU
  4381. as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
  4382. command->group_as_string = as_string;
  4383. debug_printf_parse("end of group, remembering as:'%s'\n",
  4384. command->group_as_string);
  4385. #endif
  4386. #if ENABLE_HUSH_FUNCTIONS
  4387. /* Convert "f() (cmds)" to "f() {(cmds)}" */
  4388. if (command->cmd_type == CMD_FUNCDEF && endch == ')') {
  4389. struct command *cmd2;
  4390. cmd2 = xzalloc(sizeof(*cmd2));
  4391. cmd2->cmd_type = CMD_SUBSHELL;
  4392. cmd2->group = pipe_list;
  4393. # if !BB_MMU
  4394. //UNTESTED!
  4395. cmd2->group_as_string = command->group_as_string;
  4396. command->group_as_string = xasprintf("(%s)", command->group_as_string);
  4397. # endif
  4398. pipe_list = new_pipe();
  4399. pipe_list->cmds = cmd2;
  4400. pipe_list->num_cmds = 1;
  4401. }
  4402. #endif
  4403. command->group = pipe_list;
  4404. debug_printf_parse("parse_group return %d\n", heredoc_cnt);
  4405. return heredoc_cnt;
  4406. /* command remains "open", available for possible redirects */
  4407. #undef as_string
  4408. }
  4409. #if ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS
  4410. /* Subroutines for copying $(...) and `...` things */
  4411. /* '...' */
  4412. static int add_till_single_quote(o_string *dest, struct in_str *input)
  4413. {
  4414. while (1) {
  4415. int ch = i_getch(input);
  4416. if (ch == EOF) {
  4417. syntax_error_unterm_ch('\'');
  4418. return 0;
  4419. }
  4420. if (ch == '\'')
  4421. return 1;
  4422. o_addchr(dest, ch);
  4423. }
  4424. }
  4425. static int add_till_single_quote_dquoted(o_string *dest, struct in_str *input)
  4426. {
  4427. while (1) {
  4428. int ch = i_getch(input);
  4429. if (ch == EOF) {
  4430. syntax_error_unterm_ch('\'');
  4431. return 0;
  4432. }
  4433. if (ch == '\'')
  4434. return 1;
  4435. o_addqchr(dest, ch);
  4436. }
  4437. }
  4438. /* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
  4439. static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote);
  4440. static int add_till_double_quote(o_string *dest, struct in_str *input)
  4441. {
  4442. while (1) {
  4443. int ch = i_getch(input);
  4444. if (ch == EOF) {
  4445. syntax_error_unterm_ch('"');
  4446. return 0;
  4447. }
  4448. if (ch == '"')
  4449. return 1;
  4450. if (ch == '\\') { /* \x. Copy both chars. */
  4451. o_addchr(dest, ch);
  4452. ch = i_getch(input);
  4453. }
  4454. o_addchr(dest, ch);
  4455. if (ch == '`') {
  4456. if (!add_till_backquote(dest, input, /*in_dquote:*/ 1))
  4457. return 0;
  4458. o_addchr(dest, ch);
  4459. continue;
  4460. }
  4461. //if (ch == '$') ...
  4462. }
  4463. }
  4464. /* Process `cmd` - copy contents until "`" is seen. Complicated by
  4465. * \` quoting.
  4466. * "Within the backquoted style of command substitution, backslash
  4467. * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
  4468. * The search for the matching backquote shall be satisfied by the first
  4469. * backquote found without a preceding backslash; during this search,
  4470. * if a non-escaped backquote is encountered within a shell comment,
  4471. * a here-document, an embedded command substitution of the $(command)
  4472. * form, or a quoted string, undefined results occur. A single-quoted
  4473. * or double-quoted string that begins, but does not end, within the
  4474. * "`...`" sequence produces undefined results."
  4475. * Example Output
  4476. * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
  4477. */
  4478. static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote)
  4479. {
  4480. while (1) {
  4481. int ch = i_getch(input);
  4482. if (ch == '`')
  4483. return 1;
  4484. if (ch == '\\') {
  4485. /* \x. Copy both unless it is \`, \$, \\ and maybe \" */
  4486. ch = i_getch(input);
  4487. if (ch != '`'
  4488. && ch != '$'
  4489. && ch != '\\'
  4490. && (!in_dquote || ch != '"')
  4491. ) {
  4492. o_addchr(dest, '\\');
  4493. }
  4494. }
  4495. if (ch == EOF) {
  4496. syntax_error_unterm_ch('`');
  4497. return 0;
  4498. }
  4499. o_addchr(dest, ch);
  4500. }
  4501. }
  4502. /* Process $(cmd) - copy contents until ")" is seen. Complicated by
  4503. * quoting and nested ()s.
  4504. * "With the $(command) style of command substitution, all characters
  4505. * following the open parenthesis to the matching closing parenthesis
  4506. * constitute the command. Any valid shell script can be used for command,
  4507. * except a script consisting solely of redirections which produces
  4508. * unspecified results."
  4509. * Example Output
  4510. * echo $(echo '(TEST)' BEST) (TEST) BEST
  4511. * echo $(echo 'TEST)' BEST) TEST) BEST
  4512. * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
  4513. *
  4514. * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
  4515. * can contain arbitrary constructs, just like $(cmd).
  4516. * In bash compat mode, it needs to also be able to stop on ':' or '/'
  4517. * for ${var:N[:M]} and ${var/P[/R]} parsing.
  4518. */
  4519. #define DOUBLE_CLOSE_CHAR_FLAG 0x80
  4520. static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
  4521. {
  4522. int ch;
  4523. char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
  4524. # if BASH_SUBSTR || BASH_PATTERN_SUBST
  4525. char end_char2 = end_ch >> 8;
  4526. # endif
  4527. end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
  4528. # if ENABLE_HUSH_INTERACTIVE
  4529. G.promptmode = 1; /* PS2 */
  4530. # endif
  4531. debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
  4532. while (1) {
  4533. ch = i_getch(input);
  4534. if (ch == EOF) {
  4535. syntax_error_unterm_ch(end_ch);
  4536. return 0;
  4537. }
  4538. if (ch == end_ch
  4539. # if BASH_SUBSTR || BASH_PATTERN_SUBST
  4540. || ch == end_char2
  4541. # endif
  4542. ) {
  4543. if (!dbl)
  4544. break;
  4545. /* we look for closing )) of $((EXPR)) */
  4546. if (i_peek_and_eat_bkslash_nl(input) == end_ch) {
  4547. i_getch(input); /* eat second ')' */
  4548. break;
  4549. }
  4550. }
  4551. o_addchr(dest, ch);
  4552. //bb_error_msg("%s:o_addchr('%c')", __func__, ch);
  4553. if (ch == '(' || ch == '{') {
  4554. ch = (ch == '(' ? ')' : '}');
  4555. if (!add_till_closing_bracket(dest, input, ch))
  4556. return 0;
  4557. o_addchr(dest, ch);
  4558. continue;
  4559. }
  4560. if (ch == '\'') {
  4561. if (!add_till_single_quote(dest, input))
  4562. return 0;
  4563. o_addchr(dest, ch);
  4564. continue;
  4565. }
  4566. if (ch == '"') {
  4567. if (!add_till_double_quote(dest, input))
  4568. return 0;
  4569. o_addchr(dest, ch);
  4570. continue;
  4571. }
  4572. if (ch == '`') {
  4573. if (!add_till_backquote(dest, input, /*in_dquote:*/ 0))
  4574. return 0;
  4575. o_addchr(dest, ch);
  4576. continue;
  4577. }
  4578. if (ch == '\\') {
  4579. /* \x. Copy verbatim. Important for \(, \) */
  4580. ch = i_getch(input);
  4581. if (ch == EOF) {
  4582. syntax_error_unterm_ch(end_ch);
  4583. return 0;
  4584. }
  4585. # if 0
  4586. if (ch == '\n') {
  4587. /* "backslash+newline", ignore both */
  4588. o_delchr(dest); /* undo insertion of '\' */
  4589. continue;
  4590. }
  4591. # endif
  4592. o_addchr(dest, ch);
  4593. //bb_error_msg("%s:o_addchr('%c') after '\\'", __func__, ch);
  4594. continue;
  4595. }
  4596. }
  4597. debug_printf_parse("%s return '%s' ch:'%c'\n", __func__, dest->data, ch);
  4598. return ch;
  4599. }
  4600. #endif /* ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS */
  4601. /* Return code: 0 for OK, 1 for syntax error */
  4602. #if BB_MMU
  4603. #define parse_dollar(as_string, dest, input, quote_mask) \
  4604. parse_dollar(dest, input, quote_mask)
  4605. #define as_string NULL
  4606. #endif
  4607. static int parse_dollar(o_string *as_string,
  4608. o_string *dest,
  4609. struct in_str *input, unsigned char quote_mask)
  4610. {
  4611. int ch = i_peek_and_eat_bkslash_nl(input); /* first character after the $ */
  4612. debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
  4613. if (isalpha(ch)) {
  4614. make_var:
  4615. ch = i_getch(input);
  4616. nommu_addchr(as_string, ch);
  4617. /*make_var1:*/
  4618. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4619. while (1) {
  4620. debug_printf_parse(": '%c'\n", ch);
  4621. o_addchr(dest, ch | quote_mask);
  4622. quote_mask = 0;
  4623. ch = i_peek_and_eat_bkslash_nl(input);
  4624. if (!isalnum(ch) && ch != '_') {
  4625. /* End of variable name reached */
  4626. break;
  4627. }
  4628. ch = i_getch(input);
  4629. nommu_addchr(as_string, ch);
  4630. }
  4631. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4632. } else if (isdigit(ch)) {
  4633. make_one_char_var:
  4634. ch = i_getch(input);
  4635. nommu_addchr(as_string, ch);
  4636. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4637. debug_printf_parse(": '%c'\n", ch);
  4638. o_addchr(dest, ch | quote_mask);
  4639. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4640. } else switch (ch) {
  4641. case '$': /* pid */
  4642. case '!': /* last bg pid */
  4643. case '?': /* last exit code */
  4644. case '#': /* number of args */
  4645. case '*': /* args */
  4646. case '@': /* args */
  4647. case '-': /* $- option flags set by set builtin or shell options (-i etc) */
  4648. goto make_one_char_var;
  4649. case '{': {
  4650. char len_single_ch;
  4651. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4652. ch = i_getch(input); /* eat '{' */
  4653. nommu_addchr(as_string, ch);
  4654. ch = i_getch_and_eat_bkslash_nl(input); /* first char after '{' */
  4655. /* It should be ${?}, or ${#var},
  4656. * or even ${?+subst} - operator acting on a special variable,
  4657. * or the beginning of variable name.
  4658. */
  4659. if (ch == EOF
  4660. || (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) /* not one of those */
  4661. ) {
  4662. bad_dollar_syntax:
  4663. syntax_error_unterm_str("${name}");
  4664. debug_printf_parse("parse_dollar return 0: unterminated ${name}\n");
  4665. return 0;
  4666. }
  4667. nommu_addchr(as_string, ch);
  4668. len_single_ch = ch;
  4669. ch |= quote_mask;
  4670. /* It's possible to just call add_till_closing_bracket() at this point.
  4671. * However, this regresses some of our testsuite cases
  4672. * which check invalid constructs like ${%}.
  4673. * Oh well... let's check that the var name part is fine... */
  4674. while (1) {
  4675. unsigned pos;
  4676. o_addchr(dest, ch);
  4677. debug_printf_parse(": '%c'\n", ch);
  4678. ch = i_getch(input);
  4679. nommu_addchr(as_string, ch);
  4680. if (ch == '}')
  4681. break;
  4682. if (!isalnum(ch) && ch != '_') {
  4683. unsigned end_ch;
  4684. unsigned char last_ch;
  4685. /* handle parameter expansions
  4686. * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
  4687. */
  4688. if (!strchr(VAR_SUBST_OPS, ch)) { /* ${var<bad_char>... */
  4689. if (len_single_ch != '#'
  4690. /*|| !strchr(SPECIAL_VARS_STR, ch) - disallow errors like ${#+} ? */
  4691. || i_peek(input) != '}'
  4692. ) {
  4693. goto bad_dollar_syntax;
  4694. }
  4695. /* else: it's "length of C" ${#C} op,
  4696. * where C is a single char
  4697. * special var name, e.g. ${#!}.
  4698. */
  4699. }
  4700. /* Eat everything until closing '}' (or ':') */
  4701. end_ch = '}';
  4702. if (BASH_SUBSTR
  4703. && ch == ':'
  4704. && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
  4705. ) {
  4706. /* It's ${var:N[:M]} thing */
  4707. end_ch = '}' * 0x100 + ':';
  4708. }
  4709. if (BASH_PATTERN_SUBST
  4710. && ch == '/'
  4711. ) {
  4712. /* It's ${var/[/]pattern[/repl]} thing */
  4713. if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
  4714. i_getch(input);
  4715. nommu_addchr(as_string, '/');
  4716. ch = '\\';
  4717. }
  4718. end_ch = '}' * 0x100 + '/';
  4719. }
  4720. o_addchr(dest, ch);
  4721. /* The pattern can't be empty.
  4722. * IOW: if the first char after "${v//" is a slash,
  4723. * it does not terminate the pattern - it's the first char of the pattern:
  4724. * v=/dev/ram; echo ${v////-} prints -dev-ram (pattern is "/")
  4725. * v=/dev/ram; echo ${v///r/-} prints /dev-am (pattern is "/r")
  4726. */
  4727. if (i_peek(input) == '/') {
  4728. o_addchr(dest, i_getch(input));
  4729. }
  4730. again:
  4731. if (!BB_MMU)
  4732. pos = dest->length;
  4733. #if ENABLE_HUSH_DOLLAR_OPS
  4734. last_ch = add_till_closing_bracket(dest, input, end_ch);
  4735. if (last_ch == 0) /* error? */
  4736. return 0;
  4737. #else
  4738. # error Simple code to only allow ${var} is not implemented
  4739. #endif
  4740. if (as_string) {
  4741. o_addstr(as_string, dest->data + pos);
  4742. o_addchr(as_string, last_ch);
  4743. }
  4744. if ((BASH_SUBSTR || BASH_PATTERN_SUBST)
  4745. && (end_ch & 0xff00)
  4746. ) {
  4747. /* close the first block: */
  4748. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4749. /* while parsing N from ${var:N[:M]}
  4750. * or pattern from ${var/[/]pattern[/repl]} */
  4751. if ((end_ch & 0xff) == last_ch) {
  4752. /* got ':' or '/'- parse the rest */
  4753. end_ch = '}';
  4754. goto again;
  4755. }
  4756. /* got '}' */
  4757. if (BASH_SUBSTR && end_ch == '}' * 0x100 + ':') {
  4758. /* it's ${var:N} - emulate :999999999 */
  4759. o_addstr(dest, "999999999");
  4760. } /* else: it's ${var/[/]pattern} */
  4761. }
  4762. break;
  4763. }
  4764. len_single_ch = 0; /* it can't be ${#C} op */
  4765. }
  4766. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4767. break;
  4768. }
  4769. #if ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_TICK
  4770. case '(': {
  4771. unsigned pos;
  4772. ch = i_getch(input);
  4773. nommu_addchr(as_string, ch);
  4774. # if ENABLE_FEATURE_SH_MATH
  4775. if (i_peek_and_eat_bkslash_nl(input) == '(') {
  4776. ch = i_getch(input);
  4777. nommu_addchr(as_string, ch);
  4778. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4779. o_addchr(dest, quote_mask | '+');
  4780. if (!BB_MMU)
  4781. pos = dest->length;
  4782. if (!add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG))
  4783. return 0; /* error */
  4784. if (as_string) {
  4785. o_addstr(as_string, dest->data + pos);
  4786. o_addchr(as_string, ')');
  4787. o_addchr(as_string, ')');
  4788. }
  4789. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4790. break;
  4791. }
  4792. # endif
  4793. # if ENABLE_HUSH_TICK
  4794. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4795. o_addchr(dest, quote_mask | '`');
  4796. if (!BB_MMU)
  4797. pos = dest->length;
  4798. if (!add_till_closing_bracket(dest, input, ')'))
  4799. return 0; /* error */
  4800. if (as_string) {
  4801. o_addstr(as_string, dest->data + pos);
  4802. o_addchr(as_string, ')');
  4803. }
  4804. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4805. # endif
  4806. break;
  4807. }
  4808. #endif
  4809. case '_':
  4810. goto make_var;
  4811. #if 0
  4812. /* TODO: $_: */
  4813. /* $_ Shell or shell script name; or last argument of last command
  4814. * (if last command wasn't a pipe; if it was, bash sets $_ to "");
  4815. * but in command's env, set to full pathname used to invoke it */
  4816. ch = i_getch(input);
  4817. nommu_addchr(as_string, ch);
  4818. ch = i_peek_and_eat_bkslash_nl(input);
  4819. if (isalnum(ch)) { /* it's $_name or $_123 */
  4820. ch = '_';
  4821. goto make_var1;
  4822. }
  4823. /* else: it's $_ */
  4824. #endif
  4825. default:
  4826. o_addQchr(dest, '$');
  4827. }
  4828. debug_printf_parse("parse_dollar return 1 (ok)\n");
  4829. return 1;
  4830. #undef as_string
  4831. }
  4832. #if BB_MMU
  4833. #define encode_string(as_string, dest, input, dquote_end) \
  4834. encode_string(dest, input, dquote_end)
  4835. #define as_string NULL
  4836. #endif
  4837. static int encode_string(o_string *as_string,
  4838. o_string *dest,
  4839. struct in_str *input,
  4840. int dquote_end)
  4841. {
  4842. int ch;
  4843. int next;
  4844. again:
  4845. ch = i_getch(input);
  4846. if (ch != EOF)
  4847. nommu_addchr(as_string, ch);
  4848. if (ch == dquote_end) { /* may be only '"' or EOF */
  4849. debug_printf_parse("encode_string return 1 (ok)\n");
  4850. return 1;
  4851. }
  4852. /* note: can't move it above ch == dquote_end check! */
  4853. if (ch == EOF) {
  4854. syntax_error_unterm_ch('"');
  4855. return 0; /* error */
  4856. }
  4857. next = '\0';
  4858. if (ch != '\n') {
  4859. next = i_peek(input);
  4860. }
  4861. debug_printf_parse("\" ch=%c (%d) escape=%d\n",
  4862. ch, ch, !!(dest->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
  4863. if (ch == '\\') {
  4864. if (next == EOF) {
  4865. /* Testcase: in interactive shell a file with
  4866. * echo "unterminated string\<eof>
  4867. * is sourced.
  4868. */
  4869. syntax_error_unterm_ch('"');
  4870. return 0; /* error */
  4871. }
  4872. /* bash:
  4873. * "The backslash retains its special meaning [in "..."]
  4874. * only when followed by one of the following characters:
  4875. * $, `, ", \, or <newline>. A double quote may be quoted
  4876. * within double quotes by preceding it with a backslash."
  4877. * NB: in (unquoted) heredoc, above does not apply to ",
  4878. * therefore we check for it by "next == dquote_end" cond.
  4879. */
  4880. if (next == dquote_end || strchr("$`\\\n", next)) {
  4881. ch = i_getch(input); /* eat next */
  4882. if (ch == '\n')
  4883. goto again; /* skip \<newline> */
  4884. } /* else: ch remains == '\\', and we double it below: */
  4885. o_addqchr(dest, ch); /* \c if c is a glob char, else just c */
  4886. nommu_addchr(as_string, ch);
  4887. goto again;
  4888. }
  4889. if (ch == '$') {
  4890. if (!parse_dollar(as_string, dest, input, /*quote_mask:*/ 0x80)) {
  4891. debug_printf_parse("encode_string return 0: "
  4892. "parse_dollar returned 0 (error)\n");
  4893. return 0;
  4894. }
  4895. goto again;
  4896. }
  4897. #if ENABLE_HUSH_TICK
  4898. if (ch == '`') {
  4899. //unsigned pos = dest->length;
  4900. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4901. o_addchr(dest, 0x80 | '`');
  4902. if (!add_till_backquote(dest, input, /*in_dquote:*/ dquote_end == '"'))
  4903. return 0; /* error */
  4904. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4905. //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
  4906. goto again;
  4907. }
  4908. #endif
  4909. o_addQchr(dest, ch);
  4910. if (ch == SPECIAL_VAR_SYMBOL) {
  4911. /* Convert "^C" to corresponding special variable reference */
  4912. o_addchr(dest, SPECIAL_VAR_QUOTED_SVS);
  4913. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4914. }
  4915. goto again;
  4916. #undef as_string
  4917. }
  4918. /*
  4919. * Scan input until EOF or end_trigger char.
  4920. * Return a list of pipes to execute, or NULL on EOF
  4921. * or if end_trigger character is met.
  4922. * On syntax error, exit if shell is not interactive,
  4923. * reset parsing machinery and start parsing anew,
  4924. * or return ERR_PTR.
  4925. */
  4926. static struct pipe *parse_stream(char **pstring,
  4927. int *heredoc_cnt_ptr,
  4928. struct in_str *input,
  4929. int end_trigger)
  4930. {
  4931. struct parse_context ctx;
  4932. int heredoc_cnt;
  4933. /* Single-quote triggers a bypass of the main loop until its mate is
  4934. * found. When recursing, quote state is passed in via ctx.word.o_expflags.
  4935. */
  4936. debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
  4937. end_trigger ? end_trigger : 'X');
  4938. debug_enter();
  4939. initialize_context(&ctx);
  4940. /* If very first arg is "" or '', ctx.word.data may end up NULL.
  4941. * Preventing this:
  4942. */
  4943. ctx.word.data = xzalloc(1); /* start as "", not as NULL */
  4944. /* We used to separate words on $IFS here. This was wrong.
  4945. * $IFS is used only for word splitting when $var is expanded,
  4946. * here we should use blank chars as separators, not $IFS
  4947. */
  4948. heredoc_cnt = 0;
  4949. while (1) {
  4950. const char *is_blank;
  4951. const char *is_special;
  4952. int ch;
  4953. int next;
  4954. int redir_fd;
  4955. redir_type redir_style;
  4956. ch = i_getch(input);
  4957. debug_printf_parse(": ch=%c (%d) escape=%d\n",
  4958. ch, ch, !!(ctx.word.o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
  4959. if (ch == EOF) {
  4960. struct pipe *pi;
  4961. if (heredoc_cnt) {
  4962. syntax_error_unterm_str("here document");
  4963. goto parse_error_exitcode1;
  4964. }
  4965. if (end_trigger == ')') {
  4966. syntax_error_unterm_ch('(');
  4967. goto parse_error_exitcode1;
  4968. }
  4969. if (end_trigger == '}') {
  4970. syntax_error_unterm_ch('{');
  4971. goto parse_error_exitcode1;
  4972. }
  4973. if (done_word(&ctx)) {
  4974. goto parse_error_exitcode1;
  4975. }
  4976. o_free_and_set_NULL(&ctx.word);
  4977. done_pipe(&ctx, PIPE_SEQ);
  4978. pi = ctx.list_head;
  4979. /* If we got nothing... */
  4980. /* (this makes bare "&" cmd a no-op.
  4981. * bash says: "syntax error near unexpected token '&'") */
  4982. if (pi->num_cmds == 0
  4983. IF_HAS_KEYWORDS(&& pi->res_word == RES_NONE)
  4984. ) {
  4985. free_pipe_list(pi);
  4986. pi = NULL;
  4987. }
  4988. #if !BB_MMU
  4989. debug_printf_parse("as_string1 '%s'\n", ctx.as_string.data);
  4990. if (pstring)
  4991. *pstring = ctx.as_string.data;
  4992. else
  4993. o_free(&ctx.as_string);
  4994. #endif
  4995. // heredoc_cnt must be 0 here anyway
  4996. //if (heredoc_cnt_ptr)
  4997. // *heredoc_cnt_ptr = heredoc_cnt;
  4998. debug_leave();
  4999. debug_printf_heredoc("parse_stream return heredoc_cnt:%d\n", heredoc_cnt);
  5000. debug_printf_parse("parse_stream return %p\n", pi);
  5001. return pi;
  5002. }
  5003. /* Handle "'" and "\" first, as they won't play nice with
  5004. * i_peek_and_eat_bkslash_nl() anyway:
  5005. * echo z\\
  5006. * and
  5007. * echo '\
  5008. * '
  5009. * would break.
  5010. */
  5011. if (ch == '\\') {
  5012. ch = i_getch(input);
  5013. if (ch == '\n')
  5014. continue; /* drop \<newline>, get next char */
  5015. nommu_addchr(&ctx.as_string, '\\');
  5016. if (ch == SPECIAL_VAR_SYMBOL) {
  5017. nommu_addchr(&ctx.as_string, ch);
  5018. /* Convert \^C to corresponding special variable reference */
  5019. goto case_SPECIAL_VAR_SYMBOL;
  5020. }
  5021. o_addchr(&ctx.word, '\\');
  5022. if (ch == EOF) {
  5023. /* Testcase: eval 'echo Ok\' */
  5024. /* bash-4.3.43 was removing backslash,
  5025. * but 4.4.19 retains it, most other shells too
  5026. */
  5027. continue; /* get next char */
  5028. }
  5029. /* Example: echo Hello \2>file
  5030. * we need to know that word 2 is quoted
  5031. */
  5032. ctx.word.has_quoted_part = 1;
  5033. nommu_addchr(&ctx.as_string, ch);
  5034. o_addchr(&ctx.word, ch);
  5035. continue; /* get next char */
  5036. }
  5037. nommu_addchr(&ctx.as_string, ch);
  5038. if (ch == '\'') {
  5039. ctx.word.has_quoted_part = 1;
  5040. next = i_getch(input);
  5041. if (next == '\'' && !ctx.pending_redirect)
  5042. goto insert_empty_quoted_str_marker;
  5043. ch = next;
  5044. while (1) {
  5045. if (ch == EOF) {
  5046. syntax_error_unterm_ch('\'');
  5047. goto parse_error_exitcode1;
  5048. }
  5049. nommu_addchr(&ctx.as_string, ch);
  5050. if (ch == '\'')
  5051. break;
  5052. if (ch == SPECIAL_VAR_SYMBOL) {
  5053. /* Convert raw ^C to corresponding special variable reference */
  5054. o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
  5055. o_addchr(&ctx.word, SPECIAL_VAR_QUOTED_SVS);
  5056. }
  5057. o_addqchr(&ctx.word, ch);
  5058. ch = i_getch(input);
  5059. }
  5060. continue; /* get next char */
  5061. }
  5062. next = '\0';
  5063. if (ch != '\n')
  5064. next = i_peek_and_eat_bkslash_nl(input);
  5065. is_special = "{}<>&|();#" /* special outside of "str" */
  5066. "$\"" IF_HUSH_TICK("`") /* always special */
  5067. SPECIAL_VAR_SYMBOL_STR;
  5068. #if defined(CMD_TEST2_SINGLEWORD_NOGLOB)
  5069. if (ctx.command->cmd_type == CMD_TEST2_SINGLEWORD_NOGLOB) {
  5070. /* In [[ ]], {}<>&|() are not special */
  5071. is_special += 8;
  5072. } else
  5073. #endif
  5074. /* Are { and } special here? */
  5075. if (ctx.command->argv /* word [word]{... - non-special */
  5076. || ctx.word.length /* word{... - non-special */
  5077. || ctx.word.has_quoted_part /* ""{... - non-special */
  5078. || (next != ';' /* }; - special */
  5079. && next != ')' /* }) - special */
  5080. && next != '(' /* {( - special */
  5081. && next != '&' /* }& and }&& ... - special */
  5082. && next != '|' /* }|| ... - special */
  5083. && !strchr(defifs, next) /* {word - non-special */
  5084. )
  5085. ) {
  5086. /* They are not special, skip "{}" */
  5087. is_special += 2;
  5088. }
  5089. is_special = strchr(is_special, ch);
  5090. is_blank = strchr(defifs, ch);
  5091. if (!is_special && !is_blank) { /* ordinary char */
  5092. ordinary_char:
  5093. o_addQchr(&ctx.word, ch);
  5094. if ((ctx.is_assignment == MAYBE_ASSIGNMENT
  5095. || ctx.is_assignment == WORD_IS_KEYWORD)
  5096. && ch == '='
  5097. && endofname(ctx.word.data)[0] == '='
  5098. ) {
  5099. ctx.is_assignment = DEFINITELY_ASSIGNMENT;
  5100. debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
  5101. }
  5102. continue;
  5103. }
  5104. if (is_blank) {
  5105. #if ENABLE_HUSH_LINENO_VAR
  5106. /* Case:
  5107. * "while ...; do<whitespace><newline>
  5108. * cmd ..."
  5109. * would think that "cmd" starts in <whitespace> -
  5110. * i.e., at the previous line.
  5111. * We need to skip all whitespace before newlines.
  5112. */
  5113. while (ch != '\n') {
  5114. next = i_peek(input);
  5115. if (next != ' ' && next != '\t' && next != '\n')
  5116. break; /* next char is not ws */
  5117. ch = i_getch(input);
  5118. }
  5119. /* ch == last eaten whitespace char */
  5120. #endif
  5121. if (done_word(&ctx)) {
  5122. goto parse_error_exitcode1;
  5123. }
  5124. if (ch == '\n') {
  5125. /* Is this a case when newline is simply ignored?
  5126. * Some examples:
  5127. * "cmd | <newline> cmd ..."
  5128. * "case ... in <newline> word) ..."
  5129. */
  5130. if (IS_NULL_CMD(ctx.command)
  5131. && ctx.word.length == 0
  5132. && !ctx.word.has_quoted_part
  5133. && heredoc_cnt == 0
  5134. ) {
  5135. /* This newline can be ignored. But...
  5136. * Without check #1, interactive shell
  5137. * ignores even bare <newline>,
  5138. * and shows the continuation prompt:
  5139. * ps1_prompt$ <enter>
  5140. * ps2> _ <=== wrong, should be ps1
  5141. * Without check #2, "cmd & <newline>"
  5142. * is similarly mistreated.
  5143. * (BTW, this makes "cmd & cmd"
  5144. * and "cmd && cmd" non-orthogonal.
  5145. * Really, ask yourself, why
  5146. * "cmd && <newline>" doesn't start
  5147. * cmd but waits for more input?
  5148. * The only reason is that it might be
  5149. * a "cmd1 && <nl> cmd2 &" construct,
  5150. * cmd1 may need to run in BG).
  5151. */
  5152. struct pipe *pi = ctx.list_head;
  5153. if (pi->num_cmds != 0 /* check #1 */
  5154. && pi->followup != PIPE_BG /* check #2 */
  5155. ) {
  5156. continue;
  5157. }
  5158. }
  5159. /* Treat newline as a command separator. */
  5160. done_pipe(&ctx, PIPE_SEQ);
  5161. debug_printf_heredoc("heredoc_cnt:%d\n", heredoc_cnt);
  5162. if (heredoc_cnt) {
  5163. heredoc_cnt = fetch_heredocs(&ctx.as_string, ctx.list_head, heredoc_cnt, input);
  5164. if (heredoc_cnt != 0)
  5165. goto parse_error_exitcode1;
  5166. }
  5167. ctx.is_assignment = MAYBE_ASSIGNMENT;
  5168. debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
  5169. ch = ';';
  5170. /* note: if (is_blank) continue;
  5171. * will still trigger for us */
  5172. }
  5173. }
  5174. /* "cmd}" or "cmd }..." without semicolon or &:
  5175. * } is an ordinary char in this case, even inside { cmd; }
  5176. * Pathological example: { ""}; } should exec "}" cmd
  5177. */
  5178. if (ch == '}') {
  5179. if (ctx.word.length != 0 /* word} */
  5180. || ctx.word.has_quoted_part /* ""} */
  5181. ) {
  5182. goto ordinary_char;
  5183. }
  5184. if (!IS_NULL_CMD(ctx.command)) { /* cmd } */
  5185. /* Generally, there should be semicolon: "cmd; }"
  5186. * However, bash allows to omit it if "cmd" is
  5187. * a group. Examples:
  5188. * { { echo 1; } }
  5189. * {(echo 1)}
  5190. * { echo 0 >&2 | { echo 1; } }
  5191. * { while false; do :; done }
  5192. * { case a in b) ;; esac }
  5193. */
  5194. if (ctx.command->group)
  5195. goto term_group;
  5196. goto ordinary_char;
  5197. }
  5198. if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
  5199. /* Can't be an end of {cmd}, skip the check */
  5200. goto skip_end_trigger;
  5201. /* else: } does terminate a group */
  5202. }
  5203. term_group:
  5204. if (end_trigger && end_trigger == ch
  5205. && (ch != ';' || heredoc_cnt == 0)
  5206. #if ENABLE_HUSH_CASE
  5207. && (ch != ')'
  5208. || ctx.ctx_res_w != RES_MATCH
  5209. || (!ctx.word.has_quoted_part && strcmp(ctx.word.data, "esac") == 0)
  5210. )
  5211. #endif
  5212. ) {
  5213. if (done_word(&ctx)) {
  5214. goto parse_error_exitcode1;
  5215. }
  5216. done_pipe(&ctx, PIPE_SEQ);
  5217. ctx.is_assignment = MAYBE_ASSIGNMENT;
  5218. debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
  5219. /* Do we sit outside of any if's, loops or case's? */
  5220. if (!HAS_KEYWORDS
  5221. IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
  5222. ) {
  5223. o_free_and_set_NULL(&ctx.word);
  5224. #if !BB_MMU
  5225. debug_printf_parse("as_string2 '%s'\n", ctx.as_string.data);
  5226. if (pstring)
  5227. *pstring = ctx.as_string.data;
  5228. else
  5229. o_free(&ctx.as_string);
  5230. #endif
  5231. if (ch != ';' && IS_NULL_PIPE(ctx.list_head)) {
  5232. /* Example: bare "{ }", "()" */
  5233. G.last_exitcode = 2; /* bash compat */
  5234. syntax_error_unexpected_ch(ch);
  5235. goto parse_error;
  5236. }
  5237. if (heredoc_cnt_ptr)
  5238. *heredoc_cnt_ptr = heredoc_cnt;
  5239. debug_printf_heredoc("parse_stream return heredoc_cnt:%d\n", heredoc_cnt);
  5240. debug_printf_parse("parse_stream return %p: "
  5241. "end_trigger char found\n",
  5242. ctx.list_head);
  5243. debug_leave();
  5244. return ctx.list_head;
  5245. }
  5246. }
  5247. if (is_blank)
  5248. continue;
  5249. /* Catch <, > before deciding whether this word is
  5250. * an assignment. a=1 2>z b=2: b=2 is still assignment */
  5251. switch (ch) {
  5252. case '>':
  5253. redir_fd = redirect_opt_num(&ctx.word);
  5254. if (done_word(&ctx)) {
  5255. goto parse_error_exitcode1;
  5256. }
  5257. redir_style = REDIRECT_OVERWRITE;
  5258. if (next == '>') {
  5259. redir_style = REDIRECT_APPEND;
  5260. ch = i_getch(input);
  5261. nommu_addchr(&ctx.as_string, ch);
  5262. }
  5263. #if 0
  5264. else if (next == '(') {
  5265. syntax_error(">(process) not supported");
  5266. goto parse_error_exitcode1;
  5267. }
  5268. #endif
  5269. if (parse_redirect(&ctx, redir_fd, redir_style, input))
  5270. goto parse_error_exitcode1;
  5271. continue; /* get next char */
  5272. case '<':
  5273. redir_fd = redirect_opt_num(&ctx.word);
  5274. if (done_word(&ctx)) {
  5275. goto parse_error_exitcode1;
  5276. }
  5277. redir_style = REDIRECT_INPUT;
  5278. if (next == '<') {
  5279. redir_style = REDIRECT_HEREDOC;
  5280. heredoc_cnt++;
  5281. debug_printf_heredoc("++heredoc_cnt=%d\n", heredoc_cnt);
  5282. ch = i_getch(input);
  5283. nommu_addchr(&ctx.as_string, ch);
  5284. } else if (next == '>') {
  5285. redir_style = REDIRECT_IO;
  5286. ch = i_getch(input);
  5287. nommu_addchr(&ctx.as_string, ch);
  5288. }
  5289. #if 0
  5290. else if (next == '(') {
  5291. syntax_error("<(process) not supported");
  5292. goto parse_error_exitcode1;
  5293. }
  5294. #endif
  5295. if (parse_redirect(&ctx, redir_fd, redir_style, input))
  5296. goto parse_error_exitcode1;
  5297. continue; /* get next char */
  5298. case '#':
  5299. if (ctx.word.length == 0 && !ctx.word.has_quoted_part) {
  5300. /* skip "#comment" */
  5301. /* note: we do not add it to &ctx.as_string */
  5302. /* TODO: in bash:
  5303. * comment inside $() goes to the next \n, even inside quoted string (!):
  5304. * cmd "$(cmd2 #comment)" - syntax error
  5305. * cmd "`cmd2 #comment`" - ok
  5306. * We accept both (comment ends where command subst ends, in both cases).
  5307. */
  5308. while (1) {
  5309. ch = i_peek(input);
  5310. if (ch == '\n') {
  5311. nommu_addchr(&ctx.as_string, '\n');
  5312. break;
  5313. }
  5314. ch = i_getch(input);
  5315. if (ch == EOF)
  5316. break;
  5317. }
  5318. continue; /* get next char */
  5319. }
  5320. break;
  5321. }
  5322. skip_end_trigger:
  5323. if (ctx.is_assignment == MAYBE_ASSIGNMENT
  5324. /* check that we are not in word in "a=1 2>word b=1": */
  5325. && !ctx.pending_redirect
  5326. ) {
  5327. /* ch is a special char and thus this word
  5328. * cannot be an assignment */
  5329. ctx.is_assignment = NOT_ASSIGNMENT;
  5330. debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
  5331. }
  5332. /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
  5333. switch (ch) {
  5334. case_SPECIAL_VAR_SYMBOL:
  5335. case SPECIAL_VAR_SYMBOL:
  5336. /* Convert raw ^C to corresponding special variable reference */
  5337. o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
  5338. o_addchr(&ctx.word, SPECIAL_VAR_QUOTED_SVS);
  5339. /* fall through */
  5340. case '#':
  5341. /* non-comment #: "echo a#b" etc */
  5342. o_addchr(&ctx.word, ch);
  5343. continue; /* get next char */
  5344. case '$':
  5345. if (!parse_dollar(&ctx.as_string, &ctx.word, input, /*quote_mask:*/ 0)) {
  5346. debug_printf_parse("parse_stream parse error: "
  5347. "parse_dollar returned 0 (error)\n");
  5348. goto parse_error_exitcode1;
  5349. }
  5350. continue; /* get next char */
  5351. case '"':
  5352. ctx.word.has_quoted_part = 1;
  5353. if (next == '"' && !ctx.pending_redirect) {
  5354. i_getch(input); /* eat second " */
  5355. insert_empty_quoted_str_marker:
  5356. nommu_addchr(&ctx.as_string, next);
  5357. o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
  5358. o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
  5359. continue; /* get next char */
  5360. }
  5361. if (ctx.is_assignment == NOT_ASSIGNMENT)
  5362. ctx.word.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
  5363. if (!encode_string(&ctx.as_string, &ctx.word, input, '"'))
  5364. goto parse_error_exitcode1;
  5365. ctx.word.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
  5366. continue; /* get next char */
  5367. #if ENABLE_HUSH_TICK
  5368. case '`': {
  5369. USE_FOR_NOMMU(unsigned pos;)
  5370. o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
  5371. o_addchr(&ctx.word, '`');
  5372. USE_FOR_NOMMU(pos = ctx.word.length;)
  5373. if (!add_till_backquote(&ctx.word, input, /*in_dquote:*/ 0))
  5374. goto parse_error_exitcode1;
  5375. # if !BB_MMU
  5376. o_addstr(&ctx.as_string, ctx.word.data + pos);
  5377. o_addchr(&ctx.as_string, '`');
  5378. # endif
  5379. o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
  5380. //debug_printf_subst("SUBST RES3 '%s'\n", ctx.word.data + pos);
  5381. continue; /* get next char */
  5382. }
  5383. #endif
  5384. case ';':
  5385. #if ENABLE_HUSH_CASE
  5386. case_semi:
  5387. #endif
  5388. if (done_word(&ctx)) {
  5389. goto parse_error_exitcode1;
  5390. }
  5391. done_pipe(&ctx, PIPE_SEQ);
  5392. #if ENABLE_HUSH_CASE
  5393. /* Eat multiple semicolons, detect
  5394. * whether it means something special */
  5395. while (1) {
  5396. ch = i_peek_and_eat_bkslash_nl(input);
  5397. if (ch != ';')
  5398. break;
  5399. ch = i_getch(input);
  5400. nommu_addchr(&ctx.as_string, ch);
  5401. if (ctx.ctx_res_w == RES_CASE_BODY) {
  5402. ctx.ctx_dsemicolon = 1;
  5403. ctx.ctx_res_w = RES_MATCH;
  5404. break;
  5405. }
  5406. }
  5407. #endif
  5408. new_cmd:
  5409. /* We just finished a cmd. New one may start
  5410. * with an assignment */
  5411. ctx.is_assignment = MAYBE_ASSIGNMENT;
  5412. debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
  5413. continue; /* get next char */
  5414. case '&':
  5415. if (done_word(&ctx)) {
  5416. goto parse_error_exitcode1;
  5417. }
  5418. if (next == '&') {
  5419. ch = i_getch(input);
  5420. nommu_addchr(&ctx.as_string, ch);
  5421. done_pipe(&ctx, PIPE_AND);
  5422. } else {
  5423. done_pipe(&ctx, PIPE_BG);
  5424. }
  5425. goto new_cmd;
  5426. case '|':
  5427. if (done_word(&ctx)) {
  5428. goto parse_error_exitcode1;
  5429. }
  5430. #if ENABLE_HUSH_CASE
  5431. if (ctx.ctx_res_w == RES_MATCH)
  5432. break; /* we are in case's "word | word)" */
  5433. #endif
  5434. if (next == '|') { /* || */
  5435. ch = i_getch(input);
  5436. nommu_addchr(&ctx.as_string, ch);
  5437. done_pipe(&ctx, PIPE_OR);
  5438. } else {
  5439. /* we could pick up a file descriptor choice here
  5440. * with redirect_opt_num(), but bash doesn't do it.
  5441. * "echo foo 2| cat" yields "foo 2". */
  5442. done_command(&ctx);
  5443. }
  5444. goto new_cmd;
  5445. case '(':
  5446. #if ENABLE_HUSH_CASE
  5447. /* "case... in [(]word)..." - skip '(' */
  5448. if (ctx.ctx_res_w == RES_MATCH
  5449. && ctx.command->argv == NULL /* not (word|(... */
  5450. && ctx.word.length == 0 /* not word(... */
  5451. && ctx.word.has_quoted_part == 0 /* not ""(... */
  5452. ) {
  5453. continue; /* get next char */
  5454. }
  5455. #endif
  5456. /* fall through */
  5457. case '{': {
  5458. int n = parse_group(&ctx, input, ch);
  5459. if (n < 0) {
  5460. goto parse_error_exitcode1;
  5461. }
  5462. debug_printf_heredoc("parse_group done, needs heredocs:%d\n", n);
  5463. heredoc_cnt += n;
  5464. goto new_cmd;
  5465. }
  5466. case ')':
  5467. #if ENABLE_HUSH_CASE
  5468. if (ctx.ctx_res_w == RES_MATCH)
  5469. goto case_semi;
  5470. #endif
  5471. case '}':
  5472. /* proper use of this character is caught by end_trigger:
  5473. * if we see {, we call parse_group(..., end_trigger='}')
  5474. * and it will match } earlier (not here). */
  5475. G.last_exitcode = 2;
  5476. syntax_error_unexpected_ch(ch);
  5477. goto parse_error;
  5478. default:
  5479. if (HUSH_DEBUG)
  5480. bb_error_msg_and_die("BUG: unexpected %c", ch);
  5481. }
  5482. } /* while (1) */
  5483. parse_error_exitcode1:
  5484. G.last_exitcode = 1;
  5485. parse_error:
  5486. {
  5487. struct parse_context *pctx;
  5488. IF_HAS_KEYWORDS(struct parse_context *p2;)
  5489. /* Clean up allocated tree.
  5490. * Sample for finding leaks on syntax error recovery path.
  5491. * Run it from interactive shell, watch pmap `pidof hush`.
  5492. * while if false; then false; fi; do break; fi
  5493. * Samples to catch leaks at execution:
  5494. * while if (true | { true;}); then echo ok; fi; do break; done
  5495. * while if (true | { true;}); then echo ok; fi; do (if echo ok; break; then :; fi) | cat; break; done
  5496. */
  5497. pctx = &ctx;
  5498. do {
  5499. /* Update pipe/command counts,
  5500. * otherwise freeing may miss some */
  5501. done_pipe(pctx, PIPE_SEQ);
  5502. debug_printf_clean("freeing list %p from ctx %p\n",
  5503. pctx->list_head, pctx);
  5504. debug_print_tree(pctx->list_head, 0);
  5505. free_pipe_list(pctx->list_head);
  5506. debug_printf_clean("freed list %p\n", pctx->list_head);
  5507. #if !BB_MMU
  5508. o_free(&pctx->as_string);
  5509. #endif
  5510. IF_HAS_KEYWORDS(p2 = pctx->stack;)
  5511. if (pctx != &ctx) {
  5512. free(pctx);
  5513. }
  5514. IF_HAS_KEYWORDS(pctx = p2;)
  5515. } while (HAS_KEYWORDS && pctx);
  5516. o_free(&ctx.word);
  5517. #if !BB_MMU
  5518. if (pstring)
  5519. *pstring = NULL;
  5520. #endif
  5521. debug_leave();
  5522. return ERR_PTR;
  5523. }
  5524. }
  5525. /*** Execution routines ***/
  5526. /* Expansion can recurse, need forward decls: */
  5527. #if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
  5528. #define expand_string_to_string(str, EXP_flags, do_unbackslash) \
  5529. expand_string_to_string(str)
  5530. #endif
  5531. static char *expand_string_to_string(const char *str, int EXP_flags, int do_unbackslash);
  5532. #if ENABLE_HUSH_TICK
  5533. static int process_command_subs(o_string *dest, const char *s);
  5534. #endif
  5535. static int expand_vars_to_list(o_string *output, int n, char *arg);
  5536. /* expand_strvec_to_strvec() takes a list of strings, expands
  5537. * all variable references within and returns a pointer to
  5538. * a list of expanded strings, possibly with larger number
  5539. * of strings. (Think VAR="a b"; echo $VAR).
  5540. * This new list is allocated as a single malloc block.
  5541. * NULL-terminated list of char* pointers is at the beginning of it,
  5542. * followed by strings themselves.
  5543. * Caller can deallocate entire list by single free(list). */
  5544. /* A horde of its helpers come first: */
  5545. static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
  5546. {
  5547. while (--len >= 0) {
  5548. char c = *str++;
  5549. #if ENABLE_HUSH_BRACE_EXPANSION
  5550. if (c == '{' || c == '}') {
  5551. /* { -> \{, } -> \} */
  5552. o_addchr(o, '\\');
  5553. /* And now we want to add { or } and continue:
  5554. * o_addchr(o, c);
  5555. * continue;
  5556. * luckily, just falling through achieves this.
  5557. */
  5558. }
  5559. #endif
  5560. o_addchr(o, c);
  5561. if (c == '\\') {
  5562. /* \z -> \\\z; \<eol> -> \\<eol> */
  5563. o_addchr(o, '\\');
  5564. if (len) {
  5565. len--;
  5566. o_addchr(o, '\\');
  5567. o_addchr(o, *str++);
  5568. }
  5569. }
  5570. }
  5571. }
  5572. /* Store given string, finalizing the word and starting new one whenever
  5573. * we encounter IFS char(s). This is used for expanding variable values.
  5574. * End-of-string does NOT finalize word: think about 'echo -$VAR-'.
  5575. * Return in output->ended_in_ifs:
  5576. * 1 - ended with IFS char, else 0 (this includes case of empty str).
  5577. */
  5578. static int expand_on_ifs(o_string *output, int n, const char *str)
  5579. {
  5580. int last_is_ifs = 0;
  5581. while (1) {
  5582. int word_len;
  5583. if (!*str) /* EOL - do not finalize word */
  5584. break;
  5585. word_len = strcspn(str, G.ifs);
  5586. if (word_len) {
  5587. /* We have WORD_LEN leading non-IFS chars */
  5588. if (!(output->o_expflags & EXP_FLAG_GLOB)) {
  5589. o_addblock(output, str, word_len);
  5590. } else {
  5591. /* Protect backslashes against globbing up :)
  5592. * Example: "v='\*'; echo b$v" prints "b\*"
  5593. * (and does not try to glob on "*")
  5594. */
  5595. o_addblock_duplicate_backslash(output, str, word_len);
  5596. /*/ Why can't we do it easier? */
  5597. /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
  5598. /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
  5599. }
  5600. last_is_ifs = 0;
  5601. str += word_len;
  5602. if (!*str) /* EOL - do not finalize word */
  5603. break;
  5604. }
  5605. /* We know str here points to at least one IFS char */
  5606. last_is_ifs = 1;
  5607. str += strspn(str, G.ifs_whitespace); /* skip IFS whitespace chars */
  5608. if (!*str) /* EOL - do not finalize word */
  5609. break;
  5610. if (G.ifs_whitespace != G.ifs /* usually false ($IFS is usually all whitespace), */
  5611. && strchr(G.ifs, *str) /* the second check would fail */
  5612. ) {
  5613. /* This is a non-whitespace $IFS char */
  5614. /* Skip it and IFS whitespace chars, start new word */
  5615. str++;
  5616. str += strspn(str, G.ifs_whitespace);
  5617. goto new_word;
  5618. }
  5619. /* Start new word... but not always! */
  5620. /* Case "v=' a'; echo ''$v": we do need to finalize empty word: */
  5621. if (output->has_quoted_part
  5622. /*
  5623. * Case "v=' a'; echo $v":
  5624. * here nothing precedes the space in $v expansion,
  5625. * therefore we should not finish the word
  5626. * (IOW: if there *is* word to finalize, only then do it):
  5627. * It's okay if this accesses the byte before first argv[]:
  5628. * past call to o_save_ptr() cleared it to zero byte
  5629. * (grep for -prev-ifs-check-).
  5630. */
  5631. || output->data[output->length - 1]
  5632. ) {
  5633. new_word:
  5634. o_addchr(output, '\0');
  5635. debug_print_list("expand_on_ifs", output, n);
  5636. n = o_save_ptr(output, n);
  5637. }
  5638. }
  5639. output->ended_in_ifs = last_is_ifs;
  5640. debug_print_list("expand_on_ifs[1]", output, n);
  5641. return n;
  5642. }
  5643. /* Helper to expand $((...)) and heredoc body. These act as if
  5644. * they are in double quotes, with the exception that they are not :).
  5645. * Just the rules are similar: "expand only $var and `cmd`"
  5646. *
  5647. * Returns malloced string.
  5648. * As an optimization, we return NULL if expansion is not needed.
  5649. */
  5650. static char *encode_then_expand_string(const char *str)
  5651. {
  5652. char *exp_str;
  5653. struct in_str input;
  5654. o_string dest = NULL_O_STRING;
  5655. const char *cp;
  5656. cp = str;
  5657. for (;;) {
  5658. if (!*cp) return NULL; /* string has no special chars */
  5659. if (*cp == '$') break;
  5660. if (*cp == '\\') break;
  5661. #if ENABLE_HUSH_TICK
  5662. if (*cp == '`') break;
  5663. #endif
  5664. cp++;
  5665. }
  5666. /* We need to expand. Example:
  5667. * echo $(($a + `echo 1`)) $((1 + $((2)) ))
  5668. */
  5669. setup_string_in_str(&input, str);
  5670. encode_string(NULL, &dest, &input, EOF);
  5671. //TODO: error check (encode_string returns 0 on error)?
  5672. //bb_error_msg("'%s' -> '%s'", str, dest.data);
  5673. exp_str = expand_string_to_string(dest.data,
  5674. EXP_FLAG_ESC_GLOB_CHARS,
  5675. /*unbackslash:*/ 1
  5676. );
  5677. //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
  5678. o_free(&dest);
  5679. return exp_str;
  5680. }
  5681. static const char *first_special_char_in_vararg(const char *cp)
  5682. {
  5683. for (;;) {
  5684. if (!*cp) return NULL; /* string has no special chars */
  5685. if (*cp == '$') return cp;
  5686. if (*cp == '\\') return cp;
  5687. if (*cp == '\'') return cp;
  5688. if (*cp == '"') return cp;
  5689. #if ENABLE_HUSH_TICK
  5690. if (*cp == '`') return cp;
  5691. #endif
  5692. /* dquoted "${x:+ARG}" should not glob, therefore
  5693. * '*' et al require some non-literal processing: */
  5694. if (*cp == '*') return cp;
  5695. if (*cp == '?') return cp;
  5696. if (*cp == '[') return cp;
  5697. cp++;
  5698. }
  5699. }
  5700. /* Expanding ARG in ${var#ARG}, ${var%ARG}, or ${var/ARG/ARG}.
  5701. * These can contain single- and double-quoted strings,
  5702. * and treated as if the ARG string is initially unquoted. IOW:
  5703. * ${var#ARG} and "${var#ARG}" treat ARG the same (ARG can even be
  5704. * a dquoted string: "${var#"zz"}"), the difference only comes later
  5705. * (word splitting and globbing of the ${var...} result).
  5706. */
  5707. #if !BASH_PATTERN_SUBST
  5708. #define encode_then_expand_vararg(str, handle_squotes, do_unbackslash) \
  5709. encode_then_expand_vararg(str, handle_squotes)
  5710. #endif
  5711. static char *encode_then_expand_vararg(const char *str, int handle_squotes, int do_unbackslash)
  5712. {
  5713. #if !BASH_PATTERN_SUBST && ENABLE_HUSH_CASE
  5714. const int do_unbackslash = 0;
  5715. #endif
  5716. char *exp_str;
  5717. struct in_str input;
  5718. o_string dest = NULL_O_STRING;
  5719. if (!first_special_char_in_vararg(str)) {
  5720. /* string has no special chars */
  5721. return NULL;
  5722. }
  5723. setup_string_in_str(&input, str);
  5724. dest.data = xzalloc(1); /* start as "", not as NULL */
  5725. exp_str = NULL;
  5726. for (;;) {
  5727. int ch;
  5728. ch = i_getch(&input);
  5729. debug_printf_parse("%s: ch=%c (%d) escape=%d\n",
  5730. __func__, ch, ch, !!dest.o_expflags);
  5731. if (!dest.o_expflags) {
  5732. if (ch == EOF)
  5733. break;
  5734. if (handle_squotes && ch == '\'') {
  5735. if (!add_till_single_quote_dquoted(&dest, &input))
  5736. goto ret; /* error */
  5737. continue;
  5738. }
  5739. }
  5740. if (ch == EOF) {
  5741. syntax_error_unterm_ch('"');
  5742. goto ret; /* error */
  5743. }
  5744. if (ch == '"') {
  5745. dest.o_expflags ^= EXP_FLAG_ESC_GLOB_CHARS;
  5746. continue;
  5747. }
  5748. if (ch == '\\') {
  5749. ch = i_getch(&input);
  5750. if (ch == EOF) {
  5751. //example? error message? syntax_error_unterm_ch('"');
  5752. debug_printf_parse("%s: error: \\<eof>\n", __func__);
  5753. goto ret;
  5754. }
  5755. o_addqchr(&dest, ch);
  5756. continue;
  5757. }
  5758. if (ch == '$') {
  5759. if (!parse_dollar(NULL, &dest, &input, /*quote_mask:*/ 0x80)) {
  5760. debug_printf_parse("%s: error: parse_dollar returned 0 (error)\n", __func__);
  5761. goto ret;
  5762. }
  5763. continue;
  5764. }
  5765. #if ENABLE_HUSH_TICK
  5766. if (ch == '`') {
  5767. //unsigned pos = dest->length;
  5768. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  5769. o_addchr(&dest, 0x80 | '`');
  5770. if (!add_till_backquote(&dest, &input,
  5771. /*in_dquote:*/ dest.o_expflags /* nonzero if EXP_FLAG_ESC_GLOB_CHARS set */
  5772. )
  5773. ) {
  5774. goto ret; /* error */
  5775. }
  5776. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  5777. //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
  5778. continue;
  5779. }
  5780. #endif
  5781. o_addQchr(&dest, ch);
  5782. } /* for (;;) */
  5783. debug_printf_parse("encode: '%s' -> '%s'\n", str, dest.data);
  5784. exp_str = expand_string_to_string(dest.data,
  5785. do_unbackslash ? EXP_FLAG_ESC_GLOB_CHARS : 0,
  5786. do_unbackslash
  5787. );
  5788. ret:
  5789. debug_printf_parse("expand: '%s' -> '%s'\n", dest.data, exp_str);
  5790. o_free(&dest);
  5791. return exp_str;
  5792. }
  5793. /* Expanding ARG in ${var+ARG}, ${var-ARG}
  5794. */
  5795. static int encode_then_append_var_plusminus(o_string *output, int n,
  5796. char *str, int dquoted)
  5797. {
  5798. struct in_str input;
  5799. o_string dest = NULL_O_STRING;
  5800. if (!first_special_char_in_vararg(str)
  5801. && '\0' == str[strcspn(str, G.ifs)]
  5802. ) {
  5803. /* string has no special chars
  5804. * && string has no $IFS chars
  5805. */
  5806. if (dquoted) {
  5807. /* Prints 1 (quoted expansion is a "" word, not nothing):
  5808. * set -- "${notexist-}"; echo $#
  5809. */
  5810. output->has_quoted_part = 1;
  5811. }
  5812. return expand_vars_to_list(output, n, str);
  5813. }
  5814. setup_string_in_str(&input, str);
  5815. for (;;) {
  5816. int ch;
  5817. ch = i_getch(&input);
  5818. debug_printf_parse("%s: ch=%c (%d) escape=%x\n",
  5819. __func__, ch, ch, dest.o_expflags);
  5820. if (!dest.o_expflags) {
  5821. if (ch == EOF)
  5822. break;
  5823. if (!dquoted && strchr(G.ifs, ch)) {
  5824. /* PREFIX${x:d${e}f ...} and we met space: expand "d${e}f" and start new word.
  5825. * do not assume we are at the start of the word (PREFIX above).
  5826. */
  5827. if (dest.data) {
  5828. n = expand_vars_to_list(output, n, dest.data);
  5829. o_free_and_set_NULL(&dest);
  5830. o_addchr(output, '\0');
  5831. n = o_save_ptr(output, n); /* create next word */
  5832. } else
  5833. if (output->length != o_get_last_ptr(output, n)
  5834. || output->has_quoted_part
  5835. ) {
  5836. /* For these cases:
  5837. * f() { for i; do echo "|$i|"; done; }; x=x
  5838. * f a${x:+ }b # 1st condition
  5839. * |a|
  5840. * |b|
  5841. * f ""${x:+ }b # 2nd condition
  5842. * ||
  5843. * |b|
  5844. */
  5845. o_addchr(output, '\0');
  5846. n = o_save_ptr(output, n); /* create next word */
  5847. }
  5848. continue;
  5849. }
  5850. if (!dquoted && ch == '\'') {
  5851. if (!add_till_single_quote_dquoted(&dest, &input))
  5852. goto ret; /* error */
  5853. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  5854. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  5855. continue;
  5856. }
  5857. }
  5858. if (ch == EOF) {
  5859. syntax_error_unterm_ch('"');
  5860. goto ret; /* error */
  5861. }
  5862. if (ch == '"') {
  5863. dest.o_expflags ^= EXP_FLAG_ESC_GLOB_CHARS;
  5864. if (dest.o_expflags) {
  5865. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  5866. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  5867. }
  5868. continue;
  5869. }
  5870. if (ch == '\\') {
  5871. ch = i_getch(&input);
  5872. if (ch == EOF) {
  5873. //example? error message? syntax_error_unterm_ch('"');
  5874. debug_printf_parse("%s: error: \\<eof>\n", __func__);
  5875. goto ret;
  5876. }
  5877. o_addqchr(&dest, ch);
  5878. continue;
  5879. }
  5880. if (ch == '$') {
  5881. if (!parse_dollar(NULL, &dest, &input, /*quote_mask:*/ (dest.o_expflags || dquoted) ? 0x80 : 0)) {
  5882. debug_printf_parse("%s: error: parse_dollar returned 0 (error)\n", __func__);
  5883. goto ret;
  5884. }
  5885. continue;
  5886. }
  5887. #if ENABLE_HUSH_TICK
  5888. if (ch == '`') {
  5889. //unsigned pos = dest->length;
  5890. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  5891. o_addchr(&dest, (dest.o_expflags || dquoted) ? 0x80 | '`' : '`');
  5892. if (!add_till_backquote(&dest, &input,
  5893. /*in_dquote:*/ dest.o_expflags /* nonzero if EXP_FLAG_ESC_GLOB_CHARS set */
  5894. )
  5895. ) {
  5896. goto ret; /* error */
  5897. }
  5898. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  5899. //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
  5900. continue;
  5901. }
  5902. #endif
  5903. if (dquoted) {
  5904. /* Always glob-protect if in dquotes:
  5905. * x=x; echo "${x:+/bin/c*}" - prints: /bin/c*
  5906. * x=x; echo "${x:+"/bin/c*"}" - prints: /bin/c*
  5907. */
  5908. o_addqchr(&dest, ch);
  5909. } else {
  5910. /* Glob-protect only if char is quoted:
  5911. * x=x; echo ${x:+/bin/c*} - prints many filenames
  5912. * x=x; echo ${x:+"/bin/c*"} - prints: /bin/c*
  5913. */
  5914. o_addQchr(&dest, ch);
  5915. }
  5916. } /* for (;;) */
  5917. if (dest.data) {
  5918. n = expand_vars_to_list(output, n, dest.data);
  5919. }
  5920. ret:
  5921. o_free(&dest);
  5922. return n;
  5923. }
  5924. #if ENABLE_FEATURE_SH_MATH
  5925. static arith_t expand_and_evaluate_arith(const char *arg, const char **errmsg_p)
  5926. {
  5927. arith_state_t math_state;
  5928. arith_t res;
  5929. char *exp_str;
  5930. math_state.lookupvar = get_local_var_value;
  5931. math_state.setvar = set_local_var_from_halves;
  5932. //math_state.endofname = endofname;
  5933. exp_str = encode_then_expand_string(arg);
  5934. res = arith(&math_state, exp_str ? exp_str : arg);
  5935. free(exp_str);
  5936. if (errmsg_p)
  5937. *errmsg_p = math_state.errmsg;
  5938. if (math_state.errmsg)
  5939. msg_and_die_if_script(math_state.errmsg);
  5940. return res;
  5941. }
  5942. #endif
  5943. #if BASH_PATTERN_SUBST
  5944. /* ${var/[/]pattern[/repl]} helpers */
  5945. static char *strstr_pattern(char *val, const char *pattern, int *size)
  5946. {
  5947. while (1) {
  5948. char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
  5949. debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
  5950. if (end) {
  5951. *size = end - val;
  5952. return val;
  5953. }
  5954. if (*val == '\0')
  5955. return NULL;
  5956. /* Optimization: if "*pat" did not match the start of "string",
  5957. * we know that "tring", "ring" etc will not match too:
  5958. */
  5959. if (pattern[0] == '*')
  5960. return NULL;
  5961. val++;
  5962. }
  5963. }
  5964. static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
  5965. {
  5966. char *result = NULL;
  5967. unsigned res_len = 0;
  5968. unsigned repl_len = strlen(repl);
  5969. /* Null pattern never matches, including if "var" is empty */
  5970. if (!pattern[0])
  5971. return result; /* NULL, no replaces happened */
  5972. while (1) {
  5973. int size;
  5974. char *s = strstr_pattern(val, pattern, &size);
  5975. if (!s)
  5976. break;
  5977. result = xrealloc(result, res_len + (s - val) + repl_len + 1);
  5978. strcpy(mempcpy(result + res_len, val, s - val), repl);
  5979. res_len += (s - val) + repl_len;
  5980. debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
  5981. val = s + size;
  5982. if (exp_op == '/')
  5983. break;
  5984. }
  5985. if (*val && result) {
  5986. result = xrealloc(result, res_len + strlen(val) + 1);
  5987. strcpy(result + res_len, val);
  5988. debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
  5989. }
  5990. debug_printf_varexp("result:'%s'\n", result);
  5991. return result;
  5992. }
  5993. #endif /* BASH_PATTERN_SUBST */
  5994. static int append_str_maybe_ifs_split(o_string *output, int n,
  5995. int first_ch, const char *val)
  5996. {
  5997. if (!(first_ch & 0x80)) { /* unquoted $VAR */
  5998. debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val,
  5999. !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
  6000. if (val && val[0])
  6001. n = expand_on_ifs(output, n, val);
  6002. } else { /* quoted "$VAR" */
  6003. output->has_quoted_part = 1;
  6004. debug_printf_expand("quoted '%s', output->o_escape:%d\n", val,
  6005. !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
  6006. if (val && val[0])
  6007. o_addQstr(output, val);
  6008. }
  6009. return n;
  6010. }
  6011. /* Handle <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
  6012. */
  6013. static NOINLINE int expand_one_var(o_string *output, int n,
  6014. int first_ch, char *arg, char **pp)
  6015. {
  6016. const char *val;
  6017. char *to_be_freed;
  6018. char *p;
  6019. char *var;
  6020. char exp_op;
  6021. char exp_save = exp_save; /* for compiler */
  6022. char *exp_saveptr; /* points to expansion operator */
  6023. char *exp_word = exp_word; /* for compiler */
  6024. char arg0;
  6025. val = NULL;
  6026. to_be_freed = NULL;
  6027. p = *pp;
  6028. *p = '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
  6029. var = arg;
  6030. exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
  6031. arg0 = arg[0];
  6032. arg[0] = (arg0 & 0x7f);
  6033. exp_op = 0;
  6034. if (arg[0] == '#' && arg[1] /* ${#...} but not ${#} */
  6035. && (!exp_saveptr /* and ( not(${#<op_char>...}) */
  6036. || (arg[2] == '\0' && strchr(SPECIAL_VARS_STR, arg[1])) /* or ${#C} "len of $C" ) */
  6037. ) /* NB: skipping ^^^specvar check mishandles ${#::2} */
  6038. ) {
  6039. /* It must be length operator: ${#var} */
  6040. var++;
  6041. exp_op = 'L';
  6042. } else {
  6043. /* Maybe handle parameter expansion */
  6044. if (exp_saveptr /* if 2nd char is one of expansion operators */
  6045. && strchr(NUMERIC_SPECVARS_STR, arg[0]) /* 1st char is special variable */
  6046. ) {
  6047. /* ${?:0}, ${#[:]%0} etc */
  6048. exp_saveptr = var + 1;
  6049. } else {
  6050. /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
  6051. exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
  6052. }
  6053. exp_op = exp_save = *exp_saveptr;
  6054. if (exp_op) {
  6055. exp_word = exp_saveptr + 1;
  6056. if (exp_op == ':') {
  6057. exp_op = *exp_word++;
  6058. //TODO: try ${var:} and ${var:bogus} in non-bash config
  6059. if (BASH_SUBSTR
  6060. && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
  6061. ) {
  6062. /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
  6063. exp_op = ':';
  6064. exp_word--;
  6065. }
  6066. }
  6067. *exp_saveptr = '\0';
  6068. } /* else: it's not an expansion op, but bare ${var} */
  6069. }
  6070. /* Look up the variable in question */
  6071. if (isdigit(var[0])) {
  6072. /* parse_dollar should have vetted var for us */
  6073. int nn = xatoi_positive(var);
  6074. if (nn < G.global_argc)
  6075. val = G.global_argv[nn];
  6076. /* else val remains NULL: $N with too big N */
  6077. } else {
  6078. switch (var[0]) {
  6079. case '$': /* pid */
  6080. val = utoa(G.root_pid);
  6081. break;
  6082. case '!': /* bg pid */
  6083. val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
  6084. break;
  6085. case '?': /* exitcode */
  6086. val = utoa(G.last_exitcode);
  6087. break;
  6088. case '#': /* argc */
  6089. val = utoa(G.global_argc ? G.global_argc-1 : 0);
  6090. break;
  6091. case '-': { /* active options */
  6092. /* Check set_mode() to see what option chars we support */
  6093. char *cp;
  6094. val = cp = G.optstring_buf;
  6095. if (G.o_opt[OPT_O_ERREXIT])
  6096. *cp++ = 'e';
  6097. if (G_interactive_fd)
  6098. *cp++ = 'i';
  6099. if (G_x_mode)
  6100. *cp++ = 'x';
  6101. /* If G.o_opt[OPT_O_NOEXEC] is true,
  6102. * commands read but are not executed,
  6103. * so $- can not execute too, 'n' is never seen in $-.
  6104. */
  6105. if (G.opt_c)
  6106. *cp++ = 'c';
  6107. if (G.opt_s)
  6108. *cp++ = 's';
  6109. *cp = '\0';
  6110. break;
  6111. }
  6112. default:
  6113. val = get_local_var_value(var);
  6114. }
  6115. }
  6116. /* Handle any expansions */
  6117. if (exp_op == 'L') {
  6118. reinit_unicode_for_hush();
  6119. debug_printf_expand("expand: length(%s)=", val);
  6120. val = utoa(val ? unicode_strlen(val) : 0);
  6121. debug_printf_expand("%s\n", val);
  6122. } else if (exp_op) {
  6123. if (exp_op == '%' || exp_op == '#') {
  6124. /* Standard-mandated substring removal ops:
  6125. * ${parameter%word} - remove smallest suffix pattern
  6126. * ${parameter%%word} - remove largest suffix pattern
  6127. * ${parameter#word} - remove smallest prefix pattern
  6128. * ${parameter##word} - remove largest prefix pattern
  6129. *
  6130. * Word is expanded to produce a glob pattern.
  6131. * Then var's value is matched to it and matching part removed.
  6132. */
  6133. /* bash compat: if x is "" and no shrinking of it is possible,
  6134. * inner ${...} is not evaluated. Example:
  6135. * unset b; : ${a%${b=B}}; echo $b
  6136. * assignment b=B only happens if $a is not "".
  6137. */
  6138. if (val && val[0]) {
  6139. char *t;
  6140. char *exp_exp_word;
  6141. char *loc;
  6142. unsigned scan_flags = pick_scan(exp_op, *exp_word);
  6143. if (exp_op == *exp_word) /* ## or %% */
  6144. exp_word++;
  6145. debug_printf_expand("expand: exp_word:'%s'\n", exp_word);
  6146. exp_exp_word = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 0);
  6147. if (exp_exp_word)
  6148. exp_word = exp_exp_word;
  6149. debug_printf_expand("expand: exp_word:'%s'\n", exp_word);
  6150. /*
  6151. * HACK ALERT. We depend here on the fact that
  6152. * G.global_argv and results of utoa and get_local_var_value
  6153. * are actually in writable memory:
  6154. * scan_and_match momentarily stores NULs there.
  6155. */
  6156. t = (char*)val;
  6157. loc = scan_and_match(t, exp_word, scan_flags);
  6158. debug_printf_expand("op:%c str:'%s' pat:'%s' res:'%s'\n", exp_op, t, exp_word, loc);
  6159. free(exp_exp_word);
  6160. if (loc) { /* match was found */
  6161. if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
  6162. val = loc; /* take right part */
  6163. else /* %[%] */
  6164. val = to_be_freed = xstrndup(val, loc - val); /* left */
  6165. }
  6166. }
  6167. }
  6168. #if BASH_PATTERN_SUBST
  6169. else if (exp_op == '/' || exp_op == '\\') {
  6170. /* It's ${var/[/]pattern[/repl]} thing.
  6171. * Note that in encoded form it has TWO parts:
  6172. * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
  6173. * and if // is used, it is encoded as \:
  6174. * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
  6175. */
  6176. /* bash compat: if var is "", both pattern and repl
  6177. * are still evaluated, if it is unset, then not:
  6178. * unset b; a=; : ${a/z/${b=3}}; echo $b # b=3
  6179. * unset b; unset a; : ${a/z/${b=3}}; echo $b # b not set
  6180. */
  6181. if (val /*&& val[0]*/) {
  6182. /* pattern uses non-standard expansion.
  6183. * repl should be unbackslashed and globbed
  6184. * by the usual expansion rules:
  6185. * >az >bz
  6186. * v='a bz'; echo "${v/a*z/a*z}" #prints "a*z"
  6187. * v='a bz'; echo "${v/a*z/\z}" #prints "z"
  6188. * v='a bz'; echo ${v/a*z/a*z} #prints "az"
  6189. * v='a bz'; echo ${v/a*z/\z} #prints "z"
  6190. * (note that a*z _pattern_ is never globbed!)
  6191. */
  6192. char *pattern, *repl, *t;
  6193. pattern = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 0);
  6194. if (!pattern)
  6195. pattern = xstrdup(exp_word);
  6196. debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
  6197. *p++ = SPECIAL_VAR_SYMBOL;
  6198. exp_word = p;
  6199. p = strchr(p, SPECIAL_VAR_SYMBOL);
  6200. *p = '\0';
  6201. repl = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 1);
  6202. debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
  6203. /* HACK ALERT. We depend here on the fact that
  6204. * G.global_argv and results of utoa and get_local_var_value
  6205. * are actually in writable memory:
  6206. * replace_pattern momentarily stores NULs there. */
  6207. t = (char*)val;
  6208. to_be_freed = replace_pattern(t,
  6209. pattern,
  6210. (repl ? repl : exp_word),
  6211. exp_op);
  6212. if (to_be_freed) /* at least one replace happened */
  6213. val = to_be_freed;
  6214. free(pattern);
  6215. free(repl);
  6216. } else {
  6217. /* Unset variable always gives nothing */
  6218. // a=; echo ${a/*/w} # "w"
  6219. // unset a; echo ${a/*/w} # ""
  6220. /* Just skip "replace" part */
  6221. *p++ = SPECIAL_VAR_SYMBOL;
  6222. p = strchr(p, SPECIAL_VAR_SYMBOL);
  6223. *p = '\0';
  6224. }
  6225. }
  6226. #endif /* BASH_PATTERN_SUBST */
  6227. else if (exp_op == ':') {
  6228. #if BASH_SUBSTR && ENABLE_FEATURE_SH_MATH
  6229. /* It's ${var:N[:M]} bashism.
  6230. * Note that in encoded form it has TWO parts:
  6231. * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
  6232. */
  6233. arith_t beg, len;
  6234. unsigned vallen;
  6235. const char *errmsg;
  6236. beg = expand_and_evaluate_arith(exp_word, &errmsg);
  6237. if (errmsg)
  6238. goto empty_result;
  6239. debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
  6240. *p++ = SPECIAL_VAR_SYMBOL;
  6241. exp_word = p;
  6242. p = strchr(p, SPECIAL_VAR_SYMBOL);
  6243. *p = '\0';
  6244. vallen = val ? strlen(val) : 0;
  6245. if (beg < 0) {
  6246. /* negative beg counts from the end */
  6247. beg = (arith_t)vallen + beg;
  6248. }
  6249. /* If expansion will be empty, do not even evaluate len */
  6250. if (!val || beg < 0 || beg > vallen) {
  6251. /* Why > vallen, not >=? bash:
  6252. * unset b; a=ab; : ${a:2:${b=3}}; echo $b # "", b=3 (!!!)
  6253. * unset b; a=a; : ${a:2:${b=3}}; echo $b # "", b not set
  6254. */
  6255. goto empty_result;
  6256. }
  6257. len = expand_and_evaluate_arith(exp_word, &errmsg);
  6258. if (errmsg)
  6259. goto empty_result;
  6260. debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
  6261. debug_printf_varexp("from val:'%s'\n", val);
  6262. if (len < 0) {
  6263. /* in bash, len=-n means strlen()-n */
  6264. len = (arith_t)vallen - beg + len;
  6265. if (len < 0) /* bash compat */
  6266. msg_and_die_if_script("%s: substring expression < 0", var);
  6267. }
  6268. if (len <= 0 || !val /*|| beg >= vallen*/) {
  6269. empty_result:
  6270. val = NULL;
  6271. } else {
  6272. /* Paranoia. What if user entered 9999999999999
  6273. * which fits in arith_t but not int? */
  6274. if (len > INT_MAX)
  6275. len = INT_MAX;
  6276. val = to_be_freed = xstrndup(val + beg, len);
  6277. }
  6278. debug_printf_varexp("val:'%s'\n", val);
  6279. #else /* not (HUSH_SUBSTR_EXPANSION && FEATURE_SH_MATH) */
  6280. msg_and_die_if_script("malformed ${%s:...}", var);
  6281. val = NULL;
  6282. #endif
  6283. } else { /* one of "-=+?" */
  6284. /* Standard-mandated substitution ops:
  6285. * ${var?word} - indicate error if unset
  6286. * If var is unset, word (or a message indicating it is unset
  6287. * if word is null) is written to standard error
  6288. * and the shell exits with a non-zero exit status.
  6289. * Otherwise, the value of var is substituted.
  6290. * ${var-word} - use default value
  6291. * If var is unset, word is substituted.
  6292. * ${var=word} - assign and use default value
  6293. * If var is unset, word is assigned to var.
  6294. * In all cases, final value of var is substituted.
  6295. * ${var+word} - use alternative value
  6296. * If var is unset, null is substituted.
  6297. * Otherwise, word is substituted.
  6298. *
  6299. * Word is subjected to tilde expansion, parameter expansion,
  6300. * command substitution, and arithmetic expansion.
  6301. * If word is not needed, it is not expanded.
  6302. *
  6303. * Colon forms (${var:-word}, ${var:=word} etc) do the same,
  6304. * but also treat null var as if it is unset.
  6305. *
  6306. * Word-splitting and single quote behavior:
  6307. *
  6308. * $ f() { for i; do echo "|$i|"; done; }
  6309. *
  6310. * $ x=; f ${x:?'x y' z}; echo $?
  6311. * bash: x: x y z # neither f nor "echo $?" executes
  6312. * (if interactive, bash does not exit, but merely aborts to prompt. $? is set to 1)
  6313. * $ x=; f "${x:?'x y' z}"
  6314. * bash: x: x y z # dash prints: dash: x: 'x y' z
  6315. *
  6316. * $ x=; f ${x:='x y' z}
  6317. * |x|
  6318. * |y|
  6319. * |z|
  6320. * $ x=; f "${x:='x y' z}"
  6321. * |'x y' z|
  6322. *
  6323. * $ x=x; f ${x:+'x y' z}
  6324. * |x y|
  6325. * |z|
  6326. * $ x=x; f "${x:+'x y' z}"
  6327. * |'x y' z|
  6328. *
  6329. * $ x=; f ${x:-'x y' z}
  6330. * |x y|
  6331. * |z|
  6332. * $ x=; f "${x:-'x y' z}"
  6333. * |'x y' z|
  6334. */
  6335. int use_word = (!val || ((exp_save == ':') && !val[0]));
  6336. if (exp_op == '+')
  6337. use_word = !use_word;
  6338. debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
  6339. (exp_save == ':') ? "true" : "false", use_word);
  6340. if (use_word) {
  6341. if (exp_op == '+' || exp_op == '-') {
  6342. /* ${var+word} - use alternative value */
  6343. /* ${var-word} - use default value */
  6344. n = encode_then_append_var_plusminus(output, n, exp_word,
  6345. /*dquoted:*/ (arg0 & 0x80)
  6346. );
  6347. val = NULL;
  6348. } else {
  6349. /* ${var?word} - indicate error if unset */
  6350. /* ${var=word} - assign and use default value */
  6351. to_be_freed = encode_then_expand_vararg(exp_word,
  6352. /*handle_squotes:*/ !(arg0 & 0x80),
  6353. /*unbackslash:*/ 0
  6354. );
  6355. if (to_be_freed)
  6356. exp_word = to_be_freed;
  6357. if (exp_op == '?') {
  6358. /* mimic bash message */
  6359. msg_and_die_if_script("%s: %s",
  6360. var,
  6361. exp_word[0]
  6362. ? exp_word
  6363. : "parameter null or not set"
  6364. /* ash has more specific messages, a-la: */
  6365. /*: (exp_save == ':' ? "parameter null or not set" : "parameter not set")*/
  6366. );
  6367. //TODO: how interactive bash aborts expansion mid-command?
  6368. //It aborts the entire line, returns to prompt:
  6369. // $ f() { for i; do echo "|$i|"; done; }; x=; f "${x:?'x y' z}"; echo YO
  6370. // bash: x: x y z
  6371. // $
  6372. // ("echo YO" is not executed, neither the f function call)
  6373. } else {
  6374. val = exp_word;
  6375. }
  6376. if (exp_op == '=') {
  6377. /* ${var=[word]} or ${var:=[word]} */
  6378. if (isdigit(var[0]) || var[0] == '#') {
  6379. /* mimic bash message */
  6380. msg_and_die_if_script("$%s: cannot assign in this way", var);
  6381. val = NULL;
  6382. } else {
  6383. char *new_var = xasprintf("%s=%s", var, val);
  6384. set_local_var(new_var, /*flag:*/ 0);
  6385. }
  6386. }
  6387. }
  6388. }
  6389. } /* one of "-=+?" */
  6390. *exp_saveptr = exp_save;
  6391. } /* if (exp_op) */
  6392. arg[0] = arg0;
  6393. *pp = p;
  6394. n = append_str_maybe_ifs_split(output, n, first_ch, val);
  6395. free(to_be_freed);
  6396. return n;
  6397. }
  6398. /* Expand all variable references in given string, adding words to list[]
  6399. * at n, n+1,... positions. Return updated n (so that list[n] is next one
  6400. * to be filled). This routine is extremely tricky: has to deal with
  6401. * variables/parameters with whitespace, $* and $@, and constructs like
  6402. * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
  6403. static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
  6404. {
  6405. /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
  6406. * expansion of right-hand side of assignment == 1-element expand.
  6407. */
  6408. char cant_be_null = 0; /* only bit 0x80 matters */
  6409. char *p;
  6410. debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
  6411. !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
  6412. debug_print_list("expand_vars_to_list[0]", output, n);
  6413. while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
  6414. char first_ch;
  6415. #if ENABLE_FEATURE_SH_MATH
  6416. char arith_buf[sizeof(arith_t)*3 + 2];
  6417. #endif
  6418. if (output->ended_in_ifs) {
  6419. o_addchr(output, '\0');
  6420. n = o_save_ptr(output, n);
  6421. output->ended_in_ifs = 0;
  6422. }
  6423. o_addblock(output, arg, p - arg);
  6424. debug_print_list("expand_vars_to_list[1]", output, n);
  6425. arg = ++p;
  6426. p = strchr(p, SPECIAL_VAR_SYMBOL);
  6427. /* Fetch special var name (if it is indeed one of them)
  6428. * and quote bit, force the bit on if singleword expansion -
  6429. * important for not getting v=$@ expand to many words. */
  6430. first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
  6431. /* Is this variable quoted and thus expansion can't be null?
  6432. * "$@" is special. Even if quoted, it can still
  6433. * expand to nothing (not even an empty string),
  6434. * thus it is excluded. */
  6435. if ((first_ch & 0x7f) != '@')
  6436. cant_be_null |= first_ch;
  6437. switch (first_ch & 0x7f) {
  6438. /* Highest bit in first_ch indicates that var is double-quoted */
  6439. case '*':
  6440. case '@': {
  6441. int i;
  6442. if (!G.global_argv[1])
  6443. break;
  6444. i = 1;
  6445. cant_be_null |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
  6446. if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
  6447. while (G.global_argv[i]) {
  6448. n = expand_on_ifs(output, n, G.global_argv[i]);
  6449. debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
  6450. if (G.global_argv[i++][0] && G.global_argv[i]) {
  6451. /* this argv[] is not empty and not last:
  6452. * put terminating NUL, start new word */
  6453. o_addchr(output, '\0');
  6454. debug_print_list("expand_vars_to_list[2]", output, n);
  6455. n = o_save_ptr(output, n);
  6456. debug_print_list("expand_vars_to_list[3]", output, n);
  6457. }
  6458. }
  6459. } else
  6460. /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
  6461. * and in this case should treat it like '$*' - see 'else...' below */
  6462. if (first_ch == (char)('@'|0x80) /* quoted $@ */
  6463. && !(output->o_expflags & EXP_FLAG_SINGLEWORD) /* not v="$@" case */
  6464. ) {
  6465. while (1) {
  6466. o_addQstr(output, G.global_argv[i]);
  6467. if (++i >= G.global_argc)
  6468. break;
  6469. o_addchr(output, '\0');
  6470. debug_print_list("expand_vars_to_list[4]", output, n);
  6471. n = o_save_ptr(output, n);
  6472. }
  6473. } else { /* quoted $* (or v="$@" case): add as one word */
  6474. while (1) {
  6475. o_addQstr(output, G.global_argv[i]);
  6476. if (!G.global_argv[++i])
  6477. break;
  6478. if (G.ifs[0])
  6479. o_addchr(output, G.ifs[0]);
  6480. }
  6481. output->has_quoted_part = 1;
  6482. }
  6483. break;
  6484. }
  6485. case SPECIAL_VAR_SYMBOL: {
  6486. /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
  6487. /* "Empty variable", used to make "" etc to not disappear */
  6488. output->has_quoted_part = 1;
  6489. cant_be_null = 0x80;
  6490. arg++;
  6491. break;
  6492. }
  6493. case SPECIAL_VAR_QUOTED_SVS:
  6494. /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_QUOTED_SVS><SPECIAL_VAR_SYMBOL> */
  6495. /* "^C variable", represents literal ^C char (possible in scripts) */
  6496. o_addchr(output, SPECIAL_VAR_SYMBOL);
  6497. arg++;
  6498. break;
  6499. #if ENABLE_HUSH_TICK
  6500. case '`': {
  6501. /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
  6502. o_string subst_result = NULL_O_STRING;
  6503. *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
  6504. arg++;
  6505. /* Can't just stuff it into output o_string,
  6506. * expanded result may need to be globbed
  6507. * and $IFS-split */
  6508. debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
  6509. G.last_exitcode = process_command_subs(&subst_result, arg);
  6510. G.expand_exitcode = G.last_exitcode;
  6511. debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
  6512. n = append_str_maybe_ifs_split(output, n, first_ch, subst_result.data);
  6513. o_free(&subst_result);
  6514. break;
  6515. }
  6516. #endif
  6517. #if ENABLE_FEATURE_SH_MATH
  6518. case '+': {
  6519. /* <SPECIAL_VAR_SYMBOL>+arith<SPECIAL_VAR_SYMBOL> */
  6520. arith_t res;
  6521. arg++; /* skip '+' */
  6522. *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
  6523. debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
  6524. res = expand_and_evaluate_arith(arg, NULL);
  6525. debug_printf_subst("ARITH RES '"ARITH_FMT"'\n", res);
  6526. sprintf(arith_buf, ARITH_FMT, res);
  6527. if (res < 0
  6528. && first_ch == (char)('+'|0x80)
  6529. /* && (output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS) */
  6530. ) {
  6531. /* Quoted negative ariths, like filename[0"$((-9))"],
  6532. * should not be interpreted as glob ranges.
  6533. * Convert leading '-' to '\-':
  6534. */
  6535. o_grow_by(output, 1);
  6536. output->data[output->length++] = '\\';
  6537. }
  6538. o_addstr(output, arith_buf);
  6539. break;
  6540. }
  6541. #endif
  6542. default:
  6543. /* <SPECIAL_VAR_SYMBOL>varname[ops]<SPECIAL_VAR_SYMBOL> */
  6544. n = expand_one_var(output, n, first_ch, arg, &p);
  6545. break;
  6546. } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
  6547. /* Restore NULL'ed SPECIAL_VAR_SYMBOL.
  6548. * Do the check to avoid writing to a const string. */
  6549. if (*p != SPECIAL_VAR_SYMBOL)
  6550. *p = SPECIAL_VAR_SYMBOL;
  6551. arg = ++p;
  6552. } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
  6553. if (*arg) {
  6554. /* handle trailing string */
  6555. if (output->ended_in_ifs) {
  6556. o_addchr(output, '\0');
  6557. n = o_save_ptr(output, n);
  6558. }
  6559. debug_print_list("expand_vars_to_list[a]", output, n);
  6560. /* this part is literal, and it was already pre-quoted
  6561. * if needed (much earlier), do not use o_addQstr here!
  6562. */
  6563. o_addstr(output, arg);
  6564. debug_print_list("expand_vars_to_list[b]", output, n);
  6565. } else
  6566. if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
  6567. && !(cant_be_null & 0x80) /* and all vars were not quoted */
  6568. && !output->has_quoted_part
  6569. ) {
  6570. n--;
  6571. /* allow to reuse list[n] later without re-growth */
  6572. output->has_empty_slot = 1;
  6573. }
  6574. return n;
  6575. }
  6576. static char **expand_variables(char **argv, unsigned expflags)
  6577. {
  6578. int n;
  6579. char **list;
  6580. o_string output = NULL_O_STRING;
  6581. output.o_expflags = expflags;
  6582. n = 0;
  6583. for (;;) {
  6584. /* go to next list[n] */
  6585. output.ended_in_ifs = 0;
  6586. n = o_save_ptr(&output, n);
  6587. if (!*argv)
  6588. break;
  6589. /* expand argv[i] */
  6590. n = expand_vars_to_list(&output, n, *argv++);
  6591. /* if (!output->has_empty_slot) -- need this?? */
  6592. o_addchr(&output, '\0');
  6593. }
  6594. debug_print_list("expand_variables", &output, n);
  6595. /* output.data (malloced in one block) gets returned in "list" */
  6596. list = o_finalize_list(&output, n);
  6597. debug_print_strings("expand_variables[1]", list);
  6598. return list;
  6599. }
  6600. static char **expand_strvec_to_strvec(char **argv)
  6601. {
  6602. return expand_variables(argv, EXP_FLAG_GLOB | EXP_FLAG_ESC_GLOB_CHARS);
  6603. }
  6604. #if defined(CMD_SINGLEWORD_NOGLOB) || defined(CMD_TEST2_SINGLEWORD_NOGLOB)
  6605. static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
  6606. {
  6607. return expand_variables(argv, EXP_FLAG_SINGLEWORD);
  6608. }
  6609. #endif
  6610. /* Used for expansion of right hand of assignments,
  6611. * $((...)), heredocs, variable expansion parts.
  6612. *
  6613. * NB: should NOT do globbing!
  6614. * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*"
  6615. */
  6616. static char *expand_string_to_string(const char *str, int EXP_flags, int do_unbackslash)
  6617. {
  6618. #if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
  6619. const int do_unbackslash = 1;
  6620. const int EXP_flags = EXP_FLAG_ESC_GLOB_CHARS;
  6621. #endif
  6622. char *argv[2], **list;
  6623. debug_printf_expand("string_to_string<='%s'\n", str);
  6624. /* This is generally an optimization, but it also
  6625. * handles "", which otherwise trips over !list[0] check below.
  6626. * (is this ever happens that we actually get str="" here?)
  6627. */
  6628. if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
  6629. //TODO: Can use on strings with \ too, just unbackslash() them?
  6630. debug_printf_expand("string_to_string(fast)=>'%s'\n", str);
  6631. return xstrdup(str);
  6632. }
  6633. argv[0] = (char*)str;
  6634. argv[1] = NULL;
  6635. list = expand_variables(argv, EXP_flags | EXP_FLAG_SINGLEWORD);
  6636. if (!list[0]) {
  6637. /* Example where it happens:
  6638. * x=; echo ${x:-"$@"}
  6639. */
  6640. ((char*)list)[0] = '\0';
  6641. } else {
  6642. if (HUSH_DEBUG)
  6643. if (list[1])
  6644. bb_simple_error_msg_and_die("BUG in varexp2");
  6645. /* actually, just move string 2*sizeof(char*) bytes back */
  6646. overlapping_strcpy((char*)list, list[0]);
  6647. if (do_unbackslash)
  6648. unbackslash((char*)list);
  6649. }
  6650. debug_printf_expand("string_to_string=>'%s'\n", (char*)list);
  6651. return (char*)list;
  6652. }
  6653. #if 0
  6654. static char* expand_strvec_to_string(char **argv)
  6655. {
  6656. char **list;
  6657. list = expand_variables(argv, EXP_FLAG_SINGLEWORD);
  6658. /* Convert all NULs to spaces */
  6659. if (list[0]) {
  6660. int n = 1;
  6661. while (list[n]) {
  6662. if (HUSH_DEBUG)
  6663. if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
  6664. bb_error_msg_and_die("BUG in varexp3");
  6665. /* bash uses ' ' regardless of $IFS contents */
  6666. list[n][-1] = ' ';
  6667. n++;
  6668. }
  6669. }
  6670. overlapping_strcpy((char*)list, list[0] ? list[0] : "");
  6671. debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
  6672. return (char*)list;
  6673. }
  6674. #endif
  6675. static char **expand_assignments(char **argv, int count)
  6676. {
  6677. int i;
  6678. char **p;
  6679. G.expanded_assignments = p = NULL;
  6680. /* Expand assignments into one string each */
  6681. for (i = 0; i < count; i++) {
  6682. p = add_string_to_strings(p,
  6683. expand_string_to_string(argv[i],
  6684. EXP_FLAG_ESC_GLOB_CHARS,
  6685. /*unbackslash:*/ 1
  6686. )
  6687. );
  6688. G.expanded_assignments = p;
  6689. }
  6690. G.expanded_assignments = NULL;
  6691. return p;
  6692. }
  6693. static void switch_off_special_sigs(unsigned mask)
  6694. {
  6695. unsigned sig = 0;
  6696. while ((mask >>= 1) != 0) {
  6697. sig++;
  6698. if (!(mask & 1))
  6699. continue;
  6700. #if ENABLE_HUSH_TRAP
  6701. if (G_traps) {
  6702. if (G_traps[sig] && !G_traps[sig][0])
  6703. /* trap is '', has to remain SIG_IGN */
  6704. continue;
  6705. free(G_traps[sig]);
  6706. G_traps[sig] = NULL;
  6707. }
  6708. #endif
  6709. /* We are here only if no trap or trap was not '' */
  6710. install_sighandler(sig, SIG_DFL);
  6711. }
  6712. }
  6713. #if BB_MMU
  6714. /* never called */
  6715. void re_execute_shell(char ***to_free, const char *s,
  6716. char *g_argv0, char **g_argv,
  6717. char **builtin_argv) NORETURN;
  6718. static void reset_traps_to_defaults(void)
  6719. {
  6720. /* This function is always called in a child shell
  6721. * after fork (not vfork, NOMMU doesn't use this function).
  6722. */
  6723. IF_HUSH_TRAP(unsigned sig;)
  6724. unsigned mask;
  6725. /* Child shells are not interactive.
  6726. * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
  6727. * Testcase: (while :; do :; done) + ^Z should background.
  6728. * Same goes for SIGTERM, SIGHUP, SIGINT.
  6729. */
  6730. mask = (G.special_sig_mask & SPECIAL_INTERACTIVE_SIGS) | G_fatal_sig_mask;
  6731. if (!G_traps && !mask)
  6732. return; /* already no traps and no special sigs */
  6733. /* Switch off special sigs */
  6734. switch_off_special_sigs(mask);
  6735. # if ENABLE_HUSH_JOB
  6736. G_fatal_sig_mask = 0;
  6737. # endif
  6738. G.special_sig_mask &= ~SPECIAL_INTERACTIVE_SIGS;
  6739. /* SIGQUIT,SIGCHLD and maybe SPECIAL_JOBSTOP_SIGS
  6740. * remain set in G.special_sig_mask */
  6741. # if ENABLE_HUSH_TRAP
  6742. if (!G_traps)
  6743. return;
  6744. /* Reset all sigs to default except ones with empty traps */
  6745. for (sig = 0; sig < NSIG; sig++) {
  6746. if (!G_traps[sig])
  6747. continue; /* no trap: nothing to do */
  6748. if (!G_traps[sig][0])
  6749. continue; /* empty trap: has to remain SIG_IGN */
  6750. /* sig has non-empty trap, reset it: */
  6751. free(G_traps[sig]);
  6752. G_traps[sig] = NULL;
  6753. /* There is no signal for trap 0 (EXIT) */
  6754. if (sig == 0)
  6755. continue;
  6756. install_sighandler(sig, pick_sighandler(sig));
  6757. }
  6758. # endif
  6759. }
  6760. #else /* !BB_MMU */
  6761. static void re_execute_shell(char ***to_free, const char *s,
  6762. char *g_argv0, char **g_argv,
  6763. char **builtin_argv) NORETURN;
  6764. static void re_execute_shell(char ***to_free, const char *s,
  6765. char *g_argv0, char **g_argv,
  6766. char **builtin_argv)
  6767. {
  6768. # define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
  6769. /* delims + 2 * (number of bytes in printed hex numbers) */
  6770. char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
  6771. char *heredoc_argv[4];
  6772. struct variable *cur;
  6773. # if ENABLE_HUSH_FUNCTIONS
  6774. struct function *funcp;
  6775. # endif
  6776. char **argv, **pp;
  6777. unsigned cnt;
  6778. unsigned long long empty_trap_mask;
  6779. if (!g_argv0) { /* heredoc */
  6780. argv = heredoc_argv;
  6781. argv[0] = (char *) G.argv0_for_re_execing;
  6782. argv[1] = (char *) "-<";
  6783. argv[2] = (char *) s;
  6784. argv[3] = NULL;
  6785. pp = &argv[3]; /* used as pointer to empty environment */
  6786. goto do_exec;
  6787. }
  6788. cnt = 0;
  6789. pp = builtin_argv;
  6790. if (pp) while (*pp++)
  6791. cnt++;
  6792. empty_trap_mask = 0;
  6793. if (G_traps) {
  6794. int sig;
  6795. for (sig = 1; sig < NSIG; sig++) {
  6796. if (G_traps[sig] && !G_traps[sig][0])
  6797. empty_trap_mask |= 1LL << sig;
  6798. }
  6799. }
  6800. sprintf(param_buf, NOMMU_HACK_FMT
  6801. , (unsigned) G.root_pid
  6802. , (unsigned) G.root_ppid
  6803. , (unsigned) G.last_bg_pid
  6804. , (unsigned) G.last_exitcode
  6805. , cnt
  6806. , empty_trap_mask
  6807. IF_HUSH_LOOPS(, G.depth_of_loop)
  6808. );
  6809. # undef NOMMU_HACK_FMT
  6810. /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
  6811. * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
  6812. */
  6813. cnt += 6;
  6814. for (cur = G.top_var; cur; cur = cur->next) {
  6815. if (!cur->flg_export || cur->flg_read_only)
  6816. cnt += 2;
  6817. }
  6818. # if ENABLE_HUSH_FUNCTIONS
  6819. for (funcp = G.top_func; funcp; funcp = funcp->next)
  6820. cnt += 3;
  6821. # endif
  6822. pp = g_argv;
  6823. while (*pp++)
  6824. cnt++;
  6825. *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
  6826. *pp++ = (char *) G.argv0_for_re_execing;
  6827. *pp++ = param_buf;
  6828. for (cur = G.top_var; cur; cur = cur->next) {
  6829. if (strcmp(cur->varstr, hush_version_str) == 0)
  6830. continue;
  6831. if (cur->flg_read_only) {
  6832. *pp++ = (char *) "-R";
  6833. *pp++ = cur->varstr;
  6834. } else if (!cur->flg_export) {
  6835. *pp++ = (char *) "-V";
  6836. *pp++ = cur->varstr;
  6837. }
  6838. }
  6839. # if ENABLE_HUSH_FUNCTIONS
  6840. for (funcp = G.top_func; funcp; funcp = funcp->next) {
  6841. *pp++ = (char *) "-F";
  6842. *pp++ = funcp->name;
  6843. *pp++ = funcp->body_as_string;
  6844. }
  6845. # endif
  6846. /* We can pass activated traps here. Say, -Tnn:trap_string
  6847. *
  6848. * However, POSIX says that subshells reset signals with traps
  6849. * to SIG_DFL.
  6850. * I tested bash-3.2 and it not only does that with true subshells
  6851. * of the form ( list ), but with any forked children shells.
  6852. * I set trap "echo W" WINCH; and then tried:
  6853. *
  6854. * { echo 1; sleep 20; echo 2; } &
  6855. * while true; do echo 1; sleep 20; echo 2; break; done &
  6856. * true | { echo 1; sleep 20; echo 2; } | cat
  6857. *
  6858. * In all these cases sending SIGWINCH to the child shell
  6859. * did not run the trap. If I add trap "echo V" WINCH;
  6860. * _inside_ group (just before echo 1), it works.
  6861. *
  6862. * I conclude it means we don't need to pass active traps here.
  6863. */
  6864. *pp++ = (char *) "-c";
  6865. *pp++ = (char *) s;
  6866. if (builtin_argv) {
  6867. while (*++builtin_argv)
  6868. *pp++ = *builtin_argv;
  6869. *pp++ = (char *) "";
  6870. }
  6871. *pp++ = g_argv0;
  6872. while (*g_argv)
  6873. *pp++ = *g_argv++;
  6874. /* *pp = NULL; - is already there */
  6875. pp = environ;
  6876. do_exec:
  6877. debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
  6878. /* Don't propagate SIG_IGN to the child */
  6879. if (SPECIAL_JOBSTOP_SIGS != 0)
  6880. switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
  6881. execve(bb_busybox_exec_path, argv, pp);
  6882. /* Fallback. Useful for init=/bin/hush usage etc */
  6883. if (argv[0][0] == '/')
  6884. execve(argv[0], argv, pp);
  6885. xfunc_error_retval = 127;
  6886. bb_simple_error_msg_and_die("can't re-execute the shell");
  6887. }
  6888. #endif /* !BB_MMU */
  6889. static int run_and_free_list(struct pipe *pi);
  6890. /* Executing from string: eval, sh -c '...'
  6891. * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
  6892. * end_trigger controls how often we stop parsing
  6893. * NUL: parse all, execute, return
  6894. * ';': parse till ';' or newline, execute, repeat till EOF
  6895. */
  6896. static void parse_and_run_stream(struct in_str *inp, int end_trigger)
  6897. {
  6898. /* Why we need empty flag?
  6899. * An obscure corner case "false; ``; echo $?":
  6900. * empty command in `` should still set $? to 0.
  6901. * But we can't just set $? to 0 at the start,
  6902. * this breaks "false; echo `echo $?`" case.
  6903. */
  6904. bool empty = 1;
  6905. while (1) {
  6906. struct pipe *pipe_list;
  6907. #if ENABLE_HUSH_INTERACTIVE
  6908. if (end_trigger == ';') {
  6909. G.promptmode = 0; /* PS1 */
  6910. debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
  6911. }
  6912. #endif
  6913. pipe_list = parse_stream(NULL, NULL, inp, end_trigger);
  6914. if (!pipe_list || pipe_list == ERR_PTR) { /* EOF/error */
  6915. /* If we are in "big" script
  6916. * (not in `cmd` or something similar)...
  6917. */
  6918. if (pipe_list == ERR_PTR && end_trigger == ';') {
  6919. /* Discard cached input (rest of line) */
  6920. int ch = inp->last_char;
  6921. while (ch != EOF && ch != '\n') {
  6922. //bb_error_msg("Discarded:'%c'", ch);
  6923. ch = i_getch(inp);
  6924. }
  6925. /* Force prompt */
  6926. inp->p = NULL;
  6927. /* This stream isn't empty */
  6928. empty = 0;
  6929. continue;
  6930. }
  6931. if (!pipe_list && empty)
  6932. G.last_exitcode = 0;
  6933. break;
  6934. }
  6935. debug_print_tree(pipe_list, 0);
  6936. debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
  6937. run_and_free_list(pipe_list);
  6938. empty = 0;
  6939. if (G_flag_return_in_progress == 1)
  6940. break;
  6941. }
  6942. }
  6943. static void parse_and_run_string(const char *s)
  6944. {
  6945. struct in_str input;
  6946. //IF_HUSH_LINENO_VAR(unsigned sv = G.parse_lineno;)
  6947. setup_string_in_str(&input, s);
  6948. parse_and_run_stream(&input, '\0');
  6949. //IF_HUSH_LINENO_VAR(G.parse_lineno = sv;)
  6950. }
  6951. static void parse_and_run_file(HFILE *fp)
  6952. {
  6953. struct in_str input;
  6954. IF_HUSH_LINENO_VAR(unsigned sv = G.parse_lineno;)
  6955. IF_HUSH_LINENO_VAR(G.parse_lineno = 1;)
  6956. setup_file_in_str(&input, fp);
  6957. parse_and_run_stream(&input, ';');
  6958. IF_HUSH_LINENO_VAR(G.parse_lineno = sv;)
  6959. }
  6960. #if ENABLE_HUSH_TICK
  6961. static int generate_stream_from_string(const char *s, pid_t *pid_p)
  6962. {
  6963. pid_t pid;
  6964. int channel[2];
  6965. # if !BB_MMU
  6966. char **to_free = NULL;
  6967. # endif
  6968. xpipe(channel);
  6969. pid = BB_MMU ? xfork() : xvfork();
  6970. if (pid == 0) { /* child */
  6971. disable_restore_tty_pgrp_on_exit();
  6972. /* Process substitution is not considered to be usual
  6973. * 'command execution'.
  6974. * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
  6975. */
  6976. bb_signals(0
  6977. + (1 << SIGTSTP)
  6978. + (1 << SIGTTIN)
  6979. + (1 << SIGTTOU)
  6980. , SIG_IGN);
  6981. close(channel[0]); /* NB: close _first_, then move fd! */
  6982. xmove_fd(channel[1], 1);
  6983. # if ENABLE_HUSH_TRAP
  6984. /* Awful hack for `trap` or $(trap).
  6985. *
  6986. * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
  6987. * contains an example where "trap" is executed in a subshell:
  6988. *
  6989. * save_traps=$(trap)
  6990. * ...
  6991. * eval "$save_traps"
  6992. *
  6993. * Standard does not say that "trap" in subshell shall print
  6994. * parent shell's traps. It only says that its output
  6995. * must have suitable form, but then, in the above example
  6996. * (which is not supposed to be normative), it implies that.
  6997. *
  6998. * bash (and probably other shell) does implement it
  6999. * (traps are reset to defaults, but "trap" still shows them),
  7000. * but as a result, "trap" logic is hopelessly messed up:
  7001. *
  7002. * # trap
  7003. * trap -- 'echo Ho' SIGWINCH <--- we have a handler
  7004. * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
  7005. * # true | trap <--- trap is in subshell - no output (ditto)
  7006. * # echo `true | trap` <--- in subshell - output (but traps are reset!)
  7007. * trap -- 'echo Ho' SIGWINCH
  7008. * # echo `(trap)` <--- in subshell in subshell - output
  7009. * trap -- 'echo Ho' SIGWINCH
  7010. * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
  7011. * trap -- 'echo Ho' SIGWINCH
  7012. *
  7013. * The rules when to forget and when to not forget traps
  7014. * get really complex and nonsensical.
  7015. *
  7016. * Our solution: ONLY bare $(trap) or `trap` is special.
  7017. */
  7018. s = skip_whitespace(s);
  7019. if (is_prefixed_with(s, "trap")
  7020. && skip_whitespace(s + 4)[0] == '\0'
  7021. ) {
  7022. static const char *const argv[] = { NULL, NULL };
  7023. builtin_trap((char**)argv);
  7024. fflush_all(); /* important */
  7025. _exit(0);
  7026. }
  7027. # endif
  7028. # if BB_MMU
  7029. /* Prevent it from trying to handle ctrl-z etc */
  7030. IF_HUSH_JOB(G.run_list_level = 1;)
  7031. CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
  7032. reset_traps_to_defaults();
  7033. IF_HUSH_MODE_X(G.x_mode_depth++;)
  7034. //bb_error_msg("%s: ++x_mode_depth=%d", __func__, G.x_mode_depth);
  7035. parse_and_run_string(s);
  7036. _exit(G.last_exitcode);
  7037. # else
  7038. /* We re-execute after vfork on NOMMU. This makes this script safe:
  7039. * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
  7040. * huge=`cat BIG` # was blocking here forever
  7041. * echo OK
  7042. */
  7043. re_execute_shell(&to_free,
  7044. s,
  7045. G.global_argv[0],
  7046. G.global_argv + 1,
  7047. NULL);
  7048. # endif
  7049. }
  7050. /* parent */
  7051. *pid_p = pid;
  7052. # if ENABLE_HUSH_FAST
  7053. G.count_SIGCHLD++;
  7054. //bb_error_msg("[%d] fork in generate_stream_from_string:"
  7055. // " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
  7056. // getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
  7057. # endif
  7058. enable_restore_tty_pgrp_on_exit();
  7059. # if !BB_MMU
  7060. free(to_free);
  7061. # endif
  7062. close(channel[1]);
  7063. return channel[0];
  7064. }
  7065. /* Return code is exit status of the process that is run. */
  7066. static int process_command_subs(o_string *dest, const char *s)
  7067. {
  7068. FILE *fp;
  7069. pid_t pid;
  7070. int status, ch, eol_cnt;
  7071. fp = xfdopen_for_read(generate_stream_from_string(s, &pid));
  7072. /* Now send results of command back into original context */
  7073. eol_cnt = 0;
  7074. while ((ch = getc(fp)) != EOF) {
  7075. if (ch == '\0')
  7076. continue;
  7077. if (ch == '\n') {
  7078. eol_cnt++;
  7079. continue;
  7080. }
  7081. while (eol_cnt) {
  7082. o_addchr(dest, '\n');
  7083. eol_cnt--;
  7084. }
  7085. o_addQchr(dest, ch);
  7086. }
  7087. debug_printf("done reading from `cmd` pipe, closing it\n");
  7088. fclose(fp);
  7089. /* We need to extract exitcode. Test case
  7090. * "true; echo `sleep 1; false` $?"
  7091. * should print 1 */
  7092. safe_waitpid(pid, &status, 0);
  7093. debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
  7094. return WEXITSTATUS(status);
  7095. }
  7096. #endif /* ENABLE_HUSH_TICK */
  7097. static void setup_heredoc(struct redir_struct *redir)
  7098. {
  7099. struct fd_pair pair;
  7100. pid_t pid;
  7101. int len, written;
  7102. /* the _body_ of heredoc (misleading field name) */
  7103. const char *heredoc = redir->rd_filename;
  7104. char *expanded;
  7105. #if !BB_MMU
  7106. char **to_free;
  7107. #endif
  7108. expanded = NULL;
  7109. if (!(redir->rd_dup & HEREDOC_QUOTED)) {
  7110. expanded = encode_then_expand_string(heredoc);
  7111. if (expanded)
  7112. heredoc = expanded;
  7113. }
  7114. len = strlen(heredoc);
  7115. close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
  7116. xpiped_pair(pair);
  7117. xmove_fd(pair.rd, redir->rd_fd);
  7118. /* Try writing without forking. Newer kernels have
  7119. * dynamically growing pipes. Must use non-blocking write! */
  7120. ndelay_on(pair.wr);
  7121. while (1) {
  7122. written = write(pair.wr, heredoc, len);
  7123. if (written <= 0)
  7124. break;
  7125. len -= written;
  7126. if (len == 0) {
  7127. close(pair.wr);
  7128. free(expanded);
  7129. return;
  7130. }
  7131. heredoc += written;
  7132. }
  7133. ndelay_off(pair.wr);
  7134. /* Okay, pipe buffer was not big enough */
  7135. /* Note: we must not create a stray child (bastard? :)
  7136. * for the unsuspecting parent process. Child creates a grandchild
  7137. * and exits before parent execs the process which consumes heredoc
  7138. * (that exec happens after we return from this function) */
  7139. #if !BB_MMU
  7140. to_free = NULL;
  7141. #endif
  7142. pid = xvfork();
  7143. if (pid == 0) {
  7144. /* child */
  7145. disable_restore_tty_pgrp_on_exit();
  7146. pid = BB_MMU ? xfork() : xvfork();
  7147. if (pid != 0)
  7148. _exit(0);
  7149. /* grandchild */
  7150. close(redir->rd_fd); /* read side of the pipe */
  7151. #if BB_MMU
  7152. full_write(pair.wr, heredoc, len); /* may loop or block */
  7153. _exit(0);
  7154. #else
  7155. /* Delegate blocking writes to another process */
  7156. xmove_fd(pair.wr, STDOUT_FILENO);
  7157. re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
  7158. #endif
  7159. }
  7160. /* parent */
  7161. #if ENABLE_HUSH_FAST
  7162. G.count_SIGCHLD++;
  7163. //bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
  7164. #endif
  7165. enable_restore_tty_pgrp_on_exit();
  7166. #if !BB_MMU
  7167. free(to_free);
  7168. #endif
  7169. close(pair.wr);
  7170. free(expanded);
  7171. wait(NULL); /* wait till child has died */
  7172. }
  7173. struct squirrel {
  7174. int orig_fd;
  7175. int moved_to;
  7176. /* moved_to = n: fd was moved to n; restore back to orig_fd after redir */
  7177. /* moved_to = -1: fd was opened by redirect; close orig_fd after redir */
  7178. };
  7179. static struct squirrel *append_squirrel(struct squirrel *sq, int i, int orig, int moved)
  7180. {
  7181. sq = xrealloc(sq, (i + 2) * sizeof(sq[0]));
  7182. sq[i].orig_fd = orig;
  7183. sq[i].moved_to = moved;
  7184. sq[i+1].orig_fd = -1; /* end marker */
  7185. return sq;
  7186. }
  7187. static struct squirrel *add_squirrel(struct squirrel *sq, int fd, int avoid_fd)
  7188. {
  7189. int moved_to;
  7190. int i;
  7191. i = 0;
  7192. if (sq) for (; sq[i].orig_fd >= 0; i++) {
  7193. /* If we collide with an already moved fd... */
  7194. if (fd == sq[i].moved_to) {
  7195. sq[i].moved_to = dup_CLOEXEC(sq[i].moved_to, avoid_fd);
  7196. debug_printf_redir("redirect_fd %d: already busy, moving to %d\n", fd, sq[i].moved_to);
  7197. if (sq[i].moved_to < 0) /* what? */
  7198. xfunc_die();
  7199. return sq;
  7200. }
  7201. if (fd == sq[i].orig_fd) {
  7202. /* Example: echo Hello >/dev/null 1>&2 */
  7203. debug_printf_redir("redirect_fd %d: already moved\n", fd);
  7204. return sq;
  7205. }
  7206. }
  7207. /* If this fd is open, we move and remember it; if it's closed, moved_to = -1 */
  7208. moved_to = dup_CLOEXEC(fd, avoid_fd);
  7209. debug_printf_redir("redirect_fd %d: previous fd is moved to %d (-1 if it was closed)\n", fd, moved_to);
  7210. if (moved_to < 0 && errno != EBADF)
  7211. xfunc_die();
  7212. return append_squirrel(sq, i, fd, moved_to);
  7213. }
  7214. static struct squirrel *add_squirrel_closed(struct squirrel *sq, int fd)
  7215. {
  7216. int i;
  7217. i = 0;
  7218. if (sq) for (; sq[i].orig_fd >= 0; i++) {
  7219. /* If we collide with an already moved fd... */
  7220. if (fd == sq[i].orig_fd) {
  7221. /* Examples:
  7222. * "echo 3>FILE 3>&- 3>FILE"
  7223. * "echo 3>&- 3>FILE"
  7224. * No need for last redirect to insert
  7225. * another "need to close 3" indicator.
  7226. */
  7227. debug_printf_redir("redirect_fd %d: already moved or closed\n", fd);
  7228. return sq;
  7229. }
  7230. }
  7231. debug_printf_redir("redirect_fd %d: previous fd was closed\n", fd);
  7232. return append_squirrel(sq, i, fd, -1);
  7233. }
  7234. /* fd: redirect wants this fd to be used (e.g. 3>file).
  7235. * Move all conflicting internally used fds,
  7236. * and remember them so that we can restore them later.
  7237. */
  7238. static int save_fd_on_redirect(int fd, int avoid_fd, struct squirrel **sqp)
  7239. {
  7240. if (avoid_fd < 9) /* the important case here is that it can be -1 */
  7241. avoid_fd = 9;
  7242. #if ENABLE_HUSH_INTERACTIVE
  7243. if (fd != 0 /* don't trigger for G_interactive_fd == 0 (that's "not interactive" flag) */
  7244. && fd == G_interactive_fd
  7245. ) {
  7246. /* Testcase: "ls -l /proc/$$/fd 255>&-" should work */
  7247. G_interactive_fd = xdup_CLOEXEC_and_close(G_interactive_fd, avoid_fd);
  7248. debug_printf_redir("redirect_fd %d: matches interactive_fd, moving it to %d\n", fd, G_interactive_fd);
  7249. return 1; /* "we closed fd" */
  7250. }
  7251. #endif
  7252. /* Are we called from setup_redirects(squirrel==NULL)
  7253. * in redirect in a [v]forked child?
  7254. */
  7255. if (sqp == NULL) {
  7256. /* No need to move script fds.
  7257. * For NOMMU case, it's actively wrong: we'd change ->fd
  7258. * fields in memory for the parent, but parent's fds
  7259. * aren't moved, it would use wrong fd!
  7260. * Reproducer: "cmd 3>FILE" in script.
  7261. * If we would call move_HFILEs_on_redirect(), child would:
  7262. * fcntl64(3, F_DUPFD_CLOEXEC, 10) = 10
  7263. * close(3) = 0
  7264. * and change ->fd to 10 if fd#3 is a script fd. WRONG.
  7265. */
  7266. //bb_error_msg("sqp == NULL: [v]forked child");
  7267. return 0;
  7268. }
  7269. /* If this one of script's fds? */
  7270. if (move_HFILEs_on_redirect(fd, avoid_fd))
  7271. return 1; /* yes. "we closed fd" (actually moved it) */
  7272. /* Are we called for "exec 3>FILE"? Came through
  7273. * redirect_and_varexp_helper(squirrel=ERR_PTR) -> setup_redirects(ERR_PTR)
  7274. * This case used to fail for this script:
  7275. * exec 3>FILE
  7276. * echo Ok
  7277. * ...100000 more lines...
  7278. * echo Ok
  7279. * as follows:
  7280. * read(3, "exec 3>FILE\necho Ok\necho Ok"..., 1024) = 1024
  7281. * open("FILE", O_WRONLY|O_CREAT|O_TRUNC|O_LARGEFILE, 0666) = 4
  7282. * dup2(4, 3) = 3
  7283. * ^^^^^^^^ oops, we lost fd#3 opened to our script!
  7284. * close(4) = 0
  7285. * write(1, "Ok\n", 3) = 3
  7286. * ... = 3
  7287. * write(1, "Ok\n", 3) = 3
  7288. * read(3, 0x94fbc08, 1024) = -1 EBADF (Bad file descriptor)
  7289. * ^^^^^^^^ oops, wrong fd!!!
  7290. * With this case separate from sqp == NULL and *after* move_HFILEs,
  7291. * it now works:
  7292. */
  7293. if (sqp == ERR_PTR) {
  7294. /* Don't preserve redirected fds: exec is _meant_ to change these */
  7295. //bb_error_msg("sqp == ERR_PTR: exec >FILE");
  7296. return 0;
  7297. }
  7298. /* Check whether it collides with any open fds (e.g. stdio), save fds as needed */
  7299. *sqp = add_squirrel(*sqp, fd, avoid_fd);
  7300. return 0; /* "we did not close fd" */
  7301. }
  7302. static void restore_redirects(struct squirrel *sq)
  7303. {
  7304. if (sq) {
  7305. int i;
  7306. for (i = 0; sq[i].orig_fd >= 0; i++) {
  7307. if (sq[i].moved_to >= 0) {
  7308. /* We simply die on error */
  7309. debug_printf_redir("restoring redirected fd from %d to %d\n", sq[i].moved_to, sq[i].orig_fd);
  7310. xmove_fd(sq[i].moved_to, sq[i].orig_fd);
  7311. } else {
  7312. /* cmd1 9>FILE; cmd2_should_see_fd9_closed */
  7313. debug_printf_redir("restoring redirected fd %d: closing it\n", sq[i].orig_fd);
  7314. close(sq[i].orig_fd);
  7315. }
  7316. }
  7317. free(sq);
  7318. }
  7319. if (G.HFILE_stdin
  7320. && G.HFILE_stdin->fd > STDIN_FILENO
  7321. /* we compare > STDIN, not == STDIN, since hfgetc()
  7322. * closes fd and sets ->fd to -1 if EOF is reached.
  7323. * Testcase: echo 'pwd' | hush
  7324. */
  7325. ) {
  7326. /* Testcase: interactive "read r <FILE; echo $r; read r; echo $r".
  7327. * Redirect moves ->fd to e.g. 10,
  7328. * and it is not restored above (we do not restore script fds
  7329. * after redirects, we just use new, "moved" fds).
  7330. * However for stdin, get_user_input() -> read_line_input(),
  7331. * and read builtin, depend on fd == STDIN_FILENO.
  7332. */
  7333. debug_printf_redir("restoring %d to stdin\n", G.HFILE_stdin->fd);
  7334. xmove_fd(G.HFILE_stdin->fd, STDIN_FILENO);
  7335. G.HFILE_stdin->fd = STDIN_FILENO;
  7336. }
  7337. /* If moved, G_interactive_fd stays on new fd, not restoring it */
  7338. }
  7339. #if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
  7340. static void close_saved_fds_and_FILE_fds(void)
  7341. {
  7342. if (G_interactive_fd)
  7343. close(G_interactive_fd);
  7344. close_all_HFILE_list();
  7345. }
  7346. #endif
  7347. static int internally_opened_fd(int fd, struct squirrel *sq)
  7348. {
  7349. int i;
  7350. #if ENABLE_HUSH_INTERACTIVE
  7351. if (fd == G_interactive_fd)
  7352. return 1;
  7353. #endif
  7354. /* If this one of script's fds? */
  7355. if (fd_in_HFILEs(fd))
  7356. return 1;
  7357. if (sq) for (i = 0; sq[i].orig_fd >= 0; i++) {
  7358. if (fd == sq[i].moved_to)
  7359. return 1;
  7360. }
  7361. return 0;
  7362. }
  7363. /* squirrel != NULL means we squirrel away copies of stdin, stdout,
  7364. * and stderr if they are redirected. */
  7365. static int setup_redirects(struct command *prog, struct squirrel **sqp)
  7366. {
  7367. struct redir_struct *redir;
  7368. for (redir = prog->redirects; redir; redir = redir->next) {
  7369. int newfd;
  7370. int closed;
  7371. if (redir->rd_type == REDIRECT_HEREDOC2) {
  7372. /* "rd_fd<<HERE" case */
  7373. save_fd_on_redirect(redir->rd_fd, /*avoid:*/ 0, sqp);
  7374. /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
  7375. * of the heredoc */
  7376. debug_printf_redir("set heredoc '%s'\n",
  7377. redir->rd_filename);
  7378. setup_heredoc(redir);
  7379. continue;
  7380. }
  7381. if (redir->rd_dup == REDIRFD_TO_FILE) {
  7382. /* "rd_fd<*>file" case (<*> is <,>,>>,<>) */
  7383. char *p;
  7384. int mode;
  7385. if (redir->rd_filename == NULL) {
  7386. /* Examples:
  7387. * "cmd >" (no filename)
  7388. * "cmd > <file" (2nd redirect starts too early)
  7389. */
  7390. syntax_error("invalid redirect");
  7391. continue;
  7392. }
  7393. mode = redir_table[redir->rd_type].mode;
  7394. p = expand_string_to_string(redir->rd_filename,
  7395. EXP_FLAG_ESC_GLOB_CHARS, /*unbackslash:*/ 1);
  7396. newfd = open_or_warn(p, mode);
  7397. free(p);
  7398. if (newfd < 0) {
  7399. /* Error message from open_or_warn can be lost
  7400. * if stderr has been redirected, but bash
  7401. * and ash both lose it as well
  7402. * (though zsh doesn't!)
  7403. */
  7404. return 1;
  7405. }
  7406. if (newfd == redir->rd_fd && sqp) {
  7407. /* open() gave us precisely the fd we wanted.
  7408. * This means that this fd was not busy
  7409. * (not opened to anywhere).
  7410. * Remember to close it on restore:
  7411. */
  7412. *sqp = add_squirrel_closed(*sqp, newfd);
  7413. debug_printf_redir("redir to previously closed fd %d\n", newfd);
  7414. }
  7415. } else {
  7416. /* "rd_fd>&rd_dup" or "rd_fd>&-" case */
  7417. newfd = redir->rd_dup;
  7418. }
  7419. if (newfd == redir->rd_fd)
  7420. continue;
  7421. /* if "N>FILE": move newfd to redir->rd_fd */
  7422. /* if "N>&M": dup newfd to redir->rd_fd */
  7423. /* if "N>&-": close redir->rd_fd (newfd is REDIRFD_CLOSE) */
  7424. closed = save_fd_on_redirect(redir->rd_fd, /*avoid:*/ newfd, sqp);
  7425. if (newfd == REDIRFD_CLOSE) {
  7426. /* "N>&-" means "close me" */
  7427. if (!closed) {
  7428. /* ^^^ optimization: saving may already
  7429. * have closed it. If not... */
  7430. close(redir->rd_fd);
  7431. }
  7432. /* Sometimes we do another close on restore, getting EBADF.
  7433. * Consider "echo 3>FILE 3>&-"
  7434. * first redirect remembers "need to close 3",
  7435. * and second redirect closes 3! Restore code then closes 3 again.
  7436. */
  7437. } else {
  7438. /* if newfd is a script fd or saved fd, simulate EBADF */
  7439. if (internally_opened_fd(newfd, sqp && sqp != ERR_PTR ? *sqp : NULL)) {
  7440. //errno = EBADF;
  7441. //bb_perror_msg_and_die("can't duplicate file descriptor");
  7442. newfd = -1; /* same effect as code above */
  7443. }
  7444. xdup2(newfd, redir->rd_fd);
  7445. if (redir->rd_dup == REDIRFD_TO_FILE)
  7446. /* "rd_fd > FILE" */
  7447. close(newfd);
  7448. /* else: "rd_fd > rd_dup" */
  7449. }
  7450. }
  7451. return 0;
  7452. }
  7453. static char *find_in_path(const char *arg)
  7454. {
  7455. char *ret = NULL;
  7456. const char *PATH = get_local_var_value("PATH");
  7457. if (!PATH)
  7458. return NULL;
  7459. while (1) {
  7460. const char *end = strchrnul(PATH, ':');
  7461. int sz = end - PATH; /* must be int! */
  7462. free(ret);
  7463. if (sz != 0) {
  7464. ret = xasprintf("%.*s/%s", sz, PATH, arg);
  7465. } else {
  7466. /* We have xxx::yyyy in $PATH,
  7467. * it means "use current dir" */
  7468. ret = xstrdup(arg);
  7469. }
  7470. if (access(ret, F_OK) == 0)
  7471. break;
  7472. if (*end == '\0') {
  7473. free(ret);
  7474. return NULL;
  7475. }
  7476. PATH = end + 1;
  7477. }
  7478. return ret;
  7479. }
  7480. static const struct built_in_command *find_builtin_helper(const char *name,
  7481. const struct built_in_command *x,
  7482. const struct built_in_command *end)
  7483. {
  7484. while (x != end) {
  7485. if (strcmp(name, x->b_cmd) != 0) {
  7486. x++;
  7487. continue;
  7488. }
  7489. debug_printf_exec("found builtin '%s'\n", name);
  7490. return x;
  7491. }
  7492. return NULL;
  7493. }
  7494. static const struct built_in_command *find_builtin1(const char *name)
  7495. {
  7496. return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
  7497. }
  7498. static const struct built_in_command *find_builtin(const char *name)
  7499. {
  7500. const struct built_in_command *x = find_builtin1(name);
  7501. if (x)
  7502. return x;
  7503. return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
  7504. }
  7505. #if ENABLE_HUSH_JOB && EDITING_HAS_get_exe_name
  7506. static const char * FAST_FUNC get_builtin_name(int i)
  7507. {
  7508. if (/*i >= 0 && */ i < ARRAY_SIZE(bltins1)) {
  7509. return bltins1[i].b_cmd;
  7510. }
  7511. i -= ARRAY_SIZE(bltins1);
  7512. if (i < ARRAY_SIZE(bltins2)) {
  7513. return bltins2[i].b_cmd;
  7514. }
  7515. return NULL;
  7516. }
  7517. #endif
  7518. static void remove_nested_vars(void)
  7519. {
  7520. struct variable *cur;
  7521. struct variable **cur_pp;
  7522. cur_pp = &G.top_var;
  7523. while ((cur = *cur_pp) != NULL) {
  7524. if (cur->var_nest_level <= G.var_nest_level) {
  7525. cur_pp = &cur->next;
  7526. continue;
  7527. }
  7528. /* Unexport */
  7529. if (cur->flg_export) {
  7530. debug_printf_env("unexporting nested '%s'/%u\n", cur->varstr, cur->var_nest_level);
  7531. bb_unsetenv(cur->varstr);
  7532. }
  7533. /* Remove from global list */
  7534. *cur_pp = cur->next;
  7535. /* Free */
  7536. if (!cur->max_len) {
  7537. debug_printf_env("freeing nested '%s'/%u\n", cur->varstr, cur->var_nest_level);
  7538. free(cur->varstr);
  7539. }
  7540. free(cur);
  7541. }
  7542. }
  7543. static void enter_var_nest_level(void)
  7544. {
  7545. G.var_nest_level++;
  7546. debug_printf_env("var_nest_level++ %u\n", G.var_nest_level);
  7547. /* Try: f() { echo -n .; f; }; f
  7548. * struct variable::var_nest_level is uint16_t,
  7549. * thus limiting recursion to < 2^16.
  7550. * In any case, with 8 Mbyte stack SEGV happens
  7551. * not too long after 2^16 recursions anyway.
  7552. */
  7553. if (G.var_nest_level > 0xff00)
  7554. bb_error_msg_and_die("fatal recursion (depth %u)", G.var_nest_level);
  7555. }
  7556. static void leave_var_nest_level(void)
  7557. {
  7558. G.var_nest_level--;
  7559. debug_printf_env("var_nest_level-- %u\n", G.var_nest_level);
  7560. if (HUSH_DEBUG && (int)G.var_nest_level < 0)
  7561. bb_simple_error_msg_and_die("BUG: nesting underflow");
  7562. remove_nested_vars();
  7563. }
  7564. #if ENABLE_HUSH_FUNCTIONS
  7565. static struct function **find_function_slot(const char *name)
  7566. {
  7567. struct function *funcp;
  7568. struct function **funcpp = &G.top_func;
  7569. while ((funcp = *funcpp) != NULL) {
  7570. if (strcmp(name, funcp->name) == 0) {
  7571. debug_printf_exec("found function '%s'\n", name);
  7572. break;
  7573. }
  7574. funcpp = &funcp->next;
  7575. }
  7576. return funcpp;
  7577. }
  7578. static ALWAYS_INLINE const struct function *find_function(const char *name)
  7579. {
  7580. const struct function *funcp = *find_function_slot(name);
  7581. return funcp;
  7582. }
  7583. /* Note: takes ownership on name ptr */
  7584. static struct function *new_function(char *name)
  7585. {
  7586. struct function **funcpp = find_function_slot(name);
  7587. struct function *funcp = *funcpp;
  7588. if (funcp != NULL) {
  7589. struct command *cmd = funcp->parent_cmd;
  7590. debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
  7591. if (!cmd) {
  7592. debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
  7593. free(funcp->name);
  7594. /* Note: if !funcp->body, do not free body_as_string!
  7595. * This is a special case of "-F name body" function:
  7596. * body_as_string was not malloced! */
  7597. if (funcp->body) {
  7598. free_pipe_list(funcp->body);
  7599. # if !BB_MMU
  7600. free(funcp->body_as_string);
  7601. # endif
  7602. }
  7603. } else {
  7604. debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
  7605. cmd->argv[0] = funcp->name;
  7606. cmd->group = funcp->body;
  7607. # if !BB_MMU
  7608. cmd->group_as_string = funcp->body_as_string;
  7609. # endif
  7610. }
  7611. } else {
  7612. debug_printf_exec("remembering new function '%s'\n", name);
  7613. funcp = *funcpp = xzalloc(sizeof(*funcp));
  7614. /*funcp->next = NULL;*/
  7615. }
  7616. funcp->name = name;
  7617. return funcp;
  7618. }
  7619. # if ENABLE_HUSH_UNSET
  7620. static void unset_func(const char *name)
  7621. {
  7622. struct function **funcpp = find_function_slot(name);
  7623. struct function *funcp = *funcpp;
  7624. if (funcp != NULL) {
  7625. debug_printf_exec("freeing function '%s'\n", funcp->name);
  7626. *funcpp = funcp->next;
  7627. /* funcp is unlinked now, deleting it.
  7628. * Note: if !funcp->body, the function was created by
  7629. * "-F name body", do not free ->body_as_string
  7630. * and ->name as they were not malloced. */
  7631. if (funcp->body) {
  7632. free_pipe_list(funcp->body);
  7633. free(funcp->name);
  7634. # if !BB_MMU
  7635. free(funcp->body_as_string);
  7636. # endif
  7637. }
  7638. free(funcp);
  7639. }
  7640. }
  7641. # endif
  7642. # if BB_MMU
  7643. #define exec_function(to_free, funcp, argv) \
  7644. exec_function(funcp, argv)
  7645. # endif
  7646. static void exec_function(char ***to_free,
  7647. const struct function *funcp,
  7648. char **argv) NORETURN;
  7649. static void exec_function(char ***to_free,
  7650. const struct function *funcp,
  7651. char **argv)
  7652. {
  7653. # if BB_MMU
  7654. int n;
  7655. argv[0] = G.global_argv[0];
  7656. G.global_argv = argv;
  7657. G.global_argc = n = 1 + string_array_len(argv + 1);
  7658. // Example when we are here: "cmd | func"
  7659. // func will run with saved-redirect fds open.
  7660. // $ f() { echo /proc/self/fd/*; }
  7661. // $ true | f
  7662. // /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3
  7663. // stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ DIR fd for glob
  7664. // Same in script:
  7665. // $ . ./SCRIPT
  7666. // /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3 /proc/self/fd/4
  7667. // stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ opened ./SCRIPT DIR fd for glob
  7668. // They are CLOEXEC so external programs won't see them, but
  7669. // for "more correctness" we might want to close those extra fds here:
  7670. //? close_saved_fds_and_FILE_fds();
  7671. /* "we are in a function, ok to use return" */
  7672. G_flag_return_in_progress = -1;
  7673. enter_var_nest_level();
  7674. IF_HUSH_LOCAL(G.func_nest_level++;)
  7675. /* On MMU, funcp->body is always non-NULL */
  7676. n = run_list(funcp->body);
  7677. _exit(n);
  7678. # else
  7679. //? close_saved_fds_and_FILE_fds();
  7680. //TODO: check whether "true | func_with_return" works
  7681. re_execute_shell(to_free,
  7682. funcp->body_as_string,
  7683. G.global_argv[0],
  7684. argv + 1,
  7685. NULL);
  7686. # endif
  7687. }
  7688. static int run_function(const struct function *funcp, char **argv)
  7689. {
  7690. int rc;
  7691. save_arg_t sv;
  7692. smallint sv_flg;
  7693. save_and_replace_G_args(&sv, argv);
  7694. /* "We are in function, ok to use return" */
  7695. sv_flg = G_flag_return_in_progress;
  7696. G_flag_return_in_progress = -1;
  7697. /* Make "local" variables properly shadow previous ones */
  7698. IF_HUSH_LOCAL(enter_var_nest_level();)
  7699. IF_HUSH_LOCAL(G.func_nest_level++;)
  7700. /* On MMU, funcp->body is always non-NULL */
  7701. # if !BB_MMU
  7702. if (!funcp->body) {
  7703. /* Function defined by -F */
  7704. parse_and_run_string(funcp->body_as_string);
  7705. rc = G.last_exitcode;
  7706. } else
  7707. # endif
  7708. {
  7709. rc = run_list(funcp->body);
  7710. }
  7711. IF_HUSH_LOCAL(G.func_nest_level--;)
  7712. IF_HUSH_LOCAL(leave_var_nest_level();)
  7713. G_flag_return_in_progress = sv_flg;
  7714. # if ENABLE_HUSH_TRAP
  7715. debug_printf_exec("G.return_exitcode=-1\n");
  7716. G.return_exitcode = -1; /* invalidate stashed return value */
  7717. # endif
  7718. restore_G_args(&sv, argv);
  7719. return rc;
  7720. }
  7721. #endif /* ENABLE_HUSH_FUNCTIONS */
  7722. #if BB_MMU
  7723. #define exec_builtin(to_free, x, argv) \
  7724. exec_builtin(x, argv)
  7725. #else
  7726. #define exec_builtin(to_free, x, argv) \
  7727. exec_builtin(to_free, argv)
  7728. #endif
  7729. static void exec_builtin(char ***to_free,
  7730. const struct built_in_command *x,
  7731. char **argv) NORETURN;
  7732. static void exec_builtin(char ***to_free,
  7733. const struct built_in_command *x,
  7734. char **argv)
  7735. {
  7736. #if BB_MMU
  7737. int rcode;
  7738. //? close_saved_fds_and_FILE_fds();
  7739. rcode = x->b_function(argv);
  7740. fflush_all();
  7741. _exit(rcode);
  7742. #else
  7743. fflush_all();
  7744. /* On NOMMU, we must never block!
  7745. * Example: { sleep 99 | read line; } & echo Ok
  7746. */
  7747. re_execute_shell(to_free,
  7748. argv[0],
  7749. G.global_argv[0],
  7750. G.global_argv + 1,
  7751. argv);
  7752. #endif
  7753. }
  7754. static void execvp_or_die(char **argv) NORETURN;
  7755. static void execvp_or_die(char **argv)
  7756. {
  7757. int e;
  7758. debug_printf_exec("execing '%s'\n", argv[0]);
  7759. /* Don't propagate SIG_IGN to the child */
  7760. if (SPECIAL_JOBSTOP_SIGS != 0)
  7761. switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
  7762. execvp(argv[0], argv);
  7763. e = 2;
  7764. if (errno == EACCES) e = 126;
  7765. if (errno == ENOENT) e = 127;
  7766. bb_perror_msg("can't execute '%s'", argv[0]);
  7767. _exit(e);
  7768. }
  7769. #if ENABLE_HUSH_MODE_X
  7770. static void x_mode_print_optionally_squoted(const char *str)
  7771. {
  7772. unsigned len;
  7773. const char *cp;
  7774. cp = str;
  7775. /* the set of chars which-cause-string-to-be-squoted mimics bash */
  7776. /* test a char with: bash -c 'set -x; echo "CH"' */
  7777. if (str[strcspn(str, "\\\"'`$(){}[]<>;#&|~*?!^"
  7778. " " "\001\002\003\004\005\006\007"
  7779. "\010\011\012\013\014\015\016\017"
  7780. "\020\021\022\023\024\025\026\027"
  7781. "\030\031\032\033\034\035\036\037"
  7782. )
  7783. ] == '\0'
  7784. ) {
  7785. /* string has no special chars */
  7786. x_mode_addstr(str);
  7787. return;
  7788. }
  7789. cp = str;
  7790. for (;;) {
  7791. /* print '....' up to EOL or first squote */
  7792. len = (int)(strchrnul(cp, '\'') - cp);
  7793. if (len != 0) {
  7794. x_mode_addchr('\'');
  7795. x_mode_addblock(cp, len);
  7796. x_mode_addchr('\'');
  7797. cp += len;
  7798. }
  7799. if (*cp == '\0')
  7800. break;
  7801. /* string contains squote(s), print them as \' */
  7802. x_mode_addchr('\\');
  7803. x_mode_addchr('\'');
  7804. cp++;
  7805. }
  7806. }
  7807. static void dump_cmd_in_x_mode(char **argv)
  7808. {
  7809. if (G_x_mode && argv) {
  7810. unsigned n;
  7811. /* "+[+++...][ cmd...]\n\0" */
  7812. x_mode_prefix();
  7813. n = 0;
  7814. while (argv[n]) {
  7815. x_mode_addchr(' ');
  7816. if (argv[n][0] == '\0') {
  7817. x_mode_addchr('\'');
  7818. x_mode_addchr('\'');
  7819. } else {
  7820. x_mode_print_optionally_squoted(argv[n]);
  7821. }
  7822. n++;
  7823. }
  7824. x_mode_flush();
  7825. }
  7826. }
  7827. #else
  7828. # define dump_cmd_in_x_mode(argv) ((void)0)
  7829. #endif
  7830. #if ENABLE_HUSH_COMMAND
  7831. static void if_command_vV_print_and_exit(char opt_vV, char *cmd, const char *explanation)
  7832. {
  7833. char *to_free;
  7834. if (!opt_vV)
  7835. return;
  7836. to_free = NULL;
  7837. if (!explanation) {
  7838. char *path = getenv("PATH");
  7839. explanation = to_free = find_executable(cmd, &path); /* path == NULL is ok */
  7840. if (!explanation)
  7841. _exit(1); /* PROG was not found */
  7842. if (opt_vV != 'V')
  7843. cmd = to_free; /* -v PROG prints "/path/to/PROG" */
  7844. }
  7845. printf((opt_vV == 'V') ? "%s is %s\n" : "%s\n", cmd, explanation);
  7846. free(to_free);
  7847. fflush_all();
  7848. _exit(0);
  7849. }
  7850. #else
  7851. # define if_command_vV_print_and_exit(a,b,c) ((void)0)
  7852. #endif
  7853. #if BB_MMU
  7854. #define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
  7855. pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
  7856. #define pseudo_exec(nommu_save, command, argv_expanded) \
  7857. pseudo_exec(command, argv_expanded)
  7858. #endif
  7859. /* Called after [v]fork() in run_pipe, or from builtin_exec.
  7860. * Never returns.
  7861. * Don't exit() here. If you don't exec, use _exit instead.
  7862. * The at_exit handlers apparently confuse the calling process,
  7863. * in particular stdin handling. Not sure why? -- because of vfork! (vda)
  7864. */
  7865. static void pseudo_exec_argv(nommu_save_t *nommu_save,
  7866. char **argv, int assignment_cnt,
  7867. char **argv_expanded) NORETURN;
  7868. static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
  7869. char **argv, int assignment_cnt,
  7870. char **argv_expanded)
  7871. {
  7872. const struct built_in_command *x;
  7873. struct variable **sv_shadowed;
  7874. char **new_env;
  7875. IF_HUSH_COMMAND(char opt_vV = 0;)
  7876. IF_HUSH_FUNCTIONS(const struct function *funcp;)
  7877. new_env = expand_assignments(argv, assignment_cnt);
  7878. dump_cmd_in_x_mode(new_env);
  7879. if (!argv[assignment_cnt]) {
  7880. /* Case when we are here: ... | var=val | ...
  7881. * (note that we do not exit early, i.e., do not optimize out
  7882. * expand_assignments(): think about ... | var=`sleep 1` | ...
  7883. */
  7884. free_strings(new_env);
  7885. _exit(EXIT_SUCCESS);
  7886. }
  7887. sv_shadowed = G.shadowed_vars_pp;
  7888. #if BB_MMU
  7889. G.shadowed_vars_pp = NULL; /* "don't save, free them instead" */
  7890. #else
  7891. G.shadowed_vars_pp = &nommu_save->old_vars;
  7892. G.var_nest_level++;
  7893. #endif
  7894. set_vars_and_save_old(new_env);
  7895. G.shadowed_vars_pp = sv_shadowed;
  7896. if (argv_expanded) {
  7897. argv = argv_expanded;
  7898. } else {
  7899. argv = expand_strvec_to_strvec(argv + assignment_cnt);
  7900. #if !BB_MMU
  7901. nommu_save->argv = argv;
  7902. #endif
  7903. }
  7904. dump_cmd_in_x_mode(argv);
  7905. #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
  7906. if (strchr(argv[0], '/') != NULL)
  7907. goto skip;
  7908. #endif
  7909. #if ENABLE_HUSH_FUNCTIONS
  7910. /* Check if the command matches any functions (this goes before bltins) */
  7911. funcp = find_function(argv[0]);
  7912. if (funcp)
  7913. exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
  7914. #endif
  7915. #if ENABLE_HUSH_COMMAND
  7916. /* "command BAR": run BAR without looking it up among functions
  7917. * "command -v BAR": print "BAR" or "/path/to/BAR"; or exit 1
  7918. * "command -V BAR": print "BAR is {a function,a shell builtin,/path/to/BAR}"
  7919. */
  7920. while (strcmp(argv[0], "command") == 0 && argv[1]) {
  7921. char *p;
  7922. argv++;
  7923. p = *argv;
  7924. if (p[0] != '-' || !p[1])
  7925. continue; /* bash allows "command command command [-OPT] BAR" */
  7926. for (;;) {
  7927. p++;
  7928. switch (*p) {
  7929. case '\0':
  7930. argv++;
  7931. p = *argv;
  7932. if (p[0] != '-' || !p[1])
  7933. goto after_opts;
  7934. continue; /* next arg is also -opts, process it too */
  7935. case 'v':
  7936. case 'V':
  7937. opt_vV = *p;
  7938. continue;
  7939. default:
  7940. bb_error_msg_and_die("%s: %s: invalid option", "command", argv[0]);
  7941. }
  7942. }
  7943. }
  7944. after_opts:
  7945. # if ENABLE_HUSH_FUNCTIONS
  7946. if (opt_vV && find_function(argv[0]))
  7947. if_command_vV_print_and_exit(opt_vV, argv[0], "a function");
  7948. # endif
  7949. #endif
  7950. /* Check if the command matches any of the builtins.
  7951. * Depending on context, this might be redundant. But it's
  7952. * easier to waste a few CPU cycles than it is to figure out
  7953. * if this is one of those cases.
  7954. */
  7955. /* Why "BB_MMU ? :" difference in logic? -
  7956. * On NOMMU, it is more expensive to re-execute shell
  7957. * just in order to run echo or test builtin.
  7958. * It's better to skip it here and run corresponding
  7959. * non-builtin later. */
  7960. x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
  7961. if (x) {
  7962. if_command_vV_print_and_exit(opt_vV, argv[0], "a shell builtin");
  7963. exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
  7964. }
  7965. #if ENABLE_FEATURE_SH_STANDALONE
  7966. /* Check if the command matches any busybox applets */
  7967. {
  7968. int a = find_applet_by_name(argv[0]);
  7969. if (a >= 0) {
  7970. if_command_vV_print_and_exit(opt_vV, argv[0], "an applet");
  7971. # if BB_MMU /* see above why on NOMMU it is not allowed */
  7972. if (APPLET_IS_NOEXEC(a)) {
  7973. /* Do not leak open fds from opened script files etc.
  7974. * Testcase: interactive "ls -l /proc/self/fd"
  7975. * should not show tty fd open.
  7976. */
  7977. close_saved_fds_and_FILE_fds();
  7978. //FIXME: should also close saved redir fds
  7979. //This casuses test failures in
  7980. //redir_children_should_not_see_saved_fd_2.tests
  7981. //redir_children_should_not_see_saved_fd_3.tests
  7982. //if you replace "busybox find" with just "find" in them
  7983. /* Without this, "rm -i FILE" can't be ^C'ed: */
  7984. switch_off_special_sigs(G.special_sig_mask);
  7985. debug_printf_exec("running applet '%s'\n", argv[0]);
  7986. run_noexec_applet_and_exit(a, argv[0], argv);
  7987. }
  7988. # endif
  7989. /* Re-exec ourselves */
  7990. debug_printf_exec("re-execing applet '%s'\n", argv[0]);
  7991. /* Don't propagate SIG_IGN to the child */
  7992. if (SPECIAL_JOBSTOP_SIGS != 0)
  7993. switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
  7994. execv(bb_busybox_exec_path, argv);
  7995. /* If they called chroot or otherwise made the binary no longer
  7996. * executable, fall through */
  7997. }
  7998. }
  7999. #endif
  8000. #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
  8001. skip:
  8002. #endif
  8003. if_command_vV_print_and_exit(opt_vV, argv[0], NULL);
  8004. execvp_or_die(argv);
  8005. }
  8006. /* Called after [v]fork() in run_pipe
  8007. */
  8008. static void pseudo_exec(nommu_save_t *nommu_save,
  8009. struct command *command,
  8010. char **argv_expanded) NORETURN;
  8011. static void pseudo_exec(nommu_save_t *nommu_save,
  8012. struct command *command,
  8013. char **argv_expanded)
  8014. {
  8015. #if ENABLE_HUSH_FUNCTIONS
  8016. if (command->cmd_type == CMD_FUNCDEF) {
  8017. /* Ignore funcdefs in pipes:
  8018. * true | f() { cmd }
  8019. */
  8020. _exit(0);
  8021. }
  8022. #endif
  8023. if (command->argv) {
  8024. pseudo_exec_argv(nommu_save, command->argv,
  8025. command->assignment_cnt, argv_expanded);
  8026. }
  8027. if (command->group) {
  8028. /* Cases when we are here:
  8029. * ( list )
  8030. * { list } &
  8031. * ... | ( list ) | ...
  8032. * ... | { list } | ...
  8033. */
  8034. #if BB_MMU
  8035. int rcode;
  8036. debug_printf_exec("pseudo_exec: run_list\n");
  8037. reset_traps_to_defaults();
  8038. rcode = run_list(command->group);
  8039. /* OK to leak memory by not calling free_pipe_list,
  8040. * since this process is about to exit */
  8041. _exit(rcode);
  8042. #else
  8043. re_execute_shell(&nommu_save->argv_from_re_execing,
  8044. command->group_as_string,
  8045. G.global_argv[0],
  8046. G.global_argv + 1,
  8047. NULL);
  8048. #endif
  8049. }
  8050. /* Case when we are here: ... | >file */
  8051. debug_printf_exec("pseudo_exec'ed null command\n");
  8052. _exit(EXIT_SUCCESS);
  8053. }
  8054. #if ENABLE_HUSH_JOB
  8055. static const char *get_cmdtext(struct pipe *pi)
  8056. {
  8057. char **argv;
  8058. char *p;
  8059. int len;
  8060. /* This is subtle. ->cmdtext is created only on first backgrounding.
  8061. * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
  8062. * On subsequent bg argv is trashed, but we won't use it */
  8063. if (pi->cmdtext)
  8064. return pi->cmdtext;
  8065. argv = pi->cmds[0].argv;
  8066. if (!argv) {
  8067. pi->cmdtext = xzalloc(1);
  8068. return pi->cmdtext;
  8069. }
  8070. len = 0;
  8071. do {
  8072. len += strlen(*argv) + 1;
  8073. } while (*++argv);
  8074. p = xmalloc(len);
  8075. pi->cmdtext = p;
  8076. argv = pi->cmds[0].argv;
  8077. do {
  8078. p = stpcpy(p, *argv);
  8079. *p++ = ' ';
  8080. } while (*++argv);
  8081. p[-1] = '\0';
  8082. return pi->cmdtext;
  8083. }
  8084. static void remove_job_from_table(struct pipe *pi)
  8085. {
  8086. struct pipe *prev_pipe;
  8087. if (pi == G.job_list) {
  8088. G.job_list = pi->next;
  8089. } else {
  8090. prev_pipe = G.job_list;
  8091. while (prev_pipe->next != pi)
  8092. prev_pipe = prev_pipe->next;
  8093. prev_pipe->next = pi->next;
  8094. }
  8095. G.last_jobid = 0;
  8096. if (G.job_list)
  8097. G.last_jobid = G.job_list->jobid;
  8098. }
  8099. static void delete_finished_job(struct pipe *pi)
  8100. {
  8101. remove_job_from_table(pi);
  8102. free_pipe(pi);
  8103. }
  8104. static void clean_up_last_dead_job(void)
  8105. {
  8106. if (G.job_list && !G.job_list->alive_cmds)
  8107. delete_finished_job(G.job_list);
  8108. }
  8109. static void insert_job_into_table(struct pipe *pi)
  8110. {
  8111. struct pipe *job, **jobp;
  8112. int i;
  8113. clean_up_last_dead_job();
  8114. /* Find the end of the list, and find next job ID to use */
  8115. i = 0;
  8116. jobp = &G.job_list;
  8117. while ((job = *jobp) != NULL) {
  8118. if (job->jobid > i)
  8119. i = job->jobid;
  8120. jobp = &job->next;
  8121. }
  8122. pi->jobid = i + 1;
  8123. /* Create a new job struct at the end */
  8124. job = *jobp = xmemdup(pi, sizeof(*pi));
  8125. job->next = NULL;
  8126. job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
  8127. /* Cannot copy entire pi->cmds[] vector! This causes double frees */
  8128. for (i = 0; i < pi->num_cmds; i++) {
  8129. job->cmds[i].pid = pi->cmds[i].pid;
  8130. /* all other fields are not used and stay zero */
  8131. }
  8132. job->cmdtext = xstrdup(get_cmdtext(pi));
  8133. if (G_interactive_fd)
  8134. printf("[%u] %u %s\n", job->jobid, (unsigned)job->cmds[0].pid, job->cmdtext);
  8135. G.last_jobid = job->jobid;
  8136. }
  8137. #endif /* JOB */
  8138. static int job_exited_or_stopped(struct pipe *pi)
  8139. {
  8140. int rcode, i;
  8141. if (pi->alive_cmds != pi->stopped_cmds)
  8142. return -1;
  8143. /* All processes in fg pipe have exited or stopped */
  8144. rcode = 0;
  8145. i = pi->num_cmds;
  8146. while (--i >= 0) {
  8147. rcode = pi->cmds[i].cmd_exitcode;
  8148. /* usually last process gives overall exitstatus,
  8149. * but with "set -o pipefail", last *failed* process does */
  8150. if (G.o_opt[OPT_O_PIPEFAIL] == 0 || rcode != 0)
  8151. break;
  8152. }
  8153. IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
  8154. return rcode;
  8155. }
  8156. static int process_wait_result(struct pipe *fg_pipe, pid_t childpid, int status)
  8157. {
  8158. #if ENABLE_HUSH_JOB
  8159. struct pipe *pi;
  8160. #endif
  8161. int i, dead;
  8162. dead = WIFEXITED(status) || WIFSIGNALED(status);
  8163. #if DEBUG_JOBS
  8164. if (WIFSTOPPED(status))
  8165. debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
  8166. childpid, WSTOPSIG(status), WEXITSTATUS(status));
  8167. if (WIFSIGNALED(status))
  8168. debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
  8169. childpid, WTERMSIG(status), WEXITSTATUS(status));
  8170. if (WIFEXITED(status))
  8171. debug_printf_jobs("pid %d exited, exitcode %d\n",
  8172. childpid, WEXITSTATUS(status));
  8173. #endif
  8174. /* Were we asked to wait for a fg pipe? */
  8175. if (fg_pipe) {
  8176. i = fg_pipe->num_cmds;
  8177. while (--i >= 0) {
  8178. int rcode;
  8179. debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
  8180. if (fg_pipe->cmds[i].pid != childpid)
  8181. continue;
  8182. if (dead) {
  8183. int ex;
  8184. fg_pipe->cmds[i].pid = 0;
  8185. fg_pipe->alive_cmds--;
  8186. ex = WEXITSTATUS(status);
  8187. /* bash prints killer signal's name for *last*
  8188. * process in pipe (prints just newline for SIGINT/SIGPIPE).
  8189. * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
  8190. */
  8191. if (WIFSIGNALED(status)) {
  8192. int sig = WTERMSIG(status);
  8193. #if ENABLE_HUSH_JOB
  8194. if (G.run_list_level == 1
  8195. /* ^^^^^ Do not print in nested contexts, example:
  8196. * echo `sleep 1; sh -c 'kill -9 $$'` - prints "137", NOT "Killed 137"
  8197. */
  8198. && i == fg_pipe->num_cmds-1
  8199. ) {
  8200. /* strsignal() is for bash compat. ~600 bloat versus bbox's get_signame() */
  8201. puts(sig == SIGINT || sig == SIGPIPE ? "" : strsignal(sig));
  8202. }
  8203. #endif
  8204. /* TODO: if (WCOREDUMP(status)) + " (core dumped)"; */
  8205. /* MIPS has 128 sigs (1..128), if sig==128,
  8206. * 128 + sig would result in exitcode 256 -> 0!
  8207. */
  8208. ex = 128 | sig;
  8209. }
  8210. fg_pipe->cmds[i].cmd_exitcode = ex;
  8211. } else {
  8212. fg_pipe->stopped_cmds++;
  8213. }
  8214. debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
  8215. fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
  8216. rcode = job_exited_or_stopped(fg_pipe);
  8217. if (rcode >= 0) {
  8218. /* Note: *non-interactive* bash does not continue if all processes in fg pipe
  8219. * are stopped. Testcase: "cat | cat" in a script (not on command line!)
  8220. * and "killall -STOP cat" */
  8221. if (G_interactive_fd) {
  8222. #if ENABLE_HUSH_JOB
  8223. if (fg_pipe->alive_cmds != 0)
  8224. insert_job_into_table(fg_pipe);
  8225. #endif
  8226. return rcode;
  8227. }
  8228. if (fg_pipe->alive_cmds == 0)
  8229. return rcode;
  8230. }
  8231. /* There are still running processes in the fg_pipe */
  8232. return -1;
  8233. }
  8234. /* It wasn't in fg_pipe, look for process in bg pipes */
  8235. }
  8236. #if ENABLE_HUSH_JOB
  8237. /* We were asked to wait for bg or orphaned children */
  8238. /* No need to remember exitcode in this case */
  8239. for (pi = G.job_list; pi; pi = pi->next) {
  8240. for (i = 0; i < pi->num_cmds; i++) {
  8241. if (pi->cmds[i].pid == childpid)
  8242. goto found_pi_and_prognum;
  8243. }
  8244. }
  8245. /* Happens when shell is used as init process (init=/bin/sh) */
  8246. debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
  8247. return -1; /* this wasn't a process from fg_pipe */
  8248. found_pi_and_prognum:
  8249. if (dead) {
  8250. /* child exited */
  8251. int rcode = WEXITSTATUS(status);
  8252. if (WIFSIGNALED(status))
  8253. /* NB: not 128 + sig, MIPS has sig 128 */
  8254. rcode = 128 | WTERMSIG(status);
  8255. pi->cmds[i].cmd_exitcode = rcode;
  8256. if (G.last_bg_pid == pi->cmds[i].pid)
  8257. G.last_bg_pid_exitcode = rcode;
  8258. pi->cmds[i].pid = 0;
  8259. pi->alive_cmds--;
  8260. if (!pi->alive_cmds) {
  8261. # if ENABLE_HUSH_BASH_COMPAT
  8262. G.dead_job_exitcode = job_exited_or_stopped(pi);
  8263. # endif
  8264. if (G_interactive_fd) {
  8265. printf(JOB_STATUS_FORMAT, pi->jobid,
  8266. "Done", pi->cmdtext);
  8267. delete_finished_job(pi);
  8268. } else {
  8269. /*
  8270. * bash deletes finished jobs from job table only in interactive mode,
  8271. * after "jobs" cmd, or if pid of a new process matches one of the old ones
  8272. * (see cleanup_dead_jobs(), delete_old_job(), J_NOTIFIED in bash source).
  8273. * Testcase script: "(exit 3) & sleep 1; wait %1; echo $?" prints 3 in bash.
  8274. * We only retain one "dead" job, if it's the single job on the list.
  8275. * This covers most of real-world scenarios where this is useful.
  8276. */
  8277. if (pi != G.job_list)
  8278. delete_finished_job(pi);
  8279. }
  8280. }
  8281. } else {
  8282. /* child stopped */
  8283. pi->stopped_cmds++;
  8284. }
  8285. #endif
  8286. return -1; /* this wasn't a process from fg_pipe */
  8287. }
  8288. /* Check to see if any processes have exited -- if they have,
  8289. * figure out why and see if a job has completed.
  8290. *
  8291. * If non-NULL fg_pipe: wait for its completion or stop.
  8292. * Return its exitcode or zero if stopped.
  8293. *
  8294. * Alternatively (fg_pipe == NULL, waitfor_pid != 0):
  8295. * waitpid(WNOHANG), if waitfor_pid exits or stops, return exitcode+1,
  8296. * else return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
  8297. * or 0 if no children changed status.
  8298. *
  8299. * Alternatively (fg_pipe == NULL, waitfor_pid == 0),
  8300. * return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
  8301. * or 0 if no children changed status.
  8302. */
  8303. static int checkjobs(struct pipe *fg_pipe, pid_t waitfor_pid)
  8304. {
  8305. int attributes;
  8306. int status;
  8307. int rcode = 0;
  8308. debug_printf_jobs("checkjobs %p\n", fg_pipe);
  8309. attributes = WUNTRACED;
  8310. if (fg_pipe == NULL)
  8311. attributes |= WNOHANG;
  8312. errno = 0;
  8313. #if ENABLE_HUSH_FAST
  8314. if (G.handled_SIGCHLD == G.count_SIGCHLD) {
  8315. //bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
  8316. //getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
  8317. /* There was neither fork nor SIGCHLD since last waitpid */
  8318. /* Avoid doing waitpid syscall if possible */
  8319. if (!G.we_have_children) {
  8320. errno = ECHILD;
  8321. return -1;
  8322. }
  8323. if (fg_pipe == NULL) { /* is WNOHANG set? */
  8324. /* We have children, but they did not exit
  8325. * or stop yet (we saw no SIGCHLD) */
  8326. return 0;
  8327. }
  8328. /* else: !WNOHANG, waitpid will block, can't short-circuit */
  8329. }
  8330. #endif
  8331. /* Do we do this right?
  8332. * bash-3.00# sleep 20 | false
  8333. * <ctrl-Z pressed>
  8334. * [3]+ Stopped sleep 20 | false
  8335. * bash-3.00# echo $?
  8336. * 1 <========== bg pipe is not fully done, but exitcode is already known!
  8337. * [hush 1.14.0: yes we do it right]
  8338. */
  8339. while (1) {
  8340. pid_t childpid;
  8341. #if ENABLE_HUSH_FAST
  8342. int i;
  8343. i = G.count_SIGCHLD;
  8344. #endif
  8345. childpid = waitpid(-1, &status, attributes);
  8346. if (childpid <= 0) {
  8347. if (childpid && errno != ECHILD)
  8348. bb_simple_perror_msg("waitpid");
  8349. #if ENABLE_HUSH_FAST
  8350. else { /* Until next SIGCHLD, waitpid's are useless */
  8351. G.we_have_children = (childpid == 0);
  8352. G.handled_SIGCHLD = i;
  8353. //bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
  8354. }
  8355. #endif
  8356. /* ECHILD (no children), or 0 (no change in children status) */
  8357. rcode = childpid;
  8358. break;
  8359. }
  8360. rcode = process_wait_result(fg_pipe, childpid, status);
  8361. if (rcode >= 0) {
  8362. /* fg_pipe exited or stopped */
  8363. break;
  8364. }
  8365. if (childpid == waitfor_pid) { /* "wait PID" */
  8366. debug_printf_exec("childpid==waitfor_pid:%d status:0x%08x\n", childpid, status);
  8367. rcode = WEXITSTATUS(status);
  8368. if (WIFSIGNALED(status))
  8369. rcode = 128 | WTERMSIG(status);
  8370. if (WIFSTOPPED(status))
  8371. /* bash: "cmd & wait $!" and cmd stops: $? = 128 | stopsig */
  8372. rcode = 128 | WSTOPSIG(status);
  8373. rcode++;
  8374. break; /* "wait PID" called us, give it exitcode+1 */
  8375. }
  8376. #if ENABLE_HUSH_BASH_COMPAT
  8377. if (-1 == waitfor_pid /* "wait -n" (wait for any one job) */
  8378. && G.dead_job_exitcode >= 0 /* some job did finish */
  8379. ) {
  8380. debug_printf_exec("waitfor_pid:-1\n");
  8381. rcode = G.dead_job_exitcode + 1;
  8382. break;
  8383. }
  8384. #endif
  8385. /* This wasn't one of our processes, or */
  8386. /* fg_pipe still has running processes, do waitpid again */
  8387. } /* while (waitpid succeeds)... */
  8388. return rcode;
  8389. }
  8390. #if ENABLE_HUSH_JOB
  8391. static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
  8392. {
  8393. pid_t p;
  8394. int rcode = checkjobs(fg_pipe, 0 /*(no pid to wait for)*/);
  8395. if (G_saved_tty_pgrp) {
  8396. /* Job finished, move the shell to the foreground */
  8397. p = getpgrp(); /* our process group id */
  8398. debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
  8399. tcsetpgrp(G_interactive_fd, p);
  8400. }
  8401. return rcode;
  8402. }
  8403. #endif
  8404. /* Start all the jobs, but don't wait for anything to finish.
  8405. * See checkjobs().
  8406. *
  8407. * Return code is normally -1, when the caller has to wait for children
  8408. * to finish to determine the exit status of the pipe. If the pipe
  8409. * is a simple builtin command, however, the action is done by the
  8410. * time run_pipe returns, and the exit code is provided as the
  8411. * return value.
  8412. *
  8413. * Returns -1 only if started some children. IOW: we have to
  8414. * mask out retvals of builtins etc with 0xff!
  8415. *
  8416. * The only case when we do not need to [v]fork is when the pipe
  8417. * is single, non-backgrounded, non-subshell command. Examples:
  8418. * cmd ; ... { list } ; ...
  8419. * cmd && ... { list } && ...
  8420. * cmd || ... { list } || ...
  8421. * If it is, then we can run cmd as a builtin, NOFORK,
  8422. * or (if SH_STANDALONE) an applet, and we can run the { list }
  8423. * with run_list. If it isn't one of these, we fork and exec cmd.
  8424. *
  8425. * Cases when we must fork:
  8426. * non-single: cmd | cmd
  8427. * backgrounded: cmd & { list } &
  8428. * subshell: ( list ) [&]
  8429. */
  8430. #if !ENABLE_HUSH_MODE_X
  8431. #define redirect_and_varexp_helper(command, sqp, argv_expanded) \
  8432. redirect_and_varexp_helper(command, sqp)
  8433. #endif
  8434. static int redirect_and_varexp_helper(
  8435. struct command *command,
  8436. struct squirrel **sqp,
  8437. char **argv_expanded)
  8438. {
  8439. /* Assignments occur before redirects. Try:
  8440. * a=`sleep 1` sleep 2 3>/qwe/rty
  8441. */
  8442. char **new_env = expand_assignments(command->argv, command->assignment_cnt);
  8443. dump_cmd_in_x_mode(new_env);
  8444. dump_cmd_in_x_mode(argv_expanded);
  8445. /* this takes ownership of new_env[i] elements, and frees new_env: */
  8446. set_vars_and_save_old(new_env);
  8447. return setup_redirects(command, sqp);
  8448. }
  8449. static NOINLINE int run_pipe(struct pipe *pi)
  8450. {
  8451. static const char *const null_ptr = NULL;
  8452. int cmd_no;
  8453. int next_infd;
  8454. struct command *command;
  8455. char **argv_expanded;
  8456. char **argv;
  8457. struct squirrel *squirrel = NULL;
  8458. int rcode;
  8459. debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
  8460. debug_enter();
  8461. /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
  8462. * Result should be 3 lines: q w e, qwe, q w e
  8463. */
  8464. if (G.ifs_whitespace != G.ifs)
  8465. free(G.ifs_whitespace);
  8466. G.ifs = get_local_var_value("IFS");
  8467. if (G.ifs) {
  8468. char *p;
  8469. G.ifs_whitespace = (char*)G.ifs;
  8470. p = skip_whitespace(G.ifs);
  8471. if (*p) {
  8472. /* Not all $IFS is whitespace */
  8473. char *d;
  8474. int len = p - G.ifs;
  8475. p = skip_non_whitespace(p);
  8476. G.ifs_whitespace = xmalloc(len + strlen(p) + 1); /* can overestimate */
  8477. d = mempcpy(G.ifs_whitespace, G.ifs, len);
  8478. while (*p) {
  8479. if (isspace(*p))
  8480. *d++ = *p;
  8481. p++;
  8482. }
  8483. *d = '\0';
  8484. }
  8485. } else {
  8486. G.ifs = defifs;
  8487. G.ifs_whitespace = (char*)G.ifs;
  8488. }
  8489. IF_HUSH_JOB(pi->pgrp = -1;)
  8490. pi->stopped_cmds = 0;
  8491. command = &pi->cmds[0];
  8492. argv_expanded = NULL;
  8493. if (pi->num_cmds != 1
  8494. || pi->followup == PIPE_BG
  8495. || command->cmd_type == CMD_SUBSHELL
  8496. ) {
  8497. goto must_fork;
  8498. }
  8499. pi->alive_cmds = 1;
  8500. debug_printf_exec(": group:%p argv:'%s'\n",
  8501. command->group, command->argv ? command->argv[0] : "NONE");
  8502. if (command->group) {
  8503. #if ENABLE_HUSH_FUNCTIONS
  8504. if (command->cmd_type == CMD_FUNCDEF) {
  8505. /* "executing" func () { list } */
  8506. struct function *funcp;
  8507. funcp = new_function(command->argv[0]);
  8508. /* funcp->name is already set to argv[0] */
  8509. funcp->body = command->group;
  8510. # if !BB_MMU
  8511. funcp->body_as_string = command->group_as_string;
  8512. command->group_as_string = NULL;
  8513. # endif
  8514. command->group = NULL;
  8515. command->argv[0] = NULL;
  8516. debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
  8517. funcp->parent_cmd = command;
  8518. command->child_func = funcp;
  8519. debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
  8520. debug_leave();
  8521. return EXIT_SUCCESS;
  8522. }
  8523. #endif
  8524. /* { list } */
  8525. debug_printf_exec("non-subshell group\n");
  8526. rcode = 1; /* exitcode if redir failed */
  8527. if (setup_redirects(command, &squirrel) == 0) {
  8528. debug_printf_exec(": run_list\n");
  8529. //FIXME: we need to pass squirrel down into run_list()
  8530. //for SH_STANDALONE case, or else this construct:
  8531. // { find /proc/self/fd; true; } >FILE; cmd2
  8532. //has no way of closing saved fd#1 for "find",
  8533. //and in SH_STANDALONE mode, "find" is not execed,
  8534. //therefore CLOEXEC on saved fd does not help.
  8535. rcode = run_list(command->group) & 0xff;
  8536. }
  8537. restore_redirects(squirrel);
  8538. IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
  8539. debug_leave();
  8540. debug_printf_exec("run_pipe: return %d\n", rcode);
  8541. return rcode;
  8542. }
  8543. argv = command->argv ? command->argv : (char **) &null_ptr;
  8544. {
  8545. const struct built_in_command *x;
  8546. IF_HUSH_FUNCTIONS(const struct function *funcp;)
  8547. IF_NOT_HUSH_FUNCTIONS(enum { funcp = 0 };)
  8548. struct variable **sv_shadowed;
  8549. struct variable *old_vars;
  8550. #if ENABLE_HUSH_LINENO_VAR
  8551. G.execute_lineno = command->lineno;
  8552. #endif
  8553. if (argv[command->assignment_cnt] == NULL) {
  8554. /* Assignments, but no command.
  8555. * Ensure redirects take effect (that is, create files).
  8556. * Try "a=t >file"
  8557. */
  8558. unsigned i;
  8559. G.expand_exitcode = 0;
  8560. only_assignments:
  8561. rcode = setup_redirects(command, &squirrel);
  8562. restore_redirects(squirrel);
  8563. /* Set shell variables */
  8564. i = 0;
  8565. while (i < command->assignment_cnt) {
  8566. char *p = expand_string_to_string(argv[i],
  8567. EXP_FLAG_ESC_GLOB_CHARS,
  8568. /*unbackslash:*/ 1
  8569. );
  8570. #if ENABLE_HUSH_MODE_X
  8571. if (G_x_mode) {
  8572. char *eq;
  8573. if (i == 0)
  8574. x_mode_prefix();
  8575. x_mode_addchr(' ');
  8576. eq = strchrnul(p, '=');
  8577. if (*eq) eq++;
  8578. x_mode_addblock(p, (eq - p));
  8579. x_mode_print_optionally_squoted(eq);
  8580. x_mode_flush();
  8581. }
  8582. #endif
  8583. debug_printf_env("set shell var:'%s'->'%s'\n", *argv, p);
  8584. if (set_local_var(p, /*flag:*/ 0)) {
  8585. /* assignment to readonly var / putenv error? */
  8586. rcode = 1;
  8587. }
  8588. i++;
  8589. }
  8590. /* Redirect error sets $? to 1. Otherwise,
  8591. * if evaluating assignment value set $?, retain it.
  8592. * Else, clear $?:
  8593. * false; q=`exit 2`; echo $? - should print 2
  8594. * false; x=1; echo $? - should print 0
  8595. * Because of the 2nd case, we can't just use G.last_exitcode.
  8596. */
  8597. if (rcode == 0)
  8598. rcode = G.expand_exitcode;
  8599. IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
  8600. debug_leave();
  8601. debug_printf_exec("run_pipe: return %d\n", rcode);
  8602. return rcode;
  8603. }
  8604. /* Expand the rest into (possibly) many strings each */
  8605. #if defined(CMD_TEST2_SINGLEWORD_NOGLOB)
  8606. if (command->cmd_type == CMD_TEST2_SINGLEWORD_NOGLOB)
  8607. argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
  8608. else
  8609. #endif
  8610. #if defined(CMD_SINGLEWORD_NOGLOB)
  8611. if (command->cmd_type == CMD_SINGLEWORD_NOGLOB)
  8612. argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
  8613. else
  8614. #endif
  8615. argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
  8616. /* If someone gives us an empty string: `cmd with empty output` */
  8617. if (!argv_expanded[0]) {
  8618. free(argv_expanded);
  8619. /* `false` still has to set exitcode 1 */
  8620. G.expand_exitcode = G.last_exitcode;
  8621. goto only_assignments;
  8622. }
  8623. old_vars = NULL;
  8624. sv_shadowed = G.shadowed_vars_pp;
  8625. /* Check if argv[0] matches any functions (this goes before bltins) */
  8626. IF_HUSH_FUNCTIONS(funcp = find_function(argv_expanded[0]);)
  8627. IF_HUSH_FUNCTIONS(x = NULL;)
  8628. IF_HUSH_FUNCTIONS(if (!funcp))
  8629. x = find_builtin(argv_expanded[0]);
  8630. if (x || funcp) {
  8631. if (x && x->b_function == builtin_exec && argv_expanded[1] == NULL) {
  8632. debug_printf("exec with redirects only\n");
  8633. /*
  8634. * Variable assignments are executed, but then "forgotten":
  8635. * a=`sleep 1;echo A` exec 3>&-; echo $a
  8636. * sleeps, but prints nothing.
  8637. */
  8638. enter_var_nest_level();
  8639. G.shadowed_vars_pp = &old_vars;
  8640. rcode = redirect_and_varexp_helper(command,
  8641. /*squirrel:*/ ERR_PTR,
  8642. argv_expanded
  8643. );
  8644. G.shadowed_vars_pp = sv_shadowed;
  8645. /* rcode=1 can be if redir file can't be opened */
  8646. goto clean_up_and_ret1;
  8647. }
  8648. /* Bump var nesting, or this will leak exported $a:
  8649. * a=b true; env | grep ^a=
  8650. */
  8651. enter_var_nest_level();
  8652. /* Collect all variables "shadowed" by helper
  8653. * (IOW: old vars overridden by "var1=val1 var2=val2 cmd..." syntax)
  8654. * into old_vars list:
  8655. */
  8656. G.shadowed_vars_pp = &old_vars;
  8657. rcode = redirect_and_varexp_helper(command, &squirrel, argv_expanded);
  8658. if (rcode == 0) {
  8659. if (!funcp) {
  8660. /* Do not collect *to old_vars list* vars shadowed
  8661. * by e.g. "local VAR" builtin (collect them
  8662. * in the previously nested list instead):
  8663. * don't want them to be restored immediately
  8664. * after "local" completes.
  8665. */
  8666. G.shadowed_vars_pp = sv_shadowed;
  8667. debug_printf_exec(": builtin '%s' '%s'...\n",
  8668. x->b_cmd, argv_expanded[1]);
  8669. fflush_all();
  8670. rcode = x->b_function(argv_expanded) & 0xff;
  8671. fflush_all();
  8672. }
  8673. #if ENABLE_HUSH_FUNCTIONS
  8674. else {
  8675. debug_printf_exec(": function '%s' '%s'...\n",
  8676. funcp->name, argv_expanded[1]);
  8677. rcode = run_function(funcp, argv_expanded) & 0xff;
  8678. /*
  8679. * But do collect *to old_vars list* vars shadowed
  8680. * within function execution. To that end, restore
  8681. * this pointer _after_ function run:
  8682. */
  8683. G.shadowed_vars_pp = sv_shadowed;
  8684. }
  8685. #endif
  8686. }
  8687. } else
  8688. if (ENABLE_FEATURE_SH_NOFORK && NUM_APPLETS > 1) {
  8689. int n = find_applet_by_name(argv_expanded[0]);
  8690. if (n < 0 || !APPLET_IS_NOFORK(n))
  8691. goto must_fork;
  8692. enter_var_nest_level();
  8693. /* Collect all variables "shadowed" by helper into old_vars list */
  8694. G.shadowed_vars_pp = &old_vars;
  8695. rcode = redirect_and_varexp_helper(command, &squirrel, argv_expanded);
  8696. G.shadowed_vars_pp = sv_shadowed;
  8697. if (rcode == 0) {
  8698. debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
  8699. argv_expanded[0], argv_expanded[1]);
  8700. /*
  8701. * Note: signals (^C) can't interrupt here.
  8702. * We remember them and they will be acted upon
  8703. * after applet returns.
  8704. * This makes applets which can run for a long time
  8705. * and/or wait for user input ineligible for NOFORK:
  8706. * for example, "yes" or "rm" (rm -i waits for input).
  8707. */
  8708. rcode = run_nofork_applet(n, argv_expanded);
  8709. }
  8710. } else
  8711. goto must_fork;
  8712. restore_redirects(squirrel);
  8713. clean_up_and_ret1:
  8714. leave_var_nest_level();
  8715. add_vars(old_vars);
  8716. /*
  8717. * Try "usleep 99999999" + ^C + "echo $?"
  8718. * with FEATURE_SH_NOFORK=y.
  8719. */
  8720. if (!funcp) {
  8721. /* It was builtin or nofork.
  8722. * if this would be a real fork/execed program,
  8723. * it should have died if a fatal sig was received.
  8724. * But OTOH, there was no separate process,
  8725. * the sig was sent to _shell_, not to non-existing
  8726. * child.
  8727. * Let's just handle ^C only, this one is obvious:
  8728. * we aren't ok with exitcode 0 when ^C was pressed
  8729. * during builtin/nofork.
  8730. */
  8731. if (sigismember(&G.pending_set, SIGINT))
  8732. rcode = 128 | SIGINT;
  8733. }
  8734. free(argv_expanded);
  8735. IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
  8736. debug_leave();
  8737. debug_printf_exec("run_pipe return %d\n", rcode);
  8738. return rcode;
  8739. }
  8740. must_fork:
  8741. /* NB: argv_expanded may already be created, and that
  8742. * might include `cmd` runs! Do not rerun it! We *must*
  8743. * use argv_expanded if it's non-NULL */
  8744. /* Going to fork a child per each pipe member */
  8745. pi->alive_cmds = 0;
  8746. next_infd = 0;
  8747. cmd_no = 0;
  8748. while (cmd_no < pi->num_cmds) {
  8749. struct fd_pair pipefds;
  8750. #if !BB_MMU
  8751. int sv_var_nest_level = G.var_nest_level;
  8752. volatile nommu_save_t nommu_save;
  8753. nommu_save.old_vars = NULL;
  8754. nommu_save.argv = NULL;
  8755. nommu_save.argv_from_re_execing = NULL;
  8756. #endif
  8757. command = &pi->cmds[cmd_no];
  8758. cmd_no++;
  8759. if (command->argv) {
  8760. debug_printf_exec(": pipe member '%s' '%s'...\n",
  8761. command->argv[0], command->argv[1]);
  8762. } else {
  8763. debug_printf_exec(": pipe member with no argv\n");
  8764. }
  8765. /* pipes are inserted between pairs of commands */
  8766. pipefds.rd = 0;
  8767. pipefds.wr = 1;
  8768. if (cmd_no < pi->num_cmds)
  8769. xpiped_pair(pipefds);
  8770. #if ENABLE_HUSH_LINENO_VAR
  8771. G.execute_lineno = command->lineno;
  8772. #endif
  8773. command->pid = BB_MMU ? fork() : vfork();
  8774. if (!command->pid) { /* child */
  8775. #if ENABLE_HUSH_JOB
  8776. disable_restore_tty_pgrp_on_exit();
  8777. CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
  8778. /* Every child adds itself to new process group
  8779. * with pgid == pid_of_first_child_in_pipe */
  8780. if (G.run_list_level == 1 && G_interactive_fd) {
  8781. pid_t pgrp;
  8782. pgrp = pi->pgrp;
  8783. if (pgrp < 0) /* true for 1st process only */
  8784. pgrp = getpid();
  8785. if (setpgid(0, pgrp) == 0
  8786. && pi->followup != PIPE_BG
  8787. && G_saved_tty_pgrp /* we have ctty */
  8788. ) {
  8789. /* We do it in *every* child, not just first,
  8790. * to avoid races */
  8791. tcsetpgrp(G_interactive_fd, pgrp);
  8792. }
  8793. }
  8794. #endif
  8795. if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
  8796. /* 1st cmd in backgrounded pipe
  8797. * should have its stdin /dev/null'ed */
  8798. close(0);
  8799. if (open(bb_dev_null, O_RDONLY))
  8800. xopen("/", O_RDONLY);
  8801. } else {
  8802. xmove_fd(next_infd, 0);
  8803. }
  8804. xmove_fd(pipefds.wr, 1);
  8805. if (pipefds.rd > 1)
  8806. close(pipefds.rd);
  8807. /* Like bash, explicit redirects override pipes,
  8808. * and the pipe fd (fd#1) is available for dup'ing:
  8809. * "cmd1 2>&1 | cmd2": fd#1 is duped to fd#2, thus stderr
  8810. * of cmd1 goes into pipe.
  8811. */
  8812. if (setup_redirects(command, NULL)) {
  8813. /* Happens when redir file can't be opened:
  8814. * $ hush -c 'echo FOO >&2 | echo BAR 3>/qwe/rty; echo BAZ'
  8815. * FOO
  8816. * hush: can't open '/qwe/rty': No such file or directory
  8817. * BAZ
  8818. * (echo BAR is not executed, it hits _exit(1) below)
  8819. */
  8820. _exit(1);
  8821. }
  8822. /* Stores to nommu_save list of env vars putenv'ed
  8823. * (NOMMU, on MMU we don't need that) */
  8824. /* cast away volatility... */
  8825. pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
  8826. /* pseudo_exec() does not return */
  8827. }
  8828. /* parent or error */
  8829. #if ENABLE_HUSH_FAST
  8830. G.count_SIGCHLD++;
  8831. //bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
  8832. #endif
  8833. enable_restore_tty_pgrp_on_exit();
  8834. #if !BB_MMU
  8835. /* Clean up after vforked child */
  8836. free(nommu_save.argv);
  8837. free(nommu_save.argv_from_re_execing);
  8838. G.var_nest_level = sv_var_nest_level;
  8839. remove_nested_vars();
  8840. add_vars(nommu_save.old_vars);
  8841. #endif
  8842. free(argv_expanded);
  8843. argv_expanded = NULL;
  8844. if (command->pid < 0) { /* [v]fork failed */
  8845. /* Clearly indicate, was it fork or vfork */
  8846. bb_simple_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
  8847. } else {
  8848. pi->alive_cmds++;
  8849. #if ENABLE_HUSH_JOB
  8850. /* Second and next children need to know pid of first one */
  8851. if (pi->pgrp < 0)
  8852. pi->pgrp = command->pid;
  8853. #endif
  8854. }
  8855. if (cmd_no > 1)
  8856. close(next_infd);
  8857. if (cmd_no < pi->num_cmds)
  8858. close(pipefds.wr);
  8859. /* Pass read (output) pipe end to next iteration */
  8860. next_infd = pipefds.rd;
  8861. }
  8862. if (!pi->alive_cmds) {
  8863. debug_leave();
  8864. debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
  8865. return 1;
  8866. }
  8867. debug_leave();
  8868. debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
  8869. return -1;
  8870. }
  8871. /* NB: called by pseudo_exec, and therefore must not modify any
  8872. * global data until exec/_exit (we can be a child after vfork!) */
  8873. static int run_list(struct pipe *pi)
  8874. {
  8875. #if ENABLE_HUSH_CASE
  8876. char *case_word = NULL;
  8877. #endif
  8878. #if ENABLE_HUSH_LOOPS
  8879. struct pipe *loop_top = NULL;
  8880. char **for_lcur = NULL;
  8881. char **for_list = NULL;
  8882. #endif
  8883. smallint last_followup;
  8884. smalluint rcode;
  8885. #if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
  8886. smalluint cond_code = 0;
  8887. #else
  8888. enum { cond_code = 0 };
  8889. #endif
  8890. #if HAS_KEYWORDS
  8891. smallint rword; /* RES_foo */
  8892. smallint last_rword; /* ditto */
  8893. #endif
  8894. debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
  8895. debug_enter();
  8896. #if ENABLE_HUSH_LOOPS
  8897. /* Check syntax for "for" */
  8898. {
  8899. struct pipe *cpipe;
  8900. for (cpipe = pi; cpipe; cpipe = cpipe->next) {
  8901. if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
  8902. continue;
  8903. /* current word is FOR or IN (BOLD in comments below) */
  8904. if (cpipe->next == NULL) {
  8905. syntax_error("malformed for");
  8906. debug_leave();
  8907. debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
  8908. return 1;
  8909. }
  8910. /* "FOR v; do ..." and "for v IN a b; do..." are ok */
  8911. if (cpipe->next->res_word == RES_DO)
  8912. continue;
  8913. /* next word is not "do". It must be "in" then ("FOR v in ...") */
  8914. if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
  8915. || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
  8916. ) {
  8917. syntax_error("malformed for");
  8918. debug_leave();
  8919. debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
  8920. return 1;
  8921. }
  8922. }
  8923. }
  8924. #endif
  8925. /* Past this point, all code paths should jump to ret: label
  8926. * in order to return, no direct "return" statements please.
  8927. * This helps to ensure that no memory is leaked. */
  8928. #if ENABLE_HUSH_JOB
  8929. G.run_list_level++;
  8930. #endif
  8931. #if HAS_KEYWORDS
  8932. rword = RES_NONE;
  8933. last_rword = RES_XXXX;
  8934. #endif
  8935. last_followup = PIPE_SEQ;
  8936. rcode = G.last_exitcode;
  8937. /* Go through list of pipes, (maybe) executing them. */
  8938. for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
  8939. int r;
  8940. int sv_errexit_depth;
  8941. if (G.flag_SIGINT)
  8942. break;
  8943. if (G_flag_return_in_progress == 1)
  8944. break;
  8945. IF_HAS_KEYWORDS(rword = pi->res_word;)
  8946. debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
  8947. rword, cond_code, last_rword);
  8948. sv_errexit_depth = G.errexit_depth;
  8949. if (
  8950. #if ENABLE_HUSH_IF
  8951. rword == RES_IF || rword == RES_ELIF ||
  8952. #endif
  8953. pi->followup != PIPE_SEQ
  8954. ) {
  8955. G.errexit_depth++;
  8956. }
  8957. #if ENABLE_HUSH_LOOPS
  8958. if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
  8959. && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
  8960. ) {
  8961. /* start of a loop: remember where loop starts */
  8962. loop_top = pi;
  8963. G.depth_of_loop++;
  8964. }
  8965. #endif
  8966. /* Still in the same "if...", "then..." or "do..." branch? */
  8967. if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
  8968. if ((rcode == 0 && last_followup == PIPE_OR)
  8969. || (rcode != 0 && last_followup == PIPE_AND)
  8970. ) {
  8971. /* It is "<true> || CMD" or "<false> && CMD"
  8972. * and we should not execute CMD */
  8973. debug_printf_exec("skipped cmd because of || or &&\n");
  8974. last_followup = pi->followup;
  8975. goto dont_check_jobs_but_continue;
  8976. }
  8977. }
  8978. last_followup = pi->followup;
  8979. IF_HAS_KEYWORDS(last_rword = rword;)
  8980. #if ENABLE_HUSH_IF
  8981. if (cond_code) {
  8982. if (rword == RES_THEN) {
  8983. /* if false; then ... fi has exitcode 0! */
  8984. G.last_exitcode = rcode = EXIT_SUCCESS;
  8985. /* "if <false> THEN cmd": skip cmd */
  8986. continue;
  8987. }
  8988. } else {
  8989. if (rword == RES_ELSE || rword == RES_ELIF) {
  8990. /* "if <true> then ... ELSE/ELIF cmd":
  8991. * skip cmd and all following ones */
  8992. break;
  8993. }
  8994. }
  8995. #endif
  8996. #if ENABLE_HUSH_LOOPS
  8997. if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
  8998. if (!for_lcur) {
  8999. /* first loop through for */
  9000. static const char encoded_dollar_at[] ALIGN1 = {
  9001. SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
  9002. }; /* encoded representation of "$@" */
  9003. static const char *const encoded_dollar_at_argv[] = {
  9004. encoded_dollar_at, NULL
  9005. }; /* argv list with one element: "$@" */
  9006. char **vals;
  9007. G.last_exitcode = rcode = EXIT_SUCCESS;
  9008. vals = (char**)encoded_dollar_at_argv;
  9009. if (pi->next->res_word == RES_IN) {
  9010. /* if no variable values after "in" we skip "for" */
  9011. if (!pi->next->cmds[0].argv) {
  9012. debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
  9013. break;
  9014. }
  9015. vals = pi->next->cmds[0].argv;
  9016. } /* else: "for var; do..." -> assume "$@" list */
  9017. /* create list of variable values */
  9018. debug_print_strings("for_list made from", vals);
  9019. for_list = expand_strvec_to_strvec(vals);
  9020. for_lcur = for_list;
  9021. debug_print_strings("for_list", for_list);
  9022. }
  9023. if (!*for_lcur) {
  9024. /* "for" loop is over, clean up */
  9025. free(for_list);
  9026. for_list = NULL;
  9027. for_lcur = NULL;
  9028. break;
  9029. }
  9030. /* Insert next value from for_lcur */
  9031. /* note: *for_lcur already has quotes removed, $var expanded, etc */
  9032. set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*flag:*/ 0);
  9033. continue;
  9034. }
  9035. if (rword == RES_IN) {
  9036. continue; /* "for v IN list;..." - "in" has no cmds anyway */
  9037. }
  9038. if (rword == RES_DONE) {
  9039. continue; /* "done" has no cmds too */
  9040. }
  9041. #endif
  9042. #if ENABLE_HUSH_CASE
  9043. if (rword == RES_CASE) {
  9044. debug_printf_exec("CASE cond_code:%d\n", cond_code);
  9045. case_word = expand_string_to_string(pi->cmds->argv[0],
  9046. EXP_FLAG_ESC_GLOB_CHARS, /*unbackslash:*/ 1);
  9047. debug_printf_exec("CASE word1:'%s'\n", case_word);
  9048. //unbackslash(case_word);
  9049. //debug_printf_exec("CASE word2:'%s'\n", case_word);
  9050. continue;
  9051. }
  9052. if (rword == RES_MATCH) {
  9053. char **argv;
  9054. debug_printf_exec("MATCH cond_code:%d\n", cond_code);
  9055. if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
  9056. break;
  9057. /* all prev words didn't match, does this one match? */
  9058. argv = pi->cmds->argv;
  9059. while (*argv) {
  9060. char *pattern;
  9061. debug_printf_exec("expand_string_to_string('%s')\n", *argv);
  9062. pattern = expand_string_to_string(*argv,
  9063. EXP_FLAG_ESC_GLOB_CHARS,
  9064. /*unbackslash:*/ 0
  9065. );
  9066. /* TODO: which FNM_xxx flags to use? */
  9067. cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
  9068. debug_printf_exec("fnmatch(pattern:'%s',str:'%s'):%d\n",
  9069. pattern, case_word, cond_code);
  9070. free(pattern);
  9071. if (cond_code == 0) {
  9072. /* match! we will execute this branch */
  9073. free(case_word);
  9074. case_word = NULL; /* make future "word)" stop */
  9075. break;
  9076. }
  9077. argv++;
  9078. }
  9079. continue;
  9080. }
  9081. if (rword == RES_CASE_BODY) { /* inside of a case branch */
  9082. debug_printf_exec("CASE_BODY cond_code:%d\n", cond_code);
  9083. if (cond_code != 0)
  9084. continue; /* not matched yet, skip this pipe */
  9085. }
  9086. if (rword == RES_ESAC) {
  9087. debug_printf_exec("ESAC cond_code:%d\n", cond_code);
  9088. if (case_word) {
  9089. /* "case" did not match anything: still set $? (to 0) */
  9090. G.last_exitcode = rcode = EXIT_SUCCESS;
  9091. }
  9092. }
  9093. #endif
  9094. /* Just pressing <enter> in shell should check for jobs.
  9095. * OTOH, in non-interactive shell this is useless
  9096. * and only leads to extra job checks */
  9097. if (pi->num_cmds == 0) {
  9098. if (G_interactive_fd)
  9099. goto check_jobs_and_continue;
  9100. continue;
  9101. }
  9102. /* After analyzing all keywords and conditions, we decided
  9103. * to execute this pipe. NB: have to do checkjobs(NULL)
  9104. * after run_pipe to collect any background children,
  9105. * even if list execution is to be stopped. */
  9106. debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
  9107. #if ENABLE_HUSH_LOOPS
  9108. G.flag_break_continue = 0;
  9109. #endif
  9110. rcode = r = run_pipe(pi); /* NB: rcode is a smalluint, r is int */
  9111. if (r != -1) {
  9112. /* We ran a builtin, function, or group.
  9113. * rcode is already known
  9114. * and we don't need to wait for anything. */
  9115. debug_printf_exec(": builtin/func exitcode %d\n", rcode);
  9116. G.last_exitcode = rcode;
  9117. check_and_run_traps();
  9118. #if ENABLE_HUSH_TRAP && ENABLE_HUSH_FUNCTIONS
  9119. rcode = G.last_exitcode; /* "return" in trap can change it, read back */
  9120. #endif
  9121. #if ENABLE_HUSH_LOOPS
  9122. /* Was it "break" or "continue"? */
  9123. if (G.flag_break_continue) {
  9124. smallint fbc = G.flag_break_continue;
  9125. /* We might fall into outer *loop*,
  9126. * don't want to break it too */
  9127. if (loop_top) {
  9128. G.depth_break_continue--;
  9129. if (G.depth_break_continue == 0)
  9130. G.flag_break_continue = 0;
  9131. /* else: e.g. "continue 2" should *break* once, *then* continue */
  9132. } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
  9133. if (G.depth_break_continue != 0 || fbc == BC_BREAK) {
  9134. checkjobs(NULL, 0 /*(no pid to wait for)*/);
  9135. break;
  9136. }
  9137. /* "continue": simulate end of loop */
  9138. rword = RES_DONE;
  9139. continue;
  9140. }
  9141. #endif
  9142. if (G_flag_return_in_progress == 1) {
  9143. checkjobs(NULL, 0 /*(no pid to wait for)*/);
  9144. break;
  9145. }
  9146. } else if (pi->followup == PIPE_BG) {
  9147. /* What does bash do with attempts to background builtins? */
  9148. /* even bash 3.2 doesn't do that well with nested bg:
  9149. * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
  9150. * I'm NOT treating inner &'s as jobs */
  9151. #if ENABLE_HUSH_JOB
  9152. if (G.run_list_level == 1)
  9153. insert_job_into_table(pi);
  9154. #endif
  9155. /* Last command's pid goes to $! */
  9156. G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
  9157. G.last_bg_pid_exitcode = 0;
  9158. debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
  9159. /* Check pi->pi_inverted? "! sleep 1 & echo $?": bash says 1. dash and ash say 0 */
  9160. rcode = EXIT_SUCCESS;
  9161. goto check_traps;
  9162. } else {
  9163. #if ENABLE_HUSH_JOB
  9164. if (G.run_list_level == 1 && G_interactive_fd) {
  9165. /* Waits for completion, then fg's main shell */
  9166. rcode = checkjobs_and_fg_shell(pi);
  9167. debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
  9168. goto check_traps;
  9169. }
  9170. #endif
  9171. /* This one just waits for completion */
  9172. rcode = checkjobs(pi, 0 /*(no pid to wait for)*/);
  9173. debug_printf_exec(": checkjobs exitcode %d\n", rcode);
  9174. check_traps:
  9175. G.last_exitcode = rcode;
  9176. check_and_run_traps();
  9177. #if ENABLE_HUSH_TRAP && ENABLE_HUSH_FUNCTIONS
  9178. rcode = G.last_exitcode; /* "return" in trap can change it, read back */
  9179. #endif
  9180. }
  9181. /* Handle "set -e" */
  9182. if (rcode != 0 && G.o_opt[OPT_O_ERREXIT]) {
  9183. debug_printf_exec("ERREXIT:1 errexit_depth:%d\n", G.errexit_depth);
  9184. if (G.errexit_depth == 0)
  9185. hush_exit(rcode);
  9186. }
  9187. G.errexit_depth = sv_errexit_depth;
  9188. /* Analyze how result affects subsequent commands */
  9189. #if ENABLE_HUSH_IF
  9190. if (rword == RES_IF || rword == RES_ELIF)
  9191. cond_code = rcode;
  9192. #endif
  9193. check_jobs_and_continue:
  9194. checkjobs(NULL, 0 /*(no pid to wait for)*/);
  9195. dont_check_jobs_but_continue: ;
  9196. #if ENABLE_HUSH_LOOPS
  9197. /* Beware of "while false; true; do ..."! */
  9198. if (pi->next
  9199. && (pi->next->res_word == RES_DO || pi->next->res_word == RES_DONE)
  9200. /* check for RES_DONE is needed for "while ...; do \n done" case */
  9201. ) {
  9202. if (rword == RES_WHILE) {
  9203. if (rcode) {
  9204. /* "while false; do...done" - exitcode 0 */
  9205. G.last_exitcode = rcode = EXIT_SUCCESS;
  9206. debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
  9207. break;
  9208. }
  9209. }
  9210. if (rword == RES_UNTIL) {
  9211. if (!rcode) {
  9212. debug_printf_exec(": until expr is true: breaking\n");
  9213. break;
  9214. }
  9215. }
  9216. }
  9217. #endif
  9218. } /* for (pi) */
  9219. #if ENABLE_HUSH_JOB
  9220. G.run_list_level--;
  9221. #endif
  9222. #if ENABLE_HUSH_LOOPS
  9223. if (loop_top)
  9224. G.depth_of_loop--;
  9225. free(for_list);
  9226. #endif
  9227. #if ENABLE_HUSH_CASE
  9228. free(case_word);
  9229. #endif
  9230. debug_leave();
  9231. debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
  9232. return rcode;
  9233. }
  9234. /* Select which version we will use */
  9235. static int run_and_free_list(struct pipe *pi)
  9236. {
  9237. int rcode = 0;
  9238. debug_printf_exec("run_and_free_list entered\n");
  9239. if (!G.o_opt[OPT_O_NOEXEC]) {
  9240. debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
  9241. rcode = run_list(pi);
  9242. }
  9243. /* free_pipe_list has the side effect of clearing memory.
  9244. * In the long run that function can be merged with run_list,
  9245. * but doing that now would hobble the debugging effort. */
  9246. free_pipe_list(pi);
  9247. debug_printf_exec("run_and_free_list return %d\n", rcode);
  9248. return rcode;
  9249. }
  9250. static void install_sighandlers(unsigned mask)
  9251. {
  9252. sighandler_t old_handler;
  9253. unsigned sig = 0;
  9254. while ((mask >>= 1) != 0) {
  9255. sig++;
  9256. if (!(mask & 1))
  9257. continue;
  9258. old_handler = install_sighandler(sig, pick_sighandler(sig));
  9259. /* POSIX allows shell to re-enable SIGCHLD
  9260. * even if it was SIG_IGN on entry.
  9261. * Therefore we skip IGN check for it:
  9262. */
  9263. if (sig == SIGCHLD)
  9264. continue;
  9265. /* Interactive bash re-enables SIGHUP which is SIG_IGNed on entry.
  9266. * Try:
  9267. * trap '' hup; bash; echo RET # type "kill -hup $$", see SIGHUP having effect
  9268. * trap '' hup; bash -c 'kill -hup $$; echo ALIVE' # here SIGHUP is SIG_IGNed
  9269. */
  9270. if (sig == SIGHUP && G_interactive_fd)
  9271. continue;
  9272. /* Unless one of the above signals, is it SIG_IGN? */
  9273. if (old_handler == SIG_IGN) {
  9274. /* oops... restore back to IGN, and record this fact */
  9275. install_sighandler(sig, old_handler);
  9276. #if ENABLE_HUSH_TRAP
  9277. if (!G_traps)
  9278. G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
  9279. free(G_traps[sig]);
  9280. G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
  9281. #endif
  9282. }
  9283. }
  9284. }
  9285. /* Called a few times only (or even once if "sh -c") */
  9286. static void install_special_sighandlers(void)
  9287. {
  9288. unsigned mask;
  9289. /* Which signals are shell-special? */
  9290. mask = (1 << SIGQUIT) | (1 << SIGCHLD);
  9291. if (G_interactive_fd) {
  9292. mask |= SPECIAL_INTERACTIVE_SIGS;
  9293. if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
  9294. mask |= SPECIAL_JOBSTOP_SIGS;
  9295. }
  9296. /* Careful, do not re-install handlers we already installed */
  9297. if (G.special_sig_mask != mask) {
  9298. unsigned diff = mask & ~G.special_sig_mask;
  9299. G.special_sig_mask = mask;
  9300. install_sighandlers(diff);
  9301. }
  9302. }
  9303. #if ENABLE_HUSH_JOB
  9304. /* helper */
  9305. /* Set handlers to restore tty pgrp and exit */
  9306. static void install_fatal_sighandlers(void)
  9307. {
  9308. unsigned mask;
  9309. /* We will restore tty pgrp on these signals */
  9310. mask = 0
  9311. /*+ (1 << SIGILL ) * HUSH_DEBUG*/
  9312. /*+ (1 << SIGFPE ) * HUSH_DEBUG*/
  9313. + (1 << SIGBUS ) * HUSH_DEBUG
  9314. + (1 << SIGSEGV) * HUSH_DEBUG
  9315. /*+ (1 << SIGTRAP) * HUSH_DEBUG*/
  9316. + (1 << SIGABRT)
  9317. /* bash 3.2 seems to handle these just like 'fatal' ones */
  9318. + (1 << SIGPIPE)
  9319. + (1 << SIGALRM)
  9320. /* if we are interactive, SIGHUP, SIGTERM and SIGINT are special sigs.
  9321. * if we aren't interactive... but in this case
  9322. * we never want to restore pgrp on exit, and this fn is not called
  9323. */
  9324. /*+ (1 << SIGHUP )*/
  9325. /*+ (1 << SIGTERM)*/
  9326. /*+ (1 << SIGINT )*/
  9327. ;
  9328. G_fatal_sig_mask = mask;
  9329. install_sighandlers(mask);
  9330. }
  9331. #endif
  9332. static int set_mode(int state, char mode, const char *o_opt)
  9333. {
  9334. int idx;
  9335. switch (mode) {
  9336. case 'n':
  9337. G.o_opt[OPT_O_NOEXEC] = state;
  9338. break;
  9339. case 'x':
  9340. IF_HUSH_MODE_X(G_x_mode = state;)
  9341. IF_HUSH_MODE_X(if (G.x_mode_fd <= 0) G.x_mode_fd = dup_CLOEXEC(2, 10);)
  9342. break;
  9343. case 'e':
  9344. G.o_opt[OPT_O_ERREXIT] = state;
  9345. break;
  9346. case 'o':
  9347. if (!o_opt) {
  9348. /* "set -o" or "set +o" without parameter.
  9349. * in bash, set -o produces this output:
  9350. * pipefail off
  9351. * and set +o:
  9352. * set +o pipefail
  9353. * We always use the second form.
  9354. */
  9355. const char *p = o_opt_strings;
  9356. idx = 0;
  9357. while (*p) {
  9358. printf("set %co %s\n", (G.o_opt[idx] ? '-' : '+'), p);
  9359. idx++;
  9360. p += strlen(p) + 1;
  9361. }
  9362. break;
  9363. }
  9364. idx = index_in_strings(o_opt_strings, o_opt);
  9365. if (idx >= 0) {
  9366. G.o_opt[idx] = state;
  9367. break;
  9368. }
  9369. /* fall through to error */
  9370. default:
  9371. return EXIT_FAILURE;
  9372. }
  9373. return EXIT_SUCCESS;
  9374. }
  9375. int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  9376. int hush_main(int argc, char **argv)
  9377. {
  9378. pid_t cached_getpid;
  9379. enum {
  9380. OPT_login = (1 << 0),
  9381. };
  9382. unsigned flags;
  9383. #if !BB_MMU
  9384. unsigned builtin_argc = 0;
  9385. #endif
  9386. char **e;
  9387. struct variable *cur_var;
  9388. struct variable *shell_ver;
  9389. INIT_G();
  9390. if (EXIT_SUCCESS != 0) /* if EXIT_SUCCESS == 0, it is already done */
  9391. G.last_exitcode = EXIT_SUCCESS;
  9392. #if ENABLE_HUSH_TRAP
  9393. # if ENABLE_HUSH_FUNCTIONS
  9394. G.return_exitcode = -1;
  9395. # endif
  9396. G.pre_trap_exitcode = -1;
  9397. #endif
  9398. #if ENABLE_HUSH_FAST
  9399. G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
  9400. #endif
  9401. #if !BB_MMU
  9402. G.argv0_for_re_execing = argv[0];
  9403. #endif
  9404. cached_getpid = getpid(); /* for tcsetpgrp() during init */
  9405. G.root_pid = cached_getpid; /* for $PID (NOMMU can override via -$HEXPID:HEXPPID:...) */
  9406. G.root_ppid = getppid(); /* for $PPID (NOMMU can override) */
  9407. /* Deal with HUSH_VERSION */
  9408. debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
  9409. unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
  9410. shell_ver = xzalloc(sizeof(*shell_ver));
  9411. shell_ver->flg_export = 1;
  9412. shell_ver->flg_read_only = 1;
  9413. /* Code which handles ${var<op>...} needs writable values for all variables,
  9414. * therefore we xstrdup: */
  9415. shell_ver->varstr = xstrdup(hush_version_str);
  9416. /* Create shell local variables from the values
  9417. * currently living in the environment */
  9418. G.top_var = shell_ver;
  9419. cur_var = G.top_var;
  9420. e = environ;
  9421. if (e) while (*e) {
  9422. char *value = strchr(*e, '=');
  9423. if (value) { /* paranoia */
  9424. cur_var->next = xzalloc(sizeof(*cur_var));
  9425. cur_var = cur_var->next;
  9426. cur_var->varstr = *e;
  9427. cur_var->max_len = strlen(*e);
  9428. cur_var->flg_export = 1;
  9429. }
  9430. e++;
  9431. }
  9432. /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
  9433. debug_printf_env("putenv '%s'\n", shell_ver->varstr);
  9434. putenv(shell_ver->varstr);
  9435. /* Export PWD */
  9436. set_pwd_var(SETFLAG_EXPORT);
  9437. #if BASH_HOSTNAME_VAR
  9438. /* Set (but not export) HOSTNAME unless already set */
  9439. if (!get_local_var_value("HOSTNAME")) {
  9440. struct utsname uts;
  9441. uname(&uts);
  9442. set_local_var_from_halves("HOSTNAME", uts.nodename);
  9443. }
  9444. #endif
  9445. /* IFS is not inherited from the parent environment */
  9446. set_local_var_from_halves("IFS", defifs);
  9447. if (!get_local_var_value("PATH"))
  9448. set_local_var_from_halves("PATH", bb_default_root_path);
  9449. /* PS1/PS2 are set later, if we determine that we are interactive */
  9450. /* bash also exports SHLVL and _,
  9451. * and sets (but doesn't export) the following variables:
  9452. * BASH=/bin/bash
  9453. * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
  9454. * BASH_VERSION='3.2.0(1)-release'
  9455. * HOSTTYPE=i386
  9456. * MACHTYPE=i386-pc-linux-gnu
  9457. * OSTYPE=linux-gnu
  9458. * PPID=<NNNNN> - we also do it elsewhere
  9459. * EUID=<NNNNN>
  9460. * UID=<NNNNN>
  9461. * GROUPS=()
  9462. * LINES=<NNN>
  9463. * COLUMNS=<NNN>
  9464. * BASH_ARGC=()
  9465. * BASH_ARGV=()
  9466. * BASH_LINENO=()
  9467. * BASH_SOURCE=()
  9468. * DIRSTACK=()
  9469. * PIPESTATUS=([0]="0")
  9470. * HISTFILE=/<xxx>/.bash_history
  9471. * HISTFILESIZE=500
  9472. * HISTSIZE=500
  9473. * MAILCHECK=60
  9474. * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
  9475. * SHELL=/bin/bash
  9476. * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
  9477. * TERM=dumb
  9478. * OPTERR=1
  9479. * OPTIND=1
  9480. * PS4='+ '
  9481. */
  9482. #if NUM_SCRIPTS > 0
  9483. if (argc < 0) {
  9484. char *script = get_script_content(-argc - 1);
  9485. G.global_argv = argv;
  9486. G.global_argc = string_array_len(argv);
  9487. //install_special_sighandlers(); - needed?
  9488. parse_and_run_string(script);
  9489. goto final_return;
  9490. }
  9491. #endif
  9492. /* Initialize some more globals to non-zero values */
  9493. die_func = restore_ttypgrp_and__exit;
  9494. /* Shell is non-interactive at first. We need to call
  9495. * install_special_sighandlers() if we are going to execute "sh <script>",
  9496. * "sh -c <cmds>" or login shell's /etc/profile and friends.
  9497. * If we later decide that we are interactive, we run install_special_sighandlers()
  9498. * in order to intercept (more) signals.
  9499. */
  9500. /* Parse options */
  9501. /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
  9502. flags = (argv[0] && argv[0][0] == '-') ? OPT_login : 0;
  9503. while (1) {
  9504. int opt = getopt(argc, argv, "+cexinsl"
  9505. #if !BB_MMU
  9506. "<:$:R:V:"
  9507. # if ENABLE_HUSH_FUNCTIONS
  9508. "F:"
  9509. # endif
  9510. #endif
  9511. );
  9512. if (opt <= 0)
  9513. break;
  9514. switch (opt) {
  9515. case 'c':
  9516. /* Note: -c is not an option with param!
  9517. * "hush -c -l SCRIPT" is valid. "hush -cSCRIPT" is not.
  9518. */
  9519. G.opt_c = 1;
  9520. break;
  9521. case 'i':
  9522. /* Well, we cannot just declare interactiveness,
  9523. * we have to have some stuff (ctty, etc) */
  9524. /* G_interactive_fd++; */
  9525. break;
  9526. case 's':
  9527. G.opt_s = 1;
  9528. break;
  9529. case 'l':
  9530. flags |= OPT_login;
  9531. break;
  9532. #if !BB_MMU
  9533. case '<': /* "big heredoc" support */
  9534. full_write1_str(optarg);
  9535. _exit(0);
  9536. case '$': {
  9537. unsigned long long empty_trap_mask;
  9538. G.root_pid = bb_strtou(optarg, &optarg, 16);
  9539. optarg++;
  9540. G.root_ppid = bb_strtou(optarg, &optarg, 16);
  9541. optarg++;
  9542. G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
  9543. optarg++;
  9544. G.last_exitcode = bb_strtou(optarg, &optarg, 16);
  9545. optarg++;
  9546. builtin_argc = bb_strtou(optarg, &optarg, 16);
  9547. optarg++;
  9548. empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
  9549. if (empty_trap_mask != 0) {
  9550. IF_HUSH_TRAP(int sig;)
  9551. install_special_sighandlers();
  9552. # if ENABLE_HUSH_TRAP
  9553. G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
  9554. for (sig = 1; sig < NSIG; sig++) {
  9555. if (empty_trap_mask & (1LL << sig)) {
  9556. G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
  9557. install_sighandler(sig, SIG_IGN);
  9558. }
  9559. }
  9560. # endif
  9561. }
  9562. # if ENABLE_HUSH_LOOPS
  9563. optarg++;
  9564. G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
  9565. # endif
  9566. /* Suppress "killed by signal" message, -$ hack is used
  9567. * for subshells: echo `sh -c 'kill -9 $$'`
  9568. * should be silent.
  9569. */
  9570. IF_HUSH_JOB(G.run_list_level = 1;)
  9571. # if ENABLE_HUSH_FUNCTIONS
  9572. /* nommu uses re-exec trick for "... | func | ...",
  9573. * should allow "return".
  9574. * This accidentally allows returns in subshells.
  9575. */
  9576. G_flag_return_in_progress = -1;
  9577. # endif
  9578. break;
  9579. }
  9580. case 'R':
  9581. case 'V':
  9582. set_local_var(xstrdup(optarg), opt == 'R' ? SETFLAG_MAKE_RO : 0);
  9583. break;
  9584. # if ENABLE_HUSH_FUNCTIONS
  9585. case 'F': {
  9586. struct function *funcp = new_function(optarg);
  9587. /* funcp->name is already set to optarg */
  9588. /* funcp->body is set to NULL. It's a special case. */
  9589. funcp->body_as_string = argv[optind];
  9590. optind++;
  9591. break;
  9592. }
  9593. # endif
  9594. #endif
  9595. case 'n':
  9596. case 'x':
  9597. case 'e':
  9598. if (set_mode(1, opt, NULL) == 0) /* no error */
  9599. break;
  9600. default:
  9601. bb_show_usage();
  9602. }
  9603. } /* option parsing loop */
  9604. /* Skip options. Try "hush -l": $1 should not be "-l"! */
  9605. G.global_argc = argc - (optind - 1);
  9606. G.global_argv = argv + (optind - 1);
  9607. G.global_argv[0] = argv[0];
  9608. /* If we are login shell... */
  9609. if (flags & OPT_login) {
  9610. const char *hp = NULL;
  9611. HFILE *input;
  9612. debug_printf("sourcing /etc/profile\n");
  9613. input = hfopen("/etc/profile");
  9614. run_profile:
  9615. if (input != NULL) {
  9616. install_special_sighandlers();
  9617. parse_and_run_file(input);
  9618. hfclose(input);
  9619. }
  9620. /* bash: after sourcing /etc/profile,
  9621. * tries to source (in the given order):
  9622. * ~/.bash_profile, ~/.bash_login, ~/.profile,
  9623. * stopping on first found. --noprofile turns this off.
  9624. * bash also sources ~/.bash_logout on exit.
  9625. * If called as sh, skips .bash_XXX files.
  9626. */
  9627. if (!hp) { /* unless we looped on the "goto" already */
  9628. hp = get_local_var_value("HOME");
  9629. if (hp && hp[0]) {
  9630. debug_printf("sourcing ~/.profile\n");
  9631. hp = concat_path_file(hp, ".profile");
  9632. input = hfopen(hp);
  9633. free((char*)hp);
  9634. goto run_profile;
  9635. }
  9636. }
  9637. }
  9638. /* -c takes effect *after* -l */
  9639. if (G.opt_c) {
  9640. /* Possibilities:
  9641. * sh ... -c 'script'
  9642. * sh ... -c 'script' ARG0 [ARG1...]
  9643. * On NOMMU, if builtin_argc != 0,
  9644. * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
  9645. * "" needs to be replaced with NULL
  9646. * and BARGV vector fed to builtin function.
  9647. * Note: the form without ARG0 never happens:
  9648. * sh ... -c 'builtin' BARGV... ""
  9649. */
  9650. char *script;
  9651. install_special_sighandlers();
  9652. G.global_argc--;
  9653. G.global_argv++;
  9654. #if !BB_MMU
  9655. if (builtin_argc) {
  9656. /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
  9657. const struct built_in_command *x;
  9658. x = find_builtin(G.global_argv[0]);
  9659. if (x) { /* paranoia */
  9660. argv = G.global_argv;
  9661. G.global_argc -= builtin_argc + 1; /* skip [BARGV...] "" */
  9662. G.global_argv += builtin_argc + 1;
  9663. G.global_argv[-1] = NULL; /* replace "" */
  9664. G.last_exitcode = x->b_function(argv);
  9665. }
  9666. goto final_return;
  9667. }
  9668. #endif
  9669. script = G.global_argv[0];
  9670. if (!script)
  9671. bb_error_msg_and_die(bb_msg_requires_arg, "-c");
  9672. if (!G.global_argv[1]) {
  9673. /* -c 'script' (no params): prevent empty $0 */
  9674. G.global_argv[0] = argv[0];
  9675. } else { /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
  9676. G.global_argc--;
  9677. G.global_argv++;
  9678. }
  9679. parse_and_run_string(script);
  9680. goto final_return;
  9681. }
  9682. /* -s is: hush -s ARGV1 ARGV2 (no SCRIPT) */
  9683. if (!G.opt_s && G.global_argv[1]) {
  9684. HFILE *input;
  9685. /*
  9686. * "bash <script>" (which is never interactive (unless -i?))
  9687. * sources $BASH_ENV here (without scanning $PATH).
  9688. * If called as sh, does the same but with $ENV.
  9689. * Also NB, per POSIX, $ENV should undergo parameter expansion.
  9690. */
  9691. G.global_argc--;
  9692. G.global_argv++;
  9693. debug_printf("running script '%s'\n", G.global_argv[0]);
  9694. xfunc_error_retval = 127; /* for "hush /does/not/exist" case */
  9695. input = hfopen(G.global_argv[0]);
  9696. if (!input) {
  9697. bb_simple_perror_msg_and_die(G.global_argv[0]);
  9698. }
  9699. xfunc_error_retval = 1;
  9700. install_special_sighandlers();
  9701. parse_and_run_file(input);
  9702. #if ENABLE_FEATURE_CLEAN_UP
  9703. hfclose(input);
  9704. #endif
  9705. goto final_return;
  9706. }
  9707. /* "implicit" -s: bare interactive hush shows 's' in $- */
  9708. G.opt_s = 1;
  9709. /* Up to here, shell was non-interactive. Now it may become one.
  9710. * NB: don't forget to (re)run install_special_sighandlers() as needed.
  9711. */
  9712. /* A shell is interactive if the '-i' flag was given,
  9713. * or if all of the following conditions are met:
  9714. * no -c command
  9715. * no arguments remaining or the -s flag given
  9716. * standard input is a terminal
  9717. * standard output is a terminal
  9718. * Refer to Posix.2, the description of the 'sh' utility.
  9719. */
  9720. #if ENABLE_HUSH_JOB
  9721. if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
  9722. G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
  9723. debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
  9724. if (G_saved_tty_pgrp < 0)
  9725. G_saved_tty_pgrp = 0;
  9726. /* try to dup stdin to high fd#, >= 255 */
  9727. G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, 254);
  9728. if (G_interactive_fd < 0) {
  9729. /* try to dup to any fd */
  9730. G_interactive_fd = dup(STDIN_FILENO);
  9731. if (G_interactive_fd < 0) {
  9732. /* give up */
  9733. G_interactive_fd = 0;
  9734. G_saved_tty_pgrp = 0;
  9735. }
  9736. }
  9737. }
  9738. debug_printf("interactive_fd:%d\n", G_interactive_fd);
  9739. if (G_interactive_fd) {
  9740. close_on_exec_on(G_interactive_fd);
  9741. if (G_saved_tty_pgrp) {
  9742. /* If we were run as 'hush &', sleep until we are
  9743. * in the foreground (tty pgrp == our pgrp).
  9744. * If we get started under a job aware app (like bash),
  9745. * make sure we are now in charge so we don't fight over
  9746. * who gets the foreground */
  9747. while (1) {
  9748. pid_t shell_pgrp = getpgrp();
  9749. G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
  9750. if (G_saved_tty_pgrp == shell_pgrp)
  9751. break;
  9752. /* send TTIN to ourself (should stop us) */
  9753. kill(- shell_pgrp, SIGTTIN);
  9754. }
  9755. }
  9756. /* Install more signal handlers */
  9757. install_special_sighandlers();
  9758. if (G_saved_tty_pgrp) {
  9759. /* Set other signals to restore saved_tty_pgrp */
  9760. install_fatal_sighandlers();
  9761. /* Put ourselves in our own process group
  9762. * (bash, too, does this only if ctty is available) */
  9763. bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
  9764. /* Grab control of the terminal */
  9765. tcsetpgrp(G_interactive_fd, cached_getpid);
  9766. }
  9767. enable_restore_tty_pgrp_on_exit();
  9768. # if ENABLE_FEATURE_EDITING
  9769. G.line_input_state = new_line_input_t(FOR_SHELL);
  9770. # if EDITING_HAS_get_exe_name
  9771. G.line_input_state->get_exe_name = get_builtin_name;
  9772. # endif
  9773. # endif
  9774. # if ENABLE_HUSH_SAVEHISTORY && MAX_HISTORY > 0
  9775. {
  9776. const char *hp = get_local_var_value("HISTFILE");
  9777. if (!hp) {
  9778. hp = get_local_var_value("HOME");
  9779. if (hp)
  9780. hp = concat_path_file(hp, ".hush_history");
  9781. } else {
  9782. hp = xstrdup(hp);
  9783. }
  9784. if (hp) {
  9785. G.line_input_state->hist_file = hp;
  9786. //set_local_var(xasprintf("HISTFILE=%s", ...));
  9787. }
  9788. # if ENABLE_FEATURE_SH_HISTFILESIZE
  9789. hp = get_local_var_value("HISTFILESIZE");
  9790. G.line_input_state->max_history = size_from_HISTFILESIZE(hp);
  9791. # endif
  9792. }
  9793. # endif
  9794. } else {
  9795. install_special_sighandlers();
  9796. }
  9797. #elif ENABLE_HUSH_INTERACTIVE
  9798. /* No job control compiled in, only prompt/line editing */
  9799. if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
  9800. G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, 254);
  9801. if (G_interactive_fd < 0) {
  9802. /* try to dup to any fd */
  9803. G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, -1);
  9804. if (G_interactive_fd < 0)
  9805. /* give up */
  9806. G_interactive_fd = 0;
  9807. }
  9808. }
  9809. if (G_interactive_fd) {
  9810. close_on_exec_on(G_interactive_fd);
  9811. }
  9812. install_special_sighandlers();
  9813. #else
  9814. /* We have interactiveness code disabled */
  9815. install_special_sighandlers();
  9816. #endif
  9817. /* bash:
  9818. * if interactive but not a login shell, sources ~/.bashrc
  9819. * (--norc turns this off, --rcfile <file> overrides)
  9820. */
  9821. if (G_interactive_fd) {
  9822. #if ENABLE_HUSH_INTERACTIVE && ENABLE_FEATURE_EDITING_FANCY_PROMPT
  9823. /* Set (but not export) PS1/2 unless already set */
  9824. if (!get_local_var_value("PS1"))
  9825. set_local_var_from_halves("PS1", "\\w \\$ ");
  9826. if (!get_local_var_value("PS2"))
  9827. set_local_var_from_halves("PS2", "> ");
  9828. #endif
  9829. if (!ENABLE_FEATURE_SH_EXTRA_QUIET) {
  9830. /* note: ash and hush share this string */
  9831. printf("\n\n%s %s\n"
  9832. IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
  9833. "\n",
  9834. bb_banner,
  9835. "hush - the humble shell"
  9836. );
  9837. }
  9838. }
  9839. parse_and_run_file(hfopen(NULL)); /* stdin */
  9840. final_return:
  9841. hush_exit(G.last_exitcode);
  9842. }
  9843. /*
  9844. * Built-ins
  9845. */
  9846. static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
  9847. {
  9848. return 0;
  9849. }
  9850. #if ENABLE_HUSH_TEST || ENABLE_HUSH_ECHO || ENABLE_HUSH_PRINTF || ENABLE_HUSH_KILL
  9851. static NOINLINE int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
  9852. {
  9853. int argc = string_array_len(argv);
  9854. return applet_main_func(argc, argv);
  9855. }
  9856. #endif
  9857. #if ENABLE_HUSH_TEST || BASH_TEST2
  9858. static int FAST_FUNC builtin_test(char **argv)
  9859. {
  9860. return run_applet_main(argv, test_main);
  9861. }
  9862. #endif
  9863. #if ENABLE_HUSH_ECHO
  9864. static int FAST_FUNC builtin_echo(char **argv)
  9865. {
  9866. return run_applet_main(argv, echo_main);
  9867. }
  9868. #endif
  9869. #if ENABLE_HUSH_PRINTF
  9870. static int FAST_FUNC builtin_printf(char **argv)
  9871. {
  9872. return run_applet_main(argv, printf_main);
  9873. }
  9874. #endif
  9875. #if ENABLE_HUSH_HELP
  9876. static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
  9877. {
  9878. const struct built_in_command *x;
  9879. printf(
  9880. "Built-in commands:\n"
  9881. "------------------\n");
  9882. for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
  9883. if (x->b_descr)
  9884. printf("%-10s%s\n", x->b_cmd, x->b_descr);
  9885. }
  9886. return EXIT_SUCCESS;
  9887. }
  9888. #endif
  9889. #if MAX_HISTORY && ENABLE_FEATURE_EDITING
  9890. static int FAST_FUNC builtin_history(char **argv UNUSED_PARAM)
  9891. {
  9892. show_history(G.line_input_state);
  9893. return EXIT_SUCCESS;
  9894. }
  9895. #endif
  9896. static char **skip_dash_dash(char **argv)
  9897. {
  9898. argv++;
  9899. if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
  9900. argv++;
  9901. return argv;
  9902. }
  9903. static int FAST_FUNC builtin_cd(char **argv)
  9904. {
  9905. const char *newdir;
  9906. argv = skip_dash_dash(argv);
  9907. newdir = argv[0];
  9908. if (newdir == NULL) {
  9909. /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
  9910. * bash says "bash: cd: HOME not set" and does nothing
  9911. * (exitcode 1)
  9912. */
  9913. const char *home = get_local_var_value("HOME");
  9914. newdir = home ? home : "/";
  9915. }
  9916. if (chdir(newdir)) {
  9917. /* Mimic bash message exactly */
  9918. bb_perror_msg("cd: %s", newdir);
  9919. return EXIT_FAILURE;
  9920. }
  9921. /* Read current dir (get_cwd(1) is inside) and set PWD.
  9922. * Note: do not enforce exporting. If PWD was unset or unexported,
  9923. * set it again, but do not export. bash does the same.
  9924. */
  9925. set_pwd_var(/*flag:*/ 0);
  9926. return EXIT_SUCCESS;
  9927. }
  9928. static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
  9929. {
  9930. puts(get_cwd(0));
  9931. return EXIT_SUCCESS;
  9932. }
  9933. static int FAST_FUNC builtin_eval(char **argv)
  9934. {
  9935. argv = skip_dash_dash(argv);
  9936. if (!argv[0])
  9937. return EXIT_SUCCESS;
  9938. IF_HUSH_MODE_X(G.x_mode_depth++;)
  9939. //bb_error_msg("%s: ++x_mode_depth=%d", __func__, G.x_mode_depth);
  9940. if (!argv[1]) {
  9941. /* bash:
  9942. * eval "echo Hi; done" ("done" is syntax error):
  9943. * "echo Hi" will not execute too.
  9944. */
  9945. parse_and_run_string(argv[0]);
  9946. } else {
  9947. /* "The eval utility shall construct a command by
  9948. * concatenating arguments together, separating
  9949. * each with a <space> character."
  9950. */
  9951. char *str, *p;
  9952. unsigned len = 0;
  9953. char **pp = argv;
  9954. do
  9955. len += strlen(*pp) + 1;
  9956. while (*++pp);
  9957. str = p = xmalloc(len);
  9958. pp = argv;
  9959. for (;;) {
  9960. p = stpcpy(p, *pp);
  9961. pp++;
  9962. if (!*pp)
  9963. break;
  9964. *p++ = ' ';
  9965. }
  9966. parse_and_run_string(str);
  9967. free(str);
  9968. }
  9969. IF_HUSH_MODE_X(G.x_mode_depth--;)
  9970. //bb_error_msg("%s: --x_mode_depth=%d", __func__, G.x_mode_depth);
  9971. return G.last_exitcode;
  9972. }
  9973. static int FAST_FUNC builtin_exec(char **argv)
  9974. {
  9975. argv = skip_dash_dash(argv);
  9976. if (argv[0] == NULL)
  9977. return EXIT_SUCCESS; /* bash does this */
  9978. /* Careful: we can end up here after [v]fork. Do not restore
  9979. * tty pgrp then, only top-level shell process does that */
  9980. if (G_saved_tty_pgrp && getpid() == G.root_pid)
  9981. tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
  9982. /* Saved-redirect fds, script fds and G_interactive_fd are still
  9983. * open here. However, they are all CLOEXEC, and execv below
  9984. * closes them. Try interactive "exec ls -l /proc/self/fd",
  9985. * it should show no extra open fds in the "ls" process.
  9986. * If we'd try to run builtins/NOEXECs, this would need improving.
  9987. */
  9988. //close_saved_fds_and_FILE_fds();
  9989. /* TODO: if exec fails, bash does NOT exit! We do.
  9990. * We'll need to undo trap cleanup (it's inside execvp_or_die)
  9991. * and tcsetpgrp, and this is inherently racy.
  9992. */
  9993. execvp_or_die(argv);
  9994. }
  9995. static int FAST_FUNC builtin_exit(char **argv)
  9996. {
  9997. debug_printf_exec("%s()\n", __func__);
  9998. /* interactive bash:
  9999. * # trap "echo EEE" EXIT
  10000. * # exit
  10001. * exit
  10002. * There are stopped jobs.
  10003. * (if there are _stopped_ jobs, running ones don't count)
  10004. * # exit
  10005. * exit
  10006. * EEE (then bash exits)
  10007. *
  10008. * TODO: we can use G.exiting = -1 as indicator "last cmd was exit"
  10009. */
  10010. /* note: EXIT trap is run by hush_exit */
  10011. argv = skip_dash_dash(argv);
  10012. if (argv[0] == NULL) {
  10013. #if ENABLE_HUSH_TRAP
  10014. if (G.pre_trap_exitcode >= 0) /* "exit" in trap uses $? from before the trap */
  10015. hush_exit(G.pre_trap_exitcode);
  10016. #endif
  10017. hush_exit(G.last_exitcode);
  10018. }
  10019. /* mimic bash: exit 123abc == exit 255 + error msg */
  10020. xfunc_error_retval = 255;
  10021. /* bash: exit -2 == exit 254, no error msg */
  10022. hush_exit(xatoi(argv[0]) & 0xff);
  10023. }
  10024. #if ENABLE_HUSH_TYPE
  10025. /* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
  10026. static int FAST_FUNC builtin_type(char **argv)
  10027. {
  10028. int ret = EXIT_SUCCESS;
  10029. while (*++argv) {
  10030. const char *type;
  10031. char *path = NULL;
  10032. if (0) {} /* make conditional compile easier below */
  10033. /*else if (find_alias(*argv))
  10034. type = "an alias";*/
  10035. # if ENABLE_HUSH_FUNCTIONS
  10036. else if (find_function(*argv))
  10037. type = "a function";
  10038. # endif
  10039. else if (find_builtin(*argv))
  10040. type = "a shell builtin";
  10041. else if ((path = find_in_path(*argv)) != NULL)
  10042. type = path;
  10043. else {
  10044. bb_error_msg("type: %s: not found", *argv);
  10045. ret = EXIT_FAILURE;
  10046. continue;
  10047. }
  10048. printf("%s is %s\n", *argv, type);
  10049. free(path);
  10050. }
  10051. return ret;
  10052. }
  10053. #endif
  10054. #if ENABLE_HUSH_READ
  10055. /* Interruptibility of read builtin in bash
  10056. * (tested on bash-4.2.8 by sending signals (not by ^C)):
  10057. *
  10058. * Empty trap makes read ignore corresponding signal, for any signal.
  10059. *
  10060. * SIGINT:
  10061. * - terminates non-interactive shell;
  10062. * - interrupts read in interactive shell;
  10063. * if it has non-empty trap:
  10064. * - executes trap and returns to command prompt in interactive shell;
  10065. * - executes trap and returns to read in non-interactive shell;
  10066. * SIGTERM:
  10067. * - is ignored (does not interrupt) read in interactive shell;
  10068. * - terminates non-interactive shell;
  10069. * if it has non-empty trap:
  10070. * - executes trap and returns to read;
  10071. * SIGHUP:
  10072. * - terminates shell (regardless of interactivity);
  10073. * if it has non-empty trap:
  10074. * - executes trap and returns to read;
  10075. * SIGCHLD from children:
  10076. * - does not interrupt read regardless of interactivity:
  10077. * try: sleep 1 & read x; echo $x
  10078. */
  10079. static int FAST_FUNC builtin_read(char **argv)
  10080. {
  10081. const char *r;
  10082. struct builtin_read_params params;
  10083. memset(&params, 0, sizeof(params));
  10084. /* "!": do not abort on errors.
  10085. * Option string must start with "sr" to match BUILTIN_READ_xxx
  10086. */
  10087. params.read_flags = getopt32(argv,
  10088. # if BASH_READ_D
  10089. "!srn:p:t:u:d:", &params.opt_n, &params.opt_p, &params.opt_t, &params.opt_u, &params.opt_d
  10090. # else
  10091. "!srn:p:t:u:", &params.opt_n, &params.opt_p, &params.opt_t, &params.opt_u
  10092. # endif
  10093. );
  10094. if ((uint32_t)params.read_flags == (uint32_t)-1)
  10095. return EXIT_FAILURE;
  10096. argv += optind;
  10097. params.argv = argv;
  10098. params.setvar = set_local_var_from_halves;
  10099. params.ifs = get_local_var_value("IFS"); /* can be NULL */
  10100. again:
  10101. r = shell_builtin_read(&params);
  10102. if ((uintptr_t)r == 1 && errno == EINTR) {
  10103. unsigned sig = check_and_run_traps();
  10104. if (sig != SIGINT)
  10105. goto again;
  10106. }
  10107. if ((uintptr_t)r > 1) {
  10108. bb_simple_error_msg(r);
  10109. r = (char*)(uintptr_t)1;
  10110. }
  10111. return (uintptr_t)r;
  10112. }
  10113. #endif
  10114. #if ENABLE_HUSH_UMASK
  10115. static int FAST_FUNC builtin_umask(char **argv)
  10116. {
  10117. int rc;
  10118. mode_t mask;
  10119. rc = 1;
  10120. mask = umask(0);
  10121. argv = skip_dash_dash(argv);
  10122. if (argv[0]) {
  10123. mode_t old_mask = mask;
  10124. /* numeric umasks are taken as-is */
  10125. /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
  10126. if (!isdigit(argv[0][0]))
  10127. mask ^= 0777;
  10128. mask = bb_parse_mode(argv[0], mask);
  10129. if (!isdigit(argv[0][0]))
  10130. mask ^= 0777;
  10131. if ((unsigned)mask > 0777) {
  10132. mask = old_mask;
  10133. /* bash messages:
  10134. * bash: umask: 'q': invalid symbolic mode operator
  10135. * bash: umask: 999: octal number out of range
  10136. */
  10137. bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
  10138. rc = 0;
  10139. }
  10140. } else {
  10141. /* Mimic bash */
  10142. printf("%04o\n", (unsigned) mask);
  10143. /* fall through and restore mask which we set to 0 */
  10144. }
  10145. umask(mask);
  10146. return !rc; /* rc != 0 - success */
  10147. }
  10148. #endif
  10149. #if ENABLE_HUSH_EXPORT || ENABLE_HUSH_TRAP
  10150. static void print_escaped(const char *s)
  10151. {
  10152. if (*s == '\'')
  10153. goto squote;
  10154. do {
  10155. const char *p = strchrnul(s, '\'');
  10156. /* print 'xxxx', possibly just '' */
  10157. printf("'%.*s'", (int)(p - s), s);
  10158. if (*p == '\0')
  10159. break;
  10160. s = p;
  10161. squote:
  10162. /* s points to '; print "'''...'''" */
  10163. putchar('"');
  10164. do putchar('\''); while (*++s == '\'');
  10165. putchar('"');
  10166. } while (*s);
  10167. }
  10168. #endif
  10169. #if ENABLE_HUSH_EXPORT || ENABLE_HUSH_LOCAL || ENABLE_HUSH_READONLY
  10170. static int helper_export_local(char **argv, unsigned flags)
  10171. {
  10172. do {
  10173. char *name = *argv;
  10174. const char *name_end = endofname(name);
  10175. if (*name_end == '\0') {
  10176. struct variable *var, **vpp;
  10177. vpp = get_ptr_to_local_var(name, name_end - name);
  10178. var = vpp ? *vpp : NULL;
  10179. if (flags & SETFLAG_UNEXPORT) {
  10180. /* export -n NAME (without =VALUE) */
  10181. if (var) {
  10182. var->flg_export = 0;
  10183. debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
  10184. unsetenv(name);
  10185. } /* else: export -n NOT_EXISTING_VAR: no-op */
  10186. continue;
  10187. }
  10188. if (flags & SETFLAG_EXPORT) {
  10189. /* export NAME (without =VALUE) */
  10190. if (var) {
  10191. var->flg_export = 1;
  10192. debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
  10193. putenv(var->varstr);
  10194. continue;
  10195. }
  10196. }
  10197. if (flags & SETFLAG_MAKE_RO) {
  10198. /* readonly NAME (without =VALUE) */
  10199. if (var) {
  10200. var->flg_read_only = 1;
  10201. continue;
  10202. }
  10203. }
  10204. # if ENABLE_HUSH_LOCAL
  10205. /* Is this "local" bltin? */
  10206. if (!(flags & (SETFLAG_EXPORT|SETFLAG_UNEXPORT|SETFLAG_MAKE_RO))) {
  10207. unsigned lvl = flags >> SETFLAG_VARLVL_SHIFT;
  10208. if (var && var->var_nest_level == lvl) {
  10209. /* "local x=abc; ...; local x" - ignore second local decl */
  10210. continue;
  10211. }
  10212. }
  10213. # endif
  10214. /* Exporting non-existing variable.
  10215. * bash does not put it in environment,
  10216. * but remembers that it is exported,
  10217. * and does put it in env when it is set later.
  10218. * We just set it to "" and export.
  10219. */
  10220. /* Or, it's "local NAME" (without =VALUE).
  10221. * bash sets the value to "".
  10222. */
  10223. /* Or, it's "readonly NAME" (without =VALUE).
  10224. * bash remembers NAME and disallows its creation
  10225. * in the future.
  10226. */
  10227. name = xasprintf("%s=", name);
  10228. } else {
  10229. if (*name_end != '=') {
  10230. bb_error_msg("'%s': bad variable name", name);
  10231. /* do not parse following argv[]s: */
  10232. return 1;
  10233. }
  10234. /* (Un)exporting/making local NAME=VALUE */
  10235. name = xstrdup(name);
  10236. /* Testcase: export PS1='\w \$ ' */
  10237. unbackslash(name);
  10238. }
  10239. debug_printf_env("%s: set_local_var('%s')\n", __func__, name);
  10240. if (set_local_var(name, flags))
  10241. return EXIT_FAILURE;
  10242. } while (*++argv);
  10243. return EXIT_SUCCESS;
  10244. }
  10245. #endif
  10246. #if ENABLE_HUSH_EXPORT
  10247. static int FAST_FUNC builtin_export(char **argv)
  10248. {
  10249. unsigned opt_unexport;
  10250. # if ENABLE_HUSH_EXPORT_N
  10251. /* "!": do not abort on errors */
  10252. opt_unexport = getopt32(argv, "!n");
  10253. if (opt_unexport == (uint32_t)-1)
  10254. return EXIT_FAILURE;
  10255. argv += optind;
  10256. # else
  10257. opt_unexport = 0;
  10258. argv++;
  10259. # endif
  10260. if (argv[0] == NULL) {
  10261. char **e = environ;
  10262. if (e) {
  10263. while (*e) {
  10264. # if 0
  10265. puts(*e++);
  10266. # else
  10267. /* ash emits: export VAR='VAL'
  10268. * bash: declare -x VAR="VAL"
  10269. * we follow ash example */
  10270. const char *s = *e++;
  10271. const char *p = strchr(s, '=');
  10272. if (!p) /* wtf? take next variable */
  10273. continue;
  10274. /* export var= */
  10275. printf("export %.*s", (int)(p - s) + 1, s);
  10276. print_escaped(p + 1);
  10277. putchar('\n');
  10278. # endif
  10279. }
  10280. /*fflush_all(); - done after each builtin anyway */
  10281. }
  10282. return EXIT_SUCCESS;
  10283. }
  10284. return helper_export_local(argv, opt_unexport ? SETFLAG_UNEXPORT : SETFLAG_EXPORT);
  10285. }
  10286. #endif
  10287. #if ENABLE_HUSH_LOCAL
  10288. static int FAST_FUNC builtin_local(char **argv)
  10289. {
  10290. if (G.func_nest_level == 0) {
  10291. bb_error_msg("%s: not in a function", argv[0]);
  10292. return EXIT_FAILURE; /* bash compat */
  10293. }
  10294. argv++;
  10295. /* Since all builtins run in a nested variable level,
  10296. * need to use level - 1 here. Or else the variable will be removed at once
  10297. * after builtin returns.
  10298. */
  10299. return helper_export_local(argv, (G.var_nest_level - 1) << SETFLAG_VARLVL_SHIFT);
  10300. }
  10301. #endif
  10302. #if ENABLE_HUSH_READONLY
  10303. static int FAST_FUNC builtin_readonly(char **argv)
  10304. {
  10305. argv++;
  10306. if (*argv == NULL) {
  10307. /* bash: readonly [-p]: list all readonly VARs
  10308. * (-p has no effect in bash)
  10309. */
  10310. struct variable *e;
  10311. for (e = G.top_var; e; e = e->next) {
  10312. if (e->flg_read_only) {
  10313. //TODO: quote value: readonly VAR='VAL'
  10314. printf("readonly %s\n", e->varstr);
  10315. }
  10316. }
  10317. return EXIT_SUCCESS;
  10318. }
  10319. return helper_export_local(argv, SETFLAG_MAKE_RO);
  10320. }
  10321. #endif
  10322. #if ENABLE_HUSH_UNSET
  10323. /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
  10324. static int FAST_FUNC builtin_unset(char **argv)
  10325. {
  10326. int ret;
  10327. unsigned opts;
  10328. /* "!": do not abort on errors */
  10329. /* "+": stop at 1st non-option */
  10330. opts = getopt32(argv, "!+vf");
  10331. if (opts == (unsigned)-1)
  10332. return EXIT_FAILURE;
  10333. if (opts == 3) {
  10334. bb_simple_error_msg("unset: -v and -f are exclusive");
  10335. return EXIT_FAILURE;
  10336. }
  10337. argv += optind;
  10338. ret = EXIT_SUCCESS;
  10339. while (*argv) {
  10340. if (!(opts & 2)) { /* not -f */
  10341. if (unset_local_var(*argv)) {
  10342. /* unset <nonexistent_var> doesn't fail.
  10343. * Error is when one tries to unset RO var.
  10344. * Message was printed by unset_local_var. */
  10345. ret = EXIT_FAILURE;
  10346. }
  10347. }
  10348. # if ENABLE_HUSH_FUNCTIONS
  10349. else {
  10350. unset_func(*argv);
  10351. }
  10352. # endif
  10353. argv++;
  10354. }
  10355. return ret;
  10356. }
  10357. #endif
  10358. #if ENABLE_HUSH_SET
  10359. /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
  10360. * built-in 'set' handler
  10361. * SUSv3 says:
  10362. * set [-abCefhmnuvx] [-o option] [argument...]
  10363. * set [+abCefhmnuvx] [+o option] [argument...]
  10364. * set -- [argument...]
  10365. * set -o
  10366. * set +o
  10367. * Implementations shall support the options in both their hyphen and
  10368. * plus-sign forms. These options can also be specified as options to sh.
  10369. * Examples:
  10370. * Write out all variables and their values: set
  10371. * Set $1, $2, and $3 and set "$#" to 3: set c a b
  10372. * Turn on the -x and -v options: set -xv
  10373. * Unset all positional parameters: set --
  10374. * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
  10375. * Set the positional parameters to the expansion of x, even if x expands
  10376. * with a leading '-' or '+': set -- $x
  10377. *
  10378. * So far, we only support "set -- [argument...]" and some of the short names.
  10379. */
  10380. static int FAST_FUNC builtin_set(char **argv)
  10381. {
  10382. int n;
  10383. char **pp, **g_argv;
  10384. char *arg = *++argv;
  10385. if (arg == NULL) {
  10386. struct variable *e;
  10387. for (e = G.top_var; e; e = e->next)
  10388. puts(e->varstr);
  10389. return EXIT_SUCCESS;
  10390. }
  10391. do {
  10392. if (strcmp(arg, "--") == 0) {
  10393. ++argv;
  10394. goto set_argv;
  10395. }
  10396. if (arg[0] != '+' && arg[0] != '-')
  10397. break;
  10398. for (n = 1; arg[n]; ++n) {
  10399. if (set_mode((arg[0] == '-'), arg[n], argv[1])) {
  10400. bb_error_msg("%s: %s: invalid option", "set", arg);
  10401. return EXIT_FAILURE;
  10402. }
  10403. if (arg[n] == 'o' && argv[1])
  10404. argv++;
  10405. }
  10406. } while ((arg = *++argv) != NULL);
  10407. /* Now argv[0] is 1st argument */
  10408. if (arg == NULL)
  10409. return EXIT_SUCCESS;
  10410. set_argv:
  10411. /* NB: G.global_argv[0] ($0) is never freed/changed */
  10412. g_argv = G.global_argv;
  10413. if (G.global_args_malloced) {
  10414. pp = g_argv;
  10415. while (*++pp)
  10416. free(*pp);
  10417. g_argv[1] = NULL;
  10418. } else {
  10419. G.global_args_malloced = 1;
  10420. pp = xzalloc(sizeof(pp[0]) * 2);
  10421. pp[0] = g_argv[0]; /* retain $0 */
  10422. g_argv = pp;
  10423. }
  10424. /* This realloc's G.global_argv */
  10425. G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
  10426. G.global_argc = 1 + string_array_len(pp + 1);
  10427. return EXIT_SUCCESS;
  10428. }
  10429. #endif
  10430. static int FAST_FUNC builtin_shift(char **argv)
  10431. {
  10432. int n = 1;
  10433. argv = skip_dash_dash(argv);
  10434. if (argv[0]) {
  10435. n = bb_strtou(argv[0], NULL, 10);
  10436. if (errno || n < 0) {
  10437. /* shared string with ash.c */
  10438. bb_error_msg("Illegal number: %s", argv[0]);
  10439. /*
  10440. * ash aborts in this case.
  10441. * bash prints error message and set $? to 1.
  10442. * Interestingly, for "shift 99999" bash does not
  10443. * print error message, but does set $? to 1
  10444. * (and does no shifting at all).
  10445. */
  10446. }
  10447. }
  10448. if (n >= 0 && n < G.global_argc) {
  10449. if (G_global_args_malloced) {
  10450. int m = 1;
  10451. while (m <= n)
  10452. free(G.global_argv[m++]);
  10453. }
  10454. G.global_argc -= n;
  10455. memmove(&G.global_argv[1], &G.global_argv[n+1],
  10456. G.global_argc * sizeof(G.global_argv[0]));
  10457. return EXIT_SUCCESS;
  10458. }
  10459. return EXIT_FAILURE;
  10460. }
  10461. #if ENABLE_HUSH_GETOPTS
  10462. static int FAST_FUNC builtin_getopts(char **argv)
  10463. {
  10464. /* http://pubs.opengroup.org/onlinepubs/9699919799/utilities/getopts.html
  10465. TODO:
  10466. If a required argument is not found, and getopts is not silent,
  10467. a question mark (?) is placed in VAR, OPTARG is unset, and a
  10468. diagnostic message is printed. If getopts is silent, then a
  10469. colon (:) is placed in VAR and OPTARG is set to the option
  10470. character found.
  10471. Test that VAR is a valid variable name?
  10472. "Whenever the shell is invoked, OPTIND shall be initialized to 1"
  10473. */
  10474. char cbuf[2];
  10475. const char *cp, *optstring, *var;
  10476. int c, n, exitcode, my_opterr;
  10477. unsigned count;
  10478. optstring = *++argv;
  10479. if (!optstring || !(var = *++argv)) {
  10480. bb_simple_error_msg("usage: getopts OPTSTRING VAR [ARGS]");
  10481. return EXIT_FAILURE;
  10482. }
  10483. if (argv[1])
  10484. argv[0] = G.global_argv[0]; /* for error messages in getopt() */
  10485. else
  10486. argv = G.global_argv;
  10487. cbuf[1] = '\0';
  10488. my_opterr = 0;
  10489. if (optstring[0] != ':') {
  10490. cp = get_local_var_value("OPTERR");
  10491. /* 0 if "OPTERR=0", 1 otherwise */
  10492. my_opterr = (!cp || NOT_LONE_CHAR(cp, '0'));
  10493. }
  10494. /* getopts stops on first non-option. Add "+" to force that */
  10495. /*if (optstring[0] != '+')*/ {
  10496. char *s = alloca(strlen(optstring) + 2);
  10497. sprintf(s, "+%s", optstring);
  10498. optstring = s;
  10499. }
  10500. /* Naively, now we should just
  10501. * cp = get_local_var_value("OPTIND");
  10502. * optind = cp ? atoi(cp) : 0;
  10503. * optarg = NULL;
  10504. * opterr = my_opterr;
  10505. * c = getopt(string_array_len(argv), argv, optstring);
  10506. * and be done? Not so fast...
  10507. * Unlike normal getopt() usage in C programs, here
  10508. * each successive call will (usually) have the same argv[] CONTENTS,
  10509. * but not the ADDRESSES. Worse yet, it's possible that between
  10510. * invocations of "getopts", there will be calls to shell builtins
  10511. * which use getopt() internally. Example:
  10512. * while getopts "abc" RES -a -bc -abc de; do
  10513. * unset -ff func
  10514. * done
  10515. * This would not work correctly: getopt() call inside "unset"
  10516. * modifies internal libc state which is tracking position in
  10517. * multi-option strings ("-abc"). At best, it can skip options
  10518. * or return the same option infinitely. With glibc implementation
  10519. * of getopt(), it would use outright invalid pointers and return
  10520. * garbage even _without_ "unset" mangling internal state.
  10521. *
  10522. * We resort to resetting getopt() state and calling it N times,
  10523. * until we get Nth result (or failure).
  10524. * (N == G.getopt_count is reset to 0 whenever OPTIND is [un]set).
  10525. */
  10526. GETOPT_RESET();
  10527. count = 0;
  10528. n = string_array_len(argv);
  10529. do {
  10530. optarg = NULL;
  10531. opterr = (count < G.getopt_count) ? 0 : my_opterr;
  10532. c = getopt(n, argv, optstring);
  10533. if (c < 0)
  10534. break;
  10535. count++;
  10536. } while (count <= G.getopt_count);
  10537. /* Set OPTIND. Prevent resetting of the magic counter! */
  10538. set_local_var_from_halves("OPTIND", utoa(optind));
  10539. G.getopt_count = count; /* "next time, give me N+1'th result" */
  10540. GETOPT_RESET(); /* just in case */
  10541. /* Set OPTARG */
  10542. /* Always set or unset, never left as-is, even on exit/error:
  10543. * "If no option was found, or if the option that was found
  10544. * does not have an option-argument, OPTARG shall be unset."
  10545. */
  10546. cp = optarg;
  10547. if (c == '?') {
  10548. /* If ":optstring" and unknown option is seen,
  10549. * it is stored to OPTARG.
  10550. */
  10551. if (optstring[1] == ':') {
  10552. cbuf[0] = optopt;
  10553. cp = cbuf;
  10554. }
  10555. }
  10556. if (cp)
  10557. set_local_var_from_halves("OPTARG", cp);
  10558. else
  10559. unset_local_var("OPTARG");
  10560. /* Convert -1 to "?" */
  10561. exitcode = EXIT_SUCCESS;
  10562. if (c < 0) { /* -1: end of options */
  10563. exitcode = EXIT_FAILURE;
  10564. c = '?';
  10565. }
  10566. /* Set VAR */
  10567. cbuf[0] = c;
  10568. set_local_var_from_halves(var, cbuf);
  10569. return exitcode;
  10570. }
  10571. #endif
  10572. static int FAST_FUNC builtin_source(char **argv)
  10573. {
  10574. char *arg_path, *filename;
  10575. HFILE *input;
  10576. save_arg_t sv;
  10577. char *args_need_save;
  10578. #if ENABLE_HUSH_FUNCTIONS
  10579. smallint sv_flg;
  10580. #endif
  10581. argv = skip_dash_dash(argv);
  10582. filename = argv[0];
  10583. if (!filename) {
  10584. /* bash says: "bash: .: filename argument required" */
  10585. return 2; /* bash compat */
  10586. }
  10587. arg_path = NULL;
  10588. if (!strchr(filename, '/')) {
  10589. arg_path = find_in_path(filename);
  10590. if (arg_path)
  10591. filename = arg_path;
  10592. else if (!ENABLE_HUSH_BASH_SOURCE_CURDIR) {
  10593. errno = ENOENT;
  10594. bb_simple_perror_msg(filename);
  10595. return EXIT_FAILURE;
  10596. }
  10597. }
  10598. input = hfopen(filename);
  10599. free(arg_path);
  10600. if (!input) {
  10601. bb_perror_msg("%s", filename);
  10602. /* POSIX: non-interactive shell should abort here,
  10603. * not merely fail. So far no one complained :)
  10604. */
  10605. return EXIT_FAILURE;
  10606. }
  10607. #if ENABLE_HUSH_FUNCTIONS
  10608. sv_flg = G_flag_return_in_progress;
  10609. /* "we are inside sourced file, ok to use return" */
  10610. G_flag_return_in_progress = -1;
  10611. #endif
  10612. args_need_save = argv[1]; /* used as a boolean variable */
  10613. if (args_need_save)
  10614. save_and_replace_G_args(&sv, argv);
  10615. /* "false; . ./empty_line; echo Zero:$?" should print 0 */
  10616. G.last_exitcode = 0;
  10617. parse_and_run_file(input);
  10618. hfclose(input);
  10619. if (args_need_save) /* can't use argv[1] instead: "shift" can mangle it */
  10620. restore_G_args(&sv, argv);
  10621. #if ENABLE_HUSH_FUNCTIONS
  10622. G_flag_return_in_progress = sv_flg;
  10623. #endif
  10624. return G.last_exitcode;
  10625. }
  10626. #if ENABLE_HUSH_TRAP
  10627. static int FAST_FUNC builtin_trap(char **argv)
  10628. {
  10629. int sig;
  10630. char *new_cmd;
  10631. if (!G_traps)
  10632. G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
  10633. argv++;
  10634. if (!*argv) {
  10635. int i;
  10636. /* No args: print all trapped */
  10637. for (i = 0; i < NSIG; ++i) {
  10638. if (G_traps[i]) {
  10639. printf("trap -- ");
  10640. print_escaped(G_traps[i]);
  10641. /* note: bash adds "SIG", but only if invoked
  10642. * as "bash". If called as "sh", or if set -o posix,
  10643. * then it prints short signal names.
  10644. * We are printing short names: */
  10645. printf(" %s\n", get_signame(i));
  10646. }
  10647. }
  10648. /*fflush_all(); - done after each builtin anyway */
  10649. return EXIT_SUCCESS;
  10650. }
  10651. new_cmd = NULL;
  10652. /* If first arg is a number: reset all specified signals */
  10653. sig = bb_strtou(*argv, NULL, 10);
  10654. if (errno == 0) {
  10655. int ret;
  10656. process_sig_list:
  10657. ret = EXIT_SUCCESS;
  10658. while (*argv) {
  10659. sighandler_t handler;
  10660. sig = get_signum(*argv++);
  10661. if (sig < 0) {
  10662. ret = EXIT_FAILURE;
  10663. /* Mimic bash message exactly */
  10664. bb_error_msg("trap: %s: invalid signal specification", argv[-1]);
  10665. continue;
  10666. }
  10667. free(G_traps[sig]);
  10668. G_traps[sig] = xstrdup(new_cmd);
  10669. debug_printf("trap: setting SIG%s (%i) to '%s'\n",
  10670. get_signame(sig), sig, G_traps[sig]);
  10671. /* There is no signal for 0 (EXIT) */
  10672. if (sig == 0)
  10673. continue;
  10674. if (new_cmd)
  10675. handler = (new_cmd[0] ? record_pending_signo : SIG_IGN);
  10676. else
  10677. /* We are removing trap handler */
  10678. handler = pick_sighandler(sig);
  10679. install_sighandler(sig, handler);
  10680. }
  10681. return ret;
  10682. }
  10683. if (!argv[1]) { /* no second arg */
  10684. bb_simple_error_msg("trap: invalid arguments");
  10685. return EXIT_FAILURE;
  10686. }
  10687. /* First arg is "-": reset all specified to default */
  10688. /* First arg is "--": skip it, the rest is "handler SIGs..." */
  10689. /* Everything else: set arg as signal handler
  10690. * (includes "" case, which ignores signal) */
  10691. if (argv[0][0] == '-') {
  10692. if (argv[0][1] == '\0') { /* "-" */
  10693. /* new_cmd remains NULL: "reset these sigs" */
  10694. goto reset_traps;
  10695. }
  10696. if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
  10697. argv++;
  10698. }
  10699. /* else: "-something", no special meaning */
  10700. }
  10701. new_cmd = *argv;
  10702. reset_traps:
  10703. argv++;
  10704. goto process_sig_list;
  10705. }
  10706. #endif
  10707. #if ENABLE_HUSH_JOB
  10708. static struct pipe *parse_jobspec(const char *str)
  10709. {
  10710. struct pipe *pi;
  10711. unsigned jobnum;
  10712. if (sscanf(str, "%%%u", &jobnum) != 1) {
  10713. if (str[0] != '%'
  10714. || (str[1] != '%' && str[1] != '+' && str[1] != '\0')
  10715. ) {
  10716. bb_error_msg("bad argument '%s'", str);
  10717. return NULL;
  10718. }
  10719. /* It is "%%", "%+" or "%" - current job */
  10720. jobnum = G.last_jobid;
  10721. if (jobnum == 0) {
  10722. bb_simple_error_msg("no current job");
  10723. return NULL;
  10724. }
  10725. }
  10726. for (pi = G.job_list; pi; pi = pi->next) {
  10727. if (pi->jobid == jobnum) {
  10728. return pi;
  10729. }
  10730. }
  10731. bb_error_msg("%u: no such job", jobnum);
  10732. return NULL;
  10733. }
  10734. static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
  10735. {
  10736. struct pipe *job;
  10737. const char *status_string;
  10738. checkjobs(NULL, 0 /*(no pid to wait for)*/);
  10739. for (job = G.job_list; job; job = job->next) {
  10740. if (job->alive_cmds == job->stopped_cmds)
  10741. status_string = "Stopped";
  10742. else
  10743. status_string = "Running";
  10744. printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
  10745. }
  10746. clean_up_last_dead_job();
  10747. return EXIT_SUCCESS;
  10748. }
  10749. /* built-in 'fg' and 'bg' handler */
  10750. static int FAST_FUNC builtin_fg_bg(char **argv)
  10751. {
  10752. int i;
  10753. struct pipe *pi;
  10754. if (!G_interactive_fd)
  10755. return EXIT_FAILURE;
  10756. /* If they gave us no args, assume they want the last backgrounded task */
  10757. if (!argv[1]) {
  10758. for (pi = G.job_list; pi; pi = pi->next) {
  10759. if (pi->jobid == G.last_jobid) {
  10760. goto found;
  10761. }
  10762. }
  10763. bb_error_msg("%s: no current job", argv[0]);
  10764. return EXIT_FAILURE;
  10765. }
  10766. pi = parse_jobspec(argv[1]);
  10767. if (!pi)
  10768. return EXIT_FAILURE;
  10769. found:
  10770. /* TODO: bash prints a string representation
  10771. * of job being foregrounded (like "sleep 1 | cat") */
  10772. if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
  10773. /* Put the job into the foreground. */
  10774. tcsetpgrp(G_interactive_fd, pi->pgrp);
  10775. }
  10776. /* Restart the processes in the job */
  10777. debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
  10778. for (i = 0; i < pi->num_cmds; i++) {
  10779. debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
  10780. }
  10781. pi->stopped_cmds = 0;
  10782. i = kill(- pi->pgrp, SIGCONT);
  10783. if (i < 0) {
  10784. if (errno == ESRCH) {
  10785. delete_finished_job(pi);
  10786. return EXIT_SUCCESS;
  10787. }
  10788. bb_simple_perror_msg("kill (SIGCONT)");
  10789. }
  10790. if (argv[0][0] == 'f') {
  10791. remove_job_from_table(pi); /* FG job shouldn't be in job table */
  10792. return checkjobs_and_fg_shell(pi);
  10793. }
  10794. return EXIT_SUCCESS;
  10795. }
  10796. #endif
  10797. #if ENABLE_HUSH_KILL
  10798. static int FAST_FUNC builtin_kill(char **argv)
  10799. {
  10800. int ret = 0;
  10801. # if ENABLE_HUSH_JOB
  10802. if (argv[1] && strcmp(argv[1], "-l") != 0) {
  10803. int i = 1;
  10804. do {
  10805. struct pipe *pi;
  10806. char *dst;
  10807. int j, n;
  10808. if (argv[i][0] != '%')
  10809. continue;
  10810. /*
  10811. * "kill %N" - job kill
  10812. * Converting to pgrp / pid kill
  10813. */
  10814. pi = parse_jobspec(argv[i]);
  10815. if (!pi) {
  10816. /* Eat bad jobspec */
  10817. j = i;
  10818. do {
  10819. j++;
  10820. argv[j - 1] = argv[j];
  10821. } while (argv[j]);
  10822. ret = 1;
  10823. i--;
  10824. continue;
  10825. }
  10826. /*
  10827. * In jobs started under job control, we signal
  10828. * entire process group by kill -PGRP_ID.
  10829. * This happens, f.e., in interactive shell.
  10830. *
  10831. * Otherwise, we signal each child via
  10832. * kill PID1 PID2 PID3.
  10833. * Testcases:
  10834. * sh -c 'sleep 1|sleep 1 & kill %1'
  10835. * sh -c 'true|sleep 2 & sleep 1; kill %1'
  10836. * sh -c 'true|sleep 1 & sleep 2; kill %1'
  10837. */
  10838. n = G_interactive_fd ? 1 : pi->num_cmds;
  10839. dst = alloca(n * sizeof(int)*4);
  10840. argv[i] = dst;
  10841. if (G_interactive_fd)
  10842. dst += sprintf(dst, " -%u", (int)pi->pgrp);
  10843. else for (j = 0; j < n; j++) {
  10844. struct command *cmd = &pi->cmds[j];
  10845. /* Skip exited members of the job */
  10846. if (cmd->pid == 0)
  10847. continue;
  10848. /*
  10849. * kill_main has matching code to expect
  10850. * leading space. Needed to not confuse
  10851. * negative pids with "kill -SIGNAL_NO" syntax
  10852. */
  10853. dst += sprintf(dst, " %u", (int)cmd->pid);
  10854. }
  10855. *dst = '\0';
  10856. } while (argv[++i]);
  10857. }
  10858. # endif
  10859. if (argv[1] || ret == 0) {
  10860. ret = run_applet_main(argv, kill_main);
  10861. }
  10862. /* else: ret = 1, "kill %bad_jobspec" case */
  10863. return ret;
  10864. }
  10865. #endif
  10866. #if ENABLE_HUSH_WAIT
  10867. /* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
  10868. # if !ENABLE_HUSH_JOB
  10869. # define wait_for_child_or_signal(pipe,pid) wait_for_child_or_signal(pid)
  10870. # endif
  10871. static int wait_for_child_or_signal(struct pipe *waitfor_pipe, pid_t waitfor_pid)
  10872. {
  10873. int ret = 0;
  10874. for (;;) {
  10875. int sig;
  10876. sigset_t oldset;
  10877. if (!sigisemptyset(&G.pending_set))
  10878. goto check_sig;
  10879. /* waitpid is not interruptible by SA_RESTARTed
  10880. * signals which we use. Thus, this ugly dance:
  10881. */
  10882. /* Make sure possible SIGCHLD is stored in kernel's
  10883. * pending signal mask before we call waitpid.
  10884. * Or else we may race with SIGCHLD, lose it,
  10885. * and get stuck in sigsuspend...
  10886. */
  10887. sigfillset(&oldset); /* block all signals, remember old set */
  10888. sigprocmask2(SIG_SETMASK, &oldset);
  10889. if (!sigisemptyset(&G.pending_set)) {
  10890. /* Crap! we raced with some signal! */
  10891. goto restore;
  10892. }
  10893. /*errno = 0; - checkjobs does this */
  10894. /* Can't pass waitfor_pipe into checkjobs(): it won't be interruptible */
  10895. ret = checkjobs(NULL, waitfor_pid); /* waitpid(WNOHANG) inside */
  10896. debug_printf_exec("checkjobs:%d\n", ret);
  10897. # if ENABLE_HUSH_JOB
  10898. if (waitfor_pipe) {
  10899. int rcode = job_exited_or_stopped(waitfor_pipe);
  10900. debug_printf_exec("job_exited_or_stopped:%d\n", rcode);
  10901. if (rcode >= 0) {
  10902. ret = rcode;
  10903. sigprocmask(SIG_SETMASK, &oldset, NULL);
  10904. break;
  10905. }
  10906. }
  10907. # endif
  10908. /* if ECHILD, there are no children (ret is -1 or 0) */
  10909. /* if ret == 0, no children changed state */
  10910. /* if ret != 0, it's exitcode+1 of exited waitfor_pid child */
  10911. if (errno == ECHILD || ret) {
  10912. ret--;
  10913. if (ret < 0) /* if ECHILD, may need to fix "ret" */
  10914. ret = 0;
  10915. # if ENABLE_HUSH_BASH_COMPAT
  10916. if (waitfor_pid == -1 && errno == ECHILD) {
  10917. /* exitcode of "wait -n" with no children is 127, not 0 */
  10918. ret = 127;
  10919. }
  10920. # endif
  10921. sigprocmask(SIG_SETMASK, &oldset, NULL);
  10922. break;
  10923. }
  10924. /* Wait for SIGCHLD or any other signal */
  10925. /* It is vitally important for sigsuspend that SIGCHLD has non-DFL handler! */
  10926. /* Note: sigsuspend invokes signal handler */
  10927. sigsuspend(&oldset);
  10928. /* ^^^ add "sigdelset(&oldset, SIGCHLD)" before sigsuspend
  10929. * to make sure SIGCHLD is not masked off?
  10930. * It was reported that this:
  10931. * fn() { : | return; }
  10932. * shopt -s lastpipe
  10933. * fn
  10934. * exec hush SCRIPT
  10935. * under bash 4.4.23 runs SCRIPT with SIGCHLD masked,
  10936. * making "wait" commands in SCRIPT block forever.
  10937. */
  10938. restore:
  10939. sigprocmask(SIG_SETMASK, &oldset, NULL);
  10940. check_sig:
  10941. /* So, did we get a signal? */
  10942. sig = check_and_run_traps();
  10943. if (sig /*&& sig != SIGCHLD - always true */) {
  10944. /* Do this for any (non-ignored) signal, not only for ^C */
  10945. ret = 128 | sig;
  10946. break;
  10947. }
  10948. /* SIGCHLD, or no signal, or ignored one, such as SIGQUIT. Repeat */
  10949. }
  10950. return ret;
  10951. }
  10952. static int FAST_FUNC builtin_wait(char **argv)
  10953. {
  10954. int ret;
  10955. int status;
  10956. argv = skip_dash_dash(argv);
  10957. # if ENABLE_HUSH_BASH_COMPAT
  10958. if (argv[0] && strcmp(argv[0], "-n") == 0) {
  10959. /* wait -n */
  10960. /* (bash accepts "wait -n PID" too and ignores PID) */
  10961. G.dead_job_exitcode = -1;
  10962. return wait_for_child_or_signal(NULL, -1 /*no job, wait for one job*/);
  10963. }
  10964. # endif
  10965. if (argv[0] == NULL) {
  10966. /* Don't care about wait results */
  10967. /* Note 1: must wait until there are no more children */
  10968. /* Note 2: must be interruptible */
  10969. /* Examples:
  10970. * $ sleep 3 & sleep 6 & wait
  10971. * [1] 30934 sleep 3
  10972. * [2] 30935 sleep 6
  10973. * [1] Done sleep 3
  10974. * [2] Done sleep 6
  10975. * $ sleep 3 & sleep 6 & wait
  10976. * [1] 30936 sleep 3
  10977. * [2] 30937 sleep 6
  10978. * [1] Done sleep 3
  10979. * ^C <-- after ~4 sec from keyboard
  10980. * $
  10981. */
  10982. return wait_for_child_or_signal(NULL, 0 /*no job and no pid to wait for*/);
  10983. }
  10984. do {
  10985. pid_t pid = bb_strtou(*argv, NULL, 10);
  10986. if (errno || pid <= 0) {
  10987. # if ENABLE_HUSH_JOB
  10988. if (argv[0][0] == '%') {
  10989. struct pipe *wait_pipe;
  10990. ret = 127; /* bash compat for bad jobspecs */
  10991. wait_pipe = parse_jobspec(*argv);
  10992. if (wait_pipe) {
  10993. ret = job_exited_or_stopped(wait_pipe);
  10994. if (ret < 0) {
  10995. ret = wait_for_child_or_signal(wait_pipe, 0);
  10996. } else {
  10997. /* waiting on "last dead job" removes it */
  10998. clean_up_last_dead_job();
  10999. }
  11000. }
  11001. /* else: parse_jobspec() already emitted error msg */
  11002. continue;
  11003. }
  11004. # endif
  11005. /* mimic bash message */
  11006. bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
  11007. ret = EXIT_FAILURE;
  11008. continue; /* bash checks all argv[] */
  11009. }
  11010. /* Do we have such child? */
  11011. ret = waitpid(pid, &status, WNOHANG);
  11012. if (ret < 0) {
  11013. /* No */
  11014. ret = 127;
  11015. if (errno == ECHILD) {
  11016. if (pid == G.last_bg_pid) {
  11017. /* "wait $!" but last bg task has already exited. Try:
  11018. * (sleep 1; exit 3) & sleep 2; echo $?; wait $!; echo $?
  11019. * In bash it prints exitcode 0, then 3.
  11020. * In dash, it is 127.
  11021. */
  11022. ret = G.last_bg_pid_exitcode;
  11023. } else {
  11024. /* Example: "wait 1". mimic bash message */
  11025. bb_error_msg("wait: pid %u is not a child of this shell", (unsigned)pid);
  11026. }
  11027. } else {
  11028. /* ??? */
  11029. bb_perror_msg("wait %s", *argv);
  11030. }
  11031. continue; /* bash checks all argv[] */
  11032. }
  11033. if (ret == 0) {
  11034. /* Yes, and it still runs */
  11035. ret = wait_for_child_or_signal(NULL, pid);
  11036. } else {
  11037. /* Yes, and it just exited */
  11038. process_wait_result(NULL, pid, status);
  11039. ret = WEXITSTATUS(status);
  11040. if (WIFSIGNALED(status))
  11041. ret = 128 | WTERMSIG(status);
  11042. }
  11043. } while (*++argv);
  11044. return ret;
  11045. }
  11046. #endif
  11047. #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
  11048. static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
  11049. {
  11050. if (argv[1]) {
  11051. def = bb_strtou(argv[1], NULL, 10);
  11052. if (errno || def < def_min || argv[2]) {
  11053. bb_error_msg("%s: bad arguments", argv[0]);
  11054. def = UINT_MAX;
  11055. }
  11056. }
  11057. return def;
  11058. }
  11059. #endif
  11060. #if ENABLE_HUSH_LOOPS
  11061. static int FAST_FUNC builtin_break(char **argv)
  11062. {
  11063. unsigned depth;
  11064. if (G.depth_of_loop == 0) {
  11065. bb_error_msg("%s: only meaningful in a loop", argv[0]);
  11066. /* if we came from builtin_continue(), need to undo "= 1" */
  11067. G.flag_break_continue = 0;
  11068. return EXIT_SUCCESS; /* bash compat */
  11069. }
  11070. G.flag_break_continue++; /* BC_BREAK = 1, or BC_CONTINUE = 2 */
  11071. G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
  11072. if (depth == UINT_MAX)
  11073. G.flag_break_continue = BC_BREAK;
  11074. if (G.depth_of_loop < depth)
  11075. G.depth_break_continue = G.depth_of_loop;
  11076. return EXIT_SUCCESS;
  11077. }
  11078. static int FAST_FUNC builtin_continue(char **argv)
  11079. {
  11080. G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
  11081. return builtin_break(argv);
  11082. }
  11083. #endif
  11084. #if ENABLE_HUSH_FUNCTIONS
  11085. static int FAST_FUNC builtin_return(char **argv)
  11086. {
  11087. int rc;
  11088. if (G_flag_return_in_progress != -1) {
  11089. bb_error_msg("%s: not in a function or sourced script", argv[0]);
  11090. return EXIT_FAILURE; /* bash compat */
  11091. }
  11092. G_flag_return_in_progress = 1;
  11093. /* bash:
  11094. * out of range: wraps around at 256, does not error out
  11095. * non-numeric param:
  11096. * f() { false; return qwe; }; f; echo $?
  11097. * bash: return: qwe: numeric argument required <== we do this
  11098. * 255 <== we also do this
  11099. */
  11100. rc = parse_numeric_argv1(argv, G.last_exitcode, 0);
  11101. # if ENABLE_HUSH_TRAP
  11102. if (argv[1]) { /* "return ARG" inside a running trap sets $? */
  11103. debug_printf_exec("G.return_exitcode=%d\n", rc);
  11104. G.return_exitcode = rc;
  11105. }
  11106. # endif
  11107. return rc;
  11108. }
  11109. #endif
  11110. #if ENABLE_HUSH_TIMES
  11111. static int FAST_FUNC builtin_times(char **argv UNUSED_PARAM)
  11112. {
  11113. static const uint8_t times_tbl[] ALIGN1 = {
  11114. ' ', offsetof(struct tms, tms_utime),
  11115. '\n', offsetof(struct tms, tms_stime),
  11116. ' ', offsetof(struct tms, tms_cutime),
  11117. '\n', offsetof(struct tms, tms_cstime),
  11118. 0
  11119. };
  11120. const uint8_t *p;
  11121. unsigned clk_tck;
  11122. struct tms buf;
  11123. clk_tck = bb_clk_tck();
  11124. times(&buf);
  11125. p = times_tbl;
  11126. do {
  11127. unsigned sec, frac;
  11128. unsigned long t;
  11129. t = *(clock_t *)(((char *) &buf) + p[1]);
  11130. sec = t / clk_tck;
  11131. frac = t % clk_tck;
  11132. printf("%um%u.%03us%c",
  11133. sec / 60, sec % 60,
  11134. (frac * 1000) / clk_tck,
  11135. p[0]);
  11136. p += 2;
  11137. } while (*p);
  11138. return EXIT_SUCCESS;
  11139. }
  11140. #endif
  11141. #if ENABLE_HUSH_MEMLEAK
  11142. static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
  11143. {
  11144. void *p;
  11145. unsigned long l;
  11146. # ifdef M_TRIM_THRESHOLD
  11147. /* Optional. Reduces probability of false positives */
  11148. malloc_trim(0);
  11149. # endif
  11150. /* Crude attempt to find where "free memory" starts,
  11151. * sans fragmentation. */
  11152. p = malloc(240);
  11153. l = (unsigned long)p;
  11154. free(p);
  11155. p = malloc(3400);
  11156. if (l < (unsigned long)p) l = (unsigned long)p;
  11157. free(p);
  11158. # if 0 /* debug */
  11159. {
  11160. struct mallinfo mi = mallinfo();
  11161. printf("top alloc:0x%lx malloced:%d+%d=%d\n", l,
  11162. mi.arena, mi.hblkhd, mi.arena + mi.hblkhd);
  11163. }
  11164. # endif
  11165. if (!G.memleak_value)
  11166. G.memleak_value = l;
  11167. l -= G.memleak_value;
  11168. if ((long)l < 0)
  11169. l = 0;
  11170. l /= 1024;
  11171. if (l > 127)
  11172. l = 127;
  11173. /* Exitcode is "how many kilobytes we leaked since 1st call" */
  11174. return l;
  11175. }
  11176. #endif