hush.c 251 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234
  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. * special variables (done: PWD, PPID, RANDOM)
  45. * tilde expansion
  46. * aliases
  47. * follow IFS rules more precisely, including update semantics
  48. * builtins mandated by standards we don't support:
  49. * [un]alias, command, fc, getopts, newgrp, readonly, times
  50. * make complex ${var%...} constructs support optional
  51. * make here documents optional
  52. *
  53. * Bash compat TODO:
  54. * redirection of stdout+stderr: &> and >&
  55. * reserved words: function select
  56. * advanced test: [[ ]]
  57. * process substitution: <(list) and >(list)
  58. * =~: regex operator
  59. * let EXPR [EXPR...]
  60. * Each EXPR is an arithmetic expression (ARITHMETIC EVALUATION)
  61. * If the last arg evaluates to 0, let returns 1; 0 otherwise.
  62. * NB: let `echo 'a=a + 1'` - error (IOW: multi-word expansion is used)
  63. * ((EXPR))
  64. * The EXPR is evaluated according to ARITHMETIC EVALUATION.
  65. * This is exactly equivalent to let "EXPR".
  66. * $[EXPR]: synonym for $((EXPR))
  67. *
  68. * Won't do:
  69. * In bash, export builtin is special, its arguments are assignments
  70. * and therefore expansion of them should be "one-word" expansion:
  71. * $ export i=`echo 'a b'` # export has one arg: "i=a b"
  72. * compare with:
  73. * $ ls i=`echo 'a b'` # ls has two args: "i=a" and "b"
  74. * ls: cannot access i=a: No such file or directory
  75. * ls: cannot access b: No such file or directory
  76. * Note1: same applies to local builtin.
  77. * Note2: bash 3.2.33(1) does this only if export word itself
  78. * is not quoted:
  79. * $ export i=`echo 'aaa bbb'`; echo "$i"
  80. * aaa bbb
  81. * $ "export" i=`echo 'aaa bbb'`; echo "$i"
  82. * aaa
  83. */
  84. #if !(defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) \
  85. || defined(__APPLE__) \
  86. )
  87. # include <malloc.h> /* for malloc_trim */
  88. #endif
  89. #include <glob.h>
  90. /* #include <dmalloc.h> */
  91. #if ENABLE_HUSH_CASE
  92. # include <fnmatch.h>
  93. #endif
  94. #include <sys/utsname.h> /* for setting $HOSTNAME */
  95. #include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
  96. #include "unicode.h"
  97. #include "shell_common.h"
  98. #include "math.h"
  99. #include "match.h"
  100. #if ENABLE_HUSH_RANDOM_SUPPORT
  101. # include "random.h"
  102. #else
  103. # define CLEAR_RANDOM_T(rnd) ((void)0)
  104. #endif
  105. #ifndef PIPE_BUF
  106. # define PIPE_BUF 4096 /* amount of buffering in a pipe */
  107. #endif
  108. //config:config HUSH
  109. //config: bool "hush"
  110. //config: default y
  111. //config: help
  112. //config: hush is a small shell (25k). It handles the normal flow control
  113. //config: constructs such as if/then/elif/else/fi, for/in/do/done, while loops,
  114. //config: case/esac. Redirections, here documents, $((arithmetic))
  115. //config: and functions are supported.
  116. //config:
  117. //config: It will compile and work on no-mmu systems.
  118. //config:
  119. //config: It does not handle select, aliases, tilde expansion,
  120. //config: &>file and >&file redirection of stdout+stderr.
  121. //config:
  122. //config:config HUSH_BASH_COMPAT
  123. //config: bool "bash-compatible extensions"
  124. //config: default y
  125. //config: depends on HUSH
  126. //config: help
  127. //config: Enable bash-compatible extensions.
  128. //config:
  129. //config:config HUSH_BRACE_EXPANSION
  130. //config: bool "Brace expansion"
  131. //config: default y
  132. //config: depends on HUSH_BASH_COMPAT
  133. //config: help
  134. //config: Enable {abc,def} extension.
  135. //config:
  136. //config:config HUSH_HELP
  137. //config: bool "help builtin"
  138. //config: default y
  139. //config: depends on HUSH
  140. //config: help
  141. //config: Enable help builtin in hush. Code size + ~1 kbyte.
  142. //config:
  143. //config:config HUSH_INTERACTIVE
  144. //config: bool "Interactive mode"
  145. //config: default y
  146. //config: depends on HUSH
  147. //config: help
  148. //config: Enable interactive mode (prompt and command editing).
  149. //config: Without this, hush simply reads and executes commands
  150. //config: from stdin just like a shell script from a file.
  151. //config: No prompt, no PS1/PS2 magic shell variables.
  152. //config:
  153. //config:config HUSH_SAVEHISTORY
  154. //config: bool "Save command history to .hush_history"
  155. //config: default y
  156. //config: depends on HUSH_INTERACTIVE && FEATURE_EDITING_SAVEHISTORY
  157. //config: help
  158. //config: Enable history saving in hush.
  159. //config:
  160. //config:config HUSH_JOB
  161. //config: bool "Job control"
  162. //config: default y
  163. //config: depends on HUSH_INTERACTIVE
  164. //config: help
  165. //config: Enable job control: Ctrl-Z backgrounds, Ctrl-C interrupts current
  166. //config: command (not entire shell), fg/bg builtins work. Without this option,
  167. //config: "cmd &" still works by simply spawning a process and immediately
  168. //config: prompting for next command (or executing next command in a script),
  169. //config: but no separate process group is formed.
  170. //config:
  171. //config:config HUSH_TICK
  172. //config: bool "Process substitution"
  173. //config: default y
  174. //config: depends on HUSH
  175. //config: help
  176. //config: Enable process substitution `command` and $(command) in hush.
  177. //config:
  178. //config:config HUSH_IF
  179. //config: bool "Support if/then/elif/else/fi"
  180. //config: default y
  181. //config: depends on HUSH
  182. //config: help
  183. //config: Enable if/then/elif/else/fi in hush.
  184. //config:
  185. //config:config HUSH_LOOPS
  186. //config: bool "Support for, while and until loops"
  187. //config: default y
  188. //config: depends on HUSH
  189. //config: help
  190. //config: Enable for, while and until loops in hush.
  191. //config:
  192. //config:config HUSH_CASE
  193. //config: bool "Support case ... esac statement"
  194. //config: default y
  195. //config: depends on HUSH
  196. //config: help
  197. //config: Enable case ... esac statement in hush. +400 bytes.
  198. //config:
  199. //config:config HUSH_FUNCTIONS
  200. //config: bool "Support funcname() { commands; } syntax"
  201. //config: default y
  202. //config: depends on HUSH
  203. //config: help
  204. //config: Enable support for shell functions in hush. +800 bytes.
  205. //config:
  206. //config:config HUSH_LOCAL
  207. //config: bool "Support local builtin"
  208. //config: default y
  209. //config: depends on HUSH_FUNCTIONS
  210. //config: help
  211. //config: Enable support for local variables in functions.
  212. //config:
  213. //config:config HUSH_RANDOM_SUPPORT
  214. //config: bool "Pseudorandom generator and $RANDOM variable"
  215. //config: default y
  216. //config: depends on HUSH
  217. //config: help
  218. //config: Enable pseudorandom generator and dynamic variable "$RANDOM".
  219. //config: Each read of "$RANDOM" will generate a new pseudorandom value.
  220. //config:
  221. //config:config HUSH_EXPORT_N
  222. //config: bool "Support 'export -n' option"
  223. //config: default y
  224. //config: depends on HUSH
  225. //config: help
  226. //config: export -n unexports variables. It is a bash extension.
  227. //config:
  228. //config:config HUSH_MODE_X
  229. //config: bool "Support 'hush -x' option and 'set -x' command"
  230. //config: default y
  231. //config: depends on HUSH
  232. //config: help
  233. //config: This instructs hush to print commands before execution.
  234. //config: Adds ~300 bytes.
  235. //config:
  236. //config:config MSH
  237. //config: bool "msh (deprecated: aliased to hush)"
  238. //config: default n
  239. //config: select HUSH
  240. //config: help
  241. //config: msh is deprecated and will be removed, please migrate to hush.
  242. //config:
  243. //applet:IF_HUSH(APPLET(hush, BB_DIR_BIN, BB_SUID_DROP))
  244. //applet:IF_MSH(APPLET(msh, BB_DIR_BIN, BB_SUID_DROP))
  245. //applet:IF_FEATURE_SH_IS_HUSH(APPLET_ODDNAME(sh, hush, BB_DIR_BIN, BB_SUID_DROP, sh))
  246. //applet:IF_FEATURE_BASH_IS_HUSH(APPLET_ODDNAME(bash, hush, BB_DIR_BIN, BB_SUID_DROP, bash))
  247. //kbuild:lib-$(CONFIG_HUSH) += hush.o match.o shell_common.o
  248. //kbuild:lib-$(CONFIG_HUSH_RANDOM_SUPPORT) += random.o
  249. /* -i (interactive) and -s (read stdin) are also accepted,
  250. * but currently do nothing, therefore aren't shown in help.
  251. * NOMMU-specific options are not meant to be used by users,
  252. * therefore we don't show them either.
  253. */
  254. //usage:#define hush_trivial_usage
  255. //usage: "[-nxl] [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS]]"
  256. //usage:#define hush_full_usage "\n\n"
  257. //usage: "Unix shell interpreter"
  258. //usage:#define msh_trivial_usage hush_trivial_usage
  259. //usage:#define msh_full_usage hush_full_usage
  260. //usage:#if ENABLE_FEATURE_SH_IS_HUSH
  261. //usage:# define sh_trivial_usage hush_trivial_usage
  262. //usage:# define sh_full_usage hush_full_usage
  263. //usage:#endif
  264. //usage:#if ENABLE_FEATURE_BASH_IS_HUSH
  265. //usage:# define bash_trivial_usage hush_trivial_usage
  266. //usage:# define bash_full_usage hush_full_usage
  267. //usage:#endif
  268. /* Build knobs */
  269. #define LEAK_HUNTING 0
  270. #define BUILD_AS_NOMMU 0
  271. /* Enable/disable sanity checks. Ok to enable in production,
  272. * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
  273. * Keeping 1 for now even in released versions.
  274. */
  275. #define HUSH_DEBUG 1
  276. /* Slightly bigger (+200 bytes), but faster hush.
  277. * So far it only enables a trick with counting SIGCHLDs and forks,
  278. * which allows us to do fewer waitpid's.
  279. * (we can detect a case where neither forks were done nor SIGCHLDs happened
  280. * and therefore waitpid will return the same result as last time)
  281. */
  282. #define ENABLE_HUSH_FAST 0
  283. /* TODO: implement simplified code for users which do not need ${var%...} ops
  284. * So far ${var%...} ops are always enabled:
  285. */
  286. #define ENABLE_HUSH_DOLLAR_OPS 1
  287. #if BUILD_AS_NOMMU
  288. # undef BB_MMU
  289. # undef USE_FOR_NOMMU
  290. # undef USE_FOR_MMU
  291. # define BB_MMU 0
  292. # define USE_FOR_NOMMU(...) __VA_ARGS__
  293. # define USE_FOR_MMU(...)
  294. #endif
  295. #include "NUM_APPLETS.h"
  296. #if NUM_APPLETS == 1
  297. /* STANDALONE does not make sense, and won't compile */
  298. # undef CONFIG_FEATURE_SH_STANDALONE
  299. # undef ENABLE_FEATURE_SH_STANDALONE
  300. # undef IF_FEATURE_SH_STANDALONE
  301. # undef IF_NOT_FEATURE_SH_STANDALONE
  302. # define ENABLE_FEATURE_SH_STANDALONE 0
  303. # define IF_FEATURE_SH_STANDALONE(...)
  304. # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
  305. #endif
  306. #if !ENABLE_HUSH_INTERACTIVE
  307. # undef ENABLE_FEATURE_EDITING
  308. # define ENABLE_FEATURE_EDITING 0
  309. # undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
  310. # define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
  311. # undef ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
  312. # define ENABLE_FEATURE_EDITING_SAVE_ON_EXIT 0
  313. #endif
  314. /* Do we support ANY keywords? */
  315. #if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
  316. # define HAS_KEYWORDS 1
  317. # define IF_HAS_KEYWORDS(...) __VA_ARGS__
  318. # define IF_HAS_NO_KEYWORDS(...)
  319. #else
  320. # define HAS_KEYWORDS 0
  321. # define IF_HAS_KEYWORDS(...)
  322. # define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
  323. #endif
  324. /* If you comment out one of these below, it will be #defined later
  325. * to perform debug printfs to stderr: */
  326. #define debug_printf(...) do {} while (0)
  327. /* Finer-grained debug switches */
  328. #define debug_printf_parse(...) do {} while (0)
  329. #define debug_print_tree(a, b) do {} while (0)
  330. #define debug_printf_exec(...) do {} while (0)
  331. #define debug_printf_env(...) do {} while (0)
  332. #define debug_printf_jobs(...) do {} while (0)
  333. #define debug_printf_expand(...) do {} while (0)
  334. #define debug_printf_varexp(...) do {} while (0)
  335. #define debug_printf_glob(...) do {} while (0)
  336. #define debug_printf_list(...) do {} while (0)
  337. #define debug_printf_subst(...) do {} while (0)
  338. #define debug_printf_clean(...) do {} while (0)
  339. #define ERR_PTR ((void*)(long)1)
  340. #define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
  341. #define _SPECIAL_VARS_STR "_*@$!?#"
  342. #define SPECIAL_VARS_STR ("_*@$!?#" + 1)
  343. #define NUMERIC_SPECVARS_STR ("_*@$!?#" + 3)
  344. #if ENABLE_HUSH_BASH_COMPAT
  345. /* Support / and // replace ops */
  346. /* Note that // is stored as \ in "encoded" string representation */
  347. # define VAR_ENCODED_SUBST_OPS "\\/%#:-=+?"
  348. # define VAR_SUBST_OPS ("\\/%#:-=+?" + 1)
  349. # define MINUS_PLUS_EQUAL_QUESTION ("\\/%#:-=+?" + 5)
  350. #else
  351. # define VAR_ENCODED_SUBST_OPS "%#:-=+?"
  352. # define VAR_SUBST_OPS "%#:-=+?"
  353. # define MINUS_PLUS_EQUAL_QUESTION ("%#:-=+?" + 3)
  354. #endif
  355. #define SPECIAL_VAR_SYMBOL 3
  356. struct variable;
  357. static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
  358. /* This supports saving pointers malloced in vfork child,
  359. * to be freed in the parent.
  360. */
  361. #if !BB_MMU
  362. typedef struct nommu_save_t {
  363. char **new_env;
  364. struct variable *old_vars;
  365. char **argv;
  366. char **argv_from_re_execing;
  367. } nommu_save_t;
  368. #endif
  369. enum {
  370. RES_NONE = 0,
  371. #if ENABLE_HUSH_IF
  372. RES_IF ,
  373. RES_THEN ,
  374. RES_ELIF ,
  375. RES_ELSE ,
  376. RES_FI ,
  377. #endif
  378. #if ENABLE_HUSH_LOOPS
  379. RES_FOR ,
  380. RES_WHILE ,
  381. RES_UNTIL ,
  382. RES_DO ,
  383. RES_DONE ,
  384. #endif
  385. #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
  386. RES_IN ,
  387. #endif
  388. #if ENABLE_HUSH_CASE
  389. RES_CASE ,
  390. /* three pseudo-keywords support contrived "case" syntax: */
  391. RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
  392. RES_MATCH , /* "word)" */
  393. RES_CASE_BODY, /* "this command is inside CASE" */
  394. RES_ESAC ,
  395. #endif
  396. RES_XXXX ,
  397. RES_SNTX
  398. };
  399. typedef struct o_string {
  400. char *data;
  401. int length; /* position where data is appended */
  402. int maxlen;
  403. int o_expflags;
  404. /* At least some part of the string was inside '' or "",
  405. * possibly empty one: word"", wo''rd etc. */
  406. smallint has_quoted_part;
  407. smallint has_empty_slot;
  408. smallint o_assignment; /* 0:maybe, 1:yes, 2:no */
  409. } o_string;
  410. enum {
  411. EXP_FLAG_SINGLEWORD = 0x80, /* must be 0x80 */
  412. EXP_FLAG_GLOB = 0x2,
  413. /* Protect newly added chars against globbing
  414. * by prepending \ to *, ?, [, \ */
  415. EXP_FLAG_ESC_GLOB_CHARS = 0x1,
  416. };
  417. enum {
  418. MAYBE_ASSIGNMENT = 0,
  419. DEFINITELY_ASSIGNMENT = 1,
  420. NOT_ASSIGNMENT = 2,
  421. /* Not an assignment, but next word may be: "if v=xyz cmd;" */
  422. WORD_IS_KEYWORD = 3,
  423. };
  424. /* Used for initialization: o_string foo = NULL_O_STRING; */
  425. #define NULL_O_STRING { NULL }
  426. #ifndef debug_printf_parse
  427. static const char *const assignment_flag[] = {
  428. "MAYBE_ASSIGNMENT",
  429. "DEFINITELY_ASSIGNMENT",
  430. "NOT_ASSIGNMENT",
  431. "WORD_IS_KEYWORD",
  432. };
  433. #endif
  434. typedef struct in_str {
  435. const char *p;
  436. /* eof_flag=1: last char in ->p is really an EOF */
  437. char eof_flag; /* meaningless if ->p == NULL */
  438. char peek_buf[2];
  439. #if ENABLE_HUSH_INTERACTIVE
  440. smallint promptmode; /* 0: PS1, 1: PS2 */
  441. #endif
  442. int last_char;
  443. FILE *file;
  444. int (*get) (struct in_str *) FAST_FUNC;
  445. int (*peek) (struct in_str *) FAST_FUNC;
  446. } in_str;
  447. #define i_getch(input) ((input)->get(input))
  448. #define i_peek(input) ((input)->peek(input))
  449. /* The descrip member of this structure is only used to make
  450. * debugging output pretty */
  451. static const struct {
  452. int mode;
  453. signed char default_fd;
  454. char descrip[3];
  455. } redir_table[] = {
  456. { O_RDONLY, 0, "<" },
  457. { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
  458. { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
  459. { O_CREAT|O_RDWR, 1, "<>" },
  460. { O_RDONLY, 0, "<<" },
  461. /* Should not be needed. Bogus default_fd helps in debugging */
  462. /* { O_RDONLY, 77, "<<" }, */
  463. };
  464. struct redir_struct {
  465. struct redir_struct *next;
  466. char *rd_filename; /* filename */
  467. int rd_fd; /* fd to redirect */
  468. /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
  469. int rd_dup;
  470. smallint rd_type; /* (enum redir_type) */
  471. /* note: for heredocs, rd_filename contains heredoc delimiter,
  472. * and subsequently heredoc itself; and rd_dup is a bitmask:
  473. * bit 0: do we need to trim leading tabs?
  474. * bit 1: is heredoc quoted (<<'delim' syntax) ?
  475. */
  476. };
  477. typedef enum redir_type {
  478. REDIRECT_INPUT = 0,
  479. REDIRECT_OVERWRITE = 1,
  480. REDIRECT_APPEND = 2,
  481. REDIRECT_IO = 3,
  482. REDIRECT_HEREDOC = 4,
  483. REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
  484. REDIRFD_CLOSE = -3,
  485. REDIRFD_SYNTAX_ERR = -2,
  486. REDIRFD_TO_FILE = -1,
  487. /* otherwise, rd_fd is redirected to rd_dup */
  488. HEREDOC_SKIPTABS = 1,
  489. HEREDOC_QUOTED = 2,
  490. } redir_type;
  491. struct command {
  492. pid_t pid; /* 0 if exited */
  493. int assignment_cnt; /* how many argv[i] are assignments? */
  494. smallint cmd_type; /* CMD_xxx */
  495. #define CMD_NORMAL 0
  496. #define CMD_SUBSHELL 1
  497. #if ENABLE_HUSH_BASH_COMPAT
  498. /* used for "[[ EXPR ]]" */
  499. # define CMD_SINGLEWORD_NOGLOB 2
  500. #endif
  501. #if ENABLE_HUSH_FUNCTIONS
  502. # define CMD_FUNCDEF 3
  503. #endif
  504. smalluint cmd_exitcode;
  505. /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
  506. struct pipe *group;
  507. #if !BB_MMU
  508. char *group_as_string;
  509. #endif
  510. #if ENABLE_HUSH_FUNCTIONS
  511. struct function *child_func;
  512. /* This field is used to prevent a bug here:
  513. * while...do f1() {a;}; f1; f1() {b;}; f1; done
  514. * When we execute "f1() {a;}" cmd, we create new function and clear
  515. * cmd->group, cmd->group_as_string, cmd->argv[0].
  516. * When we execute "f1() {b;}", we notice that f1 exists,
  517. * and that its "parent cmd" struct is still "alive",
  518. * we put those fields back into cmd->xxx
  519. * (struct function has ->parent_cmd ptr to facilitate that).
  520. * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
  521. * Without this trick, loop would execute a;b;b;b;...
  522. * instead of correct sequence a;b;a;b;...
  523. * When command is freed, it severs the link
  524. * (sets ->child_func->parent_cmd to NULL).
  525. */
  526. #endif
  527. char **argv; /* command name and arguments */
  528. /* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
  529. * and on execution these are substituted with their values.
  530. * Substitution can make _several_ words out of one argv[n]!
  531. * Example: argv[0]=='.^C*^C.' here: echo .$*.
  532. * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
  533. */
  534. struct redir_struct *redirects; /* I/O redirections */
  535. };
  536. /* Is there anything in this command at all? */
  537. #define IS_NULL_CMD(cmd) \
  538. (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
  539. struct pipe {
  540. struct pipe *next;
  541. int num_cmds; /* total number of commands in pipe */
  542. int alive_cmds; /* number of commands running (not exited) */
  543. int stopped_cmds; /* number of commands alive, but stopped */
  544. #if ENABLE_HUSH_JOB
  545. int jobid; /* job number */
  546. pid_t pgrp; /* process group ID for the job */
  547. char *cmdtext; /* name of job */
  548. #endif
  549. struct command *cmds; /* array of commands in pipe */
  550. smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
  551. IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
  552. IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
  553. };
  554. typedef enum pipe_style {
  555. PIPE_SEQ = 1,
  556. PIPE_AND = 2,
  557. PIPE_OR = 3,
  558. PIPE_BG = 4,
  559. } pipe_style;
  560. /* Is there anything in this pipe at all? */
  561. #define IS_NULL_PIPE(pi) \
  562. ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
  563. /* This holds pointers to the various results of parsing */
  564. struct parse_context {
  565. /* linked list of pipes */
  566. struct pipe *list_head;
  567. /* last pipe (being constructed right now) */
  568. struct pipe *pipe;
  569. /* last command in pipe (being constructed right now) */
  570. struct command *command;
  571. /* last redirect in command->redirects list */
  572. struct redir_struct *pending_redirect;
  573. #if !BB_MMU
  574. o_string as_string;
  575. #endif
  576. #if HAS_KEYWORDS
  577. smallint ctx_res_w;
  578. smallint ctx_inverted; /* "! cmd | cmd" */
  579. #if ENABLE_HUSH_CASE
  580. smallint ctx_dsemicolon; /* ";;" seen */
  581. #endif
  582. /* bitmask of FLAG_xxx, for figuring out valid reserved words */
  583. int old_flag;
  584. /* group we are enclosed in:
  585. * example: "if pipe1; pipe2; then pipe3; fi"
  586. * when we see "if" or "then", we malloc and copy current context,
  587. * and make ->stack point to it. then we parse pipeN.
  588. * when closing "then" / fi" / whatever is found,
  589. * we move list_head into ->stack->command->group,
  590. * copy ->stack into current context, and delete ->stack.
  591. * (parsing of { list } and ( list ) doesn't use this method)
  592. */
  593. struct parse_context *stack;
  594. #endif
  595. };
  596. /* On program start, environ points to initial environment.
  597. * putenv adds new pointers into it, unsetenv removes them.
  598. * Neither of these (de)allocates the strings.
  599. * setenv allocates new strings in malloc space and does putenv,
  600. * and thus setenv is unusable (leaky) for shell's purposes */
  601. #define setenv(...) setenv_is_leaky_dont_use()
  602. struct variable {
  603. struct variable *next;
  604. char *varstr; /* points to "name=" portion */
  605. #if ENABLE_HUSH_LOCAL
  606. unsigned func_nest_level;
  607. #endif
  608. int max_len; /* if > 0, name is part of initial env; else name is malloced */
  609. smallint flg_export; /* putenv should be done on this var */
  610. smallint flg_read_only;
  611. };
  612. enum {
  613. BC_BREAK = 1,
  614. BC_CONTINUE = 2,
  615. };
  616. #if ENABLE_HUSH_FUNCTIONS
  617. struct function {
  618. struct function *next;
  619. char *name;
  620. struct command *parent_cmd;
  621. struct pipe *body;
  622. # if !BB_MMU
  623. char *body_as_string;
  624. # endif
  625. };
  626. #endif
  627. /* set -/+o OPT support. (TODO: make it optional)
  628. * bash supports the following opts:
  629. * allexport off
  630. * braceexpand on
  631. * emacs on
  632. * errexit off
  633. * errtrace off
  634. * functrace off
  635. * hashall on
  636. * histexpand off
  637. * history on
  638. * ignoreeof off
  639. * interactive-comments on
  640. * keyword off
  641. * monitor on
  642. * noclobber off
  643. * noexec off
  644. * noglob off
  645. * nolog off
  646. * notify off
  647. * nounset off
  648. * onecmd off
  649. * physical off
  650. * pipefail off
  651. * posix off
  652. * privileged off
  653. * verbose off
  654. * vi off
  655. * xtrace off
  656. */
  657. static const char o_opt_strings[] ALIGN1 =
  658. "pipefail\0"
  659. "noexec\0"
  660. #if ENABLE_HUSH_MODE_X
  661. "xtrace\0"
  662. #endif
  663. ;
  664. enum {
  665. OPT_O_PIPEFAIL,
  666. OPT_O_NOEXEC,
  667. #if ENABLE_HUSH_MODE_X
  668. OPT_O_XTRACE,
  669. #endif
  670. NUM_OPT_O
  671. };
  672. /* "Globals" within this file */
  673. /* Sorted roughly by size (smaller offsets == smaller code) */
  674. struct globals {
  675. /* interactive_fd != 0 means we are an interactive shell.
  676. * If we are, then saved_tty_pgrp can also be != 0, meaning
  677. * that controlling tty is available. With saved_tty_pgrp == 0,
  678. * job control still works, but terminal signals
  679. * (^C, ^Z, ^Y, ^\) won't work at all, and background
  680. * process groups can only be created with "cmd &".
  681. * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
  682. * to give tty to the foreground process group,
  683. * and will take it back when the group is stopped (^Z)
  684. * or killed (^C).
  685. */
  686. #if ENABLE_HUSH_INTERACTIVE
  687. /* 'interactive_fd' is a fd# open to ctty, if we have one
  688. * _AND_ if we decided to act interactively */
  689. int interactive_fd;
  690. const char *PS1;
  691. const char *PS2;
  692. # define G_interactive_fd (G.interactive_fd)
  693. #else
  694. # define G_interactive_fd 0
  695. #endif
  696. #if ENABLE_FEATURE_EDITING
  697. line_input_t *line_input_state;
  698. #endif
  699. pid_t root_pid;
  700. pid_t root_ppid;
  701. pid_t last_bg_pid;
  702. #if ENABLE_HUSH_RANDOM_SUPPORT
  703. random_t random_gen;
  704. #endif
  705. #if ENABLE_HUSH_JOB
  706. int run_list_level;
  707. int last_jobid;
  708. pid_t saved_tty_pgrp;
  709. struct pipe *job_list;
  710. # define G_saved_tty_pgrp (G.saved_tty_pgrp)
  711. #else
  712. # define G_saved_tty_pgrp 0
  713. #endif
  714. char o_opt[NUM_OPT_O];
  715. #if ENABLE_HUSH_MODE_X
  716. # define G_x_mode (G.o_opt[OPT_O_XTRACE])
  717. #else
  718. # define G_x_mode 0
  719. #endif
  720. smallint flag_SIGINT;
  721. #if ENABLE_HUSH_LOOPS
  722. smallint flag_break_continue;
  723. #endif
  724. #if ENABLE_HUSH_FUNCTIONS
  725. /* 0: outside of a function (or sourced file)
  726. * -1: inside of a function, ok to use return builtin
  727. * 1: return is invoked, skip all till end of func
  728. */
  729. smallint flag_return_in_progress;
  730. #endif
  731. smallint exiting; /* used to prevent EXIT trap recursion */
  732. /* These four support $?, $#, and $1 */
  733. smalluint last_exitcode;
  734. /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
  735. smalluint global_args_malloced;
  736. /* how many non-NULL argv's we have. NB: $# + 1 */
  737. int global_argc;
  738. char **global_argv;
  739. #if !BB_MMU
  740. char *argv0_for_re_execing;
  741. #endif
  742. #if ENABLE_HUSH_LOOPS
  743. unsigned depth_break_continue;
  744. unsigned depth_of_loop;
  745. #endif
  746. const char *ifs;
  747. const char *cwd;
  748. struct variable *top_var;
  749. char **expanded_assignments;
  750. #if ENABLE_HUSH_FUNCTIONS
  751. struct function *top_func;
  752. # if ENABLE_HUSH_LOCAL
  753. struct variable **shadowed_vars_pp;
  754. unsigned func_nest_level;
  755. # endif
  756. #endif
  757. /* Signal and trap handling */
  758. #if ENABLE_HUSH_FAST
  759. unsigned count_SIGCHLD;
  760. unsigned handled_SIGCHLD;
  761. smallint we_have_children;
  762. #endif
  763. /* Which signals have non-DFL handler (even with no traps set)?
  764. * Set at the start to:
  765. * (SIGQUIT + maybe SPECIAL_INTERACTIVE_SIGS + maybe SPECIAL_JOBSTOP_SIGS)
  766. * SPECIAL_INTERACTIVE_SIGS are cleared after fork.
  767. * The rest is cleared right before execv syscalls.
  768. * Other than these two times, never modified.
  769. */
  770. unsigned special_sig_mask;
  771. #if ENABLE_HUSH_JOB
  772. unsigned fatal_sig_mask;
  773. # define G_fatal_sig_mask G.fatal_sig_mask
  774. #else
  775. # define G_fatal_sig_mask 0
  776. #endif
  777. char **traps; /* char *traps[NSIG] */
  778. sigset_t pending_set;
  779. #if HUSH_DEBUG
  780. unsigned long memleak_value;
  781. int debug_indent;
  782. #endif
  783. struct sigaction sa;
  784. char user_input_buf[ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 2];
  785. };
  786. #define G (*ptr_to_globals)
  787. /* Not #defining name to G.name - this quickly gets unwieldy
  788. * (too many defines). Also, I actually prefer to see when a variable
  789. * is global, thus "G." prefix is a useful hint */
  790. #define INIT_G() do { \
  791. SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
  792. /* memset(&G.sa, 0, sizeof(G.sa)); */ \
  793. sigfillset(&G.sa.sa_mask); \
  794. G.sa.sa_flags = SA_RESTART; \
  795. } while (0)
  796. /* Function prototypes for builtins */
  797. static int builtin_cd(char **argv) FAST_FUNC;
  798. static int builtin_echo(char **argv) FAST_FUNC;
  799. static int builtin_eval(char **argv) FAST_FUNC;
  800. static int builtin_exec(char **argv) FAST_FUNC;
  801. static int builtin_exit(char **argv) FAST_FUNC;
  802. static int builtin_export(char **argv) FAST_FUNC;
  803. #if ENABLE_HUSH_JOB
  804. static int builtin_fg_bg(char **argv) FAST_FUNC;
  805. static int builtin_jobs(char **argv) FAST_FUNC;
  806. #endif
  807. #if ENABLE_HUSH_HELP
  808. static int builtin_help(char **argv) FAST_FUNC;
  809. #endif
  810. #if MAX_HISTORY && ENABLE_FEATURE_EDITING
  811. static int builtin_history(char **argv) FAST_FUNC;
  812. #endif
  813. #if ENABLE_HUSH_LOCAL
  814. static int builtin_local(char **argv) FAST_FUNC;
  815. #endif
  816. #if HUSH_DEBUG
  817. static int builtin_memleak(char **argv) FAST_FUNC;
  818. #endif
  819. #if ENABLE_PRINTF
  820. static int builtin_printf(char **argv) FAST_FUNC;
  821. #endif
  822. static int builtin_pwd(char **argv) FAST_FUNC;
  823. static int builtin_read(char **argv) FAST_FUNC;
  824. static int builtin_set(char **argv) FAST_FUNC;
  825. static int builtin_shift(char **argv) FAST_FUNC;
  826. static int builtin_source(char **argv) FAST_FUNC;
  827. static int builtin_test(char **argv) FAST_FUNC;
  828. static int builtin_trap(char **argv) FAST_FUNC;
  829. static int builtin_type(char **argv) FAST_FUNC;
  830. static int builtin_true(char **argv) FAST_FUNC;
  831. static int builtin_umask(char **argv) FAST_FUNC;
  832. static int builtin_unset(char **argv) FAST_FUNC;
  833. static int builtin_wait(char **argv) FAST_FUNC;
  834. #if ENABLE_HUSH_LOOPS
  835. static int builtin_break(char **argv) FAST_FUNC;
  836. static int builtin_continue(char **argv) FAST_FUNC;
  837. #endif
  838. #if ENABLE_HUSH_FUNCTIONS
  839. static int builtin_return(char **argv) FAST_FUNC;
  840. #endif
  841. /* Table of built-in functions. They can be forked or not, depending on
  842. * context: within pipes, they fork. As simple commands, they do not.
  843. * When used in non-forking context, they can change global variables
  844. * in the parent shell process. If forked, of course they cannot.
  845. * For example, 'unset foo | whatever' will parse and run, but foo will
  846. * still be set at the end. */
  847. struct built_in_command {
  848. const char *b_cmd;
  849. int (*b_function)(char **argv) FAST_FUNC;
  850. #if ENABLE_HUSH_HELP
  851. const char *b_descr;
  852. # define BLTIN(cmd, func, help) { cmd, func, help }
  853. #else
  854. # define BLTIN(cmd, func, help) { cmd, func }
  855. #endif
  856. };
  857. static const struct built_in_command bltins1[] = {
  858. BLTIN("." , builtin_source , "Run commands in a file"),
  859. BLTIN(":" , builtin_true , NULL),
  860. #if ENABLE_HUSH_JOB
  861. BLTIN("bg" , builtin_fg_bg , "Resume a job in the background"),
  862. #endif
  863. #if ENABLE_HUSH_LOOPS
  864. BLTIN("break" , builtin_break , "Exit from a loop"),
  865. #endif
  866. BLTIN("cd" , builtin_cd , "Change directory"),
  867. #if ENABLE_HUSH_LOOPS
  868. BLTIN("continue" , builtin_continue, "Start new loop iteration"),
  869. #endif
  870. BLTIN("eval" , builtin_eval , "Construct and run shell command"),
  871. BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
  872. BLTIN("exit" , builtin_exit , "Exit"),
  873. BLTIN("export" , builtin_export , "Set environment variables"),
  874. #if ENABLE_HUSH_JOB
  875. BLTIN("fg" , builtin_fg_bg , "Bring job into the foreground"),
  876. #endif
  877. #if ENABLE_HUSH_HELP
  878. BLTIN("help" , builtin_help , NULL),
  879. #endif
  880. #if MAX_HISTORY && ENABLE_FEATURE_EDITING
  881. BLTIN("history" , builtin_history , "Show command history"),
  882. #endif
  883. #if ENABLE_HUSH_JOB
  884. BLTIN("jobs" , builtin_jobs , "List jobs"),
  885. #endif
  886. #if ENABLE_HUSH_LOCAL
  887. BLTIN("local" , builtin_local , "Set local variables"),
  888. #endif
  889. #if HUSH_DEBUG
  890. BLTIN("memleak" , builtin_memleak , NULL),
  891. #endif
  892. BLTIN("read" , builtin_read , "Input into variable"),
  893. #if ENABLE_HUSH_FUNCTIONS
  894. BLTIN("return" , builtin_return , "Return from a function"),
  895. #endif
  896. BLTIN("set" , builtin_set , "Set/unset positional parameters"),
  897. BLTIN("shift" , builtin_shift , "Shift positional parameters"),
  898. #if ENABLE_HUSH_BASH_COMPAT
  899. BLTIN("source" , builtin_source , "Run commands in a file"),
  900. #endif
  901. BLTIN("trap" , builtin_trap , "Trap signals"),
  902. BLTIN("true" , builtin_true , NULL),
  903. BLTIN("type" , builtin_type , "Show command type"),
  904. BLTIN("ulimit" , shell_builtin_ulimit , "Control resource limits"),
  905. BLTIN("umask" , builtin_umask , "Set file creation mask"),
  906. BLTIN("unset" , builtin_unset , "Unset variables"),
  907. BLTIN("wait" , builtin_wait , "Wait for process"),
  908. };
  909. /* For now, echo and test are unconditionally enabled.
  910. * Maybe make it configurable? */
  911. static const struct built_in_command bltins2[] = {
  912. BLTIN("[" , builtin_test , NULL),
  913. BLTIN("echo" , builtin_echo , NULL),
  914. #if ENABLE_PRINTF
  915. BLTIN("printf" , builtin_printf , NULL),
  916. #endif
  917. BLTIN("pwd" , builtin_pwd , NULL),
  918. BLTIN("test" , builtin_test , NULL),
  919. };
  920. /* Debug printouts.
  921. */
  922. #if HUSH_DEBUG
  923. /* prevent disasters with G.debug_indent < 0 */
  924. # define indent() fdprintf(2, "%*s", (G.debug_indent * 2) & 0xff, "")
  925. # define debug_enter() (G.debug_indent++)
  926. # define debug_leave() (G.debug_indent--)
  927. #else
  928. # define indent() ((void)0)
  929. # define debug_enter() ((void)0)
  930. # define debug_leave() ((void)0)
  931. #endif
  932. #ifndef debug_printf
  933. # define debug_printf(...) (indent(), fdprintf(2, __VA_ARGS__))
  934. #endif
  935. #ifndef debug_printf_parse
  936. # define debug_printf_parse(...) (indent(), fdprintf(2, __VA_ARGS__))
  937. #endif
  938. #ifndef debug_printf_exec
  939. #define debug_printf_exec(...) (indent(), fdprintf(2, __VA_ARGS__))
  940. #endif
  941. #ifndef debug_printf_env
  942. # define debug_printf_env(...) (indent(), fdprintf(2, __VA_ARGS__))
  943. #endif
  944. #ifndef debug_printf_jobs
  945. # define debug_printf_jobs(...) (indent(), fdprintf(2, __VA_ARGS__))
  946. # define DEBUG_JOBS 1
  947. #else
  948. # define DEBUG_JOBS 0
  949. #endif
  950. #ifndef debug_printf_expand
  951. # define debug_printf_expand(...) (indent(), fdprintf(2, __VA_ARGS__))
  952. # define DEBUG_EXPAND 1
  953. #else
  954. # define DEBUG_EXPAND 0
  955. #endif
  956. #ifndef debug_printf_varexp
  957. # define debug_printf_varexp(...) (indent(), fdprintf(2, __VA_ARGS__))
  958. #endif
  959. #ifndef debug_printf_glob
  960. # define debug_printf_glob(...) (indent(), fdprintf(2, __VA_ARGS__))
  961. # define DEBUG_GLOB 1
  962. #else
  963. # define DEBUG_GLOB 0
  964. #endif
  965. #ifndef debug_printf_list
  966. # define debug_printf_list(...) (indent(), fdprintf(2, __VA_ARGS__))
  967. #endif
  968. #ifndef debug_printf_subst
  969. # define debug_printf_subst(...) (indent(), fdprintf(2, __VA_ARGS__))
  970. #endif
  971. #ifndef debug_printf_clean
  972. # define debug_printf_clean(...) (indent(), fdprintf(2, __VA_ARGS__))
  973. # define DEBUG_CLEAN 1
  974. #else
  975. # define DEBUG_CLEAN 0
  976. #endif
  977. #if DEBUG_EXPAND
  978. static void debug_print_strings(const char *prefix, char **vv)
  979. {
  980. indent();
  981. fdprintf(2, "%s:\n", prefix);
  982. while (*vv)
  983. fdprintf(2, " '%s'\n", *vv++);
  984. }
  985. #else
  986. # define debug_print_strings(prefix, vv) ((void)0)
  987. #endif
  988. /* Leak hunting. Use hush_leaktool.sh for post-processing.
  989. */
  990. #if LEAK_HUNTING
  991. static void *xxmalloc(int lineno, size_t size)
  992. {
  993. void *ptr = xmalloc((size + 0xff) & ~0xff);
  994. fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
  995. return ptr;
  996. }
  997. static void *xxrealloc(int lineno, void *ptr, size_t size)
  998. {
  999. ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
  1000. fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
  1001. return ptr;
  1002. }
  1003. static char *xxstrdup(int lineno, const char *str)
  1004. {
  1005. char *ptr = xstrdup(str);
  1006. fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
  1007. return ptr;
  1008. }
  1009. static void xxfree(void *ptr)
  1010. {
  1011. fdprintf(2, "free %p\n", ptr);
  1012. free(ptr);
  1013. }
  1014. # define xmalloc(s) xxmalloc(__LINE__, s)
  1015. # define xrealloc(p, s) xxrealloc(__LINE__, p, s)
  1016. # define xstrdup(s) xxstrdup(__LINE__, s)
  1017. # define free(p) xxfree(p)
  1018. #endif
  1019. /* Syntax and runtime errors. They always abort scripts.
  1020. * In interactive use they usually discard unparsed and/or unexecuted commands
  1021. * and return to the prompt.
  1022. * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
  1023. */
  1024. #if HUSH_DEBUG < 2
  1025. # define die_if_script(lineno, ...) die_if_script(__VA_ARGS__)
  1026. # define syntax_error(lineno, msg) syntax_error(msg)
  1027. # define syntax_error_at(lineno, msg) syntax_error_at(msg)
  1028. # define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
  1029. # define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
  1030. # define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
  1031. #endif
  1032. static void die_if_script(unsigned lineno, const char *fmt, ...)
  1033. {
  1034. va_list p;
  1035. #if HUSH_DEBUG >= 2
  1036. bb_error_msg("hush.c:%u", lineno);
  1037. #endif
  1038. va_start(p, fmt);
  1039. bb_verror_msg(fmt, p, NULL);
  1040. va_end(p);
  1041. if (!G_interactive_fd)
  1042. xfunc_die();
  1043. }
  1044. static void syntax_error(unsigned lineno UNUSED_PARAM, const char *msg)
  1045. {
  1046. if (msg)
  1047. bb_error_msg("syntax error: %s", msg);
  1048. else
  1049. bb_error_msg("syntax error");
  1050. }
  1051. static void syntax_error_at(unsigned lineno UNUSED_PARAM, const char *msg)
  1052. {
  1053. bb_error_msg("syntax error at '%s'", msg);
  1054. }
  1055. static void syntax_error_unterm_str(unsigned lineno UNUSED_PARAM, const char *s)
  1056. {
  1057. bb_error_msg("syntax error: unterminated %s", s);
  1058. }
  1059. static void syntax_error_unterm_ch(unsigned lineno, char ch)
  1060. {
  1061. char msg[2] = { ch, '\0' };
  1062. syntax_error_unterm_str(lineno, msg);
  1063. }
  1064. static void syntax_error_unexpected_ch(unsigned lineno UNUSED_PARAM, int ch)
  1065. {
  1066. char msg[2];
  1067. msg[0] = ch;
  1068. msg[1] = '\0';
  1069. bb_error_msg("syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
  1070. }
  1071. #if HUSH_DEBUG < 2
  1072. # undef die_if_script
  1073. # undef syntax_error
  1074. # undef syntax_error_at
  1075. # undef syntax_error_unterm_ch
  1076. # undef syntax_error_unterm_str
  1077. # undef syntax_error_unexpected_ch
  1078. #else
  1079. # define die_if_script(...) die_if_script(__LINE__, __VA_ARGS__)
  1080. # define syntax_error(msg) syntax_error(__LINE__, msg)
  1081. # define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
  1082. # define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
  1083. # define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
  1084. # define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
  1085. #endif
  1086. #if ENABLE_HUSH_INTERACTIVE
  1087. static void cmdedit_update_prompt(void);
  1088. #else
  1089. # define cmdedit_update_prompt() ((void)0)
  1090. #endif
  1091. /* Utility functions
  1092. */
  1093. /* Replace each \x with x in place, return ptr past NUL. */
  1094. static char *unbackslash(char *src)
  1095. {
  1096. char *dst = src = strchrnul(src, '\\');
  1097. while (1) {
  1098. if (*src == '\\')
  1099. src++;
  1100. if ((*dst++ = *src++) == '\0')
  1101. break;
  1102. }
  1103. return dst;
  1104. }
  1105. static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
  1106. {
  1107. int i;
  1108. unsigned count1;
  1109. unsigned count2;
  1110. char **v;
  1111. v = strings;
  1112. count1 = 0;
  1113. if (v) {
  1114. while (*v) {
  1115. count1++;
  1116. v++;
  1117. }
  1118. }
  1119. count2 = 0;
  1120. v = add;
  1121. while (*v) {
  1122. count2++;
  1123. v++;
  1124. }
  1125. v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
  1126. v[count1 + count2] = NULL;
  1127. i = count2;
  1128. while (--i >= 0)
  1129. v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
  1130. return v;
  1131. }
  1132. #if LEAK_HUNTING
  1133. static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
  1134. {
  1135. char **ptr = add_strings_to_strings(strings, add, need_to_dup);
  1136. fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
  1137. return ptr;
  1138. }
  1139. #define add_strings_to_strings(strings, add, need_to_dup) \
  1140. xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
  1141. #endif
  1142. /* Note: takes ownership of "add" ptr (it is not strdup'ed) */
  1143. static char **add_string_to_strings(char **strings, char *add)
  1144. {
  1145. char *v[2];
  1146. v[0] = add;
  1147. v[1] = NULL;
  1148. return add_strings_to_strings(strings, v, /*dup:*/ 0);
  1149. }
  1150. #if LEAK_HUNTING
  1151. static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
  1152. {
  1153. char **ptr = add_string_to_strings(strings, add);
  1154. fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
  1155. return ptr;
  1156. }
  1157. #define add_string_to_strings(strings, add) \
  1158. xx_add_string_to_strings(__LINE__, strings, add)
  1159. #endif
  1160. static void free_strings(char **strings)
  1161. {
  1162. char **v;
  1163. if (!strings)
  1164. return;
  1165. v = strings;
  1166. while (*v) {
  1167. free(*v);
  1168. v++;
  1169. }
  1170. free(strings);
  1171. }
  1172. /* Helpers for setting new $n and restoring them back
  1173. */
  1174. typedef struct save_arg_t {
  1175. char *sv_argv0;
  1176. char **sv_g_argv;
  1177. int sv_g_argc;
  1178. smallint sv_g_malloced;
  1179. } save_arg_t;
  1180. static void save_and_replace_G_args(save_arg_t *sv, char **argv)
  1181. {
  1182. int n;
  1183. sv->sv_argv0 = argv[0];
  1184. sv->sv_g_argv = G.global_argv;
  1185. sv->sv_g_argc = G.global_argc;
  1186. sv->sv_g_malloced = G.global_args_malloced;
  1187. argv[0] = G.global_argv[0]; /* retain $0 */
  1188. G.global_argv = argv;
  1189. G.global_args_malloced = 0;
  1190. n = 1;
  1191. while (*++argv)
  1192. n++;
  1193. G.global_argc = n;
  1194. }
  1195. static void restore_G_args(save_arg_t *sv, char **argv)
  1196. {
  1197. char **pp;
  1198. if (G.global_args_malloced) {
  1199. /* someone ran "set -- arg1 arg2 ...", undo */
  1200. pp = G.global_argv;
  1201. while (*++pp) /* note: does not free $0 */
  1202. free(*pp);
  1203. free(G.global_argv);
  1204. }
  1205. argv[0] = sv->sv_argv0;
  1206. G.global_argv = sv->sv_g_argv;
  1207. G.global_argc = sv->sv_g_argc;
  1208. G.global_args_malloced = sv->sv_g_malloced;
  1209. }
  1210. /* Basic theory of signal handling in shell
  1211. * ========================================
  1212. * This does not describe what hush does, rather, it is current understanding
  1213. * what it _should_ do. If it doesn't, it's a bug.
  1214. * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
  1215. *
  1216. * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
  1217. * is finished or backgrounded. It is the same in interactive and
  1218. * non-interactive shells, and is the same regardless of whether
  1219. * a user trap handler is installed or a shell special one is in effect.
  1220. * ^C or ^Z from keyboard seems to execute "at once" because it usually
  1221. * backgrounds (i.e. stops) or kills all members of currently running
  1222. * pipe.
  1223. *
  1224. * Wait builtin is interruptible by signals for which user trap is set
  1225. * or by SIGINT in interactive shell.
  1226. *
  1227. * Trap handlers will execute even within trap handlers. (right?)
  1228. *
  1229. * User trap handlers are forgotten when subshell ("(cmd)") is entered,
  1230. * except for handlers set to '' (empty string).
  1231. *
  1232. * If job control is off, backgrounded commands ("cmd &")
  1233. * have SIGINT, SIGQUIT set to SIG_IGN.
  1234. *
  1235. * Commands which are run in command substitution ("`cmd`")
  1236. * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
  1237. *
  1238. * Ordinary commands have signals set to SIG_IGN/DFL as inherited
  1239. * by the shell from its parent.
  1240. *
  1241. * Signals which differ from SIG_DFL action
  1242. * (note: child (i.e., [v]forked) shell is not an interactive shell):
  1243. *
  1244. * SIGQUIT: ignore
  1245. * SIGTERM (interactive): ignore
  1246. * SIGHUP (interactive):
  1247. * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
  1248. * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
  1249. * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
  1250. * that all pipe members are stopped. Try this in bash:
  1251. * while :; do :; done - ^Z does not background it
  1252. * (while :; do :; done) - ^Z backgrounds it
  1253. * SIGINT (interactive): wait for last pipe, ignore the rest
  1254. * of the command line, show prompt. NB: ^C does not send SIGINT
  1255. * to interactive shell while shell is waiting for a pipe,
  1256. * since shell is bg'ed (is not in foreground process group).
  1257. * Example 1: this waits 5 sec, but does not execute ls:
  1258. * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
  1259. * Example 2: this does not wait and does not execute ls:
  1260. * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
  1261. * Example 3: this does not wait 5 sec, but executes ls:
  1262. * "sleep 5; ls -l" + press ^C
  1263. * Example 4: this does not wait and does not execute ls:
  1264. * "sleep 5 & wait; ls -l" + press ^C
  1265. *
  1266. * (What happens to signals which are IGN on shell start?)
  1267. * (What happens with signal mask on shell start?)
  1268. *
  1269. * Old implementation
  1270. * ==================
  1271. * We use in-kernel pending signal mask to determine which signals were sent.
  1272. * We block all signals which we don't want to take action immediately,
  1273. * i.e. we block all signals which need to have special handling as described
  1274. * above, and all signals which have traps set.
  1275. * After each pipe execution, we extract any pending signals via sigtimedwait()
  1276. * and act on them.
  1277. *
  1278. * unsigned special_sig_mask: a mask of such "special" signals
  1279. * sigset_t blocked_set: current blocked signal set
  1280. *
  1281. * "trap - SIGxxx":
  1282. * clear bit in blocked_set unless it is also in special_sig_mask
  1283. * "trap 'cmd' SIGxxx":
  1284. * set bit in blocked_set (even if 'cmd' is '')
  1285. * after [v]fork, if we plan to be a shell:
  1286. * unblock signals with special interactive handling
  1287. * (child shell is not interactive),
  1288. * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
  1289. * after [v]fork, if we plan to exec:
  1290. * POSIX says fork clears pending signal mask in child - no need to clear it.
  1291. * Restore blocked signal set to one inherited by shell just prior to exec.
  1292. *
  1293. * Note: as a result, we do not use signal handlers much. The only uses
  1294. * are to count SIGCHLDs
  1295. * and to restore tty pgrp on signal-induced exit.
  1296. *
  1297. * Note 2 (compat):
  1298. * Standard says "When a subshell is entered, traps that are not being ignored
  1299. * are set to the default actions". bash interprets it so that traps which
  1300. * are set to '' (ignore) are NOT reset to defaults. We do the same.
  1301. *
  1302. * Problem: the above approach makes it unwieldy to catch signals while
  1303. * we are in read builtin, or while we read commands from stdin:
  1304. * masked signals are not visible!
  1305. *
  1306. * New implementation
  1307. * ==================
  1308. * We record each signal we are interested in by installing signal handler
  1309. * for them - a bit like emulating kernel pending signal mask in userspace.
  1310. * We are interested in: signals which need to have special handling
  1311. * as described above, and all signals which have traps set.
  1312. * Signals are recorded in pending_set.
  1313. * After each pipe execution, we extract any pending signals
  1314. * and act on them.
  1315. *
  1316. * unsigned special_sig_mask: a mask of shell-special signals.
  1317. * unsigned fatal_sig_mask: a mask of signals on which we restore tty pgrp.
  1318. * char *traps[sig] if trap for sig is set (even if it's '').
  1319. * sigset_t pending_set: set of sigs we received.
  1320. *
  1321. * "trap - SIGxxx":
  1322. * if sig is in special_sig_mask, set handler back to:
  1323. * record_pending_signo, or to IGN if it's a tty stop signal
  1324. * if sig is in fatal_sig_mask, set handler back to sigexit.
  1325. * else: set handler back to SIG_DFL
  1326. * "trap 'cmd' SIGxxx":
  1327. * set handler to record_pending_signo.
  1328. * "trap '' SIGxxx":
  1329. * set handler to SIG_IGN.
  1330. * after [v]fork, if we plan to be a shell:
  1331. * set signals with special interactive handling to SIG_DFL
  1332. * (because child shell is not interactive),
  1333. * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
  1334. * after [v]fork, if we plan to exec:
  1335. * POSIX says fork clears pending signal mask in child - no need to clear it.
  1336. *
  1337. * To make wait builtin interruptible, we handle SIGCHLD as special signal,
  1338. * otherwise (if we leave it SIG_DFL) sigsuspend in wait builtin will not wake up on it.
  1339. *
  1340. * Note (compat):
  1341. * Standard says "When a subshell is entered, traps that are not being ignored
  1342. * are set to the default actions". bash interprets it so that traps which
  1343. * are set to '' (ignore) are NOT reset to defaults. We do the same.
  1344. */
  1345. enum {
  1346. SPECIAL_INTERACTIVE_SIGS = 0
  1347. | (1 << SIGTERM)
  1348. | (1 << SIGINT)
  1349. | (1 << SIGHUP)
  1350. ,
  1351. SPECIAL_JOBSTOP_SIGS = 0
  1352. #if ENABLE_HUSH_JOB
  1353. | (1 << SIGTTIN)
  1354. | (1 << SIGTTOU)
  1355. | (1 << SIGTSTP)
  1356. #endif
  1357. ,
  1358. };
  1359. static void record_pending_signo(int sig)
  1360. {
  1361. sigaddset(&G.pending_set, sig);
  1362. #if ENABLE_HUSH_FAST
  1363. if (sig == SIGCHLD) {
  1364. G.count_SIGCHLD++;
  1365. //bb_error_msg("[%d] SIGCHLD_handler: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
  1366. }
  1367. #endif
  1368. }
  1369. static sighandler_t install_sighandler(int sig, sighandler_t handler)
  1370. {
  1371. struct sigaction old_sa;
  1372. /* We could use signal() to install handlers... almost:
  1373. * except that we need to mask ALL signals while handlers run.
  1374. * I saw signal nesting in strace, race window isn't small.
  1375. * SA_RESTART is also needed, but in Linux, signal()
  1376. * sets SA_RESTART too.
  1377. */
  1378. /* memset(&G.sa, 0, sizeof(G.sa)); - already done */
  1379. /* sigfillset(&G.sa.sa_mask); - already done */
  1380. /* G.sa.sa_flags = SA_RESTART; - already done */
  1381. G.sa.sa_handler = handler;
  1382. sigaction(sig, &G.sa, &old_sa);
  1383. return old_sa.sa_handler;
  1384. }
  1385. static void hush_exit(int exitcode) NORETURN;
  1386. static void fflush_and__exit(void) NORETURN;
  1387. static void restore_ttypgrp_and__exit(void) NORETURN;
  1388. static void restore_ttypgrp_and__exit(void)
  1389. {
  1390. /* xfunc has failed! die die die */
  1391. /* no EXIT traps, this is an escape hatch! */
  1392. G.exiting = 1;
  1393. hush_exit(xfunc_error_retval);
  1394. }
  1395. /* Needed only on some libc:
  1396. * It was observed that on exit(), fgetc'ed buffered data
  1397. * gets "unwound" via lseek(fd, -NUM, SEEK_CUR).
  1398. * With the net effect that even after fork(), not vfork(),
  1399. * exit() in NOEXECed applet in "sh SCRIPT":
  1400. * noexec_applet_here
  1401. * echo END_OF_SCRIPT
  1402. * lseeks fd in input FILE object from EOF to "e" in "echo END_OF_SCRIPT".
  1403. * This makes "echo END_OF_SCRIPT" executed twice.
  1404. * Similar problems can be seen with die_if_script() -> xfunc_die()
  1405. * and in `cmd` handling.
  1406. * If set as die_func(), this makes xfunc_die() exit via _exit(), not exit():
  1407. */
  1408. static void fflush_and__exit(void)
  1409. {
  1410. fflush_all();
  1411. _exit(xfunc_error_retval);
  1412. }
  1413. #if ENABLE_HUSH_JOB
  1414. /* After [v]fork, in child: do not restore tty pgrp on xfunc death */
  1415. # define disable_restore_tty_pgrp_on_exit() (die_func = fflush_and__exit)
  1416. /* After [v]fork, in parent: restore tty pgrp on xfunc death */
  1417. # define enable_restore_tty_pgrp_on_exit() (die_func = restore_ttypgrp_and__exit)
  1418. /* Restores tty foreground process group, and exits.
  1419. * May be called as signal handler for fatal signal
  1420. * (will resend signal to itself, producing correct exit state)
  1421. * or called directly with -EXITCODE.
  1422. * We also call it if xfunc is exiting.
  1423. */
  1424. static void sigexit(int sig) NORETURN;
  1425. static void sigexit(int sig)
  1426. {
  1427. /* Careful: we can end up here after [v]fork. Do not restore
  1428. * tty pgrp then, only top-level shell process does that */
  1429. if (G_saved_tty_pgrp && getpid() == G.root_pid) {
  1430. /* Disable all signals: job control, SIGPIPE, etc.
  1431. * Mostly paranoid measure, to prevent infinite SIGTTOU.
  1432. */
  1433. sigprocmask_allsigs(SIG_BLOCK);
  1434. tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
  1435. }
  1436. /* Not a signal, just exit */
  1437. if (sig <= 0)
  1438. _exit(- sig);
  1439. kill_myself_with_sig(sig); /* does not return */
  1440. }
  1441. #else
  1442. # define disable_restore_tty_pgrp_on_exit() ((void)0)
  1443. # define enable_restore_tty_pgrp_on_exit() ((void)0)
  1444. #endif
  1445. static sighandler_t pick_sighandler(unsigned sig)
  1446. {
  1447. sighandler_t handler = SIG_DFL;
  1448. if (sig < sizeof(unsigned)*8) {
  1449. unsigned sigmask = (1 << sig);
  1450. #if ENABLE_HUSH_JOB
  1451. /* is sig fatal? */
  1452. if (G_fatal_sig_mask & sigmask)
  1453. handler = sigexit;
  1454. else
  1455. #endif
  1456. /* sig has special handling? */
  1457. if (G.special_sig_mask & sigmask) {
  1458. handler = record_pending_signo;
  1459. /* TTIN/TTOU/TSTP can't be set to record_pending_signo
  1460. * in order to ignore them: they will be raised
  1461. * in an endless loop when we try to do some
  1462. * terminal ioctls! We do have to _ignore_ these.
  1463. */
  1464. if (SPECIAL_JOBSTOP_SIGS & sigmask)
  1465. handler = SIG_IGN;
  1466. }
  1467. }
  1468. return handler;
  1469. }
  1470. /* Restores tty foreground process group, and exits. */
  1471. static void hush_exit(int exitcode)
  1472. {
  1473. #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
  1474. save_history(G.line_input_state);
  1475. #endif
  1476. fflush_all();
  1477. if (G.exiting <= 0 && G.traps && G.traps[0] && G.traps[0][0]) {
  1478. char *argv[3];
  1479. /* argv[0] is unused */
  1480. argv[1] = G.traps[0];
  1481. argv[2] = NULL;
  1482. G.exiting = 1; /* prevent EXIT trap recursion */
  1483. /* Note: G.traps[0] is not cleared!
  1484. * "trap" will still show it, if executed
  1485. * in the handler */
  1486. builtin_eval(argv);
  1487. }
  1488. #if ENABLE_FEATURE_CLEAN_UP
  1489. {
  1490. struct variable *cur_var;
  1491. if (G.cwd != bb_msg_unknown)
  1492. free((char*)G.cwd);
  1493. cur_var = G.top_var;
  1494. while (cur_var) {
  1495. struct variable *tmp = cur_var;
  1496. if (!cur_var->max_len)
  1497. free(cur_var->varstr);
  1498. cur_var = cur_var->next;
  1499. free(tmp);
  1500. }
  1501. }
  1502. #endif
  1503. fflush_all();
  1504. #if ENABLE_HUSH_JOB
  1505. sigexit(- (exitcode & 0xff));
  1506. #else
  1507. _exit(exitcode);
  1508. #endif
  1509. }
  1510. //TODO: return a mask of ALL handled sigs?
  1511. static int check_and_run_traps(void)
  1512. {
  1513. int last_sig = 0;
  1514. while (1) {
  1515. int sig;
  1516. if (sigisemptyset(&G.pending_set))
  1517. break;
  1518. sig = 0;
  1519. do {
  1520. sig++;
  1521. if (sigismember(&G.pending_set, sig)) {
  1522. sigdelset(&G.pending_set, sig);
  1523. goto got_sig;
  1524. }
  1525. } while (sig < NSIG);
  1526. break;
  1527. got_sig:
  1528. if (G.traps && G.traps[sig]) {
  1529. if (G.traps[sig][0]) {
  1530. /* We have user-defined handler */
  1531. smalluint save_rcode;
  1532. char *argv[3];
  1533. /* argv[0] is unused */
  1534. argv[1] = G.traps[sig];
  1535. argv[2] = NULL;
  1536. save_rcode = G.last_exitcode;
  1537. builtin_eval(argv);
  1538. G.last_exitcode = save_rcode;
  1539. last_sig = sig;
  1540. } /* else: "" trap, ignoring signal */
  1541. continue;
  1542. }
  1543. /* not a trap: special action */
  1544. switch (sig) {
  1545. case SIGINT:
  1546. /* Builtin was ^C'ed, make it look prettier: */
  1547. bb_putchar('\n');
  1548. G.flag_SIGINT = 1;
  1549. last_sig = sig;
  1550. break;
  1551. #if ENABLE_HUSH_JOB
  1552. case SIGHUP: {
  1553. struct pipe *job;
  1554. /* bash is observed to signal whole process groups,
  1555. * not individual processes */
  1556. for (job = G.job_list; job; job = job->next) {
  1557. if (job->pgrp <= 0)
  1558. continue;
  1559. debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
  1560. if (kill(- job->pgrp, SIGHUP) == 0)
  1561. kill(- job->pgrp, SIGCONT);
  1562. }
  1563. sigexit(SIGHUP);
  1564. }
  1565. #endif
  1566. #if ENABLE_HUSH_FAST
  1567. case SIGCHLD:
  1568. G.count_SIGCHLD++;
  1569. //bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
  1570. /* Note:
  1571. * We dont do 'last_sig = sig' here -> NOT returning this sig.
  1572. * This simplifies wait builtin a bit.
  1573. */
  1574. break;
  1575. #endif
  1576. default: /* ignored: */
  1577. /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
  1578. /* Note:
  1579. * We dont do 'last_sig = sig' here -> NOT returning this sig.
  1580. * Example: wait is not interrupted by TERM
  1581. * in interactive shell, because TERM is ignored.
  1582. */
  1583. break;
  1584. }
  1585. }
  1586. return last_sig;
  1587. }
  1588. static const char *get_cwd(int force)
  1589. {
  1590. if (force || G.cwd == NULL) {
  1591. /* xrealloc_getcwd_or_warn(arg) calls free(arg),
  1592. * we must not try to free(bb_msg_unknown) */
  1593. if (G.cwd == bb_msg_unknown)
  1594. G.cwd = NULL;
  1595. G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
  1596. if (!G.cwd)
  1597. G.cwd = bb_msg_unknown;
  1598. }
  1599. return G.cwd;
  1600. }
  1601. /*
  1602. * Shell and environment variable support
  1603. */
  1604. static struct variable **get_ptr_to_local_var(const char *name, unsigned len)
  1605. {
  1606. struct variable **pp;
  1607. struct variable *cur;
  1608. pp = &G.top_var;
  1609. while ((cur = *pp) != NULL) {
  1610. if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
  1611. return pp;
  1612. pp = &cur->next;
  1613. }
  1614. return NULL;
  1615. }
  1616. static const char* FAST_FUNC get_local_var_value(const char *name)
  1617. {
  1618. struct variable **vpp;
  1619. unsigned len = strlen(name);
  1620. if (G.expanded_assignments) {
  1621. char **cpp = G.expanded_assignments;
  1622. while (*cpp) {
  1623. char *cp = *cpp;
  1624. if (strncmp(cp, name, len) == 0 && cp[len] == '=')
  1625. return cp + len + 1;
  1626. cpp++;
  1627. }
  1628. }
  1629. vpp = get_ptr_to_local_var(name, len);
  1630. if (vpp)
  1631. return (*vpp)->varstr + len + 1;
  1632. if (strcmp(name, "PPID") == 0)
  1633. return utoa(G.root_ppid);
  1634. // bash compat: UID? EUID?
  1635. #if ENABLE_HUSH_RANDOM_SUPPORT
  1636. if (strcmp(name, "RANDOM") == 0)
  1637. return utoa(next_random(&G.random_gen));
  1638. #endif
  1639. return NULL;
  1640. }
  1641. /* str holds "NAME=VAL" and is expected to be malloced.
  1642. * We take ownership of it.
  1643. * flg_export:
  1644. * 0: do not change export flag
  1645. * (if creating new variable, flag will be 0)
  1646. * 1: set export flag and putenv the variable
  1647. * -1: clear export flag and unsetenv the variable
  1648. * flg_read_only is set only when we handle -R var=val
  1649. */
  1650. #if !BB_MMU && ENABLE_HUSH_LOCAL
  1651. /* all params are used */
  1652. #elif BB_MMU && ENABLE_HUSH_LOCAL
  1653. #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
  1654. set_local_var(str, flg_export, local_lvl)
  1655. #elif BB_MMU && !ENABLE_HUSH_LOCAL
  1656. #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
  1657. set_local_var(str, flg_export)
  1658. #elif !BB_MMU && !ENABLE_HUSH_LOCAL
  1659. #define set_local_var(str, flg_export, local_lvl, flg_read_only) \
  1660. set_local_var(str, flg_export, flg_read_only)
  1661. #endif
  1662. static int set_local_var(char *str, int flg_export, int local_lvl, int flg_read_only)
  1663. {
  1664. struct variable **var_pp;
  1665. struct variable *cur;
  1666. char *free_me = NULL;
  1667. char *eq_sign;
  1668. int name_len;
  1669. eq_sign = strchr(str, '=');
  1670. if (!eq_sign) { /* not expected to ever happen? */
  1671. free(str);
  1672. return -1;
  1673. }
  1674. name_len = eq_sign - str + 1; /* including '=' */
  1675. var_pp = &G.top_var;
  1676. while ((cur = *var_pp) != NULL) {
  1677. if (strncmp(cur->varstr, str, name_len) != 0) {
  1678. var_pp = &cur->next;
  1679. continue;
  1680. }
  1681. /* We found an existing var with this name */
  1682. if (cur->flg_read_only) {
  1683. #if !BB_MMU
  1684. if (!flg_read_only)
  1685. #endif
  1686. bb_error_msg("%s: readonly variable", str);
  1687. free(str);
  1688. return -1;
  1689. }
  1690. if (flg_export == -1) { // "&& cur->flg_export" ?
  1691. debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
  1692. *eq_sign = '\0';
  1693. unsetenv(str);
  1694. *eq_sign = '=';
  1695. }
  1696. #if ENABLE_HUSH_LOCAL
  1697. if (cur->func_nest_level < local_lvl) {
  1698. /* New variable is declared as local,
  1699. * and existing one is global, or local
  1700. * from enclosing function.
  1701. * Remove and save old one: */
  1702. *var_pp = cur->next;
  1703. cur->next = *G.shadowed_vars_pp;
  1704. *G.shadowed_vars_pp = cur;
  1705. /* bash 3.2.33(1) and exported vars:
  1706. * # export z=z
  1707. * # f() { local z=a; env | grep ^z; }
  1708. * # f
  1709. * z=a
  1710. * # env | grep ^z
  1711. * z=z
  1712. */
  1713. if (cur->flg_export)
  1714. flg_export = 1;
  1715. break;
  1716. }
  1717. #endif
  1718. if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
  1719. free_and_exp:
  1720. free(str);
  1721. goto exp;
  1722. }
  1723. if (cur->max_len != 0) {
  1724. if (cur->max_len >= strlen(str)) {
  1725. /* This one is from startup env, reuse space */
  1726. strcpy(cur->varstr, str);
  1727. goto free_and_exp;
  1728. }
  1729. /* Can't reuse */
  1730. cur->max_len = 0;
  1731. goto set_str_and_exp;
  1732. }
  1733. /* max_len == 0 signifies "malloced" var, which we can
  1734. * (and have to) free. But we can't free(cur->varstr) here:
  1735. * if cur->flg_export is 1, it is in the environment.
  1736. * We should either unsetenv+free, or wait until putenv,
  1737. * then putenv(new)+free(old).
  1738. */
  1739. free_me = cur->varstr;
  1740. goto set_str_and_exp;
  1741. }
  1742. /* Not found - create new variable struct */
  1743. cur = xzalloc(sizeof(*cur));
  1744. #if ENABLE_HUSH_LOCAL
  1745. cur->func_nest_level = local_lvl;
  1746. #endif
  1747. cur->next = *var_pp;
  1748. *var_pp = cur;
  1749. set_str_and_exp:
  1750. cur->varstr = str;
  1751. #if !BB_MMU
  1752. cur->flg_read_only = flg_read_only;
  1753. #endif
  1754. exp:
  1755. if (flg_export == 1)
  1756. cur->flg_export = 1;
  1757. if (name_len == 4 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
  1758. cmdedit_update_prompt();
  1759. if (cur->flg_export) {
  1760. if (flg_export == -1) {
  1761. cur->flg_export = 0;
  1762. /* unsetenv was already done */
  1763. } else {
  1764. int i;
  1765. debug_printf_env("%s: putenv '%s'\n", __func__, cur->varstr);
  1766. i = putenv(cur->varstr);
  1767. /* only now we can free old exported malloced string */
  1768. free(free_me);
  1769. return i;
  1770. }
  1771. }
  1772. free(free_me);
  1773. return 0;
  1774. }
  1775. /* Used at startup and after each cd */
  1776. static void set_pwd_var(int exp)
  1777. {
  1778. set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)),
  1779. /*exp:*/ exp, /*lvl:*/ 0, /*ro:*/ 0);
  1780. }
  1781. static int unset_local_var_len(const char *name, int name_len)
  1782. {
  1783. struct variable *cur;
  1784. struct variable **var_pp;
  1785. if (!name)
  1786. return EXIT_SUCCESS;
  1787. var_pp = &G.top_var;
  1788. while ((cur = *var_pp) != NULL) {
  1789. if (strncmp(cur->varstr, name, name_len) == 0 && cur->varstr[name_len] == '=') {
  1790. if (cur->flg_read_only) {
  1791. bb_error_msg("%s: readonly variable", name);
  1792. return EXIT_FAILURE;
  1793. }
  1794. *var_pp = cur->next;
  1795. debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
  1796. bb_unsetenv(cur->varstr);
  1797. if (name_len == 3 && cur->varstr[0] == 'P' && cur->varstr[1] == 'S')
  1798. cmdedit_update_prompt();
  1799. if (!cur->max_len)
  1800. free(cur->varstr);
  1801. free(cur);
  1802. return EXIT_SUCCESS;
  1803. }
  1804. var_pp = &cur->next;
  1805. }
  1806. return EXIT_SUCCESS;
  1807. }
  1808. static int unset_local_var(const char *name)
  1809. {
  1810. return unset_local_var_len(name, strlen(name));
  1811. }
  1812. static void unset_vars(char **strings)
  1813. {
  1814. char **v;
  1815. if (!strings)
  1816. return;
  1817. v = strings;
  1818. while (*v) {
  1819. const char *eq = strchrnul(*v, '=');
  1820. unset_local_var_len(*v, (int)(eq - *v));
  1821. v++;
  1822. }
  1823. free(strings);
  1824. }
  1825. static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
  1826. {
  1827. char *var = xasprintf("%s=%s", name, val);
  1828. set_local_var(var, /*flags:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
  1829. }
  1830. /*
  1831. * Helpers for "var1=val1 var2=val2 cmd" feature
  1832. */
  1833. static void add_vars(struct variable *var)
  1834. {
  1835. struct variable *next;
  1836. while (var) {
  1837. next = var->next;
  1838. var->next = G.top_var;
  1839. G.top_var = var;
  1840. if (var->flg_export) {
  1841. debug_printf_env("%s: restoring exported '%s'\n", __func__, var->varstr);
  1842. putenv(var->varstr);
  1843. } else {
  1844. debug_printf_env("%s: restoring variable '%s'\n", __func__, var->varstr);
  1845. }
  1846. var = next;
  1847. }
  1848. }
  1849. static struct variable *set_vars_and_save_old(char **strings)
  1850. {
  1851. char **s;
  1852. struct variable *old = NULL;
  1853. if (!strings)
  1854. return old;
  1855. s = strings;
  1856. while (*s) {
  1857. struct variable *var_p;
  1858. struct variable **var_pp;
  1859. char *eq;
  1860. eq = strchr(*s, '=');
  1861. if (eq) {
  1862. var_pp = get_ptr_to_local_var(*s, eq - *s);
  1863. if (var_pp) {
  1864. /* Remove variable from global linked list */
  1865. var_p = *var_pp;
  1866. debug_printf_env("%s: removing '%s'\n", __func__, var_p->varstr);
  1867. *var_pp = var_p->next;
  1868. /* Add it to returned list */
  1869. var_p->next = old;
  1870. old = var_p;
  1871. }
  1872. set_local_var(*s, /*exp:*/ 1, /*lvl:*/ 0, /*ro:*/ 0);
  1873. }
  1874. s++;
  1875. }
  1876. return old;
  1877. }
  1878. /*
  1879. * Unicode helper
  1880. */
  1881. static void reinit_unicode_for_hush(void)
  1882. {
  1883. /* Unicode support should be activated even if LANG is set
  1884. * _during_ shell execution, not only if it was set when
  1885. * shell was started. Therefore, re-check LANG every time:
  1886. */
  1887. if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
  1888. || ENABLE_UNICODE_USING_LOCALE
  1889. ) {
  1890. const char *s = get_local_var_value("LC_ALL");
  1891. if (!s) s = get_local_var_value("LC_CTYPE");
  1892. if (!s) s = get_local_var_value("LANG");
  1893. reinit_unicode(s);
  1894. }
  1895. }
  1896. /*
  1897. * in_str support
  1898. */
  1899. static int FAST_FUNC static_get(struct in_str *i)
  1900. {
  1901. int ch = *i->p;
  1902. if (ch != '\0') {
  1903. i->p++;
  1904. i->last_char = ch;
  1905. return ch;
  1906. }
  1907. return EOF;
  1908. }
  1909. static int FAST_FUNC static_peek(struct in_str *i)
  1910. {
  1911. return *i->p;
  1912. }
  1913. #if ENABLE_HUSH_INTERACTIVE
  1914. static void cmdedit_update_prompt(void)
  1915. {
  1916. if (ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
  1917. G.PS1 = get_local_var_value("PS1");
  1918. if (G.PS1 == NULL)
  1919. G.PS1 = "\\w \\$ ";
  1920. G.PS2 = get_local_var_value("PS2");
  1921. } else {
  1922. G.PS1 = NULL;
  1923. }
  1924. if (G.PS2 == NULL)
  1925. G.PS2 = "> ";
  1926. }
  1927. static const char *setup_prompt_string(int promptmode)
  1928. {
  1929. const char *prompt_str;
  1930. debug_printf("setup_prompt_string %d ", promptmode);
  1931. if (!ENABLE_FEATURE_EDITING_FANCY_PROMPT) {
  1932. /* Set up the prompt */
  1933. if (promptmode == 0) { /* PS1 */
  1934. free((char*)G.PS1);
  1935. /* bash uses $PWD value, even if it is set by user.
  1936. * It uses current dir only if PWD is unset.
  1937. * We always use current dir. */
  1938. G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
  1939. prompt_str = G.PS1;
  1940. } else
  1941. prompt_str = G.PS2;
  1942. } else
  1943. prompt_str = (promptmode == 0) ? G.PS1 : G.PS2;
  1944. debug_printf("result '%s'\n", prompt_str);
  1945. return prompt_str;
  1946. }
  1947. static void get_user_input(struct in_str *i)
  1948. {
  1949. int r;
  1950. const char *prompt_str;
  1951. prompt_str = setup_prompt_string(i->promptmode);
  1952. # if ENABLE_FEATURE_EDITING
  1953. /* Enable command line editing only while a command line
  1954. * is actually being read */
  1955. do {
  1956. reinit_unicode_for_hush();
  1957. G.flag_SIGINT = 0;
  1958. /* buglet: SIGINT will not make new prompt to appear _at once_,
  1959. * only after <Enter>. (^C will work) */
  1960. r = read_line_input(G.line_input_state, prompt_str, G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1, /*timeout*/ -1);
  1961. /* catch *SIGINT* etc (^C is handled by read_line_input) */
  1962. check_and_run_traps();
  1963. } while (r == 0 || G.flag_SIGINT); /* repeat if ^C or SIGINT */
  1964. i->eof_flag = (r < 0);
  1965. if (i->eof_flag) { /* EOF/error detected */
  1966. G.user_input_buf[0] = EOF; /* yes, it will be truncated, it's ok */
  1967. G.user_input_buf[1] = '\0';
  1968. }
  1969. # else
  1970. do {
  1971. G.flag_SIGINT = 0;
  1972. if (i->last_char == '\0' || i->last_char == '\n') {
  1973. /* Why check_and_run_traps here? Try this interactively:
  1974. * $ trap 'echo INT' INT; (sleep 2; kill -INT $$) &
  1975. * $ <[enter], repeatedly...>
  1976. * Without check_and_run_traps, handler never runs.
  1977. */
  1978. check_and_run_traps();
  1979. fputs(prompt_str, stdout);
  1980. }
  1981. fflush_all();
  1982. G.user_input_buf[0] = r = fgetc(i->file);
  1983. /*G.user_input_buf[1] = '\0'; - already is and never changed */
  1984. } while (G.flag_SIGINT);
  1985. i->eof_flag = (r == EOF);
  1986. # endif
  1987. i->p = G.user_input_buf;
  1988. }
  1989. #endif /* INTERACTIVE */
  1990. /* This is the magic location that prints prompts
  1991. * and gets data back from the user */
  1992. static int FAST_FUNC file_get(struct in_str *i)
  1993. {
  1994. int ch;
  1995. /* If there is data waiting, eat it up */
  1996. if (i->p && *i->p) {
  1997. #if ENABLE_HUSH_INTERACTIVE
  1998. take_cached:
  1999. #endif
  2000. ch = *i->p++;
  2001. if (i->eof_flag && !*i->p)
  2002. ch = EOF;
  2003. /* note: ch is never NUL */
  2004. } else {
  2005. /* need to double check i->file because we might be doing something
  2006. * more complicated by now, like sourcing or substituting. */
  2007. #if ENABLE_HUSH_INTERACTIVE
  2008. if (G_interactive_fd && i->file == stdin) {
  2009. do {
  2010. get_user_input(i);
  2011. } while (!*i->p); /* need non-empty line */
  2012. i->promptmode = 1; /* PS2 */
  2013. goto take_cached;
  2014. }
  2015. #endif
  2016. do ch = fgetc(i->file); while (ch == '\0');
  2017. }
  2018. debug_printf("file_get: got '%c' %d\n", ch, ch);
  2019. i->last_char = ch;
  2020. return ch;
  2021. }
  2022. /* All callers guarantee this routine will never
  2023. * be used right after a newline, so prompting is not needed.
  2024. */
  2025. static int FAST_FUNC file_peek(struct in_str *i)
  2026. {
  2027. int ch;
  2028. if (i->p && *i->p) {
  2029. if (i->eof_flag && !i->p[1])
  2030. return EOF;
  2031. return *i->p;
  2032. /* note: ch is never NUL */
  2033. }
  2034. do ch = fgetc(i->file); while (ch == '\0');
  2035. i->eof_flag = (ch == EOF);
  2036. i->peek_buf[0] = ch;
  2037. i->peek_buf[1] = '\0';
  2038. i->p = i->peek_buf;
  2039. debug_printf("file_peek: got '%c' %d\n", ch, ch);
  2040. return ch;
  2041. }
  2042. static void setup_file_in_str(struct in_str *i, FILE *f)
  2043. {
  2044. memset(i, 0, sizeof(*i));
  2045. i->peek = file_peek;
  2046. i->get = file_get;
  2047. /* i->promptmode = 0; - PS1 (memset did it) */
  2048. i->file = f;
  2049. /* i->p = NULL; */
  2050. }
  2051. static void setup_string_in_str(struct in_str *i, const char *s)
  2052. {
  2053. memset(i, 0, sizeof(*i));
  2054. i->peek = static_peek;
  2055. i->get = static_get;
  2056. /* i->promptmode = 0; - PS1 (memset did it) */
  2057. i->p = s;
  2058. /* i->eof_flag = 0; */
  2059. }
  2060. /*
  2061. * o_string support
  2062. */
  2063. #define B_CHUNK (32 * sizeof(char*))
  2064. static void o_reset_to_empty_unquoted(o_string *o)
  2065. {
  2066. o->length = 0;
  2067. o->has_quoted_part = 0;
  2068. if (o->data)
  2069. o->data[0] = '\0';
  2070. }
  2071. static void o_free(o_string *o)
  2072. {
  2073. free(o->data);
  2074. memset(o, 0, sizeof(*o));
  2075. }
  2076. static ALWAYS_INLINE void o_free_unsafe(o_string *o)
  2077. {
  2078. free(o->data);
  2079. }
  2080. static void o_grow_by(o_string *o, int len)
  2081. {
  2082. if (o->length + len > o->maxlen) {
  2083. o->maxlen += (2*len > B_CHUNK ? 2*len : B_CHUNK);
  2084. o->data = xrealloc(o->data, 1 + o->maxlen);
  2085. }
  2086. }
  2087. static void o_addchr(o_string *o, int ch)
  2088. {
  2089. debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
  2090. o_grow_by(o, 1);
  2091. o->data[o->length] = ch;
  2092. o->length++;
  2093. o->data[o->length] = '\0';
  2094. }
  2095. static void o_addblock(o_string *o, const char *str, int len)
  2096. {
  2097. o_grow_by(o, len);
  2098. memcpy(&o->data[o->length], str, len);
  2099. o->length += len;
  2100. o->data[o->length] = '\0';
  2101. }
  2102. static void o_addstr(o_string *o, const char *str)
  2103. {
  2104. o_addblock(o, str, strlen(str));
  2105. }
  2106. #if !BB_MMU
  2107. static void nommu_addchr(o_string *o, int ch)
  2108. {
  2109. if (o)
  2110. o_addchr(o, ch);
  2111. }
  2112. #else
  2113. # define nommu_addchr(o, str) ((void)0)
  2114. #endif
  2115. static void o_addstr_with_NUL(o_string *o, const char *str)
  2116. {
  2117. o_addblock(o, str, strlen(str) + 1);
  2118. }
  2119. /*
  2120. * HUSH_BRACE_EXPANSION code needs corresponding quoting on variable expansion side.
  2121. * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
  2122. * Apparently, on unquoted $v bash still does globbing
  2123. * ("v='*.txt'; echo $v" prints all .txt files),
  2124. * but NOT brace expansion! Thus, there should be TWO independent
  2125. * quoting mechanisms on $v expansion side: one protects
  2126. * $v from brace expansion, and other additionally protects "$v" against globbing.
  2127. * We have only second one.
  2128. */
  2129. #if ENABLE_HUSH_BRACE_EXPANSION
  2130. # define MAYBE_BRACES "{}"
  2131. #else
  2132. # define MAYBE_BRACES ""
  2133. #endif
  2134. /* My analysis of quoting semantics tells me that state information
  2135. * is associated with a destination, not a source.
  2136. */
  2137. static void o_addqchr(o_string *o, int ch)
  2138. {
  2139. int sz = 1;
  2140. char *found = strchr("*?[\\" MAYBE_BRACES, ch);
  2141. if (found)
  2142. sz++;
  2143. o_grow_by(o, sz);
  2144. if (found) {
  2145. o->data[o->length] = '\\';
  2146. o->length++;
  2147. }
  2148. o->data[o->length] = ch;
  2149. o->length++;
  2150. o->data[o->length] = '\0';
  2151. }
  2152. static void o_addQchr(o_string *o, int ch)
  2153. {
  2154. int sz = 1;
  2155. if ((o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)
  2156. && strchr("*?[\\" MAYBE_BRACES, ch)
  2157. ) {
  2158. sz++;
  2159. o->data[o->length] = '\\';
  2160. o->length++;
  2161. }
  2162. o_grow_by(o, sz);
  2163. o->data[o->length] = ch;
  2164. o->length++;
  2165. o->data[o->length] = '\0';
  2166. }
  2167. static void o_addqblock(o_string *o, const char *str, int len)
  2168. {
  2169. while (len) {
  2170. char ch;
  2171. int sz;
  2172. int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
  2173. if (ordinary_cnt > len) /* paranoia */
  2174. ordinary_cnt = len;
  2175. o_addblock(o, str, ordinary_cnt);
  2176. if (ordinary_cnt == len)
  2177. return; /* NUL is already added by o_addblock */
  2178. str += ordinary_cnt;
  2179. len -= ordinary_cnt + 1; /* we are processing + 1 char below */
  2180. ch = *str++;
  2181. sz = 1;
  2182. if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
  2183. sz++;
  2184. o->data[o->length] = '\\';
  2185. o->length++;
  2186. }
  2187. o_grow_by(o, sz);
  2188. o->data[o->length] = ch;
  2189. o->length++;
  2190. }
  2191. o->data[o->length] = '\0';
  2192. }
  2193. static void o_addQblock(o_string *o, const char *str, int len)
  2194. {
  2195. if (!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)) {
  2196. o_addblock(o, str, len);
  2197. return;
  2198. }
  2199. o_addqblock(o, str, len);
  2200. }
  2201. static void o_addQstr(o_string *o, const char *str)
  2202. {
  2203. o_addQblock(o, str, strlen(str));
  2204. }
  2205. /* A special kind of o_string for $VAR and `cmd` expansion.
  2206. * It contains char* list[] at the beginning, which is grown in 16 element
  2207. * increments. Actual string data starts at the next multiple of 16 * (char*).
  2208. * list[i] contains an INDEX (int!) into this string data.
  2209. * It means that if list[] needs to grow, data needs to be moved higher up
  2210. * but list[i]'s need not be modified.
  2211. * NB: remembering how many list[i]'s you have there is crucial.
  2212. * o_finalize_list() operation post-processes this structure - calculates
  2213. * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
  2214. */
  2215. #if DEBUG_EXPAND || DEBUG_GLOB
  2216. static void debug_print_list(const char *prefix, o_string *o, int n)
  2217. {
  2218. char **list = (char**)o->data;
  2219. int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
  2220. int i = 0;
  2221. indent();
  2222. fdprintf(2, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d glob:%d quoted:%d escape:%d\n",
  2223. prefix, list, n, string_start, o->length, o->maxlen,
  2224. !!(o->o_expflags & EXP_FLAG_GLOB),
  2225. o->has_quoted_part,
  2226. !!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
  2227. while (i < n) {
  2228. indent();
  2229. fdprintf(2, " list[%d]=%d '%s' %p\n", i, (int)(uintptr_t)list[i],
  2230. o->data + (int)(uintptr_t)list[i] + string_start,
  2231. o->data + (int)(uintptr_t)list[i] + string_start);
  2232. i++;
  2233. }
  2234. if (n) {
  2235. const char *p = o->data + (int)(uintptr_t)list[n - 1] + string_start;
  2236. indent();
  2237. fdprintf(2, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
  2238. }
  2239. }
  2240. #else
  2241. # define debug_print_list(prefix, o, n) ((void)0)
  2242. #endif
  2243. /* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
  2244. * in list[n] so that it points past last stored byte so far.
  2245. * It returns n+1. */
  2246. static int o_save_ptr_helper(o_string *o, int n)
  2247. {
  2248. char **list = (char**)o->data;
  2249. int string_start;
  2250. int string_len;
  2251. if (!o->has_empty_slot) {
  2252. string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
  2253. string_len = o->length - string_start;
  2254. if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
  2255. debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
  2256. /* list[n] points to string_start, make space for 16 more pointers */
  2257. o->maxlen += 0x10 * sizeof(list[0]);
  2258. o->data = xrealloc(o->data, o->maxlen + 1);
  2259. list = (char**)o->data;
  2260. memmove(list + n + 0x10, list + n, string_len);
  2261. o->length += 0x10 * sizeof(list[0]);
  2262. } else {
  2263. debug_printf_list("list[%d]=%d string_start=%d\n",
  2264. n, string_len, string_start);
  2265. }
  2266. } else {
  2267. /* We have empty slot at list[n], reuse without growth */
  2268. string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
  2269. string_len = o->length - string_start;
  2270. debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
  2271. n, string_len, string_start);
  2272. o->has_empty_slot = 0;
  2273. }
  2274. o->has_quoted_part = 0;
  2275. list[n] = (char*)(uintptr_t)string_len;
  2276. return n + 1;
  2277. }
  2278. /* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
  2279. static int o_get_last_ptr(o_string *o, int n)
  2280. {
  2281. char **list = (char**)o->data;
  2282. int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
  2283. return ((int)(uintptr_t)list[n-1]) + string_start;
  2284. }
  2285. #if ENABLE_HUSH_BRACE_EXPANSION
  2286. /* There in a GNU extension, GLOB_BRACE, but it is not usable:
  2287. * first, it processes even {a} (no commas), second,
  2288. * I didn't manage to make it return strings when they don't match
  2289. * existing files. Need to re-implement it.
  2290. */
  2291. /* Helper */
  2292. static int glob_needed(const char *s)
  2293. {
  2294. while (*s) {
  2295. if (*s == '\\') {
  2296. if (!s[1])
  2297. return 0;
  2298. s += 2;
  2299. continue;
  2300. }
  2301. if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
  2302. return 1;
  2303. s++;
  2304. }
  2305. return 0;
  2306. }
  2307. /* Return pointer to next closing brace or to comma */
  2308. static const char *next_brace_sub(const char *cp)
  2309. {
  2310. unsigned depth = 0;
  2311. cp++;
  2312. while (*cp != '\0') {
  2313. if (*cp == '\\') {
  2314. if (*++cp == '\0')
  2315. break;
  2316. cp++;
  2317. continue;
  2318. }
  2319. if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
  2320. break;
  2321. if (*cp++ == '{')
  2322. depth++;
  2323. }
  2324. return *cp != '\0' ? cp : NULL;
  2325. }
  2326. /* Recursive brace globber. Note: may garble pattern[]. */
  2327. static int glob_brace(char *pattern, o_string *o, int n)
  2328. {
  2329. char *new_pattern_buf;
  2330. const char *begin;
  2331. const char *next;
  2332. const char *rest;
  2333. const char *p;
  2334. size_t rest_len;
  2335. debug_printf_glob("glob_brace('%s')\n", pattern);
  2336. begin = pattern;
  2337. while (1) {
  2338. if (*begin == '\0')
  2339. goto simple_glob;
  2340. if (*begin == '{') {
  2341. /* Find the first sub-pattern and at the same time
  2342. * find the rest after the closing brace */
  2343. next = next_brace_sub(begin);
  2344. if (next == NULL) {
  2345. /* An illegal expression */
  2346. goto simple_glob;
  2347. }
  2348. if (*next == '}') {
  2349. /* "{abc}" with no commas - illegal
  2350. * brace expr, disregard and skip it */
  2351. begin = next + 1;
  2352. continue;
  2353. }
  2354. break;
  2355. }
  2356. if (*begin == '\\' && begin[1] != '\0')
  2357. begin++;
  2358. begin++;
  2359. }
  2360. debug_printf_glob("begin:%s\n", begin);
  2361. debug_printf_glob("next:%s\n", next);
  2362. /* Now find the end of the whole brace expression */
  2363. rest = next;
  2364. while (*rest != '}') {
  2365. rest = next_brace_sub(rest);
  2366. if (rest == NULL) {
  2367. /* An illegal expression */
  2368. goto simple_glob;
  2369. }
  2370. debug_printf_glob("rest:%s\n", rest);
  2371. }
  2372. rest_len = strlen(++rest) + 1;
  2373. /* We are sure the brace expression is well-formed */
  2374. /* Allocate working buffer large enough for our work */
  2375. new_pattern_buf = xmalloc(strlen(pattern));
  2376. /* We have a brace expression. BEGIN points to the opening {,
  2377. * NEXT points past the terminator of the first element, and REST
  2378. * points past the final }. We will accumulate result names from
  2379. * recursive runs for each brace alternative in the buffer using
  2380. * GLOB_APPEND. */
  2381. p = begin + 1;
  2382. while (1) {
  2383. /* Construct the new glob expression */
  2384. memcpy(
  2385. mempcpy(
  2386. mempcpy(new_pattern_buf,
  2387. /* We know the prefix for all sub-patterns */
  2388. pattern, begin - pattern),
  2389. p, next - p),
  2390. rest, rest_len);
  2391. /* Note: glob_brace() may garble new_pattern_buf[].
  2392. * That's why we re-copy prefix every time (1st memcpy above).
  2393. */
  2394. n = glob_brace(new_pattern_buf, o, n);
  2395. if (*next == '}') {
  2396. /* We saw the last entry */
  2397. break;
  2398. }
  2399. p = next + 1;
  2400. next = next_brace_sub(next);
  2401. }
  2402. free(new_pattern_buf);
  2403. return n;
  2404. simple_glob:
  2405. {
  2406. int gr;
  2407. glob_t globdata;
  2408. memset(&globdata, 0, sizeof(globdata));
  2409. gr = glob(pattern, 0, NULL, &globdata);
  2410. debug_printf_glob("glob('%s'):%d\n", pattern, gr);
  2411. if (gr != 0) {
  2412. if (gr == GLOB_NOMATCH) {
  2413. globfree(&globdata);
  2414. /* NB: garbles parameter */
  2415. unbackslash(pattern);
  2416. o_addstr_with_NUL(o, pattern);
  2417. debug_printf_glob("glob pattern '%s' is literal\n", pattern);
  2418. return o_save_ptr_helper(o, n);
  2419. }
  2420. if (gr == GLOB_NOSPACE)
  2421. bb_error_msg_and_die(bb_msg_memory_exhausted);
  2422. /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
  2423. * but we didn't specify it. Paranoia again. */
  2424. bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
  2425. }
  2426. if (globdata.gl_pathv && globdata.gl_pathv[0]) {
  2427. char **argv = globdata.gl_pathv;
  2428. while (1) {
  2429. o_addstr_with_NUL(o, *argv);
  2430. n = o_save_ptr_helper(o, n);
  2431. argv++;
  2432. if (!*argv)
  2433. break;
  2434. }
  2435. }
  2436. globfree(&globdata);
  2437. }
  2438. return n;
  2439. }
  2440. /* Performs globbing on last list[],
  2441. * saving each result as a new list[].
  2442. */
  2443. static int perform_glob(o_string *o, int n)
  2444. {
  2445. char *pattern, *copy;
  2446. debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
  2447. if (!o->data)
  2448. return o_save_ptr_helper(o, n);
  2449. pattern = o->data + o_get_last_ptr(o, n);
  2450. debug_printf_glob("glob pattern '%s'\n", pattern);
  2451. if (!glob_needed(pattern)) {
  2452. /* unbackslash last string in o in place, fix length */
  2453. o->length = unbackslash(pattern) - o->data;
  2454. debug_printf_glob("glob pattern '%s' is literal\n", pattern);
  2455. return o_save_ptr_helper(o, n);
  2456. }
  2457. copy = xstrdup(pattern);
  2458. /* "forget" pattern in o */
  2459. o->length = pattern - o->data;
  2460. n = glob_brace(copy, o, n);
  2461. free(copy);
  2462. if (DEBUG_GLOB)
  2463. debug_print_list("perform_glob returning", o, n);
  2464. return n;
  2465. }
  2466. #else /* !HUSH_BRACE_EXPANSION */
  2467. /* Helper */
  2468. static int glob_needed(const char *s)
  2469. {
  2470. while (*s) {
  2471. if (*s == '\\') {
  2472. if (!s[1])
  2473. return 0;
  2474. s += 2;
  2475. continue;
  2476. }
  2477. if (*s == '*' || *s == '[' || *s == '?')
  2478. return 1;
  2479. s++;
  2480. }
  2481. return 0;
  2482. }
  2483. /* Performs globbing on last list[],
  2484. * saving each result as a new list[].
  2485. */
  2486. static int perform_glob(o_string *o, int n)
  2487. {
  2488. glob_t globdata;
  2489. int gr;
  2490. char *pattern;
  2491. debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
  2492. if (!o->data)
  2493. return o_save_ptr_helper(o, n);
  2494. pattern = o->data + o_get_last_ptr(o, n);
  2495. debug_printf_glob("glob pattern '%s'\n", pattern);
  2496. if (!glob_needed(pattern)) {
  2497. literal:
  2498. /* unbackslash last string in o in place, fix length */
  2499. o->length = unbackslash(pattern) - o->data;
  2500. debug_printf_glob("glob pattern '%s' is literal\n", pattern);
  2501. return o_save_ptr_helper(o, n);
  2502. }
  2503. memset(&globdata, 0, sizeof(globdata));
  2504. /* Can't use GLOB_NOCHECK: it does not unescape the string.
  2505. * If we glob "*.\*" and don't find anything, we need
  2506. * to fall back to using literal "*.*", but GLOB_NOCHECK
  2507. * will return "*.\*"!
  2508. */
  2509. gr = glob(pattern, 0, NULL, &globdata);
  2510. debug_printf_glob("glob('%s'):%d\n", pattern, gr);
  2511. if (gr != 0) {
  2512. if (gr == GLOB_NOMATCH) {
  2513. globfree(&globdata);
  2514. goto literal;
  2515. }
  2516. if (gr == GLOB_NOSPACE)
  2517. bb_error_msg_and_die(bb_msg_memory_exhausted);
  2518. /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
  2519. * but we didn't specify it. Paranoia again. */
  2520. bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
  2521. }
  2522. if (globdata.gl_pathv && globdata.gl_pathv[0]) {
  2523. char **argv = globdata.gl_pathv;
  2524. /* "forget" pattern in o */
  2525. o->length = pattern - o->data;
  2526. while (1) {
  2527. o_addstr_with_NUL(o, *argv);
  2528. n = o_save_ptr_helper(o, n);
  2529. argv++;
  2530. if (!*argv)
  2531. break;
  2532. }
  2533. }
  2534. globfree(&globdata);
  2535. if (DEBUG_GLOB)
  2536. debug_print_list("perform_glob returning", o, n);
  2537. return n;
  2538. }
  2539. #endif /* !HUSH_BRACE_EXPANSION */
  2540. /* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered.
  2541. * Otherwise, just finish current list[] and start new */
  2542. static int o_save_ptr(o_string *o, int n)
  2543. {
  2544. if (o->o_expflags & EXP_FLAG_GLOB) {
  2545. /* If o->has_empty_slot, list[n] was already globbed
  2546. * (if it was requested back then when it was filled)
  2547. * so don't do that again! */
  2548. if (!o->has_empty_slot)
  2549. return perform_glob(o, n); /* o_save_ptr_helper is inside */
  2550. }
  2551. return o_save_ptr_helper(o, n);
  2552. }
  2553. /* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
  2554. static char **o_finalize_list(o_string *o, int n)
  2555. {
  2556. char **list;
  2557. int string_start;
  2558. n = o_save_ptr(o, n); /* force growth for list[n] if necessary */
  2559. if (DEBUG_EXPAND)
  2560. debug_print_list("finalized", o, n);
  2561. debug_printf_expand("finalized n:%d\n", n);
  2562. list = (char**)o->data;
  2563. string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
  2564. list[--n] = NULL;
  2565. while (n) {
  2566. n--;
  2567. list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
  2568. }
  2569. return list;
  2570. }
  2571. static void free_pipe_list(struct pipe *pi);
  2572. /* Returns pi->next - next pipe in the list */
  2573. static struct pipe *free_pipe(struct pipe *pi)
  2574. {
  2575. struct pipe *next;
  2576. int i;
  2577. debug_printf_clean("free_pipe (pid %d)\n", getpid());
  2578. for (i = 0; i < pi->num_cmds; i++) {
  2579. struct command *command;
  2580. struct redir_struct *r, *rnext;
  2581. command = &pi->cmds[i];
  2582. debug_printf_clean(" command %d:\n", i);
  2583. if (command->argv) {
  2584. if (DEBUG_CLEAN) {
  2585. int a;
  2586. char **p;
  2587. for (a = 0, p = command->argv; *p; a++, p++) {
  2588. debug_printf_clean(" argv[%d] = %s\n", a, *p);
  2589. }
  2590. }
  2591. free_strings(command->argv);
  2592. //command->argv = NULL;
  2593. }
  2594. /* not "else if": on syntax error, we may have both! */
  2595. if (command->group) {
  2596. debug_printf_clean(" begin group (cmd_type:%d)\n",
  2597. command->cmd_type);
  2598. free_pipe_list(command->group);
  2599. debug_printf_clean(" end group\n");
  2600. //command->group = NULL;
  2601. }
  2602. /* else is crucial here.
  2603. * If group != NULL, child_func is meaningless */
  2604. #if ENABLE_HUSH_FUNCTIONS
  2605. else if (command->child_func) {
  2606. debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
  2607. command->child_func->parent_cmd = NULL;
  2608. }
  2609. #endif
  2610. #if !BB_MMU
  2611. free(command->group_as_string);
  2612. //command->group_as_string = NULL;
  2613. #endif
  2614. for (r = command->redirects; r; r = rnext) {
  2615. debug_printf_clean(" redirect %d%s",
  2616. r->rd_fd, redir_table[r->rd_type].descrip);
  2617. /* guard against the case >$FOO, where foo is unset or blank */
  2618. if (r->rd_filename) {
  2619. debug_printf_clean(" fname:'%s'\n", r->rd_filename);
  2620. free(r->rd_filename);
  2621. //r->rd_filename = NULL;
  2622. }
  2623. debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
  2624. rnext = r->next;
  2625. free(r);
  2626. }
  2627. //command->redirects = NULL;
  2628. }
  2629. free(pi->cmds); /* children are an array, they get freed all at once */
  2630. //pi->cmds = NULL;
  2631. #if ENABLE_HUSH_JOB
  2632. free(pi->cmdtext);
  2633. //pi->cmdtext = NULL;
  2634. #endif
  2635. next = pi->next;
  2636. free(pi);
  2637. return next;
  2638. }
  2639. static void free_pipe_list(struct pipe *pi)
  2640. {
  2641. while (pi) {
  2642. #if HAS_KEYWORDS
  2643. debug_printf_clean("pipe reserved word %d\n", pi->res_word);
  2644. #endif
  2645. debug_printf_clean("pipe followup code %d\n", pi->followup);
  2646. pi = free_pipe(pi);
  2647. }
  2648. }
  2649. /*** Parsing routines ***/
  2650. #ifndef debug_print_tree
  2651. static void debug_print_tree(struct pipe *pi, int lvl)
  2652. {
  2653. static const char *const PIPE[] = {
  2654. [PIPE_SEQ] = "SEQ",
  2655. [PIPE_AND] = "AND",
  2656. [PIPE_OR ] = "OR" ,
  2657. [PIPE_BG ] = "BG" ,
  2658. };
  2659. static const char *RES[] = {
  2660. [RES_NONE ] = "NONE" ,
  2661. # if ENABLE_HUSH_IF
  2662. [RES_IF ] = "IF" ,
  2663. [RES_THEN ] = "THEN" ,
  2664. [RES_ELIF ] = "ELIF" ,
  2665. [RES_ELSE ] = "ELSE" ,
  2666. [RES_FI ] = "FI" ,
  2667. # endif
  2668. # if ENABLE_HUSH_LOOPS
  2669. [RES_FOR ] = "FOR" ,
  2670. [RES_WHILE] = "WHILE",
  2671. [RES_UNTIL] = "UNTIL",
  2672. [RES_DO ] = "DO" ,
  2673. [RES_DONE ] = "DONE" ,
  2674. # endif
  2675. # if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
  2676. [RES_IN ] = "IN" ,
  2677. # endif
  2678. # if ENABLE_HUSH_CASE
  2679. [RES_CASE ] = "CASE" ,
  2680. [RES_CASE_IN ] = "CASE_IN" ,
  2681. [RES_MATCH] = "MATCH",
  2682. [RES_CASE_BODY] = "CASE_BODY",
  2683. [RES_ESAC ] = "ESAC" ,
  2684. # endif
  2685. [RES_XXXX ] = "XXXX" ,
  2686. [RES_SNTX ] = "SNTX" ,
  2687. };
  2688. static const char *const CMDTYPE[] = {
  2689. "{}",
  2690. "()",
  2691. "[noglob]",
  2692. # if ENABLE_HUSH_FUNCTIONS
  2693. "func()",
  2694. # endif
  2695. };
  2696. int pin, prn;
  2697. pin = 0;
  2698. while (pi) {
  2699. fdprintf(2, "%*spipe %d res_word=%s followup=%d %s\n", lvl*2, "",
  2700. pin, RES[pi->res_word], pi->followup, PIPE[pi->followup]);
  2701. prn = 0;
  2702. while (prn < pi->num_cmds) {
  2703. struct command *command = &pi->cmds[prn];
  2704. char **argv = command->argv;
  2705. fdprintf(2, "%*s cmd %d assignment_cnt:%d",
  2706. lvl*2, "", prn,
  2707. command->assignment_cnt);
  2708. if (command->group) {
  2709. fdprintf(2, " group %s: (argv=%p)%s%s\n",
  2710. CMDTYPE[command->cmd_type],
  2711. argv
  2712. # if !BB_MMU
  2713. , " group_as_string:", command->group_as_string
  2714. # else
  2715. , "", ""
  2716. # endif
  2717. );
  2718. debug_print_tree(command->group, lvl+1);
  2719. prn++;
  2720. continue;
  2721. }
  2722. if (argv) while (*argv) {
  2723. fdprintf(2, " '%s'", *argv);
  2724. argv++;
  2725. }
  2726. fdprintf(2, "\n");
  2727. prn++;
  2728. }
  2729. pi = pi->next;
  2730. pin++;
  2731. }
  2732. }
  2733. #endif /* debug_print_tree */
  2734. static struct pipe *new_pipe(void)
  2735. {
  2736. struct pipe *pi;
  2737. pi = xzalloc(sizeof(struct pipe));
  2738. /*pi->followup = 0; - deliberately invalid value */
  2739. /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
  2740. return pi;
  2741. }
  2742. /* Command (member of a pipe) is complete, or we start a new pipe
  2743. * if ctx->command is NULL.
  2744. * No errors possible here.
  2745. */
  2746. static int done_command(struct parse_context *ctx)
  2747. {
  2748. /* The command is really already in the pipe structure, so
  2749. * advance the pipe counter and make a new, null command. */
  2750. struct pipe *pi = ctx->pipe;
  2751. struct command *command = ctx->command;
  2752. if (command) {
  2753. if (IS_NULL_CMD(command)) {
  2754. debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
  2755. goto clear_and_ret;
  2756. }
  2757. pi->num_cmds++;
  2758. debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
  2759. //debug_print_tree(ctx->list_head, 20);
  2760. } else {
  2761. debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
  2762. }
  2763. /* Only real trickiness here is that the uncommitted
  2764. * command structure is not counted in pi->num_cmds. */
  2765. pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
  2766. ctx->command = command = &pi->cmds[pi->num_cmds];
  2767. clear_and_ret:
  2768. memset(command, 0, sizeof(*command));
  2769. return pi->num_cmds; /* used only for 0/nonzero check */
  2770. }
  2771. static void done_pipe(struct parse_context *ctx, pipe_style type)
  2772. {
  2773. int not_null;
  2774. debug_printf_parse("done_pipe entered, followup %d\n", type);
  2775. /* Close previous command */
  2776. not_null = done_command(ctx);
  2777. ctx->pipe->followup = type;
  2778. #if HAS_KEYWORDS
  2779. ctx->pipe->pi_inverted = ctx->ctx_inverted;
  2780. ctx->ctx_inverted = 0;
  2781. ctx->pipe->res_word = ctx->ctx_res_w;
  2782. #endif
  2783. /* Without this check, even just <enter> on command line generates
  2784. * tree of three NOPs (!). Which is harmless but annoying.
  2785. * IOW: it is safe to do it unconditionally. */
  2786. if (not_null
  2787. #if ENABLE_HUSH_IF
  2788. || ctx->ctx_res_w == RES_FI
  2789. #endif
  2790. #if ENABLE_HUSH_LOOPS
  2791. || ctx->ctx_res_w == RES_DONE
  2792. || ctx->ctx_res_w == RES_FOR
  2793. || ctx->ctx_res_w == RES_IN
  2794. #endif
  2795. #if ENABLE_HUSH_CASE
  2796. || ctx->ctx_res_w == RES_ESAC
  2797. #endif
  2798. ) {
  2799. struct pipe *new_p;
  2800. debug_printf_parse("done_pipe: adding new pipe: "
  2801. "not_null:%d ctx->ctx_res_w:%d\n",
  2802. not_null, ctx->ctx_res_w);
  2803. new_p = new_pipe();
  2804. ctx->pipe->next = new_p;
  2805. ctx->pipe = new_p;
  2806. /* RES_THEN, RES_DO etc are "sticky" -
  2807. * they remain set for pipes inside if/while.
  2808. * This is used to control execution.
  2809. * RES_FOR and RES_IN are NOT sticky (needed to support
  2810. * cases where variable or value happens to match a keyword):
  2811. */
  2812. #if ENABLE_HUSH_LOOPS
  2813. if (ctx->ctx_res_w == RES_FOR
  2814. || ctx->ctx_res_w == RES_IN)
  2815. ctx->ctx_res_w = RES_NONE;
  2816. #endif
  2817. #if ENABLE_HUSH_CASE
  2818. if (ctx->ctx_res_w == RES_MATCH)
  2819. ctx->ctx_res_w = RES_CASE_BODY;
  2820. if (ctx->ctx_res_w == RES_CASE)
  2821. ctx->ctx_res_w = RES_CASE_IN;
  2822. #endif
  2823. ctx->command = NULL; /* trick done_command below */
  2824. /* Create the memory for command, roughly:
  2825. * ctx->pipe->cmds = new struct command;
  2826. * ctx->command = &ctx->pipe->cmds[0];
  2827. */
  2828. done_command(ctx);
  2829. //debug_print_tree(ctx->list_head, 10);
  2830. }
  2831. debug_printf_parse("done_pipe return\n");
  2832. }
  2833. static void initialize_context(struct parse_context *ctx)
  2834. {
  2835. memset(ctx, 0, sizeof(*ctx));
  2836. ctx->pipe = ctx->list_head = new_pipe();
  2837. /* Create the memory for command, roughly:
  2838. * ctx->pipe->cmds = new struct command;
  2839. * ctx->command = &ctx->pipe->cmds[0];
  2840. */
  2841. done_command(ctx);
  2842. }
  2843. /* If a reserved word is found and processed, parse context is modified
  2844. * and 1 is returned.
  2845. */
  2846. #if HAS_KEYWORDS
  2847. struct reserved_combo {
  2848. char literal[6];
  2849. unsigned char res;
  2850. unsigned char assignment_flag;
  2851. int flag;
  2852. };
  2853. enum {
  2854. FLAG_END = (1 << RES_NONE ),
  2855. # if ENABLE_HUSH_IF
  2856. FLAG_IF = (1 << RES_IF ),
  2857. FLAG_THEN = (1 << RES_THEN ),
  2858. FLAG_ELIF = (1 << RES_ELIF ),
  2859. FLAG_ELSE = (1 << RES_ELSE ),
  2860. FLAG_FI = (1 << RES_FI ),
  2861. # endif
  2862. # if ENABLE_HUSH_LOOPS
  2863. FLAG_FOR = (1 << RES_FOR ),
  2864. FLAG_WHILE = (1 << RES_WHILE),
  2865. FLAG_UNTIL = (1 << RES_UNTIL),
  2866. FLAG_DO = (1 << RES_DO ),
  2867. FLAG_DONE = (1 << RES_DONE ),
  2868. FLAG_IN = (1 << RES_IN ),
  2869. # endif
  2870. # if ENABLE_HUSH_CASE
  2871. FLAG_MATCH = (1 << RES_MATCH),
  2872. FLAG_ESAC = (1 << RES_ESAC ),
  2873. # endif
  2874. FLAG_START = (1 << RES_XXXX ),
  2875. };
  2876. static const struct reserved_combo* match_reserved_word(o_string *word)
  2877. {
  2878. /* Mostly a list of accepted follow-up reserved words.
  2879. * FLAG_END means we are done with the sequence, and are ready
  2880. * to turn the compound list into a command.
  2881. * FLAG_START means the word must start a new compound list.
  2882. */
  2883. static const struct reserved_combo reserved_list[] = {
  2884. # if ENABLE_HUSH_IF
  2885. { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
  2886. { "if", RES_IF, MAYBE_ASSIGNMENT, FLAG_THEN | FLAG_START },
  2887. { "then", RES_THEN, MAYBE_ASSIGNMENT, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
  2888. { "elif", RES_ELIF, MAYBE_ASSIGNMENT, FLAG_THEN },
  2889. { "else", RES_ELSE, MAYBE_ASSIGNMENT, FLAG_FI },
  2890. { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
  2891. # endif
  2892. # if ENABLE_HUSH_LOOPS
  2893. { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
  2894. { "while", RES_WHILE, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
  2895. { "until", RES_UNTIL, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
  2896. { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
  2897. { "do", RES_DO, MAYBE_ASSIGNMENT, FLAG_DONE },
  2898. { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
  2899. # endif
  2900. # if ENABLE_HUSH_CASE
  2901. { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
  2902. { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
  2903. # endif
  2904. };
  2905. const struct reserved_combo *r;
  2906. for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
  2907. if (strcmp(word->data, r->literal) == 0)
  2908. return r;
  2909. }
  2910. return NULL;
  2911. }
  2912. /* Return 0: not a keyword, 1: keyword
  2913. */
  2914. static int reserved_word(o_string *word, struct parse_context *ctx)
  2915. {
  2916. # if ENABLE_HUSH_CASE
  2917. static const struct reserved_combo reserved_match = {
  2918. "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
  2919. };
  2920. # endif
  2921. const struct reserved_combo *r;
  2922. if (word->has_quoted_part)
  2923. return 0;
  2924. r = match_reserved_word(word);
  2925. if (!r)
  2926. return 0;
  2927. debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
  2928. # if ENABLE_HUSH_CASE
  2929. if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
  2930. /* "case word IN ..." - IN part starts first MATCH part */
  2931. r = &reserved_match;
  2932. } else
  2933. # endif
  2934. if (r->flag == 0) { /* '!' */
  2935. if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
  2936. syntax_error("! ! command");
  2937. ctx->ctx_res_w = RES_SNTX;
  2938. }
  2939. ctx->ctx_inverted = 1;
  2940. return 1;
  2941. }
  2942. if (r->flag & FLAG_START) {
  2943. struct parse_context *old;
  2944. old = xmalloc(sizeof(*old));
  2945. debug_printf_parse("push stack %p\n", old);
  2946. *old = *ctx; /* physical copy */
  2947. initialize_context(ctx);
  2948. ctx->stack = old;
  2949. } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
  2950. syntax_error_at(word->data);
  2951. ctx->ctx_res_w = RES_SNTX;
  2952. return 1;
  2953. } else {
  2954. /* "{...} fi" is ok. "{...} if" is not
  2955. * Example:
  2956. * if { echo foo; } then { echo bar; } fi */
  2957. if (ctx->command->group)
  2958. done_pipe(ctx, PIPE_SEQ);
  2959. }
  2960. ctx->ctx_res_w = r->res;
  2961. ctx->old_flag = r->flag;
  2962. word->o_assignment = r->assignment_flag;
  2963. debug_printf_parse("word->o_assignment='%s'\n", assignment_flag[word->o_assignment]);
  2964. if (ctx->old_flag & FLAG_END) {
  2965. struct parse_context *old;
  2966. done_pipe(ctx, PIPE_SEQ);
  2967. debug_printf_parse("pop stack %p\n", ctx->stack);
  2968. old = ctx->stack;
  2969. old->command->group = ctx->list_head;
  2970. old->command->cmd_type = CMD_NORMAL;
  2971. # if !BB_MMU
  2972. /* At this point, the compound command's string is in
  2973. * ctx->as_string... except for the leading keyword!
  2974. * Consider this example: "echo a | if true; then echo a; fi"
  2975. * ctx->as_string will contain "true; then echo a; fi",
  2976. * with "if " remaining in old->as_string!
  2977. */
  2978. {
  2979. char *str;
  2980. int len = old->as_string.length;
  2981. /* Concatenate halves */
  2982. o_addstr(&old->as_string, ctx->as_string.data);
  2983. o_free_unsafe(&ctx->as_string);
  2984. /* Find where leading keyword starts in first half */
  2985. str = old->as_string.data + len;
  2986. if (str > old->as_string.data)
  2987. str--; /* skip whitespace after keyword */
  2988. while (str > old->as_string.data && isalpha(str[-1]))
  2989. str--;
  2990. /* Ugh, we're done with this horrid hack */
  2991. old->command->group_as_string = xstrdup(str);
  2992. debug_printf_parse("pop, remembering as:'%s'\n",
  2993. old->command->group_as_string);
  2994. }
  2995. # endif
  2996. *ctx = *old; /* physical copy */
  2997. free(old);
  2998. }
  2999. return 1;
  3000. }
  3001. #endif /* HAS_KEYWORDS */
  3002. /* Word is complete, look at it and update parsing context.
  3003. * Normal return is 0. Syntax errors return 1.
  3004. * Note: on return, word is reset, but not o_free'd!
  3005. */
  3006. static int done_word(o_string *word, struct parse_context *ctx)
  3007. {
  3008. struct command *command = ctx->command;
  3009. debug_printf_parse("done_word entered: '%s' %p\n", word->data, command);
  3010. if (word->length == 0 && !word->has_quoted_part) {
  3011. debug_printf_parse("done_word return 0: true null, ignored\n");
  3012. return 0;
  3013. }
  3014. if (ctx->pending_redirect) {
  3015. /* We do not glob in e.g. >*.tmp case. bash seems to glob here
  3016. * only if run as "bash", not "sh" */
  3017. /* http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
  3018. * "2.7 Redirection
  3019. * ...the word that follows the redirection operator
  3020. * shall be subjected to tilde expansion, parameter expansion,
  3021. * command substitution, arithmetic expansion, and quote
  3022. * removal. Pathname expansion shall not be performed
  3023. * on the word by a non-interactive shell; an interactive
  3024. * shell may perform it, but shall do so only when
  3025. * the expansion would result in one word."
  3026. */
  3027. ctx->pending_redirect->rd_filename = xstrdup(word->data);
  3028. /* Cater for >\file case:
  3029. * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
  3030. * Same with heredocs:
  3031. * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
  3032. */
  3033. if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
  3034. unbackslash(ctx->pending_redirect->rd_filename);
  3035. /* Is it <<"HEREDOC"? */
  3036. if (word->has_quoted_part) {
  3037. ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
  3038. }
  3039. }
  3040. debug_printf_parse("word stored in rd_filename: '%s'\n", word->data);
  3041. ctx->pending_redirect = NULL;
  3042. } else {
  3043. #if HAS_KEYWORDS
  3044. # if ENABLE_HUSH_CASE
  3045. if (ctx->ctx_dsemicolon
  3046. && strcmp(word->data, "esac") != 0 /* not "... pattern) cmd;; esac" */
  3047. ) {
  3048. /* already done when ctx_dsemicolon was set to 1: */
  3049. /* ctx->ctx_res_w = RES_MATCH; */
  3050. ctx->ctx_dsemicolon = 0;
  3051. } else
  3052. # endif
  3053. if (!command->argv /* if it's the first word... */
  3054. # if ENABLE_HUSH_LOOPS
  3055. && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
  3056. && ctx->ctx_res_w != RES_IN
  3057. # endif
  3058. # if ENABLE_HUSH_CASE
  3059. && ctx->ctx_res_w != RES_CASE
  3060. # endif
  3061. ) {
  3062. int reserved = reserved_word(word, ctx);
  3063. debug_printf_parse("checking for reserved-ness: %d\n", reserved);
  3064. if (reserved) {
  3065. o_reset_to_empty_unquoted(word);
  3066. debug_printf_parse("done_word return %d\n",
  3067. (ctx->ctx_res_w == RES_SNTX));
  3068. return (ctx->ctx_res_w == RES_SNTX);
  3069. }
  3070. # if ENABLE_HUSH_BASH_COMPAT
  3071. if (strcmp(word->data, "[[") == 0) {
  3072. command->cmd_type = CMD_SINGLEWORD_NOGLOB;
  3073. }
  3074. /* fall through */
  3075. # endif
  3076. }
  3077. #endif
  3078. if (command->group) {
  3079. /* "{ echo foo; } echo bar" - bad */
  3080. syntax_error_at(word->data);
  3081. debug_printf_parse("done_word return 1: syntax error, "
  3082. "groups and arglists don't mix\n");
  3083. return 1;
  3084. }
  3085. /* If this word wasn't an assignment, next ones definitely
  3086. * can't be assignments. Even if they look like ones. */
  3087. if (word->o_assignment != DEFINITELY_ASSIGNMENT
  3088. && word->o_assignment != WORD_IS_KEYWORD
  3089. ) {
  3090. word->o_assignment = NOT_ASSIGNMENT;
  3091. } else {
  3092. if (word->o_assignment == DEFINITELY_ASSIGNMENT) {
  3093. command->assignment_cnt++;
  3094. debug_printf_parse("++assignment_cnt=%d\n", command->assignment_cnt);
  3095. }
  3096. debug_printf_parse("word->o_assignment was:'%s'\n", assignment_flag[word->o_assignment]);
  3097. word->o_assignment = MAYBE_ASSIGNMENT;
  3098. }
  3099. debug_printf_parse("word->o_assignment='%s'\n", assignment_flag[word->o_assignment]);
  3100. if (word->has_quoted_part
  3101. /* optimization: and if it's ("" or '') or ($v... or `cmd`...): */
  3102. && (word->data[0] == '\0' || word->data[0] == SPECIAL_VAR_SYMBOL)
  3103. /* (otherwise it's known to be not empty and is already safe) */
  3104. ) {
  3105. /* exclude "$@" - it can expand to no word despite "" */
  3106. char *p = word->data;
  3107. while (p[0] == SPECIAL_VAR_SYMBOL
  3108. && (p[1] & 0x7f) == '@'
  3109. && p[2] == SPECIAL_VAR_SYMBOL
  3110. ) {
  3111. p += 3;
  3112. }
  3113. }
  3114. command->argv = add_string_to_strings(command->argv, xstrdup(word->data));
  3115. debug_print_strings("word appended to argv", command->argv);
  3116. }
  3117. #if ENABLE_HUSH_LOOPS
  3118. if (ctx->ctx_res_w == RES_FOR) {
  3119. if (word->has_quoted_part
  3120. || !is_well_formed_var_name(command->argv[0], '\0')
  3121. ) {
  3122. /* bash says just "not a valid identifier" */
  3123. syntax_error("not a valid identifier in for");
  3124. return 1;
  3125. }
  3126. /* Force FOR to have just one word (variable name) */
  3127. /* NB: basically, this makes hush see "for v in ..."
  3128. * syntax as if it is "for v; in ...". FOR and IN become
  3129. * two pipe structs in parse tree. */
  3130. done_pipe(ctx, PIPE_SEQ);
  3131. }
  3132. #endif
  3133. #if ENABLE_HUSH_CASE
  3134. /* Force CASE to have just one word */
  3135. if (ctx->ctx_res_w == RES_CASE) {
  3136. done_pipe(ctx, PIPE_SEQ);
  3137. }
  3138. #endif
  3139. o_reset_to_empty_unquoted(word);
  3140. debug_printf_parse("done_word return 0\n");
  3141. return 0;
  3142. }
  3143. /* Peek ahead in the input to find out if we have a "&n" construct,
  3144. * as in "2>&1", that represents duplicating a file descriptor.
  3145. * Return:
  3146. * REDIRFD_CLOSE if >&- "close fd" construct is seen,
  3147. * REDIRFD_SYNTAX_ERR if syntax error,
  3148. * REDIRFD_TO_FILE if no & was seen,
  3149. * or the number found.
  3150. */
  3151. #if BB_MMU
  3152. #define parse_redir_right_fd(as_string, input) \
  3153. parse_redir_right_fd(input)
  3154. #endif
  3155. static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
  3156. {
  3157. int ch, d, ok;
  3158. ch = i_peek(input);
  3159. if (ch != '&')
  3160. return REDIRFD_TO_FILE;
  3161. ch = i_getch(input); /* get the & */
  3162. nommu_addchr(as_string, ch);
  3163. ch = i_peek(input);
  3164. if (ch == '-') {
  3165. ch = i_getch(input);
  3166. nommu_addchr(as_string, ch);
  3167. return REDIRFD_CLOSE;
  3168. }
  3169. d = 0;
  3170. ok = 0;
  3171. while (ch != EOF && isdigit(ch)) {
  3172. d = d*10 + (ch-'0');
  3173. ok = 1;
  3174. ch = i_getch(input);
  3175. nommu_addchr(as_string, ch);
  3176. ch = i_peek(input);
  3177. }
  3178. if (ok) return d;
  3179. //TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
  3180. bb_error_msg("ambiguous redirect");
  3181. return REDIRFD_SYNTAX_ERR;
  3182. }
  3183. /* Return code is 0 normal, 1 if a syntax error is detected
  3184. */
  3185. static int parse_redirect(struct parse_context *ctx,
  3186. int fd,
  3187. redir_type style,
  3188. struct in_str *input)
  3189. {
  3190. struct command *command = ctx->command;
  3191. struct redir_struct *redir;
  3192. struct redir_struct **redirp;
  3193. int dup_num;
  3194. dup_num = REDIRFD_TO_FILE;
  3195. if (style != REDIRECT_HEREDOC) {
  3196. /* Check for a '>&1' type redirect */
  3197. dup_num = parse_redir_right_fd(&ctx->as_string, input);
  3198. if (dup_num == REDIRFD_SYNTAX_ERR)
  3199. return 1;
  3200. } else {
  3201. int ch = i_peek(input);
  3202. dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
  3203. if (dup_num) { /* <<-... */
  3204. ch = i_getch(input);
  3205. nommu_addchr(&ctx->as_string, ch);
  3206. ch = i_peek(input);
  3207. }
  3208. }
  3209. if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
  3210. int ch = i_peek(input);
  3211. if (ch == '|') {
  3212. /* >|FILE redirect ("clobbering" >).
  3213. * Since we do not support "set -o noclobber" yet,
  3214. * >| and > are the same for now. Just eat |.
  3215. */
  3216. ch = i_getch(input);
  3217. nommu_addchr(&ctx->as_string, ch);
  3218. }
  3219. }
  3220. /* Create a new redir_struct and append it to the linked list */
  3221. redirp = &command->redirects;
  3222. while ((redir = *redirp) != NULL) {
  3223. redirp = &(redir->next);
  3224. }
  3225. *redirp = redir = xzalloc(sizeof(*redir));
  3226. /* redir->next = NULL; */
  3227. /* redir->rd_filename = NULL; */
  3228. redir->rd_type = style;
  3229. redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
  3230. debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
  3231. redir_table[style].descrip);
  3232. redir->rd_dup = dup_num;
  3233. if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
  3234. /* Erik had a check here that the file descriptor in question
  3235. * is legit; I postpone that to "run time"
  3236. * A "-" representation of "close me" shows up as a -3 here */
  3237. debug_printf_parse("duplicating redirect '%d>&%d'\n",
  3238. redir->rd_fd, redir->rd_dup);
  3239. } else {
  3240. /* Set ctx->pending_redirect, so we know what to do at the
  3241. * end of the next parsed word. */
  3242. ctx->pending_redirect = redir;
  3243. }
  3244. return 0;
  3245. }
  3246. /* If a redirect is immediately preceded by a number, that number is
  3247. * supposed to tell which file descriptor to redirect. This routine
  3248. * looks for such preceding numbers. In an ideal world this routine
  3249. * needs to handle all the following classes of redirects...
  3250. * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
  3251. * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
  3252. * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
  3253. * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
  3254. *
  3255. * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
  3256. * "2.7 Redirection
  3257. * ... If n is quoted, the number shall not be recognized as part of
  3258. * the redirection expression. For example:
  3259. * echo \2>a
  3260. * writes the character 2 into file a"
  3261. * We are getting it right by setting ->has_quoted_part on any \<char>
  3262. *
  3263. * A -1 return means no valid number was found,
  3264. * the caller should use the appropriate default for this redirection.
  3265. */
  3266. static int redirect_opt_num(o_string *o)
  3267. {
  3268. int num;
  3269. if (o->data == NULL)
  3270. return -1;
  3271. num = bb_strtou(o->data, NULL, 10);
  3272. if (errno || num < 0)
  3273. return -1;
  3274. o_reset_to_empty_unquoted(o);
  3275. return num;
  3276. }
  3277. #if BB_MMU
  3278. #define fetch_till_str(as_string, input, word, skip_tabs) \
  3279. fetch_till_str(input, word, skip_tabs)
  3280. #endif
  3281. static char *fetch_till_str(o_string *as_string,
  3282. struct in_str *input,
  3283. const char *word,
  3284. int heredoc_flags)
  3285. {
  3286. o_string heredoc = NULL_O_STRING;
  3287. unsigned past_EOL;
  3288. int prev = 0; /* not \ */
  3289. int ch;
  3290. goto jump_in;
  3291. while (1) {
  3292. ch = i_getch(input);
  3293. if (ch != EOF)
  3294. nommu_addchr(as_string, ch);
  3295. if ((ch == '\n' || ch == EOF)
  3296. && ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\')
  3297. ) {
  3298. if (strcmp(heredoc.data + past_EOL, word) == 0) {
  3299. heredoc.data[past_EOL] = '\0';
  3300. debug_printf_parse("parsed heredoc '%s'\n", heredoc.data);
  3301. return heredoc.data;
  3302. }
  3303. while (ch == '\n') {
  3304. o_addchr(&heredoc, ch);
  3305. prev = ch;
  3306. jump_in:
  3307. past_EOL = heredoc.length;
  3308. do {
  3309. ch = i_getch(input);
  3310. if (ch != EOF)
  3311. nommu_addchr(as_string, ch);
  3312. } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
  3313. }
  3314. }
  3315. if (ch == EOF) {
  3316. o_free_unsafe(&heredoc);
  3317. return NULL;
  3318. }
  3319. o_addchr(&heredoc, ch);
  3320. nommu_addchr(as_string, ch);
  3321. if (prev == '\\' && ch == '\\')
  3322. /* Correctly handle foo\\<eol> (not a line cont.) */
  3323. prev = 0; /* not \ */
  3324. else
  3325. prev = ch;
  3326. }
  3327. }
  3328. /* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
  3329. * and load them all. There should be exactly heredoc_cnt of them.
  3330. */
  3331. static int fetch_heredocs(int heredoc_cnt, struct parse_context *ctx, struct in_str *input)
  3332. {
  3333. struct pipe *pi = ctx->list_head;
  3334. while (pi && heredoc_cnt) {
  3335. int i;
  3336. struct command *cmd = pi->cmds;
  3337. debug_printf_parse("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
  3338. pi->num_cmds,
  3339. cmd->argv ? cmd->argv[0] : "NONE");
  3340. for (i = 0; i < pi->num_cmds; i++) {
  3341. struct redir_struct *redir = cmd->redirects;
  3342. debug_printf_parse("fetch_heredocs: %d cmd argv0:'%s'\n",
  3343. i, cmd->argv ? cmd->argv[0] : "NONE");
  3344. while (redir) {
  3345. if (redir->rd_type == REDIRECT_HEREDOC) {
  3346. char *p;
  3347. redir->rd_type = REDIRECT_HEREDOC2;
  3348. /* redir->rd_dup is (ab)used to indicate <<- */
  3349. p = fetch_till_str(&ctx->as_string, input,
  3350. redir->rd_filename, redir->rd_dup);
  3351. if (!p) {
  3352. syntax_error("unexpected EOF in here document");
  3353. return 1;
  3354. }
  3355. free(redir->rd_filename);
  3356. redir->rd_filename = p;
  3357. heredoc_cnt--;
  3358. }
  3359. redir = redir->next;
  3360. }
  3361. cmd++;
  3362. }
  3363. pi = pi->next;
  3364. }
  3365. #if 0
  3366. /* Should be 0. If it isn't, it's a parse error */
  3367. if (heredoc_cnt)
  3368. bb_error_msg_and_die("heredoc BUG 2");
  3369. #endif
  3370. return 0;
  3371. }
  3372. static int run_list(struct pipe *pi);
  3373. #if BB_MMU
  3374. #define parse_stream(pstring, input, end_trigger) \
  3375. parse_stream(input, end_trigger)
  3376. #endif
  3377. static struct pipe *parse_stream(char **pstring,
  3378. struct in_str *input,
  3379. int end_trigger);
  3380. #if !ENABLE_HUSH_FUNCTIONS
  3381. #define parse_group(dest, ctx, input, ch) \
  3382. parse_group(ctx, input, ch)
  3383. #endif
  3384. static int parse_group(o_string *dest, struct parse_context *ctx,
  3385. struct in_str *input, int ch)
  3386. {
  3387. /* dest contains characters seen prior to ( or {.
  3388. * Typically it's empty, but for function defs,
  3389. * it contains function name (without '()'). */
  3390. struct pipe *pipe_list;
  3391. int endch;
  3392. struct command *command = ctx->command;
  3393. debug_printf_parse("parse_group entered\n");
  3394. #if ENABLE_HUSH_FUNCTIONS
  3395. if (ch == '(' && !dest->has_quoted_part) {
  3396. if (dest->length)
  3397. if (done_word(dest, ctx))
  3398. return 1;
  3399. if (!command->argv)
  3400. goto skip; /* (... */
  3401. if (command->argv[1]) { /* word word ... (... */
  3402. syntax_error_unexpected_ch('(');
  3403. return 1;
  3404. }
  3405. /* it is "word(..." or "word (..." */
  3406. do
  3407. ch = i_getch(input);
  3408. while (ch == ' ' || ch == '\t');
  3409. if (ch != ')') {
  3410. syntax_error_unexpected_ch(ch);
  3411. return 1;
  3412. }
  3413. nommu_addchr(&ctx->as_string, ch);
  3414. do
  3415. ch = i_getch(input);
  3416. while (ch == ' ' || ch == '\t' || ch == '\n');
  3417. if (ch != '{') {
  3418. syntax_error_unexpected_ch(ch);
  3419. return 1;
  3420. }
  3421. nommu_addchr(&ctx->as_string, ch);
  3422. command->cmd_type = CMD_FUNCDEF;
  3423. goto skip;
  3424. }
  3425. #endif
  3426. #if 0 /* Prevented by caller */
  3427. if (command->argv /* word [word]{... */
  3428. || dest->length /* word{... */
  3429. || dest->has_quoted_part /* ""{... */
  3430. ) {
  3431. syntax_error(NULL);
  3432. debug_printf_parse("parse_group return 1: "
  3433. "syntax error, groups and arglists don't mix\n");
  3434. return 1;
  3435. }
  3436. #endif
  3437. #if ENABLE_HUSH_FUNCTIONS
  3438. skip:
  3439. #endif
  3440. endch = '}';
  3441. if (ch == '(') {
  3442. endch = ')';
  3443. command->cmd_type = CMD_SUBSHELL;
  3444. } else {
  3445. /* bash does not allow "{echo...", requires whitespace */
  3446. ch = i_getch(input);
  3447. if (ch != ' ' && ch != '\t' && ch != '\n') {
  3448. syntax_error_unexpected_ch(ch);
  3449. return 1;
  3450. }
  3451. nommu_addchr(&ctx->as_string, ch);
  3452. }
  3453. {
  3454. #if BB_MMU
  3455. # define as_string NULL
  3456. #else
  3457. char *as_string = NULL;
  3458. #endif
  3459. pipe_list = parse_stream(&as_string, input, endch);
  3460. #if !BB_MMU
  3461. if (as_string)
  3462. o_addstr(&ctx->as_string, as_string);
  3463. #endif
  3464. /* empty ()/{} or parse error? */
  3465. if (!pipe_list || pipe_list == ERR_PTR) {
  3466. /* parse_stream already emitted error msg */
  3467. if (!BB_MMU)
  3468. free(as_string);
  3469. debug_printf_parse("parse_group return 1: "
  3470. "parse_stream returned %p\n", pipe_list);
  3471. return 1;
  3472. }
  3473. command->group = pipe_list;
  3474. #if !BB_MMU
  3475. as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
  3476. command->group_as_string = as_string;
  3477. debug_printf_parse("end of group, remembering as:'%s'\n",
  3478. command->group_as_string);
  3479. #endif
  3480. #undef as_string
  3481. }
  3482. debug_printf_parse("parse_group return 0\n");
  3483. return 0;
  3484. /* command remains "open", available for possible redirects */
  3485. }
  3486. #if ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS
  3487. /* Subroutines for copying $(...) and `...` things */
  3488. static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote);
  3489. /* '...' */
  3490. static int add_till_single_quote(o_string *dest, struct in_str *input)
  3491. {
  3492. while (1) {
  3493. int ch = i_getch(input);
  3494. if (ch == EOF) {
  3495. syntax_error_unterm_ch('\'');
  3496. return 0;
  3497. }
  3498. if (ch == '\'')
  3499. return 1;
  3500. o_addchr(dest, ch);
  3501. }
  3502. }
  3503. /* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
  3504. static int add_till_double_quote(o_string *dest, struct in_str *input)
  3505. {
  3506. while (1) {
  3507. int ch = i_getch(input);
  3508. if (ch == EOF) {
  3509. syntax_error_unterm_ch('"');
  3510. return 0;
  3511. }
  3512. if (ch == '"')
  3513. return 1;
  3514. if (ch == '\\') { /* \x. Copy both chars. */
  3515. o_addchr(dest, ch);
  3516. ch = i_getch(input);
  3517. }
  3518. o_addchr(dest, ch);
  3519. if (ch == '`') {
  3520. if (!add_till_backquote(dest, input, /*in_dquote:*/ 1))
  3521. return 0;
  3522. o_addchr(dest, ch);
  3523. continue;
  3524. }
  3525. //if (ch == '$') ...
  3526. }
  3527. }
  3528. /* Process `cmd` - copy contents until "`" is seen. Complicated by
  3529. * \` quoting.
  3530. * "Within the backquoted style of command substitution, backslash
  3531. * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
  3532. * The search for the matching backquote shall be satisfied by the first
  3533. * backquote found without a preceding backslash; during this search,
  3534. * if a non-escaped backquote is encountered within a shell comment,
  3535. * a here-document, an embedded command substitution of the $(command)
  3536. * form, or a quoted string, undefined results occur. A single-quoted
  3537. * or double-quoted string that begins, but does not end, within the
  3538. * "`...`" sequence produces undefined results."
  3539. * Example Output
  3540. * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
  3541. */
  3542. static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote)
  3543. {
  3544. while (1) {
  3545. int ch = i_getch(input);
  3546. if (ch == '`')
  3547. return 1;
  3548. if (ch == '\\') {
  3549. /* \x. Copy both unless it is \`, \$, \\ and maybe \" */
  3550. ch = i_getch(input);
  3551. if (ch != '`'
  3552. && ch != '$'
  3553. && ch != '\\'
  3554. && (!in_dquote || ch != '"')
  3555. ) {
  3556. o_addchr(dest, '\\');
  3557. }
  3558. }
  3559. if (ch == EOF) {
  3560. syntax_error_unterm_ch('`');
  3561. return 0;
  3562. }
  3563. o_addchr(dest, ch);
  3564. }
  3565. }
  3566. /* Process $(cmd) - copy contents until ")" is seen. Complicated by
  3567. * quoting and nested ()s.
  3568. * "With the $(command) style of command substitution, all characters
  3569. * following the open parenthesis to the matching closing parenthesis
  3570. * constitute the command. Any valid shell script can be used for command,
  3571. * except a script consisting solely of redirections which produces
  3572. * unspecified results."
  3573. * Example Output
  3574. * echo $(echo '(TEST)' BEST) (TEST) BEST
  3575. * echo $(echo 'TEST)' BEST) TEST) BEST
  3576. * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
  3577. *
  3578. * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
  3579. * can contain arbitrary constructs, just like $(cmd).
  3580. * In bash compat mode, it needs to also be able to stop on ':' or '/'
  3581. * for ${var:N[:M]} and ${var/P[/R]} parsing.
  3582. */
  3583. #define DOUBLE_CLOSE_CHAR_FLAG 0x80
  3584. static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
  3585. {
  3586. int ch;
  3587. char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
  3588. # if ENABLE_HUSH_BASH_COMPAT
  3589. char end_char2 = end_ch >> 8;
  3590. # endif
  3591. end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
  3592. while (1) {
  3593. ch = i_getch(input);
  3594. if (ch == EOF) {
  3595. syntax_error_unterm_ch(end_ch);
  3596. return 0;
  3597. }
  3598. if (ch == end_ch IF_HUSH_BASH_COMPAT( || ch == end_char2)) {
  3599. if (!dbl)
  3600. break;
  3601. /* we look for closing )) of $((EXPR)) */
  3602. if (i_peek(input) == end_ch) {
  3603. i_getch(input); /* eat second ')' */
  3604. break;
  3605. }
  3606. }
  3607. o_addchr(dest, ch);
  3608. if (ch == '(' || ch == '{') {
  3609. ch = (ch == '(' ? ')' : '}');
  3610. if (!add_till_closing_bracket(dest, input, ch))
  3611. return 0;
  3612. o_addchr(dest, ch);
  3613. continue;
  3614. }
  3615. if (ch == '\'') {
  3616. if (!add_till_single_quote(dest, input))
  3617. return 0;
  3618. o_addchr(dest, ch);
  3619. continue;
  3620. }
  3621. if (ch == '"') {
  3622. if (!add_till_double_quote(dest, input))
  3623. return 0;
  3624. o_addchr(dest, ch);
  3625. continue;
  3626. }
  3627. if (ch == '`') {
  3628. if (!add_till_backquote(dest, input, /*in_dquote:*/ 0))
  3629. return 0;
  3630. o_addchr(dest, ch);
  3631. continue;
  3632. }
  3633. if (ch == '\\') {
  3634. /* \x. Copy verbatim. Important for \(, \) */
  3635. ch = i_getch(input);
  3636. if (ch == EOF) {
  3637. syntax_error_unterm_ch(')');
  3638. return 0;
  3639. }
  3640. o_addchr(dest, ch);
  3641. continue;
  3642. }
  3643. }
  3644. return ch;
  3645. }
  3646. #endif /* ENABLE_HUSH_TICK || ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_DOLLAR_OPS */
  3647. /* Return code: 0 for OK, 1 for syntax error */
  3648. #if BB_MMU
  3649. #define parse_dollar(as_string, dest, input, quote_mask) \
  3650. parse_dollar(dest, input, quote_mask)
  3651. #define as_string NULL
  3652. #endif
  3653. static int parse_dollar(o_string *as_string,
  3654. o_string *dest,
  3655. struct in_str *input, unsigned char quote_mask)
  3656. {
  3657. int ch = i_peek(input); /* first character after the $ */
  3658. debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
  3659. if (isalpha(ch)) {
  3660. ch = i_getch(input);
  3661. nommu_addchr(as_string, ch);
  3662. make_var:
  3663. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  3664. while (1) {
  3665. debug_printf_parse(": '%c'\n", ch);
  3666. o_addchr(dest, ch | quote_mask);
  3667. quote_mask = 0;
  3668. ch = i_peek(input);
  3669. if (!isalnum(ch) && ch != '_')
  3670. break;
  3671. ch = i_getch(input);
  3672. nommu_addchr(as_string, ch);
  3673. }
  3674. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  3675. } else if (isdigit(ch)) {
  3676. make_one_char_var:
  3677. ch = i_getch(input);
  3678. nommu_addchr(as_string, ch);
  3679. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  3680. debug_printf_parse(": '%c'\n", ch);
  3681. o_addchr(dest, ch | quote_mask);
  3682. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  3683. } else switch (ch) {
  3684. case '$': /* pid */
  3685. case '!': /* last bg pid */
  3686. case '?': /* last exit code */
  3687. case '#': /* number of args */
  3688. case '*': /* args */
  3689. case '@': /* args */
  3690. goto make_one_char_var;
  3691. case '{': {
  3692. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  3693. ch = i_getch(input); /* eat '{' */
  3694. nommu_addchr(as_string, ch);
  3695. ch = i_getch(input); /* first char after '{' */
  3696. /* It should be ${?}, or ${#var},
  3697. * or even ${?+subst} - operator acting on a special variable,
  3698. * or the beginning of variable name.
  3699. */
  3700. if (ch == EOF
  3701. || (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) /* not one of those */
  3702. ) {
  3703. bad_dollar_syntax:
  3704. syntax_error_unterm_str("${name}");
  3705. debug_printf_parse("parse_dollar return 0: unterminated ${name}\n");
  3706. return 0;
  3707. }
  3708. nommu_addchr(as_string, ch);
  3709. ch |= quote_mask;
  3710. /* It's possible to just call add_till_closing_bracket() at this point.
  3711. * However, this regresses some of our testsuite cases
  3712. * which check invalid constructs like ${%}.
  3713. * Oh well... let's check that the var name part is fine... */
  3714. while (1) {
  3715. unsigned pos;
  3716. o_addchr(dest, ch);
  3717. debug_printf_parse(": '%c'\n", ch);
  3718. ch = i_getch(input);
  3719. nommu_addchr(as_string, ch);
  3720. if (ch == '}')
  3721. break;
  3722. if (!isalnum(ch) && ch != '_') {
  3723. unsigned end_ch;
  3724. unsigned char last_ch;
  3725. /* handle parameter expansions
  3726. * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
  3727. */
  3728. if (!strchr(VAR_SUBST_OPS, ch)) /* ${var<bad_char>... */
  3729. goto bad_dollar_syntax;
  3730. /* Eat everything until closing '}' (or ':') */
  3731. end_ch = '}';
  3732. if (ENABLE_HUSH_BASH_COMPAT
  3733. && ch == ':'
  3734. && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
  3735. ) {
  3736. /* It's ${var:N[:M]} thing */
  3737. end_ch = '}' * 0x100 + ':';
  3738. }
  3739. if (ENABLE_HUSH_BASH_COMPAT
  3740. && ch == '/'
  3741. ) {
  3742. /* It's ${var/[/]pattern[/repl]} thing */
  3743. if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
  3744. i_getch(input);
  3745. nommu_addchr(as_string, '/');
  3746. ch = '\\';
  3747. }
  3748. end_ch = '}' * 0x100 + '/';
  3749. }
  3750. o_addchr(dest, ch);
  3751. again:
  3752. if (!BB_MMU)
  3753. pos = dest->length;
  3754. #if ENABLE_HUSH_DOLLAR_OPS
  3755. last_ch = add_till_closing_bracket(dest, input, end_ch);
  3756. if (last_ch == 0) /* error? */
  3757. return 0;
  3758. #else
  3759. #error Simple code to only allow ${var} is not implemented
  3760. #endif
  3761. if (as_string) {
  3762. o_addstr(as_string, dest->data + pos);
  3763. o_addchr(as_string, last_ch);
  3764. }
  3765. if (ENABLE_HUSH_BASH_COMPAT && (end_ch & 0xff00)) {
  3766. /* close the first block: */
  3767. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  3768. /* while parsing N from ${var:N[:M]}
  3769. * or pattern from ${var/[/]pattern[/repl]} */
  3770. if ((end_ch & 0xff) == last_ch) {
  3771. /* got ':' or '/'- parse the rest */
  3772. end_ch = '}';
  3773. goto again;
  3774. }
  3775. /* got '}' */
  3776. if (end_ch == '}' * 0x100 + ':') {
  3777. /* it's ${var:N} - emulate :999999999 */
  3778. o_addstr(dest, "999999999");
  3779. } /* else: it's ${var/[/]pattern} */
  3780. }
  3781. break;
  3782. }
  3783. }
  3784. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  3785. break;
  3786. }
  3787. #if ENABLE_SH_MATH_SUPPORT || ENABLE_HUSH_TICK
  3788. case '(': {
  3789. unsigned pos;
  3790. ch = i_getch(input);
  3791. nommu_addchr(as_string, ch);
  3792. # if ENABLE_SH_MATH_SUPPORT
  3793. if (i_peek(input) == '(') {
  3794. ch = i_getch(input);
  3795. nommu_addchr(as_string, ch);
  3796. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  3797. o_addchr(dest, /*quote_mask |*/ '+');
  3798. if (!BB_MMU)
  3799. pos = dest->length;
  3800. if (!add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG))
  3801. return 0; /* error */
  3802. if (as_string) {
  3803. o_addstr(as_string, dest->data + pos);
  3804. o_addchr(as_string, ')');
  3805. o_addchr(as_string, ')');
  3806. }
  3807. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  3808. break;
  3809. }
  3810. # endif
  3811. # if ENABLE_HUSH_TICK
  3812. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  3813. o_addchr(dest, quote_mask | '`');
  3814. if (!BB_MMU)
  3815. pos = dest->length;
  3816. if (!add_till_closing_bracket(dest, input, ')'))
  3817. return 0; /* error */
  3818. if (as_string) {
  3819. o_addstr(as_string, dest->data + pos);
  3820. o_addchr(as_string, ')');
  3821. }
  3822. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  3823. # endif
  3824. break;
  3825. }
  3826. #endif
  3827. case '_':
  3828. ch = i_getch(input);
  3829. nommu_addchr(as_string, ch);
  3830. ch = i_peek(input);
  3831. if (isalnum(ch)) { /* it's $_name or $_123 */
  3832. ch = '_';
  3833. goto make_var;
  3834. }
  3835. /* else: it's $_ */
  3836. /* TODO: $_ and $-: */
  3837. /* $_ Shell or shell script name; or last argument of last command
  3838. * (if last command wasn't a pipe; if it was, bash sets $_ to "");
  3839. * but in command's env, set to full pathname used to invoke it */
  3840. /* $- Option flags set by set builtin or shell options (-i etc) */
  3841. default:
  3842. o_addQchr(dest, '$');
  3843. }
  3844. debug_printf_parse("parse_dollar return 1 (ok)\n");
  3845. return 1;
  3846. #undef as_string
  3847. }
  3848. #if BB_MMU
  3849. # if ENABLE_HUSH_BASH_COMPAT
  3850. #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
  3851. encode_string(dest, input, dquote_end, process_bkslash)
  3852. # else
  3853. /* only ${var/pattern/repl} (its pattern part) needs additional mode */
  3854. #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
  3855. encode_string(dest, input, dquote_end)
  3856. # endif
  3857. #define as_string NULL
  3858. #else /* !MMU */
  3859. # if ENABLE_HUSH_BASH_COMPAT
  3860. /* all parameters are needed, no macro tricks */
  3861. # else
  3862. #define encode_string(as_string, dest, input, dquote_end, process_bkslash) \
  3863. encode_string(as_string, dest, input, dquote_end)
  3864. # endif
  3865. #endif
  3866. static int encode_string(o_string *as_string,
  3867. o_string *dest,
  3868. struct in_str *input,
  3869. int dquote_end,
  3870. int process_bkslash)
  3871. {
  3872. #if !ENABLE_HUSH_BASH_COMPAT
  3873. const int process_bkslash = 1;
  3874. #endif
  3875. int ch;
  3876. int next;
  3877. again:
  3878. ch = i_getch(input);
  3879. if (ch != EOF)
  3880. nommu_addchr(as_string, ch);
  3881. if (ch == dquote_end) { /* may be only '"' or EOF */
  3882. debug_printf_parse("encode_string return 1 (ok)\n");
  3883. return 1;
  3884. }
  3885. /* note: can't move it above ch == dquote_end check! */
  3886. if (ch == EOF) {
  3887. syntax_error_unterm_ch('"');
  3888. return 0; /* error */
  3889. }
  3890. next = '\0';
  3891. if (ch != '\n') {
  3892. next = i_peek(input);
  3893. }
  3894. debug_printf_parse("\" ch=%c (%d) escape=%d\n",
  3895. ch, ch, !!(dest->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
  3896. if (process_bkslash && ch == '\\') {
  3897. if (next == EOF) {
  3898. syntax_error("\\<eof>");
  3899. xfunc_die();
  3900. }
  3901. /* bash:
  3902. * "The backslash retains its special meaning [in "..."]
  3903. * only when followed by one of the following characters:
  3904. * $, `, ", \, or <newline>. A double quote may be quoted
  3905. * within double quotes by preceding it with a backslash."
  3906. * NB: in (unquoted) heredoc, above does not apply to ",
  3907. * therefore we check for it by "next == dquote_end" cond.
  3908. */
  3909. if (next == dquote_end || strchr("$`\\\n", next)) {
  3910. ch = i_getch(input); /* eat next */
  3911. if (ch == '\n')
  3912. goto again; /* skip \<newline> */
  3913. } /* else: ch remains == '\\', and we double it below: */
  3914. o_addqchr(dest, ch); /* \c if c is a glob char, else just c */
  3915. nommu_addchr(as_string, ch);
  3916. goto again;
  3917. }
  3918. if (ch == '$') {
  3919. if (!parse_dollar(as_string, dest, input, /*quote_mask:*/ 0x80)) {
  3920. debug_printf_parse("encode_string return 0: "
  3921. "parse_dollar returned 0 (error)\n");
  3922. return 0;
  3923. }
  3924. goto again;
  3925. }
  3926. #if ENABLE_HUSH_TICK
  3927. if (ch == '`') {
  3928. //unsigned pos = dest->length;
  3929. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  3930. o_addchr(dest, 0x80 | '`');
  3931. if (!add_till_backquote(dest, input, /*in_dquote:*/ dquote_end == '"'))
  3932. return 0; /* error */
  3933. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  3934. //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
  3935. goto again;
  3936. }
  3937. #endif
  3938. o_addQchr(dest, ch);
  3939. goto again;
  3940. #undef as_string
  3941. }
  3942. /*
  3943. * Scan input until EOF or end_trigger char.
  3944. * Return a list of pipes to execute, or NULL on EOF
  3945. * or if end_trigger character is met.
  3946. * On syntax error, exit if shell is not interactive,
  3947. * reset parsing machinery and start parsing anew,
  3948. * or return ERR_PTR.
  3949. */
  3950. static struct pipe *parse_stream(char **pstring,
  3951. struct in_str *input,
  3952. int end_trigger)
  3953. {
  3954. struct parse_context ctx;
  3955. o_string dest = NULL_O_STRING;
  3956. int heredoc_cnt;
  3957. /* Single-quote triggers a bypass of the main loop until its mate is
  3958. * found. When recursing, quote state is passed in via dest->o_expflags.
  3959. */
  3960. debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
  3961. end_trigger ? end_trigger : 'X');
  3962. debug_enter();
  3963. /* If very first arg is "" or '', dest.data may end up NULL.
  3964. * Preventing this: */
  3965. o_addchr(&dest, '\0');
  3966. dest.length = 0;
  3967. /* We used to separate words on $IFS here. This was wrong.
  3968. * $IFS is used only for word splitting when $var is expanded,
  3969. * here we should use blank chars as separators, not $IFS
  3970. */
  3971. if (MAYBE_ASSIGNMENT != 0)
  3972. dest.o_assignment = MAYBE_ASSIGNMENT;
  3973. initialize_context(&ctx);
  3974. heredoc_cnt = 0;
  3975. while (1) {
  3976. const char *is_blank;
  3977. const char *is_special;
  3978. int ch;
  3979. int next;
  3980. int redir_fd;
  3981. redir_type redir_style;
  3982. ch = i_getch(input);
  3983. debug_printf_parse(": ch=%c (%d) escape=%d\n",
  3984. ch, ch, !!(dest.o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
  3985. if (ch == EOF) {
  3986. struct pipe *pi;
  3987. if (heredoc_cnt) {
  3988. syntax_error_unterm_str("here document");
  3989. goto parse_error;
  3990. }
  3991. /* end_trigger == '}' case errors out earlier,
  3992. * checking only ')' */
  3993. if (end_trigger == ')') {
  3994. syntax_error_unterm_ch('(');
  3995. goto parse_error;
  3996. }
  3997. if (done_word(&dest, &ctx)) {
  3998. goto parse_error;
  3999. }
  4000. o_free(&dest);
  4001. done_pipe(&ctx, PIPE_SEQ);
  4002. pi = ctx.list_head;
  4003. /* If we got nothing... */
  4004. /* (this makes bare "&" cmd a no-op.
  4005. * bash says: "syntax error near unexpected token '&'") */
  4006. if (pi->num_cmds == 0
  4007. IF_HAS_KEYWORDS(&& pi->res_word == RES_NONE)
  4008. ) {
  4009. free_pipe_list(pi);
  4010. pi = NULL;
  4011. }
  4012. #if !BB_MMU
  4013. debug_printf_parse("as_string1 '%s'\n", ctx.as_string.data);
  4014. if (pstring)
  4015. *pstring = ctx.as_string.data;
  4016. else
  4017. o_free_unsafe(&ctx.as_string);
  4018. #endif
  4019. debug_leave();
  4020. debug_printf_parse("parse_stream return %p\n", pi);
  4021. return pi;
  4022. }
  4023. nommu_addchr(&ctx.as_string, ch);
  4024. next = '\0';
  4025. if (ch != '\n')
  4026. next = i_peek(input);
  4027. is_special = "{}<>;&|()#'" /* special outside of "str" */
  4028. "\\$\"" IF_HUSH_TICK("`"); /* always special */
  4029. /* Are { and } special here? */
  4030. if (ctx.command->argv /* word [word]{... - non-special */
  4031. || dest.length /* word{... - non-special */
  4032. || dest.has_quoted_part /* ""{... - non-special */
  4033. || (next != ';' /* }; - special */
  4034. && next != ')' /* }) - special */
  4035. && next != '&' /* }& and }&& ... - special */
  4036. && next != '|' /* }|| ... - special */
  4037. && !strchr(defifs, next) /* {word - non-special */
  4038. )
  4039. ) {
  4040. /* They are not special, skip "{}" */
  4041. is_special += 2;
  4042. }
  4043. is_special = strchr(is_special, ch);
  4044. is_blank = strchr(defifs, ch);
  4045. if (!is_special && !is_blank) { /* ordinary char */
  4046. ordinary_char:
  4047. o_addQchr(&dest, ch);
  4048. if ((dest.o_assignment == MAYBE_ASSIGNMENT
  4049. || dest.o_assignment == WORD_IS_KEYWORD)
  4050. && ch == '='
  4051. && is_well_formed_var_name(dest.data, '=')
  4052. ) {
  4053. dest.o_assignment = DEFINITELY_ASSIGNMENT;
  4054. debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
  4055. }
  4056. continue;
  4057. }
  4058. if (is_blank) {
  4059. if (done_word(&dest, &ctx)) {
  4060. goto parse_error;
  4061. }
  4062. if (ch == '\n') {
  4063. /* Is this a case when newline is simply ignored?
  4064. * Some examples:
  4065. * "cmd | <newline> cmd ..."
  4066. * "case ... in <newline> word) ..."
  4067. */
  4068. if (IS_NULL_CMD(ctx.command)
  4069. && dest.length == 0 && !dest.has_quoted_part
  4070. ) {
  4071. /* This newline can be ignored. But...
  4072. * Without check #1, interactive shell
  4073. * ignores even bare <newline>,
  4074. * and shows the continuation prompt:
  4075. * ps1_prompt$ <enter>
  4076. * ps2> _ <=== wrong, should be ps1
  4077. * Without check #2, "cmd & <newline>"
  4078. * is similarly mistreated.
  4079. * (BTW, this makes "cmd & cmd"
  4080. * and "cmd && cmd" non-orthogonal.
  4081. * Really, ask yourself, why
  4082. * "cmd && <newline>" doesn't start
  4083. * cmd but waits for more input?
  4084. * No reason...)
  4085. */
  4086. struct pipe *pi = ctx.list_head;
  4087. if (pi->num_cmds != 0 /* check #1 */
  4088. && pi->followup != PIPE_BG /* check #2 */
  4089. ) {
  4090. continue;
  4091. }
  4092. }
  4093. /* Treat newline as a command separator. */
  4094. done_pipe(&ctx, PIPE_SEQ);
  4095. debug_printf_parse("heredoc_cnt:%d\n", heredoc_cnt);
  4096. if (heredoc_cnt) {
  4097. if (fetch_heredocs(heredoc_cnt, &ctx, input)) {
  4098. goto parse_error;
  4099. }
  4100. heredoc_cnt = 0;
  4101. }
  4102. dest.o_assignment = MAYBE_ASSIGNMENT;
  4103. debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
  4104. ch = ';';
  4105. /* note: if (is_blank) continue;
  4106. * will still trigger for us */
  4107. }
  4108. }
  4109. /* "cmd}" or "cmd }..." without semicolon or &:
  4110. * } is an ordinary char in this case, even inside { cmd; }
  4111. * Pathological example: { ""}; } should exec "}" cmd
  4112. */
  4113. if (ch == '}') {
  4114. if (!IS_NULL_CMD(ctx.command) /* cmd } */
  4115. || dest.length != 0 /* word} */
  4116. || dest.has_quoted_part /* ""} */
  4117. ) {
  4118. goto ordinary_char;
  4119. }
  4120. if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
  4121. goto skip_end_trigger;
  4122. /* else: } does terminate a group */
  4123. }
  4124. if (end_trigger && end_trigger == ch
  4125. && (ch != ';' || heredoc_cnt == 0)
  4126. #if ENABLE_HUSH_CASE
  4127. && (ch != ')'
  4128. || ctx.ctx_res_w != RES_MATCH
  4129. || (!dest.has_quoted_part && strcmp(dest.data, "esac") == 0)
  4130. )
  4131. #endif
  4132. ) {
  4133. if (heredoc_cnt) {
  4134. /* This is technically valid:
  4135. * { cat <<HERE; }; echo Ok
  4136. * heredoc
  4137. * heredoc
  4138. * HERE
  4139. * but we don't support this.
  4140. * We require heredoc to be in enclosing {}/(),
  4141. * if any.
  4142. */
  4143. syntax_error_unterm_str("here document");
  4144. goto parse_error;
  4145. }
  4146. if (done_word(&dest, &ctx)) {
  4147. goto parse_error;
  4148. }
  4149. done_pipe(&ctx, PIPE_SEQ);
  4150. dest.o_assignment = MAYBE_ASSIGNMENT;
  4151. debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
  4152. /* Do we sit outside of any if's, loops or case's? */
  4153. if (!HAS_KEYWORDS
  4154. IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
  4155. ) {
  4156. o_free(&dest);
  4157. #if !BB_MMU
  4158. debug_printf_parse("as_string2 '%s'\n", ctx.as_string.data);
  4159. if (pstring)
  4160. *pstring = ctx.as_string.data;
  4161. else
  4162. o_free_unsafe(&ctx.as_string);
  4163. #endif
  4164. debug_leave();
  4165. debug_printf_parse("parse_stream return %p: "
  4166. "end_trigger char found\n",
  4167. ctx.list_head);
  4168. return ctx.list_head;
  4169. }
  4170. }
  4171. skip_end_trigger:
  4172. if (is_blank)
  4173. continue;
  4174. /* Catch <, > before deciding whether this word is
  4175. * an assignment. a=1 2>z b=2: b=2 is still assignment */
  4176. switch (ch) {
  4177. case '>':
  4178. redir_fd = redirect_opt_num(&dest);
  4179. if (done_word(&dest, &ctx)) {
  4180. goto parse_error;
  4181. }
  4182. redir_style = REDIRECT_OVERWRITE;
  4183. if (next == '>') {
  4184. redir_style = REDIRECT_APPEND;
  4185. ch = i_getch(input);
  4186. nommu_addchr(&ctx.as_string, ch);
  4187. }
  4188. #if 0
  4189. else if (next == '(') {
  4190. syntax_error(">(process) not supported");
  4191. goto parse_error;
  4192. }
  4193. #endif
  4194. if (parse_redirect(&ctx, redir_fd, redir_style, input))
  4195. goto parse_error;
  4196. continue; /* back to top of while (1) */
  4197. case '<':
  4198. redir_fd = redirect_opt_num(&dest);
  4199. if (done_word(&dest, &ctx)) {
  4200. goto parse_error;
  4201. }
  4202. redir_style = REDIRECT_INPUT;
  4203. if (next == '<') {
  4204. redir_style = REDIRECT_HEREDOC;
  4205. heredoc_cnt++;
  4206. debug_printf_parse("++heredoc_cnt=%d\n", heredoc_cnt);
  4207. ch = i_getch(input);
  4208. nommu_addchr(&ctx.as_string, ch);
  4209. } else if (next == '>') {
  4210. redir_style = REDIRECT_IO;
  4211. ch = i_getch(input);
  4212. nommu_addchr(&ctx.as_string, ch);
  4213. }
  4214. #if 0
  4215. else if (next == '(') {
  4216. syntax_error("<(process) not supported");
  4217. goto parse_error;
  4218. }
  4219. #endif
  4220. if (parse_redirect(&ctx, redir_fd, redir_style, input))
  4221. goto parse_error;
  4222. continue; /* back to top of while (1) */
  4223. case '#':
  4224. if (dest.length == 0 && !dest.has_quoted_part) {
  4225. /* skip "#comment" */
  4226. while (1) {
  4227. ch = i_peek(input);
  4228. if (ch == EOF || ch == '\n')
  4229. break;
  4230. i_getch(input);
  4231. /* note: we do not add it to &ctx.as_string */
  4232. }
  4233. nommu_addchr(&ctx.as_string, '\n');
  4234. continue; /* back to top of while (1) */
  4235. }
  4236. break;
  4237. case '\\':
  4238. if (next == '\n') {
  4239. /* It's "\<newline>" */
  4240. #if !BB_MMU
  4241. /* Remove trailing '\' from ctx.as_string */
  4242. ctx.as_string.data[--ctx.as_string.length] = '\0';
  4243. #endif
  4244. ch = i_getch(input); /* eat it */
  4245. continue; /* back to top of while (1) */
  4246. }
  4247. break;
  4248. }
  4249. if (dest.o_assignment == MAYBE_ASSIGNMENT
  4250. /* check that we are not in word in "a=1 2>word b=1": */
  4251. && !ctx.pending_redirect
  4252. ) {
  4253. /* ch is a special char and thus this word
  4254. * cannot be an assignment */
  4255. dest.o_assignment = NOT_ASSIGNMENT;
  4256. debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
  4257. }
  4258. /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
  4259. switch (ch) {
  4260. case '#': /* non-comment #: "echo a#b" etc */
  4261. o_addQchr(&dest, ch);
  4262. break;
  4263. case '\\':
  4264. if (next == EOF) {
  4265. syntax_error("\\<eof>");
  4266. xfunc_die();
  4267. }
  4268. ch = i_getch(input);
  4269. /* note: ch != '\n' (that case does not reach this place) */
  4270. o_addchr(&dest, '\\');
  4271. /*nommu_addchr(&ctx.as_string, '\\'); - already done */
  4272. o_addchr(&dest, ch);
  4273. nommu_addchr(&ctx.as_string, ch);
  4274. /* Example: echo Hello \2>file
  4275. * we need to know that word 2 is quoted */
  4276. dest.has_quoted_part = 1;
  4277. break;
  4278. case '$':
  4279. if (!parse_dollar(&ctx.as_string, &dest, input, /*quote_mask:*/ 0)) {
  4280. debug_printf_parse("parse_stream parse error: "
  4281. "parse_dollar returned 0 (error)\n");
  4282. goto parse_error;
  4283. }
  4284. break;
  4285. case '\'':
  4286. dest.has_quoted_part = 1;
  4287. if (next == '\'' && !ctx.pending_redirect) {
  4288. insert_empty_quoted_str_marker:
  4289. nommu_addchr(&ctx.as_string, next);
  4290. i_getch(input); /* eat second ' */
  4291. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  4292. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  4293. } else {
  4294. while (1) {
  4295. ch = i_getch(input);
  4296. if (ch == EOF) {
  4297. syntax_error_unterm_ch('\'');
  4298. goto parse_error;
  4299. }
  4300. nommu_addchr(&ctx.as_string, ch);
  4301. if (ch == '\'')
  4302. break;
  4303. o_addqchr(&dest, ch);
  4304. }
  4305. }
  4306. break;
  4307. case '"':
  4308. dest.has_quoted_part = 1;
  4309. if (next == '"' && !ctx.pending_redirect)
  4310. goto insert_empty_quoted_str_marker;
  4311. if (dest.o_assignment == NOT_ASSIGNMENT)
  4312. dest.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
  4313. if (!encode_string(&ctx.as_string, &dest, input, '"', /*process_bkslash:*/ 1))
  4314. goto parse_error;
  4315. dest.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
  4316. break;
  4317. #if ENABLE_HUSH_TICK
  4318. case '`': {
  4319. USE_FOR_NOMMU(unsigned pos;)
  4320. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  4321. o_addchr(&dest, '`');
  4322. USE_FOR_NOMMU(pos = dest.length;)
  4323. if (!add_till_backquote(&dest, input, /*in_dquote:*/ 0))
  4324. goto parse_error;
  4325. # if !BB_MMU
  4326. o_addstr(&ctx.as_string, dest.data + pos);
  4327. o_addchr(&ctx.as_string, '`');
  4328. # endif
  4329. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  4330. //debug_printf_subst("SUBST RES3 '%s'\n", dest.data + pos);
  4331. break;
  4332. }
  4333. #endif
  4334. case ';':
  4335. #if ENABLE_HUSH_CASE
  4336. case_semi:
  4337. #endif
  4338. if (done_word(&dest, &ctx)) {
  4339. goto parse_error;
  4340. }
  4341. done_pipe(&ctx, PIPE_SEQ);
  4342. #if ENABLE_HUSH_CASE
  4343. /* Eat multiple semicolons, detect
  4344. * whether it means something special */
  4345. while (1) {
  4346. ch = i_peek(input);
  4347. if (ch != ';')
  4348. break;
  4349. ch = i_getch(input);
  4350. nommu_addchr(&ctx.as_string, ch);
  4351. if (ctx.ctx_res_w == RES_CASE_BODY) {
  4352. ctx.ctx_dsemicolon = 1;
  4353. ctx.ctx_res_w = RES_MATCH;
  4354. break;
  4355. }
  4356. }
  4357. #endif
  4358. new_cmd:
  4359. /* We just finished a cmd. New one may start
  4360. * with an assignment */
  4361. dest.o_assignment = MAYBE_ASSIGNMENT;
  4362. debug_printf_parse("dest.o_assignment='%s'\n", assignment_flag[dest.o_assignment]);
  4363. break;
  4364. case '&':
  4365. if (done_word(&dest, &ctx)) {
  4366. goto parse_error;
  4367. }
  4368. if (next == '&') {
  4369. ch = i_getch(input);
  4370. nommu_addchr(&ctx.as_string, ch);
  4371. done_pipe(&ctx, PIPE_AND);
  4372. } else {
  4373. done_pipe(&ctx, PIPE_BG);
  4374. }
  4375. goto new_cmd;
  4376. case '|':
  4377. if (done_word(&dest, &ctx)) {
  4378. goto parse_error;
  4379. }
  4380. #if ENABLE_HUSH_CASE
  4381. if (ctx.ctx_res_w == RES_MATCH)
  4382. break; /* we are in case's "word | word)" */
  4383. #endif
  4384. if (next == '|') { /* || */
  4385. ch = i_getch(input);
  4386. nommu_addchr(&ctx.as_string, ch);
  4387. done_pipe(&ctx, PIPE_OR);
  4388. } else {
  4389. /* we could pick up a file descriptor choice here
  4390. * with redirect_opt_num(), but bash doesn't do it.
  4391. * "echo foo 2| cat" yields "foo 2". */
  4392. done_command(&ctx);
  4393. }
  4394. goto new_cmd;
  4395. case '(':
  4396. #if ENABLE_HUSH_CASE
  4397. /* "case... in [(]word)..." - skip '(' */
  4398. if (ctx.ctx_res_w == RES_MATCH
  4399. && ctx.command->argv == NULL /* not (word|(... */
  4400. && dest.length == 0 /* not word(... */
  4401. && dest.has_quoted_part == 0 /* not ""(... */
  4402. ) {
  4403. continue;
  4404. }
  4405. #endif
  4406. case '{':
  4407. if (parse_group(&dest, &ctx, input, ch) != 0) {
  4408. goto parse_error;
  4409. }
  4410. goto new_cmd;
  4411. case ')':
  4412. #if ENABLE_HUSH_CASE
  4413. if (ctx.ctx_res_w == RES_MATCH)
  4414. goto case_semi;
  4415. #endif
  4416. case '}':
  4417. /* proper use of this character is caught by end_trigger:
  4418. * if we see {, we call parse_group(..., end_trigger='}')
  4419. * and it will match } earlier (not here). */
  4420. syntax_error_unexpected_ch(ch);
  4421. goto parse_error;
  4422. default:
  4423. if (HUSH_DEBUG)
  4424. bb_error_msg_and_die("BUG: unexpected %c\n", ch);
  4425. }
  4426. } /* while (1) */
  4427. parse_error:
  4428. {
  4429. struct parse_context *pctx;
  4430. IF_HAS_KEYWORDS(struct parse_context *p2;)
  4431. /* Clean up allocated tree.
  4432. * Sample for finding leaks on syntax error recovery path.
  4433. * Run it from interactive shell, watch pmap `pidof hush`.
  4434. * while if false; then false; fi; do break; fi
  4435. * Samples to catch leaks at execution:
  4436. * while if (true | {true;}); then echo ok; fi; do break; done
  4437. * while if (true | {true;}); then echo ok; fi; do (if echo ok; break; then :; fi) | cat; break; done
  4438. */
  4439. pctx = &ctx;
  4440. do {
  4441. /* Update pipe/command counts,
  4442. * otherwise freeing may miss some */
  4443. done_pipe(pctx, PIPE_SEQ);
  4444. debug_printf_clean("freeing list %p from ctx %p\n",
  4445. pctx->list_head, pctx);
  4446. debug_print_tree(pctx->list_head, 0);
  4447. free_pipe_list(pctx->list_head);
  4448. debug_printf_clean("freed list %p\n", pctx->list_head);
  4449. #if !BB_MMU
  4450. o_free_unsafe(&pctx->as_string);
  4451. #endif
  4452. IF_HAS_KEYWORDS(p2 = pctx->stack;)
  4453. if (pctx != &ctx) {
  4454. free(pctx);
  4455. }
  4456. IF_HAS_KEYWORDS(pctx = p2;)
  4457. } while (HAS_KEYWORDS && pctx);
  4458. o_free(&dest);
  4459. G.last_exitcode = 1;
  4460. #if !BB_MMU
  4461. if (pstring)
  4462. *pstring = NULL;
  4463. #endif
  4464. debug_leave();
  4465. return ERR_PTR;
  4466. }
  4467. }
  4468. /*** Execution routines ***/
  4469. /* Expansion can recurse, need forward decls: */
  4470. #if !ENABLE_HUSH_BASH_COMPAT
  4471. /* only ${var/pattern/repl} (its pattern part) needs additional mode */
  4472. #define expand_string_to_string(str, do_unbackslash) \
  4473. expand_string_to_string(str)
  4474. #endif
  4475. static char *expand_string_to_string(const char *str, int do_unbackslash);
  4476. #if ENABLE_HUSH_TICK
  4477. static int process_command_subs(o_string *dest, const char *s);
  4478. #endif
  4479. /* expand_strvec_to_strvec() takes a list of strings, expands
  4480. * all variable references within and returns a pointer to
  4481. * a list of expanded strings, possibly with larger number
  4482. * of strings. (Think VAR="a b"; echo $VAR).
  4483. * This new list is allocated as a single malloc block.
  4484. * NULL-terminated list of char* pointers is at the beginning of it,
  4485. * followed by strings themselves.
  4486. * Caller can deallocate entire list by single free(list). */
  4487. /* A horde of its helpers come first: */
  4488. static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
  4489. {
  4490. while (--len >= 0) {
  4491. char c = *str++;
  4492. #if ENABLE_HUSH_BRACE_EXPANSION
  4493. if (c == '{' || c == '}') {
  4494. /* { -> \{, } -> \} */
  4495. o_addchr(o, '\\');
  4496. /* And now we want to add { or } and continue:
  4497. * o_addchr(o, c);
  4498. * continue;
  4499. * luckily, just falling throught achieves this.
  4500. */
  4501. }
  4502. #endif
  4503. o_addchr(o, c);
  4504. if (c == '\\') {
  4505. /* \z -> \\\z; \<eol> -> \\<eol> */
  4506. o_addchr(o, '\\');
  4507. if (len) {
  4508. len--;
  4509. o_addchr(o, '\\');
  4510. o_addchr(o, *str++);
  4511. }
  4512. }
  4513. }
  4514. }
  4515. /* Store given string, finalizing the word and starting new one whenever
  4516. * we encounter IFS char(s). This is used for expanding variable values.
  4517. * End-of-string does NOT finalize word: think about 'echo -$VAR-'.
  4518. * Return in *ended_with_ifs:
  4519. * 1 - ended with IFS char, else 0 (this includes case of empty str).
  4520. */
  4521. static int expand_on_ifs(int *ended_with_ifs, o_string *output, int n, const char *str)
  4522. {
  4523. int last_is_ifs = 0;
  4524. while (1) {
  4525. int word_len;
  4526. if (!*str) /* EOL - do not finalize word */
  4527. break;
  4528. word_len = strcspn(str, G.ifs);
  4529. if (word_len) {
  4530. /* We have WORD_LEN leading non-IFS chars */
  4531. if (!(output->o_expflags & EXP_FLAG_GLOB)) {
  4532. o_addblock(output, str, word_len);
  4533. } else {
  4534. /* Protect backslashes against globbing up :)
  4535. * Example: "v='\*'; echo b$v" prints "b\*"
  4536. * (and does not try to glob on "*")
  4537. */
  4538. o_addblock_duplicate_backslash(output, str, word_len);
  4539. /*/ Why can't we do it easier? */
  4540. /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
  4541. /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
  4542. }
  4543. last_is_ifs = 0;
  4544. str += word_len;
  4545. if (!*str) /* EOL - do not finalize word */
  4546. break;
  4547. }
  4548. /* We know str here points to at least one IFS char */
  4549. last_is_ifs = 1;
  4550. str += strspn(str, G.ifs); /* skip IFS chars */
  4551. if (!*str) /* EOL - do not finalize word */
  4552. break;
  4553. /* Start new word... but not always! */
  4554. /* Case "v=' a'; echo ''$v": we do need to finalize empty word: */
  4555. if (output->has_quoted_part
  4556. /* Case "v=' a'; echo $v":
  4557. * here nothing precedes the space in $v expansion,
  4558. * therefore we should not finish the word
  4559. * (IOW: if there *is* word to finalize, only then do it):
  4560. */
  4561. || (n > 0 && output->data[output->length - 1])
  4562. ) {
  4563. o_addchr(output, '\0');
  4564. debug_print_list("expand_on_ifs", output, n);
  4565. n = o_save_ptr(output, n);
  4566. }
  4567. }
  4568. if (ended_with_ifs)
  4569. *ended_with_ifs = last_is_ifs;
  4570. debug_print_list("expand_on_ifs[1]", output, n);
  4571. return n;
  4572. }
  4573. /* Helper to expand $((...)) and heredoc body. These act as if
  4574. * they are in double quotes, with the exception that they are not :).
  4575. * Just the rules are similar: "expand only $var and `cmd`"
  4576. *
  4577. * Returns malloced string.
  4578. * As an optimization, we return NULL if expansion is not needed.
  4579. */
  4580. #if !ENABLE_HUSH_BASH_COMPAT
  4581. /* only ${var/pattern/repl} (its pattern part) needs additional mode */
  4582. #define encode_then_expand_string(str, process_bkslash, do_unbackslash) \
  4583. encode_then_expand_string(str)
  4584. #endif
  4585. static char *encode_then_expand_string(const char *str, int process_bkslash, int do_unbackslash)
  4586. {
  4587. char *exp_str;
  4588. struct in_str input;
  4589. o_string dest = NULL_O_STRING;
  4590. if (!strchr(str, '$')
  4591. && !strchr(str, '\\')
  4592. #if ENABLE_HUSH_TICK
  4593. && !strchr(str, '`')
  4594. #endif
  4595. ) {
  4596. return NULL;
  4597. }
  4598. /* We need to expand. Example:
  4599. * echo $(($a + `echo 1`)) $((1 + $((2)) ))
  4600. */
  4601. setup_string_in_str(&input, str);
  4602. encode_string(NULL, &dest, &input, EOF, process_bkslash);
  4603. //TODO: error check (encode_string returns 0 on error)?
  4604. //bb_error_msg("'%s' -> '%s'", str, dest.data);
  4605. exp_str = expand_string_to_string(dest.data, /*unbackslash:*/ do_unbackslash);
  4606. //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
  4607. o_free_unsafe(&dest);
  4608. return exp_str;
  4609. }
  4610. #if ENABLE_SH_MATH_SUPPORT
  4611. static arith_t expand_and_evaluate_arith(const char *arg, const char **errmsg_p)
  4612. {
  4613. arith_state_t math_state;
  4614. arith_t res;
  4615. char *exp_str;
  4616. math_state.lookupvar = get_local_var_value;
  4617. math_state.setvar = set_local_var_from_halves;
  4618. //math_state.endofname = endofname;
  4619. exp_str = encode_then_expand_string(arg, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
  4620. res = arith(&math_state, exp_str ? exp_str : arg);
  4621. free(exp_str);
  4622. if (errmsg_p)
  4623. *errmsg_p = math_state.errmsg;
  4624. if (math_state.errmsg)
  4625. die_if_script(math_state.errmsg);
  4626. return res;
  4627. }
  4628. #endif
  4629. #if ENABLE_HUSH_BASH_COMPAT
  4630. /* ${var/[/]pattern[/repl]} helpers */
  4631. static char *strstr_pattern(char *val, const char *pattern, int *size)
  4632. {
  4633. while (1) {
  4634. char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
  4635. debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
  4636. if (end) {
  4637. *size = end - val;
  4638. return val;
  4639. }
  4640. if (*val == '\0')
  4641. return NULL;
  4642. /* Optimization: if "*pat" did not match the start of "string",
  4643. * we know that "tring", "ring" etc will not match too:
  4644. */
  4645. if (pattern[0] == '*')
  4646. return NULL;
  4647. val++;
  4648. }
  4649. }
  4650. static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
  4651. {
  4652. char *result = NULL;
  4653. unsigned res_len = 0;
  4654. unsigned repl_len = strlen(repl);
  4655. while (1) {
  4656. int size;
  4657. char *s = strstr_pattern(val, pattern, &size);
  4658. if (!s)
  4659. break;
  4660. result = xrealloc(result, res_len + (s - val) + repl_len + 1);
  4661. memcpy(result + res_len, val, s - val);
  4662. res_len += s - val;
  4663. strcpy(result + res_len, repl);
  4664. res_len += repl_len;
  4665. debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
  4666. val = s + size;
  4667. if (exp_op == '/')
  4668. break;
  4669. }
  4670. if (val[0] && result) {
  4671. result = xrealloc(result, res_len + strlen(val) + 1);
  4672. strcpy(result + res_len, val);
  4673. debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
  4674. }
  4675. debug_printf_varexp("result:'%s'\n", result);
  4676. return result;
  4677. }
  4678. #endif
  4679. /* Helper:
  4680. * Handles <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
  4681. */
  4682. static NOINLINE const char *expand_one_var(char **to_be_freed_pp, char *arg, char **pp)
  4683. {
  4684. const char *val = NULL;
  4685. char *to_be_freed = NULL;
  4686. char *p = *pp;
  4687. char *var;
  4688. char first_char;
  4689. char exp_op;
  4690. char exp_save = exp_save; /* for compiler */
  4691. char *exp_saveptr; /* points to expansion operator */
  4692. char *exp_word = exp_word; /* for compiler */
  4693. char arg0;
  4694. *p = '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
  4695. var = arg;
  4696. exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
  4697. arg0 = arg[0];
  4698. first_char = arg[0] = arg0 & 0x7f;
  4699. exp_op = 0;
  4700. if (first_char == '#' /* ${#... */
  4701. && arg[1] && !exp_saveptr /* not ${#} and not ${#<op_char>...} */
  4702. ) {
  4703. /* It must be length operator: ${#var} */
  4704. var++;
  4705. exp_op = 'L';
  4706. } else {
  4707. /* Maybe handle parameter expansion */
  4708. if (exp_saveptr /* if 2nd char is one of expansion operators */
  4709. && strchr(NUMERIC_SPECVARS_STR, first_char) /* 1st char is special variable */
  4710. ) {
  4711. /* ${?:0}, ${#[:]%0} etc */
  4712. exp_saveptr = var + 1;
  4713. } else {
  4714. /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
  4715. exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
  4716. }
  4717. exp_op = exp_save = *exp_saveptr;
  4718. if (exp_op) {
  4719. exp_word = exp_saveptr + 1;
  4720. if (exp_op == ':') {
  4721. exp_op = *exp_word++;
  4722. //TODO: try ${var:} and ${var:bogus} in non-bash config
  4723. if (ENABLE_HUSH_BASH_COMPAT
  4724. && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
  4725. ) {
  4726. /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
  4727. exp_op = ':';
  4728. exp_word--;
  4729. }
  4730. }
  4731. *exp_saveptr = '\0';
  4732. } /* else: it's not an expansion op, but bare ${var} */
  4733. }
  4734. /* Look up the variable in question */
  4735. if (isdigit(var[0])) {
  4736. /* parse_dollar should have vetted var for us */
  4737. int n = xatoi_positive(var);
  4738. if (n < G.global_argc)
  4739. val = G.global_argv[n];
  4740. /* else val remains NULL: $N with too big N */
  4741. } else {
  4742. switch (var[0]) {
  4743. case '$': /* pid */
  4744. val = utoa(G.root_pid);
  4745. break;
  4746. case '!': /* bg pid */
  4747. val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
  4748. break;
  4749. case '?': /* exitcode */
  4750. val = utoa(G.last_exitcode);
  4751. break;
  4752. case '#': /* argc */
  4753. val = utoa(G.global_argc ? G.global_argc-1 : 0);
  4754. break;
  4755. default:
  4756. val = get_local_var_value(var);
  4757. }
  4758. }
  4759. /* Handle any expansions */
  4760. if (exp_op == 'L') {
  4761. reinit_unicode_for_hush();
  4762. debug_printf_expand("expand: length(%s)=", val);
  4763. val = utoa(val ? unicode_strlen(val) : 0);
  4764. debug_printf_expand("%s\n", val);
  4765. } else if (exp_op) {
  4766. if (exp_op == '%' || exp_op == '#') {
  4767. /* Standard-mandated substring removal ops:
  4768. * ${parameter%word} - remove smallest suffix pattern
  4769. * ${parameter%%word} - remove largest suffix pattern
  4770. * ${parameter#word} - remove smallest prefix pattern
  4771. * ${parameter##word} - remove largest prefix pattern
  4772. *
  4773. * Word is expanded to produce a glob pattern.
  4774. * Then var's value is matched to it and matching part removed.
  4775. */
  4776. if (val && val[0]) {
  4777. char *t;
  4778. char *exp_exp_word;
  4779. char *loc;
  4780. unsigned scan_flags = pick_scan(exp_op, *exp_word);
  4781. if (exp_op == *exp_word) /* ## or %% */
  4782. exp_word++;
  4783. exp_exp_word = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
  4784. if (exp_exp_word)
  4785. exp_word = exp_exp_word;
  4786. /* HACK ALERT. We depend here on the fact that
  4787. * G.global_argv and results of utoa and get_local_var_value
  4788. * are actually in writable memory:
  4789. * scan_and_match momentarily stores NULs there. */
  4790. t = (char*)val;
  4791. loc = scan_and_match(t, exp_word, scan_flags);
  4792. //bb_error_msg("op:%c str:'%s' pat:'%s' res:'%s'",
  4793. // exp_op, t, exp_word, loc);
  4794. free(exp_exp_word);
  4795. if (loc) { /* match was found */
  4796. if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
  4797. val = loc; /* take right part */
  4798. else /* %[%] */
  4799. val = to_be_freed = xstrndup(val, loc - val); /* left */
  4800. }
  4801. }
  4802. }
  4803. #if ENABLE_HUSH_BASH_COMPAT
  4804. else if (exp_op == '/' || exp_op == '\\') {
  4805. /* It's ${var/[/]pattern[/repl]} thing.
  4806. * Note that in encoded form it has TWO parts:
  4807. * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
  4808. * and if // is used, it is encoded as \:
  4809. * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
  4810. */
  4811. /* Empty variable always gives nothing: */
  4812. // "v=''; echo ${v/*/w}" prints "", not "w"
  4813. if (val && val[0]) {
  4814. /* pattern uses non-standard expansion.
  4815. * repl should be unbackslashed and globbed
  4816. * by the usual expansion rules:
  4817. * >az; >bz;
  4818. * v='a bz'; echo "${v/a*z/a*z}" prints "a*z"
  4819. * v='a bz'; echo "${v/a*z/\z}" prints "\z"
  4820. * v='a bz'; echo ${v/a*z/a*z} prints "az"
  4821. * v='a bz'; echo ${v/a*z/\z} prints "z"
  4822. * (note that a*z _pattern_ is never globbed!)
  4823. */
  4824. char *pattern, *repl, *t;
  4825. pattern = encode_then_expand_string(exp_word, /*process_bkslash:*/ 0, /*unbackslash:*/ 0);
  4826. if (!pattern)
  4827. pattern = xstrdup(exp_word);
  4828. debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
  4829. *p++ = SPECIAL_VAR_SYMBOL;
  4830. exp_word = p;
  4831. p = strchr(p, SPECIAL_VAR_SYMBOL);
  4832. *p = '\0';
  4833. repl = encode_then_expand_string(exp_word, /*process_bkslash:*/ arg0 & 0x80, /*unbackslash:*/ 1);
  4834. debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
  4835. /* HACK ALERT. We depend here on the fact that
  4836. * G.global_argv and results of utoa and get_local_var_value
  4837. * are actually in writable memory:
  4838. * replace_pattern momentarily stores NULs there. */
  4839. t = (char*)val;
  4840. to_be_freed = replace_pattern(t,
  4841. pattern,
  4842. (repl ? repl : exp_word),
  4843. exp_op);
  4844. if (to_be_freed) /* at least one replace happened */
  4845. val = to_be_freed;
  4846. free(pattern);
  4847. free(repl);
  4848. }
  4849. }
  4850. #endif
  4851. else if (exp_op == ':') {
  4852. #if ENABLE_HUSH_BASH_COMPAT && ENABLE_SH_MATH_SUPPORT
  4853. /* It's ${var:N[:M]} bashism.
  4854. * Note that in encoded form it has TWO parts:
  4855. * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
  4856. */
  4857. arith_t beg, len;
  4858. const char *errmsg;
  4859. beg = expand_and_evaluate_arith(exp_word, &errmsg);
  4860. if (errmsg)
  4861. goto arith_err;
  4862. debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
  4863. *p++ = SPECIAL_VAR_SYMBOL;
  4864. exp_word = p;
  4865. p = strchr(p, SPECIAL_VAR_SYMBOL);
  4866. *p = '\0';
  4867. len = expand_and_evaluate_arith(exp_word, &errmsg);
  4868. if (errmsg)
  4869. goto arith_err;
  4870. debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
  4871. if (len >= 0) { /* bash compat: len < 0 is illegal */
  4872. if (beg < 0) /* bash compat */
  4873. beg = 0;
  4874. debug_printf_varexp("from val:'%s'\n", val);
  4875. if (len == 0 || !val || beg >= strlen(val)) {
  4876. arith_err:
  4877. val = NULL;
  4878. } else {
  4879. /* Paranoia. What if user entered 9999999999999
  4880. * which fits in arith_t but not int? */
  4881. if (len >= INT_MAX)
  4882. len = INT_MAX;
  4883. val = to_be_freed = xstrndup(val + beg, len);
  4884. }
  4885. debug_printf_varexp("val:'%s'\n", val);
  4886. } else
  4887. #endif
  4888. {
  4889. die_if_script("malformed ${%s:...}", var);
  4890. val = NULL;
  4891. }
  4892. } else { /* one of "-=+?" */
  4893. /* Standard-mandated substitution ops:
  4894. * ${var?word} - indicate error if unset
  4895. * If var is unset, word (or a message indicating it is unset
  4896. * if word is null) is written to standard error
  4897. * and the shell exits with a non-zero exit status.
  4898. * Otherwise, the value of var is substituted.
  4899. * ${var-word} - use default value
  4900. * If var is unset, word is substituted.
  4901. * ${var=word} - assign and use default value
  4902. * If var is unset, word is assigned to var.
  4903. * In all cases, final value of var is substituted.
  4904. * ${var+word} - use alternative value
  4905. * If var is unset, null is substituted.
  4906. * Otherwise, word is substituted.
  4907. *
  4908. * Word is subjected to tilde expansion, parameter expansion,
  4909. * command substitution, and arithmetic expansion.
  4910. * If word is not needed, it is not expanded.
  4911. *
  4912. * Colon forms (${var:-word}, ${var:=word} etc) do the same,
  4913. * but also treat null var as if it is unset.
  4914. */
  4915. int use_word = (!val || ((exp_save == ':') && !val[0]));
  4916. if (exp_op == '+')
  4917. use_word = !use_word;
  4918. debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
  4919. (exp_save == ':') ? "true" : "false", use_word);
  4920. if (use_word) {
  4921. to_be_freed = encode_then_expand_string(exp_word, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
  4922. if (to_be_freed)
  4923. exp_word = to_be_freed;
  4924. if (exp_op == '?') {
  4925. /* mimic bash message */
  4926. die_if_script("%s: %s",
  4927. var,
  4928. exp_word[0] ? exp_word : "parameter null or not set"
  4929. );
  4930. //TODO: how interactive bash aborts expansion mid-command?
  4931. } else {
  4932. val = exp_word;
  4933. }
  4934. if (exp_op == '=') {
  4935. /* ${var=[word]} or ${var:=[word]} */
  4936. if (isdigit(var[0]) || var[0] == '#') {
  4937. /* mimic bash message */
  4938. die_if_script("$%s: cannot assign in this way", var);
  4939. val = NULL;
  4940. } else {
  4941. char *new_var = xasprintf("%s=%s", var, val);
  4942. set_local_var(new_var, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
  4943. }
  4944. }
  4945. }
  4946. } /* one of "-=+?" */
  4947. *exp_saveptr = exp_save;
  4948. } /* if (exp_op) */
  4949. arg[0] = arg0;
  4950. *pp = p;
  4951. *to_be_freed_pp = to_be_freed;
  4952. return val;
  4953. }
  4954. /* Expand all variable references in given string, adding words to list[]
  4955. * at n, n+1,... positions. Return updated n (so that list[n] is next one
  4956. * to be filled). This routine is extremely tricky: has to deal with
  4957. * variables/parameters with whitespace, $* and $@, and constructs like
  4958. * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
  4959. static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
  4960. {
  4961. /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
  4962. * expansion of right-hand side of assignment == 1-element expand.
  4963. */
  4964. char cant_be_null = 0; /* only bit 0x80 matters */
  4965. int ended_in_ifs = 0; /* did last unquoted expansion end with IFS chars? */
  4966. char *p;
  4967. debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
  4968. !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
  4969. debug_print_list("expand_vars_to_list", output, n);
  4970. n = o_save_ptr(output, n);
  4971. debug_print_list("expand_vars_to_list[0]", output, n);
  4972. while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
  4973. char first_ch;
  4974. char *to_be_freed = NULL;
  4975. const char *val = NULL;
  4976. #if ENABLE_HUSH_TICK
  4977. o_string subst_result = NULL_O_STRING;
  4978. #endif
  4979. #if ENABLE_SH_MATH_SUPPORT
  4980. char arith_buf[sizeof(arith_t)*3 + 2];
  4981. #endif
  4982. if (ended_in_ifs) {
  4983. o_addchr(output, '\0');
  4984. n = o_save_ptr(output, n);
  4985. ended_in_ifs = 0;
  4986. }
  4987. o_addblock(output, arg, p - arg);
  4988. debug_print_list("expand_vars_to_list[1]", output, n);
  4989. arg = ++p;
  4990. p = strchr(p, SPECIAL_VAR_SYMBOL);
  4991. /* Fetch special var name (if it is indeed one of them)
  4992. * and quote bit, force the bit on if singleword expansion -
  4993. * important for not getting v=$@ expand to many words. */
  4994. first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
  4995. /* Is this variable quoted and thus expansion can't be null?
  4996. * "$@" is special. Even if quoted, it can still
  4997. * expand to nothing (not even an empty string),
  4998. * thus it is excluded. */
  4999. if ((first_ch & 0x7f) != '@')
  5000. cant_be_null |= first_ch;
  5001. switch (first_ch & 0x7f) {
  5002. /* Highest bit in first_ch indicates that var is double-quoted */
  5003. case '*':
  5004. case '@': {
  5005. int i;
  5006. if (!G.global_argv[1])
  5007. break;
  5008. i = 1;
  5009. cant_be_null |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
  5010. if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
  5011. while (G.global_argv[i]) {
  5012. n = expand_on_ifs(NULL, output, n, G.global_argv[i]);
  5013. debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
  5014. if (G.global_argv[i++][0] && G.global_argv[i]) {
  5015. /* this argv[] is not empty and not last:
  5016. * put terminating NUL, start new word */
  5017. o_addchr(output, '\0');
  5018. debug_print_list("expand_vars_to_list[2]", output, n);
  5019. n = o_save_ptr(output, n);
  5020. debug_print_list("expand_vars_to_list[3]", output, n);
  5021. }
  5022. }
  5023. } else
  5024. /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
  5025. * and in this case should treat it like '$*' - see 'else...' below */
  5026. if (first_ch == ('@'|0x80) /* quoted $@ */
  5027. && !(output->o_expflags & EXP_FLAG_SINGLEWORD) /* not v="$@" case */
  5028. ) {
  5029. while (1) {
  5030. o_addQstr(output, G.global_argv[i]);
  5031. if (++i >= G.global_argc)
  5032. break;
  5033. o_addchr(output, '\0');
  5034. debug_print_list("expand_vars_to_list[4]", output, n);
  5035. n = o_save_ptr(output, n);
  5036. }
  5037. } else { /* quoted $* (or v="$@" case): add as one word */
  5038. while (1) {
  5039. o_addQstr(output, G.global_argv[i]);
  5040. if (!G.global_argv[++i])
  5041. break;
  5042. if (G.ifs[0])
  5043. o_addchr(output, G.ifs[0]);
  5044. }
  5045. output->has_quoted_part = 1;
  5046. }
  5047. break;
  5048. }
  5049. case SPECIAL_VAR_SYMBOL: /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
  5050. /* "Empty variable", used to make "" etc to not disappear */
  5051. output->has_quoted_part = 1;
  5052. arg++;
  5053. cant_be_null = 0x80;
  5054. break;
  5055. #if ENABLE_HUSH_TICK
  5056. case '`': /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
  5057. *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
  5058. arg++;
  5059. /* Can't just stuff it into output o_string,
  5060. * expanded result may need to be globbed
  5061. * and $IFS-splitted */
  5062. debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
  5063. G.last_exitcode = process_command_subs(&subst_result, arg);
  5064. debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
  5065. val = subst_result.data;
  5066. goto store_val;
  5067. #endif
  5068. #if ENABLE_SH_MATH_SUPPORT
  5069. case '+': { /* <SPECIAL_VAR_SYMBOL>+cmd<SPECIAL_VAR_SYMBOL> */
  5070. arith_t res;
  5071. arg++; /* skip '+' */
  5072. *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
  5073. debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
  5074. res = expand_and_evaluate_arith(arg, NULL);
  5075. debug_printf_subst("ARITH RES '"ARITH_FMT"'\n", res);
  5076. sprintf(arith_buf, ARITH_FMT, res);
  5077. val = arith_buf;
  5078. break;
  5079. }
  5080. #endif
  5081. default:
  5082. val = expand_one_var(&to_be_freed, arg, &p);
  5083. IF_HUSH_TICK(store_val:)
  5084. if (!(first_ch & 0x80)) { /* unquoted $VAR */
  5085. debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val,
  5086. !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
  5087. if (val && val[0]) {
  5088. n = expand_on_ifs(&ended_in_ifs, output, n, val);
  5089. val = NULL;
  5090. }
  5091. } else { /* quoted $VAR, val will be appended below */
  5092. output->has_quoted_part = 1;
  5093. debug_printf_expand("quoted '%s', output->o_escape:%d\n", val,
  5094. !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
  5095. }
  5096. break;
  5097. } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
  5098. if (val && val[0]) {
  5099. o_addQstr(output, val);
  5100. }
  5101. free(to_be_freed);
  5102. /* Restore NULL'ed SPECIAL_VAR_SYMBOL.
  5103. * Do the check to avoid writing to a const string. */
  5104. if (*p != SPECIAL_VAR_SYMBOL)
  5105. *p = SPECIAL_VAR_SYMBOL;
  5106. #if ENABLE_HUSH_TICK
  5107. o_free(&subst_result);
  5108. #endif
  5109. arg = ++p;
  5110. } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
  5111. if (arg[0]) {
  5112. if (ended_in_ifs) {
  5113. o_addchr(output, '\0');
  5114. n = o_save_ptr(output, n);
  5115. }
  5116. debug_print_list("expand_vars_to_list[a]", output, n);
  5117. /* this part is literal, and it was already pre-quoted
  5118. * if needed (much earlier), do not use o_addQstr here! */
  5119. o_addstr_with_NUL(output, arg);
  5120. debug_print_list("expand_vars_to_list[b]", output, n);
  5121. } else if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
  5122. && !(cant_be_null & 0x80) /* and all vars were not quoted. */
  5123. ) {
  5124. n--;
  5125. /* allow to reuse list[n] later without re-growth */
  5126. output->has_empty_slot = 1;
  5127. } else {
  5128. o_addchr(output, '\0');
  5129. }
  5130. return n;
  5131. }
  5132. static char **expand_variables(char **argv, unsigned expflags)
  5133. {
  5134. int n;
  5135. char **list;
  5136. o_string output = NULL_O_STRING;
  5137. output.o_expflags = expflags;
  5138. n = 0;
  5139. while (*argv) {
  5140. n = expand_vars_to_list(&output, n, *argv);
  5141. argv++;
  5142. }
  5143. debug_print_list("expand_variables", &output, n);
  5144. /* output.data (malloced in one block) gets returned in "list" */
  5145. list = o_finalize_list(&output, n);
  5146. debug_print_strings("expand_variables[1]", list);
  5147. return list;
  5148. }
  5149. static char **expand_strvec_to_strvec(char **argv)
  5150. {
  5151. return expand_variables(argv, EXP_FLAG_GLOB | EXP_FLAG_ESC_GLOB_CHARS);
  5152. }
  5153. #if ENABLE_HUSH_BASH_COMPAT
  5154. static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
  5155. {
  5156. return expand_variables(argv, EXP_FLAG_SINGLEWORD);
  5157. }
  5158. #endif
  5159. /* Used for expansion of right hand of assignments,
  5160. * $((...)), heredocs, variable espansion parts.
  5161. *
  5162. * NB: should NOT do globbing!
  5163. * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*"
  5164. */
  5165. static char *expand_string_to_string(const char *str, int do_unbackslash)
  5166. {
  5167. #if !ENABLE_HUSH_BASH_COMPAT
  5168. const int do_unbackslash = 1;
  5169. #endif
  5170. char *argv[2], **list;
  5171. debug_printf_expand("string_to_string<='%s'\n", str);
  5172. /* This is generally an optimization, but it also
  5173. * handles "", which otherwise trips over !list[0] check below.
  5174. * (is this ever happens that we actually get str="" here?)
  5175. */
  5176. if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
  5177. //TODO: Can use on strings with \ too, just unbackslash() them?
  5178. debug_printf_expand("string_to_string(fast)=>'%s'\n", str);
  5179. return xstrdup(str);
  5180. }
  5181. argv[0] = (char*)str;
  5182. argv[1] = NULL;
  5183. list = expand_variables(argv, do_unbackslash
  5184. ? EXP_FLAG_ESC_GLOB_CHARS | EXP_FLAG_SINGLEWORD
  5185. : EXP_FLAG_SINGLEWORD
  5186. );
  5187. if (HUSH_DEBUG)
  5188. if (!list[0] || list[1])
  5189. bb_error_msg_and_die("BUG in varexp2");
  5190. /* actually, just move string 2*sizeof(char*) bytes back */
  5191. overlapping_strcpy((char*)list, list[0]);
  5192. if (do_unbackslash)
  5193. unbackslash((char*)list);
  5194. debug_printf_expand("string_to_string=>'%s'\n", (char*)list);
  5195. return (char*)list;
  5196. }
  5197. /* Used for "eval" builtin */
  5198. static char* expand_strvec_to_string(char **argv)
  5199. {
  5200. char **list;
  5201. list = expand_variables(argv, EXP_FLAG_SINGLEWORD);
  5202. /* Convert all NULs to spaces */
  5203. if (list[0]) {
  5204. int n = 1;
  5205. while (list[n]) {
  5206. if (HUSH_DEBUG)
  5207. if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
  5208. bb_error_msg_and_die("BUG in varexp3");
  5209. /* bash uses ' ' regardless of $IFS contents */
  5210. list[n][-1] = ' ';
  5211. n++;
  5212. }
  5213. }
  5214. overlapping_strcpy((char*)list, list[0]);
  5215. debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
  5216. return (char*)list;
  5217. }
  5218. static char **expand_assignments(char **argv, int count)
  5219. {
  5220. int i;
  5221. char **p;
  5222. G.expanded_assignments = p = NULL;
  5223. /* Expand assignments into one string each */
  5224. for (i = 0; i < count; i++) {
  5225. G.expanded_assignments = p = add_string_to_strings(p, expand_string_to_string(argv[i], /*unbackslash:*/ 1));
  5226. }
  5227. G.expanded_assignments = NULL;
  5228. return p;
  5229. }
  5230. static void switch_off_special_sigs(unsigned mask)
  5231. {
  5232. unsigned sig = 0;
  5233. while ((mask >>= 1) != 0) {
  5234. sig++;
  5235. if (!(mask & 1))
  5236. continue;
  5237. if (G.traps) {
  5238. if (G.traps[sig] && !G.traps[sig][0])
  5239. /* trap is '', has to remain SIG_IGN */
  5240. continue;
  5241. free(G.traps[sig]);
  5242. G.traps[sig] = NULL;
  5243. }
  5244. /* We are here only if no trap or trap was not '' */
  5245. install_sighandler(sig, SIG_DFL);
  5246. }
  5247. }
  5248. #if BB_MMU
  5249. /* never called */
  5250. void re_execute_shell(char ***to_free, const char *s,
  5251. char *g_argv0, char **g_argv,
  5252. char **builtin_argv) NORETURN;
  5253. static void reset_traps_to_defaults(void)
  5254. {
  5255. /* This function is always called in a child shell
  5256. * after fork (not vfork, NOMMU doesn't use this function).
  5257. */
  5258. unsigned sig;
  5259. unsigned mask;
  5260. /* Child shells are not interactive.
  5261. * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
  5262. * Testcase: (while :; do :; done) + ^Z should background.
  5263. * Same goes for SIGTERM, SIGHUP, SIGINT.
  5264. */
  5265. mask = (G.special_sig_mask & SPECIAL_INTERACTIVE_SIGS) | G_fatal_sig_mask;
  5266. if (!G.traps && !mask)
  5267. return; /* already no traps and no special sigs */
  5268. /* Switch off special sigs */
  5269. switch_off_special_sigs(mask);
  5270. #if ENABLE_HUSH_JOB
  5271. G_fatal_sig_mask = 0;
  5272. #endif
  5273. G.special_sig_mask &= ~SPECIAL_INTERACTIVE_SIGS;
  5274. /* SIGQUIT,SIGCHLD and maybe SPECIAL_JOBSTOP_SIGS
  5275. * remain set in G.special_sig_mask */
  5276. if (!G.traps)
  5277. return;
  5278. /* Reset all sigs to default except ones with empty traps */
  5279. for (sig = 0; sig < NSIG; sig++) {
  5280. if (!G.traps[sig])
  5281. continue; /* no trap: nothing to do */
  5282. if (!G.traps[sig][0])
  5283. continue; /* empty trap: has to remain SIG_IGN */
  5284. /* sig has non-empty trap, reset it: */
  5285. free(G.traps[sig]);
  5286. G.traps[sig] = NULL;
  5287. /* There is no signal for trap 0 (EXIT) */
  5288. if (sig == 0)
  5289. continue;
  5290. install_sighandler(sig, pick_sighandler(sig));
  5291. }
  5292. }
  5293. #else /* !BB_MMU */
  5294. static void re_execute_shell(char ***to_free, const char *s,
  5295. char *g_argv0, char **g_argv,
  5296. char **builtin_argv) NORETURN;
  5297. static void re_execute_shell(char ***to_free, const char *s,
  5298. char *g_argv0, char **g_argv,
  5299. char **builtin_argv)
  5300. {
  5301. # define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
  5302. /* delims + 2 * (number of bytes in printed hex numbers) */
  5303. char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
  5304. char *heredoc_argv[4];
  5305. struct variable *cur;
  5306. # if ENABLE_HUSH_FUNCTIONS
  5307. struct function *funcp;
  5308. # endif
  5309. char **argv, **pp;
  5310. unsigned cnt;
  5311. unsigned long long empty_trap_mask;
  5312. if (!g_argv0) { /* heredoc */
  5313. argv = heredoc_argv;
  5314. argv[0] = (char *) G.argv0_for_re_execing;
  5315. argv[1] = (char *) "-<";
  5316. argv[2] = (char *) s;
  5317. argv[3] = NULL;
  5318. pp = &argv[3]; /* used as pointer to empty environment */
  5319. goto do_exec;
  5320. }
  5321. cnt = 0;
  5322. pp = builtin_argv;
  5323. if (pp) while (*pp++)
  5324. cnt++;
  5325. empty_trap_mask = 0;
  5326. if (G.traps) {
  5327. int sig;
  5328. for (sig = 1; sig < NSIG; sig++) {
  5329. if (G.traps[sig] && !G.traps[sig][0])
  5330. empty_trap_mask |= 1LL << sig;
  5331. }
  5332. }
  5333. sprintf(param_buf, NOMMU_HACK_FMT
  5334. , (unsigned) G.root_pid
  5335. , (unsigned) G.root_ppid
  5336. , (unsigned) G.last_bg_pid
  5337. , (unsigned) G.last_exitcode
  5338. , cnt
  5339. , empty_trap_mask
  5340. IF_HUSH_LOOPS(, G.depth_of_loop)
  5341. );
  5342. # undef NOMMU_HACK_FMT
  5343. /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
  5344. * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
  5345. */
  5346. cnt += 6;
  5347. for (cur = G.top_var; cur; cur = cur->next) {
  5348. if (!cur->flg_export || cur->flg_read_only)
  5349. cnt += 2;
  5350. }
  5351. # if ENABLE_HUSH_FUNCTIONS
  5352. for (funcp = G.top_func; funcp; funcp = funcp->next)
  5353. cnt += 3;
  5354. # endif
  5355. pp = g_argv;
  5356. while (*pp++)
  5357. cnt++;
  5358. *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
  5359. *pp++ = (char *) G.argv0_for_re_execing;
  5360. *pp++ = param_buf;
  5361. for (cur = G.top_var; cur; cur = cur->next) {
  5362. if (strcmp(cur->varstr, hush_version_str) == 0)
  5363. continue;
  5364. if (cur->flg_read_only) {
  5365. *pp++ = (char *) "-R";
  5366. *pp++ = cur->varstr;
  5367. } else if (!cur->flg_export) {
  5368. *pp++ = (char *) "-V";
  5369. *pp++ = cur->varstr;
  5370. }
  5371. }
  5372. # if ENABLE_HUSH_FUNCTIONS
  5373. for (funcp = G.top_func; funcp; funcp = funcp->next) {
  5374. *pp++ = (char *) "-F";
  5375. *pp++ = funcp->name;
  5376. *pp++ = funcp->body_as_string;
  5377. }
  5378. # endif
  5379. /* We can pass activated traps here. Say, -Tnn:trap_string
  5380. *
  5381. * However, POSIX says that subshells reset signals with traps
  5382. * to SIG_DFL.
  5383. * I tested bash-3.2 and it not only does that with true subshells
  5384. * of the form ( list ), but with any forked children shells.
  5385. * I set trap "echo W" WINCH; and then tried:
  5386. *
  5387. * { echo 1; sleep 20; echo 2; } &
  5388. * while true; do echo 1; sleep 20; echo 2; break; done &
  5389. * true | { echo 1; sleep 20; echo 2; } | cat
  5390. *
  5391. * In all these cases sending SIGWINCH to the child shell
  5392. * did not run the trap. If I add trap "echo V" WINCH;
  5393. * _inside_ group (just before echo 1), it works.
  5394. *
  5395. * I conclude it means we don't need to pass active traps here.
  5396. */
  5397. *pp++ = (char *) "-c";
  5398. *pp++ = (char *) s;
  5399. if (builtin_argv) {
  5400. while (*++builtin_argv)
  5401. *pp++ = *builtin_argv;
  5402. *pp++ = (char *) "";
  5403. }
  5404. *pp++ = g_argv0;
  5405. while (*g_argv)
  5406. *pp++ = *g_argv++;
  5407. /* *pp = NULL; - is already there */
  5408. pp = environ;
  5409. do_exec:
  5410. debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
  5411. /* Don't propagate SIG_IGN to the child */
  5412. if (SPECIAL_JOBSTOP_SIGS != 0)
  5413. switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
  5414. execve(bb_busybox_exec_path, argv, pp);
  5415. /* Fallback. Useful for init=/bin/hush usage etc */
  5416. if (argv[0][0] == '/')
  5417. execve(argv[0], argv, pp);
  5418. xfunc_error_retval = 127;
  5419. bb_error_msg_and_die("can't re-execute the shell");
  5420. }
  5421. #endif /* !BB_MMU */
  5422. static int run_and_free_list(struct pipe *pi);
  5423. /* Executing from string: eval, sh -c '...'
  5424. * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
  5425. * end_trigger controls how often we stop parsing
  5426. * NUL: parse all, execute, return
  5427. * ';': parse till ';' or newline, execute, repeat till EOF
  5428. */
  5429. static void parse_and_run_stream(struct in_str *inp, int end_trigger)
  5430. {
  5431. /* Why we need empty flag?
  5432. * An obscure corner case "false; ``; echo $?":
  5433. * empty command in `` should still set $? to 0.
  5434. * But we can't just set $? to 0 at the start,
  5435. * this breaks "false; echo `echo $?`" case.
  5436. */
  5437. bool empty = 1;
  5438. while (1) {
  5439. struct pipe *pipe_list;
  5440. #if ENABLE_HUSH_INTERACTIVE
  5441. if (end_trigger == ';')
  5442. inp->promptmode = 0; /* PS1 */
  5443. #endif
  5444. pipe_list = parse_stream(NULL, inp, end_trigger);
  5445. if (!pipe_list || pipe_list == ERR_PTR) { /* EOF/error */
  5446. /* If we are in "big" script
  5447. * (not in `cmd` or something similar)...
  5448. */
  5449. if (pipe_list == ERR_PTR && end_trigger == ';') {
  5450. /* Discard cached input (rest of line) */
  5451. int ch = inp->last_char;
  5452. while (ch != EOF && ch != '\n') {
  5453. //bb_error_msg("Discarded:'%c'", ch);
  5454. ch = i_getch(inp);
  5455. }
  5456. /* Force prompt */
  5457. inp->p = NULL;
  5458. /* This stream isn't empty */
  5459. empty = 0;
  5460. continue;
  5461. }
  5462. if (!pipe_list && empty)
  5463. G.last_exitcode = 0;
  5464. break;
  5465. }
  5466. debug_print_tree(pipe_list, 0);
  5467. debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
  5468. run_and_free_list(pipe_list);
  5469. empty = 0;
  5470. #if ENABLE_HUSH_FUNCTIONS
  5471. if (G.flag_return_in_progress == 1)
  5472. break;
  5473. #endif
  5474. }
  5475. }
  5476. static void parse_and_run_string(const char *s)
  5477. {
  5478. struct in_str input;
  5479. setup_string_in_str(&input, s);
  5480. parse_and_run_stream(&input, '\0');
  5481. }
  5482. static void parse_and_run_file(FILE *f)
  5483. {
  5484. struct in_str input;
  5485. setup_file_in_str(&input, f);
  5486. parse_and_run_stream(&input, ';');
  5487. }
  5488. #if ENABLE_HUSH_TICK
  5489. static FILE *generate_stream_from_string(const char *s, pid_t *pid_p)
  5490. {
  5491. pid_t pid;
  5492. int channel[2];
  5493. # if !BB_MMU
  5494. char **to_free = NULL;
  5495. # endif
  5496. xpipe(channel);
  5497. pid = BB_MMU ? xfork() : xvfork();
  5498. if (pid == 0) { /* child */
  5499. disable_restore_tty_pgrp_on_exit();
  5500. /* Process substitution is not considered to be usual
  5501. * 'command execution'.
  5502. * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
  5503. */
  5504. bb_signals(0
  5505. + (1 << SIGTSTP)
  5506. + (1 << SIGTTIN)
  5507. + (1 << SIGTTOU)
  5508. , SIG_IGN);
  5509. CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
  5510. close(channel[0]); /* NB: close _first_, then move fd! */
  5511. xmove_fd(channel[1], 1);
  5512. /* Prevent it from trying to handle ctrl-z etc */
  5513. IF_HUSH_JOB(G.run_list_level = 1;)
  5514. /* Awful hack for `trap` or $(trap).
  5515. *
  5516. * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
  5517. * contains an example where "trap" is executed in a subshell:
  5518. *
  5519. * save_traps=$(trap)
  5520. * ...
  5521. * eval "$save_traps"
  5522. *
  5523. * Standard does not say that "trap" in subshell shall print
  5524. * parent shell's traps. It only says that its output
  5525. * must have suitable form, but then, in the above example
  5526. * (which is not supposed to be normative), it implies that.
  5527. *
  5528. * bash (and probably other shell) does implement it
  5529. * (traps are reset to defaults, but "trap" still shows them),
  5530. * but as a result, "trap" logic is hopelessly messed up:
  5531. *
  5532. * # trap
  5533. * trap -- 'echo Ho' SIGWINCH <--- we have a handler
  5534. * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
  5535. * # true | trap <--- trap is in subshell - no output (ditto)
  5536. * # echo `true | trap` <--- in subshell - output (but traps are reset!)
  5537. * trap -- 'echo Ho' SIGWINCH
  5538. * # echo `(trap)` <--- in subshell in subshell - output
  5539. * trap -- 'echo Ho' SIGWINCH
  5540. * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
  5541. * trap -- 'echo Ho' SIGWINCH
  5542. *
  5543. * The rules when to forget and when to not forget traps
  5544. * get really complex and nonsensical.
  5545. *
  5546. * Our solution: ONLY bare $(trap) or `trap` is special.
  5547. */
  5548. s = skip_whitespace(s);
  5549. if (is_prefixed_with(s, "trap")
  5550. && skip_whitespace(s + 4)[0] == '\0'
  5551. ) {
  5552. static const char *const argv[] = { NULL, NULL };
  5553. builtin_trap((char**)argv);
  5554. fflush_all(); /* important */
  5555. _exit(0);
  5556. }
  5557. # if BB_MMU
  5558. reset_traps_to_defaults();
  5559. parse_and_run_string(s);
  5560. _exit(G.last_exitcode);
  5561. # else
  5562. /* We re-execute after vfork on NOMMU. This makes this script safe:
  5563. * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
  5564. * huge=`cat BIG` # was blocking here forever
  5565. * echo OK
  5566. */
  5567. re_execute_shell(&to_free,
  5568. s,
  5569. G.global_argv[0],
  5570. G.global_argv + 1,
  5571. NULL);
  5572. # endif
  5573. }
  5574. /* parent */
  5575. *pid_p = pid;
  5576. # if ENABLE_HUSH_FAST
  5577. G.count_SIGCHLD++;
  5578. //bb_error_msg("[%d] fork in generate_stream_from_string:"
  5579. // " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
  5580. // getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
  5581. # endif
  5582. enable_restore_tty_pgrp_on_exit();
  5583. # if !BB_MMU
  5584. free(to_free);
  5585. # endif
  5586. close(channel[1]);
  5587. close_on_exec_on(channel[0]);
  5588. return xfdopen_for_read(channel[0]);
  5589. }
  5590. /* Return code is exit status of the process that is run. */
  5591. static int process_command_subs(o_string *dest, const char *s)
  5592. {
  5593. FILE *fp;
  5594. struct in_str pipe_str;
  5595. pid_t pid;
  5596. int status, ch, eol_cnt;
  5597. fp = generate_stream_from_string(s, &pid);
  5598. /* Now send results of command back into original context */
  5599. setup_file_in_str(&pipe_str, fp);
  5600. eol_cnt = 0;
  5601. while ((ch = i_getch(&pipe_str)) != EOF) {
  5602. if (ch == '\n') {
  5603. eol_cnt++;
  5604. continue;
  5605. }
  5606. while (eol_cnt) {
  5607. o_addchr(dest, '\n');
  5608. eol_cnt--;
  5609. }
  5610. o_addQchr(dest, ch);
  5611. }
  5612. debug_printf("done reading from `cmd` pipe, closing it\n");
  5613. fclose(fp);
  5614. /* We need to extract exitcode. Test case
  5615. * "true; echo `sleep 1; false` $?"
  5616. * should print 1 */
  5617. safe_waitpid(pid, &status, 0);
  5618. debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
  5619. return WEXITSTATUS(status);
  5620. }
  5621. #endif /* ENABLE_HUSH_TICK */
  5622. static void setup_heredoc(struct redir_struct *redir)
  5623. {
  5624. struct fd_pair pair;
  5625. pid_t pid;
  5626. int len, written;
  5627. /* the _body_ of heredoc (misleading field name) */
  5628. const char *heredoc = redir->rd_filename;
  5629. char *expanded;
  5630. #if !BB_MMU
  5631. char **to_free;
  5632. #endif
  5633. expanded = NULL;
  5634. if (!(redir->rd_dup & HEREDOC_QUOTED)) {
  5635. expanded = encode_then_expand_string(heredoc, /*process_bkslash:*/ 1, /*unbackslash:*/ 1);
  5636. if (expanded)
  5637. heredoc = expanded;
  5638. }
  5639. len = strlen(heredoc);
  5640. close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
  5641. xpiped_pair(pair);
  5642. xmove_fd(pair.rd, redir->rd_fd);
  5643. /* Try writing without forking. Newer kernels have
  5644. * dynamically growing pipes. Must use non-blocking write! */
  5645. ndelay_on(pair.wr);
  5646. while (1) {
  5647. written = write(pair.wr, heredoc, len);
  5648. if (written <= 0)
  5649. break;
  5650. len -= written;
  5651. if (len == 0) {
  5652. close(pair.wr);
  5653. free(expanded);
  5654. return;
  5655. }
  5656. heredoc += written;
  5657. }
  5658. ndelay_off(pair.wr);
  5659. /* Okay, pipe buffer was not big enough */
  5660. /* Note: we must not create a stray child (bastard? :)
  5661. * for the unsuspecting parent process. Child creates a grandchild
  5662. * and exits before parent execs the process which consumes heredoc
  5663. * (that exec happens after we return from this function) */
  5664. #if !BB_MMU
  5665. to_free = NULL;
  5666. #endif
  5667. pid = xvfork();
  5668. if (pid == 0) {
  5669. /* child */
  5670. disable_restore_tty_pgrp_on_exit();
  5671. pid = BB_MMU ? xfork() : xvfork();
  5672. if (pid != 0)
  5673. _exit(0);
  5674. /* grandchild */
  5675. close(redir->rd_fd); /* read side of the pipe */
  5676. #if BB_MMU
  5677. full_write(pair.wr, heredoc, len); /* may loop or block */
  5678. _exit(0);
  5679. #else
  5680. /* Delegate blocking writes to another process */
  5681. xmove_fd(pair.wr, STDOUT_FILENO);
  5682. re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
  5683. #endif
  5684. }
  5685. /* parent */
  5686. #if ENABLE_HUSH_FAST
  5687. G.count_SIGCHLD++;
  5688. //bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
  5689. #endif
  5690. enable_restore_tty_pgrp_on_exit();
  5691. #if !BB_MMU
  5692. free(to_free);
  5693. #endif
  5694. close(pair.wr);
  5695. free(expanded);
  5696. wait(NULL); /* wait till child has died */
  5697. }
  5698. /* squirrel != NULL means we squirrel away copies of stdin, stdout,
  5699. * and stderr if they are redirected. */
  5700. static int setup_redirects(struct command *prog, int squirrel[])
  5701. {
  5702. int openfd, mode;
  5703. struct redir_struct *redir;
  5704. for (redir = prog->redirects; redir; redir = redir->next) {
  5705. if (redir->rd_type == REDIRECT_HEREDOC2) {
  5706. /* rd_fd<<HERE case */
  5707. if (squirrel && redir->rd_fd < 3
  5708. && squirrel[redir->rd_fd] < 0
  5709. ) {
  5710. squirrel[redir->rd_fd] = dup(redir->rd_fd);
  5711. }
  5712. /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
  5713. * of the heredoc */
  5714. debug_printf_parse("set heredoc '%s'\n",
  5715. redir->rd_filename);
  5716. setup_heredoc(redir);
  5717. continue;
  5718. }
  5719. if (redir->rd_dup == REDIRFD_TO_FILE) {
  5720. /* rd_fd<*>file case (<*> is <,>,>>,<>) */
  5721. char *p;
  5722. if (redir->rd_filename == NULL) {
  5723. /* Something went wrong in the parse.
  5724. * Pretend it didn't happen */
  5725. bb_error_msg("bug in redirect parse");
  5726. continue;
  5727. }
  5728. mode = redir_table[redir->rd_type].mode;
  5729. p = expand_string_to_string(redir->rd_filename, /*unbackslash:*/ 1);
  5730. openfd = open_or_warn(p, mode);
  5731. free(p);
  5732. if (openfd < 0) {
  5733. /* this could get lost if stderr has been redirected, but
  5734. * bash and ash both lose it as well (though zsh doesn't!) */
  5735. //what the above comment tries to say?
  5736. return 1;
  5737. }
  5738. } else {
  5739. /* rd_fd<*>rd_dup or rd_fd<*>- cases */
  5740. openfd = redir->rd_dup;
  5741. }
  5742. if (openfd != redir->rd_fd) {
  5743. if (squirrel && redir->rd_fd < 3
  5744. && squirrel[redir->rd_fd] < 0
  5745. ) {
  5746. squirrel[redir->rd_fd] = dup(redir->rd_fd);
  5747. }
  5748. if (openfd == REDIRFD_CLOSE) {
  5749. /* "n>-" means "close me" */
  5750. close(redir->rd_fd);
  5751. } else {
  5752. xdup2(openfd, redir->rd_fd);
  5753. if (redir->rd_dup == REDIRFD_TO_FILE)
  5754. close(openfd);
  5755. }
  5756. }
  5757. }
  5758. return 0;
  5759. }
  5760. static void restore_redirects(int squirrel[])
  5761. {
  5762. int i, fd;
  5763. for (i = 0; i < 3; i++) {
  5764. fd = squirrel[i];
  5765. if (fd != -1) {
  5766. /* We simply die on error */
  5767. xmove_fd(fd, i);
  5768. }
  5769. }
  5770. }
  5771. static char *find_in_path(const char *arg)
  5772. {
  5773. char *ret = NULL;
  5774. const char *PATH = get_local_var_value("PATH");
  5775. if (!PATH)
  5776. return NULL;
  5777. while (1) {
  5778. const char *end = strchrnul(PATH, ':');
  5779. int sz = end - PATH; /* must be int! */
  5780. free(ret);
  5781. if (sz != 0) {
  5782. ret = xasprintf("%.*s/%s", sz, PATH, arg);
  5783. } else {
  5784. /* We have xxx::yyyy in $PATH,
  5785. * it means "use current dir" */
  5786. ret = xstrdup(arg);
  5787. }
  5788. if (access(ret, F_OK) == 0)
  5789. break;
  5790. if (*end == '\0') {
  5791. free(ret);
  5792. return NULL;
  5793. }
  5794. PATH = end + 1;
  5795. }
  5796. return ret;
  5797. }
  5798. static const struct built_in_command *find_builtin_helper(const char *name,
  5799. const struct built_in_command *x,
  5800. const struct built_in_command *end)
  5801. {
  5802. while (x != end) {
  5803. if (strcmp(name, x->b_cmd) != 0) {
  5804. x++;
  5805. continue;
  5806. }
  5807. debug_printf_exec("found builtin '%s'\n", name);
  5808. return x;
  5809. }
  5810. return NULL;
  5811. }
  5812. static const struct built_in_command *find_builtin1(const char *name)
  5813. {
  5814. return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
  5815. }
  5816. static const struct built_in_command *find_builtin(const char *name)
  5817. {
  5818. const struct built_in_command *x = find_builtin1(name);
  5819. if (x)
  5820. return x;
  5821. return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
  5822. }
  5823. #if ENABLE_HUSH_FUNCTIONS
  5824. static struct function **find_function_slot(const char *name)
  5825. {
  5826. struct function **funcpp = &G.top_func;
  5827. while (*funcpp) {
  5828. if (strcmp(name, (*funcpp)->name) == 0) {
  5829. break;
  5830. }
  5831. funcpp = &(*funcpp)->next;
  5832. }
  5833. return funcpp;
  5834. }
  5835. static const struct function *find_function(const char *name)
  5836. {
  5837. const struct function *funcp = *find_function_slot(name);
  5838. if (funcp)
  5839. debug_printf_exec("found function '%s'\n", name);
  5840. return funcp;
  5841. }
  5842. /* Note: takes ownership on name ptr */
  5843. static struct function *new_function(char *name)
  5844. {
  5845. struct function **funcpp = find_function_slot(name);
  5846. struct function *funcp = *funcpp;
  5847. if (funcp != NULL) {
  5848. struct command *cmd = funcp->parent_cmd;
  5849. debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
  5850. if (!cmd) {
  5851. debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
  5852. free(funcp->name);
  5853. /* Note: if !funcp->body, do not free body_as_string!
  5854. * This is a special case of "-F name body" function:
  5855. * body_as_string was not malloced! */
  5856. if (funcp->body) {
  5857. free_pipe_list(funcp->body);
  5858. # if !BB_MMU
  5859. free(funcp->body_as_string);
  5860. # endif
  5861. }
  5862. } else {
  5863. debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
  5864. cmd->argv[0] = funcp->name;
  5865. cmd->group = funcp->body;
  5866. # if !BB_MMU
  5867. cmd->group_as_string = funcp->body_as_string;
  5868. # endif
  5869. }
  5870. } else {
  5871. debug_printf_exec("remembering new function '%s'\n", name);
  5872. funcp = *funcpp = xzalloc(sizeof(*funcp));
  5873. /*funcp->next = NULL;*/
  5874. }
  5875. funcp->name = name;
  5876. return funcp;
  5877. }
  5878. static void unset_func(const char *name)
  5879. {
  5880. struct function **funcpp = find_function_slot(name);
  5881. struct function *funcp = *funcpp;
  5882. if (funcp != NULL) {
  5883. debug_printf_exec("freeing function '%s'\n", funcp->name);
  5884. *funcpp = funcp->next;
  5885. /* funcp is unlinked now, deleting it.
  5886. * Note: if !funcp->body, the function was created by
  5887. * "-F name body", do not free ->body_as_string
  5888. * and ->name as they were not malloced. */
  5889. if (funcp->body) {
  5890. free_pipe_list(funcp->body);
  5891. free(funcp->name);
  5892. # if !BB_MMU
  5893. free(funcp->body_as_string);
  5894. # endif
  5895. }
  5896. free(funcp);
  5897. }
  5898. }
  5899. # if BB_MMU
  5900. #define exec_function(to_free, funcp, argv) \
  5901. exec_function(funcp, argv)
  5902. # endif
  5903. static void exec_function(char ***to_free,
  5904. const struct function *funcp,
  5905. char **argv) NORETURN;
  5906. static void exec_function(char ***to_free,
  5907. const struct function *funcp,
  5908. char **argv)
  5909. {
  5910. # if BB_MMU
  5911. int n = 1;
  5912. argv[0] = G.global_argv[0];
  5913. G.global_argv = argv;
  5914. while (*++argv)
  5915. n++;
  5916. G.global_argc = n;
  5917. /* On MMU, funcp->body is always non-NULL */
  5918. n = run_list(funcp->body);
  5919. fflush_all();
  5920. _exit(n);
  5921. # else
  5922. re_execute_shell(to_free,
  5923. funcp->body_as_string,
  5924. G.global_argv[0],
  5925. argv + 1,
  5926. NULL);
  5927. # endif
  5928. }
  5929. static int run_function(const struct function *funcp, char **argv)
  5930. {
  5931. int rc;
  5932. save_arg_t sv;
  5933. smallint sv_flg;
  5934. save_and_replace_G_args(&sv, argv);
  5935. /* "we are in function, ok to use return" */
  5936. sv_flg = G.flag_return_in_progress;
  5937. G.flag_return_in_progress = -1;
  5938. # if ENABLE_HUSH_LOCAL
  5939. G.func_nest_level++;
  5940. # endif
  5941. /* On MMU, funcp->body is always non-NULL */
  5942. # if !BB_MMU
  5943. if (!funcp->body) {
  5944. /* Function defined by -F */
  5945. parse_and_run_string(funcp->body_as_string);
  5946. rc = G.last_exitcode;
  5947. } else
  5948. # endif
  5949. {
  5950. rc = run_list(funcp->body);
  5951. }
  5952. # if ENABLE_HUSH_LOCAL
  5953. {
  5954. struct variable *var;
  5955. struct variable **var_pp;
  5956. var_pp = &G.top_var;
  5957. while ((var = *var_pp) != NULL) {
  5958. if (var->func_nest_level < G.func_nest_level) {
  5959. var_pp = &var->next;
  5960. continue;
  5961. }
  5962. /* Unexport */
  5963. if (var->flg_export)
  5964. bb_unsetenv(var->varstr);
  5965. /* Remove from global list */
  5966. *var_pp = var->next;
  5967. /* Free */
  5968. if (!var->max_len)
  5969. free(var->varstr);
  5970. free(var);
  5971. }
  5972. G.func_nest_level--;
  5973. }
  5974. # endif
  5975. G.flag_return_in_progress = sv_flg;
  5976. restore_G_args(&sv, argv);
  5977. return rc;
  5978. }
  5979. #endif /* ENABLE_HUSH_FUNCTIONS */
  5980. #if BB_MMU
  5981. #define exec_builtin(to_free, x, argv) \
  5982. exec_builtin(x, argv)
  5983. #else
  5984. #define exec_builtin(to_free, x, argv) \
  5985. exec_builtin(to_free, argv)
  5986. #endif
  5987. static void exec_builtin(char ***to_free,
  5988. const struct built_in_command *x,
  5989. char **argv) NORETURN;
  5990. static void exec_builtin(char ***to_free,
  5991. const struct built_in_command *x,
  5992. char **argv)
  5993. {
  5994. #if BB_MMU
  5995. int rcode;
  5996. fflush_all();
  5997. rcode = x->b_function(argv);
  5998. fflush_all();
  5999. _exit(rcode);
  6000. #else
  6001. fflush_all();
  6002. /* On NOMMU, we must never block!
  6003. * Example: { sleep 99 | read line; } & echo Ok
  6004. */
  6005. re_execute_shell(to_free,
  6006. argv[0],
  6007. G.global_argv[0],
  6008. G.global_argv + 1,
  6009. argv);
  6010. #endif
  6011. }
  6012. static void execvp_or_die(char **argv) NORETURN;
  6013. static void execvp_or_die(char **argv)
  6014. {
  6015. debug_printf_exec("execing '%s'\n", argv[0]);
  6016. /* Don't propagate SIG_IGN to the child */
  6017. if (SPECIAL_JOBSTOP_SIGS != 0)
  6018. switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
  6019. execvp(argv[0], argv);
  6020. bb_perror_msg("can't execute '%s'", argv[0]);
  6021. _exit(127); /* bash compat */
  6022. }
  6023. #if ENABLE_HUSH_MODE_X
  6024. static void dump_cmd_in_x_mode(char **argv)
  6025. {
  6026. if (G_x_mode && argv) {
  6027. /* We want to output the line in one write op */
  6028. char *buf, *p;
  6029. int len;
  6030. int n;
  6031. len = 3;
  6032. n = 0;
  6033. while (argv[n])
  6034. len += strlen(argv[n++]) + 1;
  6035. buf = xmalloc(len);
  6036. buf[0] = '+';
  6037. p = buf + 1;
  6038. n = 0;
  6039. while (argv[n])
  6040. p += sprintf(p, " %s", argv[n++]);
  6041. *p++ = '\n';
  6042. *p = '\0';
  6043. fputs(buf, stderr);
  6044. free(buf);
  6045. }
  6046. }
  6047. #else
  6048. # define dump_cmd_in_x_mode(argv) ((void)0)
  6049. #endif
  6050. #if BB_MMU
  6051. #define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
  6052. pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
  6053. #define pseudo_exec(nommu_save, command, argv_expanded) \
  6054. pseudo_exec(command, argv_expanded)
  6055. #endif
  6056. /* Called after [v]fork() in run_pipe, or from builtin_exec.
  6057. * Never returns.
  6058. * Don't exit() here. If you don't exec, use _exit instead.
  6059. * The at_exit handlers apparently confuse the calling process,
  6060. * in particular stdin handling. Not sure why? -- because of vfork! (vda)
  6061. */
  6062. static void pseudo_exec_argv(nommu_save_t *nommu_save,
  6063. char **argv, int assignment_cnt,
  6064. char **argv_expanded) NORETURN;
  6065. static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
  6066. char **argv, int assignment_cnt,
  6067. char **argv_expanded)
  6068. {
  6069. char **new_env;
  6070. new_env = expand_assignments(argv, assignment_cnt);
  6071. dump_cmd_in_x_mode(new_env);
  6072. if (!argv[assignment_cnt]) {
  6073. /* Case when we are here: ... | var=val | ...
  6074. * (note that we do not exit early, i.e., do not optimize out
  6075. * expand_assignments(): think about ... | var=`sleep 1` | ...
  6076. */
  6077. free_strings(new_env);
  6078. _exit(EXIT_SUCCESS);
  6079. }
  6080. #if BB_MMU
  6081. set_vars_and_save_old(new_env);
  6082. free(new_env); /* optional */
  6083. /* we can also destroy set_vars_and_save_old's return value,
  6084. * to save memory */
  6085. #else
  6086. nommu_save->new_env = new_env;
  6087. nommu_save->old_vars = set_vars_and_save_old(new_env);
  6088. #endif
  6089. if (argv_expanded) {
  6090. argv = argv_expanded;
  6091. } else {
  6092. argv = expand_strvec_to_strvec(argv + assignment_cnt);
  6093. #if !BB_MMU
  6094. nommu_save->argv = argv;
  6095. #endif
  6096. }
  6097. dump_cmd_in_x_mode(argv);
  6098. #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
  6099. if (strchr(argv[0], '/') != NULL)
  6100. goto skip;
  6101. #endif
  6102. /* Check if the command matches any of the builtins.
  6103. * Depending on context, this might be redundant. But it's
  6104. * easier to waste a few CPU cycles than it is to figure out
  6105. * if this is one of those cases.
  6106. */
  6107. {
  6108. /* On NOMMU, it is more expensive to re-execute shell
  6109. * just in order to run echo or test builtin.
  6110. * It's better to skip it here and run corresponding
  6111. * non-builtin later. */
  6112. const struct built_in_command *x;
  6113. x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
  6114. if (x) {
  6115. exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
  6116. }
  6117. }
  6118. #if ENABLE_HUSH_FUNCTIONS
  6119. /* Check if the command matches any functions */
  6120. {
  6121. const struct function *funcp = find_function(argv[0]);
  6122. if (funcp) {
  6123. exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
  6124. }
  6125. }
  6126. #endif
  6127. #if ENABLE_FEATURE_SH_STANDALONE
  6128. /* Check if the command matches any busybox applets */
  6129. {
  6130. int a = find_applet_by_name(argv[0]);
  6131. if (a >= 0) {
  6132. # if BB_MMU /* see above why on NOMMU it is not allowed */
  6133. if (APPLET_IS_NOEXEC(a)) {
  6134. debug_printf_exec("running applet '%s'\n", argv[0]);
  6135. run_applet_no_and_exit(a, argv);
  6136. }
  6137. # endif
  6138. /* Re-exec ourselves */
  6139. debug_printf_exec("re-execing applet '%s'\n", argv[0]);
  6140. /* Don't propagate SIG_IGN to the child */
  6141. if (SPECIAL_JOBSTOP_SIGS != 0)
  6142. switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
  6143. execv(bb_busybox_exec_path, argv);
  6144. /* If they called chroot or otherwise made the binary no longer
  6145. * executable, fall through */
  6146. }
  6147. }
  6148. #endif
  6149. #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
  6150. skip:
  6151. #endif
  6152. execvp_or_die(argv);
  6153. }
  6154. /* Called after [v]fork() in run_pipe
  6155. */
  6156. static void pseudo_exec(nommu_save_t *nommu_save,
  6157. struct command *command,
  6158. char **argv_expanded) NORETURN;
  6159. static void pseudo_exec(nommu_save_t *nommu_save,
  6160. struct command *command,
  6161. char **argv_expanded)
  6162. {
  6163. if (command->argv) {
  6164. pseudo_exec_argv(nommu_save, command->argv,
  6165. command->assignment_cnt, argv_expanded);
  6166. }
  6167. if (command->group) {
  6168. /* Cases when we are here:
  6169. * ( list )
  6170. * { list } &
  6171. * ... | ( list ) | ...
  6172. * ... | { list } | ...
  6173. */
  6174. #if BB_MMU
  6175. int rcode;
  6176. debug_printf_exec("pseudo_exec: run_list\n");
  6177. reset_traps_to_defaults();
  6178. rcode = run_list(command->group);
  6179. /* OK to leak memory by not calling free_pipe_list,
  6180. * since this process is about to exit */
  6181. _exit(rcode);
  6182. #else
  6183. re_execute_shell(&nommu_save->argv_from_re_execing,
  6184. command->group_as_string,
  6185. G.global_argv[0],
  6186. G.global_argv + 1,
  6187. NULL);
  6188. #endif
  6189. }
  6190. /* Case when we are here: ... | >file */
  6191. debug_printf_exec("pseudo_exec'ed null command\n");
  6192. _exit(EXIT_SUCCESS);
  6193. }
  6194. #if ENABLE_HUSH_JOB
  6195. static const char *get_cmdtext(struct pipe *pi)
  6196. {
  6197. char **argv;
  6198. char *p;
  6199. int len;
  6200. /* This is subtle. ->cmdtext is created only on first backgrounding.
  6201. * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
  6202. * On subsequent bg argv is trashed, but we won't use it */
  6203. if (pi->cmdtext)
  6204. return pi->cmdtext;
  6205. argv = pi->cmds[0].argv;
  6206. if (!argv || !argv[0]) {
  6207. pi->cmdtext = xzalloc(1);
  6208. return pi->cmdtext;
  6209. }
  6210. len = 0;
  6211. do {
  6212. len += strlen(*argv) + 1;
  6213. } while (*++argv);
  6214. p = xmalloc(len);
  6215. pi->cmdtext = p;
  6216. argv = pi->cmds[0].argv;
  6217. do {
  6218. len = strlen(*argv);
  6219. memcpy(p, *argv, len);
  6220. p += len;
  6221. *p++ = ' ';
  6222. } while (*++argv);
  6223. p[-1] = '\0';
  6224. return pi->cmdtext;
  6225. }
  6226. static void insert_bg_job(struct pipe *pi)
  6227. {
  6228. struct pipe *job, **jobp;
  6229. int i;
  6230. /* Linear search for the ID of the job to use */
  6231. pi->jobid = 1;
  6232. for (job = G.job_list; job; job = job->next)
  6233. if (job->jobid >= pi->jobid)
  6234. pi->jobid = job->jobid + 1;
  6235. /* Add job to the list of running jobs */
  6236. jobp = &G.job_list;
  6237. while ((job = *jobp) != NULL)
  6238. jobp = &job->next;
  6239. job = *jobp = xmalloc(sizeof(*job));
  6240. *job = *pi; /* physical copy */
  6241. job->next = NULL;
  6242. job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
  6243. /* Cannot copy entire pi->cmds[] vector! This causes double frees */
  6244. for (i = 0; i < pi->num_cmds; i++) {
  6245. job->cmds[i].pid = pi->cmds[i].pid;
  6246. /* all other fields are not used and stay zero */
  6247. }
  6248. job->cmdtext = xstrdup(get_cmdtext(pi));
  6249. if (G_interactive_fd)
  6250. printf("[%d] %d %s\n", job->jobid, job->cmds[0].pid, job->cmdtext);
  6251. G.last_jobid = job->jobid;
  6252. }
  6253. static void remove_bg_job(struct pipe *pi)
  6254. {
  6255. struct pipe *prev_pipe;
  6256. if (pi == G.job_list) {
  6257. G.job_list = pi->next;
  6258. } else {
  6259. prev_pipe = G.job_list;
  6260. while (prev_pipe->next != pi)
  6261. prev_pipe = prev_pipe->next;
  6262. prev_pipe->next = pi->next;
  6263. }
  6264. if (G.job_list)
  6265. G.last_jobid = G.job_list->jobid;
  6266. else
  6267. G.last_jobid = 0;
  6268. }
  6269. /* Remove a backgrounded job */
  6270. static void delete_finished_bg_job(struct pipe *pi)
  6271. {
  6272. remove_bg_job(pi);
  6273. free_pipe(pi);
  6274. }
  6275. #endif /* JOB */
  6276. /* Check to see if any processes have exited -- if they
  6277. * have, figure out why and see if a job has completed */
  6278. static int checkjobs(struct pipe *fg_pipe)
  6279. {
  6280. int attributes;
  6281. int status;
  6282. #if ENABLE_HUSH_JOB
  6283. struct pipe *pi;
  6284. #endif
  6285. pid_t childpid;
  6286. int rcode = 0;
  6287. debug_printf_jobs("checkjobs %p\n", fg_pipe);
  6288. attributes = WUNTRACED;
  6289. if (fg_pipe == NULL)
  6290. attributes |= WNOHANG;
  6291. errno = 0;
  6292. #if ENABLE_HUSH_FAST
  6293. if (G.handled_SIGCHLD == G.count_SIGCHLD) {
  6294. //bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
  6295. //getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
  6296. /* There was neither fork nor SIGCHLD since last waitpid */
  6297. /* Avoid doing waitpid syscall if possible */
  6298. if (!G.we_have_children) {
  6299. errno = ECHILD;
  6300. return -1;
  6301. }
  6302. if (fg_pipe == NULL) { /* is WNOHANG set? */
  6303. /* We have children, but they did not exit
  6304. * or stop yet (we saw no SIGCHLD) */
  6305. return 0;
  6306. }
  6307. /* else: !WNOHANG, waitpid will block, can't short-circuit */
  6308. }
  6309. #endif
  6310. /* Do we do this right?
  6311. * bash-3.00# sleep 20 | false
  6312. * <ctrl-Z pressed>
  6313. * [3]+ Stopped sleep 20 | false
  6314. * bash-3.00# echo $?
  6315. * 1 <========== bg pipe is not fully done, but exitcode is already known!
  6316. * [hush 1.14.0: yes we do it right]
  6317. */
  6318. wait_more:
  6319. while (1) {
  6320. int i;
  6321. int dead;
  6322. #if ENABLE_HUSH_FAST
  6323. i = G.count_SIGCHLD;
  6324. #endif
  6325. childpid = waitpid(-1, &status, attributes);
  6326. if (childpid <= 0) {
  6327. if (childpid && errno != ECHILD)
  6328. bb_perror_msg("waitpid");
  6329. #if ENABLE_HUSH_FAST
  6330. else { /* Until next SIGCHLD, waitpid's are useless */
  6331. G.we_have_children = (childpid == 0);
  6332. G.handled_SIGCHLD = i;
  6333. //bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
  6334. }
  6335. #endif
  6336. break;
  6337. }
  6338. dead = WIFEXITED(status) || WIFSIGNALED(status);
  6339. #if DEBUG_JOBS
  6340. if (WIFSTOPPED(status))
  6341. debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
  6342. childpid, WSTOPSIG(status), WEXITSTATUS(status));
  6343. if (WIFSIGNALED(status))
  6344. debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
  6345. childpid, WTERMSIG(status), WEXITSTATUS(status));
  6346. if (WIFEXITED(status))
  6347. debug_printf_jobs("pid %d exited, exitcode %d\n",
  6348. childpid, WEXITSTATUS(status));
  6349. #endif
  6350. /* Were we asked to wait for fg pipe? */
  6351. if (fg_pipe) {
  6352. i = fg_pipe->num_cmds;
  6353. while (--i >= 0) {
  6354. debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
  6355. if (fg_pipe->cmds[i].pid != childpid)
  6356. continue;
  6357. if (dead) {
  6358. int ex;
  6359. fg_pipe->cmds[i].pid = 0;
  6360. fg_pipe->alive_cmds--;
  6361. ex = WEXITSTATUS(status);
  6362. /* bash prints killer signal's name for *last*
  6363. * process in pipe (prints just newline for SIGINT/SIGPIPE).
  6364. * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
  6365. */
  6366. if (WIFSIGNALED(status)) {
  6367. int sig = WTERMSIG(status);
  6368. if (i == fg_pipe->num_cmds-1)
  6369. /* TODO: use strsignal() instead for bash compat? but that's bloat... */
  6370. puts(sig == SIGINT || sig == SIGPIPE ? "" : get_signame(sig));
  6371. /* TODO: if (WCOREDUMP(status)) + " (core dumped)"; */
  6372. /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
  6373. * Maybe we need to use sig | 128? */
  6374. ex = sig + 128;
  6375. }
  6376. fg_pipe->cmds[i].cmd_exitcode = ex;
  6377. } else {
  6378. fg_pipe->stopped_cmds++;
  6379. }
  6380. debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
  6381. fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
  6382. if (fg_pipe->alive_cmds == fg_pipe->stopped_cmds) {
  6383. /* All processes in fg pipe have exited or stopped */
  6384. i = fg_pipe->num_cmds;
  6385. while (--i >= 0) {
  6386. rcode = fg_pipe->cmds[i].cmd_exitcode;
  6387. /* usually last process gives overall exitstatus,
  6388. * but with "set -o pipefail", last *failed* process does */
  6389. if (G.o_opt[OPT_O_PIPEFAIL] == 0 || rcode != 0)
  6390. break;
  6391. }
  6392. IF_HAS_KEYWORDS(if (fg_pipe->pi_inverted) rcode = !rcode;)
  6393. /* Note: *non-interactive* bash does not continue if all processes in fg pipe
  6394. * are stopped. Testcase: "cat | cat" in a script (not on command line!)
  6395. * and "killall -STOP cat" */
  6396. if (G_interactive_fd) {
  6397. #if ENABLE_HUSH_JOB
  6398. if (fg_pipe->alive_cmds != 0)
  6399. insert_bg_job(fg_pipe);
  6400. #endif
  6401. return rcode;
  6402. }
  6403. if (fg_pipe->alive_cmds == 0)
  6404. return rcode;
  6405. }
  6406. /* There are still running processes in the fg pipe */
  6407. goto wait_more; /* do waitpid again */
  6408. }
  6409. /* it wasnt fg_pipe, look for process in bg pipes */
  6410. }
  6411. #if ENABLE_HUSH_JOB
  6412. /* We asked to wait for bg or orphaned children */
  6413. /* No need to remember exitcode in this case */
  6414. for (pi = G.job_list; pi; pi = pi->next) {
  6415. for (i = 0; i < pi->num_cmds; i++) {
  6416. if (pi->cmds[i].pid == childpid)
  6417. goto found_pi_and_prognum;
  6418. }
  6419. }
  6420. /* Happens when shell is used as init process (init=/bin/sh) */
  6421. debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
  6422. continue; /* do waitpid again */
  6423. found_pi_and_prognum:
  6424. if (dead) {
  6425. /* child exited */
  6426. pi->cmds[i].pid = 0;
  6427. pi->alive_cmds--;
  6428. if (!pi->alive_cmds) {
  6429. if (G_interactive_fd)
  6430. printf(JOB_STATUS_FORMAT, pi->jobid,
  6431. "Done", pi->cmdtext);
  6432. delete_finished_bg_job(pi);
  6433. }
  6434. } else {
  6435. /* child stopped */
  6436. pi->stopped_cmds++;
  6437. }
  6438. #endif
  6439. } /* while (waitpid succeeds)... */
  6440. return rcode;
  6441. }
  6442. #if ENABLE_HUSH_JOB
  6443. static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
  6444. {
  6445. pid_t p;
  6446. int rcode = checkjobs(fg_pipe);
  6447. if (G_saved_tty_pgrp) {
  6448. /* Job finished, move the shell to the foreground */
  6449. p = getpgrp(); /* our process group id */
  6450. debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
  6451. tcsetpgrp(G_interactive_fd, p);
  6452. }
  6453. return rcode;
  6454. }
  6455. #endif
  6456. /* Start all the jobs, but don't wait for anything to finish.
  6457. * See checkjobs().
  6458. *
  6459. * Return code is normally -1, when the caller has to wait for children
  6460. * to finish to determine the exit status of the pipe. If the pipe
  6461. * is a simple builtin command, however, the action is done by the
  6462. * time run_pipe returns, and the exit code is provided as the
  6463. * return value.
  6464. *
  6465. * Returns -1 only if started some children. IOW: we have to
  6466. * mask out retvals of builtins etc with 0xff!
  6467. *
  6468. * The only case when we do not need to [v]fork is when the pipe
  6469. * is single, non-backgrounded, non-subshell command. Examples:
  6470. * cmd ; ... { list } ; ...
  6471. * cmd && ... { list } && ...
  6472. * cmd || ... { list } || ...
  6473. * If it is, then we can run cmd as a builtin, NOFORK,
  6474. * or (if SH_STANDALONE) an applet, and we can run the { list }
  6475. * with run_list. If it isn't one of these, we fork and exec cmd.
  6476. *
  6477. * Cases when we must fork:
  6478. * non-single: cmd | cmd
  6479. * backgrounded: cmd & { list } &
  6480. * subshell: ( list ) [&]
  6481. */
  6482. #if !ENABLE_HUSH_MODE_X
  6483. #define redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel, argv_expanded) \
  6484. redirect_and_varexp_helper(new_env_p, old_vars_p, command, squirrel)
  6485. #endif
  6486. static int redirect_and_varexp_helper(char ***new_env_p,
  6487. struct variable **old_vars_p,
  6488. struct command *command,
  6489. int squirrel[3],
  6490. char **argv_expanded)
  6491. {
  6492. /* setup_redirects acts on file descriptors, not FILEs.
  6493. * This is perfect for work that comes after exec().
  6494. * Is it really safe for inline use? Experimentally,
  6495. * things seem to work. */
  6496. int rcode = setup_redirects(command, squirrel);
  6497. if (rcode == 0) {
  6498. char **new_env = expand_assignments(command->argv, command->assignment_cnt);
  6499. *new_env_p = new_env;
  6500. dump_cmd_in_x_mode(new_env);
  6501. dump_cmd_in_x_mode(argv_expanded);
  6502. if (old_vars_p)
  6503. *old_vars_p = set_vars_and_save_old(new_env);
  6504. }
  6505. return rcode;
  6506. }
  6507. static NOINLINE int run_pipe(struct pipe *pi)
  6508. {
  6509. static const char *const null_ptr = NULL;
  6510. int cmd_no;
  6511. int next_infd;
  6512. struct command *command;
  6513. char **argv_expanded;
  6514. char **argv;
  6515. /* it is not always needed, but we aim to smaller code */
  6516. int squirrel[] = { -1, -1, -1 };
  6517. int rcode;
  6518. debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
  6519. debug_enter();
  6520. /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
  6521. * Result should be 3 lines: q w e, qwe, q w e
  6522. */
  6523. G.ifs = get_local_var_value("IFS");
  6524. if (!G.ifs)
  6525. G.ifs = defifs;
  6526. IF_HUSH_JOB(pi->pgrp = -1;)
  6527. pi->stopped_cmds = 0;
  6528. command = &pi->cmds[0];
  6529. argv_expanded = NULL;
  6530. if (pi->num_cmds != 1
  6531. || pi->followup == PIPE_BG
  6532. || command->cmd_type == CMD_SUBSHELL
  6533. ) {
  6534. goto must_fork;
  6535. }
  6536. pi->alive_cmds = 1;
  6537. debug_printf_exec(": group:%p argv:'%s'\n",
  6538. command->group, command->argv ? command->argv[0] : "NONE");
  6539. if (command->group) {
  6540. #if ENABLE_HUSH_FUNCTIONS
  6541. if (command->cmd_type == CMD_FUNCDEF) {
  6542. /* "executing" func () { list } */
  6543. struct function *funcp;
  6544. funcp = new_function(command->argv[0]);
  6545. /* funcp->name is already set to argv[0] */
  6546. funcp->body = command->group;
  6547. # if !BB_MMU
  6548. funcp->body_as_string = command->group_as_string;
  6549. command->group_as_string = NULL;
  6550. # endif
  6551. command->group = NULL;
  6552. command->argv[0] = NULL;
  6553. debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
  6554. funcp->parent_cmd = command;
  6555. command->child_func = funcp;
  6556. debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
  6557. debug_leave();
  6558. return EXIT_SUCCESS;
  6559. }
  6560. #endif
  6561. /* { list } */
  6562. debug_printf("non-subshell group\n");
  6563. rcode = 1; /* exitcode if redir failed */
  6564. if (setup_redirects(command, squirrel) == 0) {
  6565. debug_printf_exec(": run_list\n");
  6566. rcode = run_list(command->group) & 0xff;
  6567. }
  6568. restore_redirects(squirrel);
  6569. IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
  6570. debug_leave();
  6571. debug_printf_exec("run_pipe: return %d\n", rcode);
  6572. return rcode;
  6573. }
  6574. argv = command->argv ? command->argv : (char **) &null_ptr;
  6575. {
  6576. const struct built_in_command *x;
  6577. #if ENABLE_HUSH_FUNCTIONS
  6578. const struct function *funcp;
  6579. #else
  6580. enum { funcp = 0 };
  6581. #endif
  6582. char **new_env = NULL;
  6583. struct variable *old_vars = NULL;
  6584. if (argv[command->assignment_cnt] == NULL) {
  6585. /* Assignments, but no command */
  6586. /* Ensure redirects take effect (that is, create files).
  6587. * Try "a=t >file" */
  6588. #if 0 /* A few cases in testsuite fail with this code. FIXME */
  6589. rcode = redirect_and_varexp_helper(&new_env, /*old_vars:*/ NULL, command, squirrel, /*argv_expanded:*/ NULL);
  6590. /* Set shell variables */
  6591. if (new_env) {
  6592. argv = new_env;
  6593. while (*argv) {
  6594. set_local_var(*argv, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
  6595. /* Do we need to flag set_local_var() errors?
  6596. * "assignment to readonly var" and "putenv error"
  6597. */
  6598. argv++;
  6599. }
  6600. }
  6601. /* Redirect error sets $? to 1. Otherwise,
  6602. * if evaluating assignment value set $?, retain it.
  6603. * Try "false; q=`exit 2`; echo $?" - should print 2: */
  6604. if (rcode == 0)
  6605. rcode = G.last_exitcode;
  6606. /* Exit, _skipping_ variable restoring code: */
  6607. goto clean_up_and_ret0;
  6608. #else /* Older, bigger, but more correct code */
  6609. rcode = setup_redirects(command, squirrel);
  6610. restore_redirects(squirrel);
  6611. /* Set shell variables */
  6612. if (G_x_mode)
  6613. bb_putchar_stderr('+');
  6614. while (*argv) {
  6615. char *p = expand_string_to_string(*argv, /*unbackslash:*/ 1);
  6616. if (G_x_mode)
  6617. fprintf(stderr, " %s", p);
  6618. debug_printf_exec("set shell var:'%s'->'%s'\n",
  6619. *argv, p);
  6620. set_local_var(p, /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
  6621. /* Do we need to flag set_local_var() errors?
  6622. * "assignment to readonly var" and "putenv error"
  6623. */
  6624. argv++;
  6625. }
  6626. if (G_x_mode)
  6627. bb_putchar_stderr('\n');
  6628. /* Redirect error sets $? to 1. Otherwise,
  6629. * if evaluating assignment value set $?, retain it.
  6630. * Try "false; q=`exit 2`; echo $?" - should print 2: */
  6631. if (rcode == 0)
  6632. rcode = G.last_exitcode;
  6633. IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
  6634. debug_leave();
  6635. debug_printf_exec("run_pipe: return %d\n", rcode);
  6636. return rcode;
  6637. #endif
  6638. }
  6639. /* Expand the rest into (possibly) many strings each */
  6640. #if ENABLE_HUSH_BASH_COMPAT
  6641. if (command->cmd_type == CMD_SINGLEWORD_NOGLOB) {
  6642. argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
  6643. } else
  6644. #endif
  6645. {
  6646. argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
  6647. }
  6648. /* if someone gives us an empty string: `cmd with empty output` */
  6649. if (!argv_expanded[0]) {
  6650. free(argv_expanded);
  6651. debug_leave();
  6652. return G.last_exitcode;
  6653. }
  6654. x = find_builtin(argv_expanded[0]);
  6655. #if ENABLE_HUSH_FUNCTIONS
  6656. funcp = NULL;
  6657. if (!x)
  6658. funcp = find_function(argv_expanded[0]);
  6659. #endif
  6660. if (x || funcp) {
  6661. if (!funcp) {
  6662. if (x->b_function == builtin_exec && argv_expanded[1] == NULL) {
  6663. debug_printf("exec with redirects only\n");
  6664. rcode = setup_redirects(command, NULL);
  6665. goto clean_up_and_ret1;
  6666. }
  6667. }
  6668. rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
  6669. if (rcode == 0) {
  6670. if (!funcp) {
  6671. debug_printf_exec(": builtin '%s' '%s'...\n",
  6672. x->b_cmd, argv_expanded[1]);
  6673. fflush_all();
  6674. rcode = x->b_function(argv_expanded) & 0xff;
  6675. fflush_all();
  6676. }
  6677. #if ENABLE_HUSH_FUNCTIONS
  6678. else {
  6679. # if ENABLE_HUSH_LOCAL
  6680. struct variable **sv;
  6681. sv = G.shadowed_vars_pp;
  6682. G.shadowed_vars_pp = &old_vars;
  6683. # endif
  6684. debug_printf_exec(": function '%s' '%s'...\n",
  6685. funcp->name, argv_expanded[1]);
  6686. rcode = run_function(funcp, argv_expanded) & 0xff;
  6687. # if ENABLE_HUSH_LOCAL
  6688. G.shadowed_vars_pp = sv;
  6689. # endif
  6690. }
  6691. #endif
  6692. }
  6693. clean_up_and_ret:
  6694. unset_vars(new_env);
  6695. add_vars(old_vars);
  6696. /* clean_up_and_ret0: */
  6697. restore_redirects(squirrel);
  6698. clean_up_and_ret1:
  6699. free(argv_expanded);
  6700. IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
  6701. debug_leave();
  6702. debug_printf_exec("run_pipe return %d\n", rcode);
  6703. return rcode;
  6704. }
  6705. if (ENABLE_FEATURE_SH_NOFORK) {
  6706. int n = find_applet_by_name(argv_expanded[0]);
  6707. if (n >= 0 && APPLET_IS_NOFORK(n)) {
  6708. rcode = redirect_and_varexp_helper(&new_env, &old_vars, command, squirrel, argv_expanded);
  6709. if (rcode == 0) {
  6710. debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
  6711. argv_expanded[0], argv_expanded[1]);
  6712. rcode = run_nofork_applet(n, argv_expanded);
  6713. }
  6714. goto clean_up_and_ret;
  6715. }
  6716. }
  6717. /* It is neither builtin nor applet. We must fork. */
  6718. }
  6719. must_fork:
  6720. /* NB: argv_expanded may already be created, and that
  6721. * might include `cmd` runs! Do not rerun it! We *must*
  6722. * use argv_expanded if it's non-NULL */
  6723. /* Going to fork a child per each pipe member */
  6724. pi->alive_cmds = 0;
  6725. next_infd = 0;
  6726. cmd_no = 0;
  6727. while (cmd_no < pi->num_cmds) {
  6728. struct fd_pair pipefds;
  6729. #if !BB_MMU
  6730. volatile nommu_save_t nommu_save;
  6731. nommu_save.new_env = NULL;
  6732. nommu_save.old_vars = NULL;
  6733. nommu_save.argv = NULL;
  6734. nommu_save.argv_from_re_execing = NULL;
  6735. #endif
  6736. command = &pi->cmds[cmd_no];
  6737. cmd_no++;
  6738. if (command->argv) {
  6739. debug_printf_exec(": pipe member '%s' '%s'...\n",
  6740. command->argv[0], command->argv[1]);
  6741. } else {
  6742. debug_printf_exec(": pipe member with no argv\n");
  6743. }
  6744. /* pipes are inserted between pairs of commands */
  6745. pipefds.rd = 0;
  6746. pipefds.wr = 1;
  6747. if (cmd_no < pi->num_cmds)
  6748. xpiped_pair(pipefds);
  6749. command->pid = BB_MMU ? fork() : vfork();
  6750. if (!command->pid) { /* child */
  6751. #if ENABLE_HUSH_JOB
  6752. disable_restore_tty_pgrp_on_exit();
  6753. CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
  6754. /* Every child adds itself to new process group
  6755. * with pgid == pid_of_first_child_in_pipe */
  6756. if (G.run_list_level == 1 && G_interactive_fd) {
  6757. pid_t pgrp;
  6758. pgrp = pi->pgrp;
  6759. if (pgrp < 0) /* true for 1st process only */
  6760. pgrp = getpid();
  6761. if (setpgid(0, pgrp) == 0
  6762. && pi->followup != PIPE_BG
  6763. && G_saved_tty_pgrp /* we have ctty */
  6764. ) {
  6765. /* We do it in *every* child, not just first,
  6766. * to avoid races */
  6767. tcsetpgrp(G_interactive_fd, pgrp);
  6768. }
  6769. }
  6770. #endif
  6771. if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
  6772. /* 1st cmd in backgrounded pipe
  6773. * should have its stdin /dev/null'ed */
  6774. close(0);
  6775. if (open(bb_dev_null, O_RDONLY))
  6776. xopen("/", O_RDONLY);
  6777. } else {
  6778. xmove_fd(next_infd, 0);
  6779. }
  6780. xmove_fd(pipefds.wr, 1);
  6781. if (pipefds.rd > 1)
  6782. close(pipefds.rd);
  6783. /* Like bash, explicit redirects override pipes,
  6784. * and the pipe fd is available for dup'ing. */
  6785. if (setup_redirects(command, NULL))
  6786. _exit(1);
  6787. /* Stores to nommu_save list of env vars putenv'ed
  6788. * (NOMMU, on MMU we don't need that) */
  6789. /* cast away volatility... */
  6790. pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
  6791. /* pseudo_exec() does not return */
  6792. }
  6793. /* parent or error */
  6794. #if ENABLE_HUSH_FAST
  6795. G.count_SIGCHLD++;
  6796. //bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
  6797. #endif
  6798. enable_restore_tty_pgrp_on_exit();
  6799. #if !BB_MMU
  6800. /* Clean up after vforked child */
  6801. free(nommu_save.argv);
  6802. free(nommu_save.argv_from_re_execing);
  6803. unset_vars(nommu_save.new_env);
  6804. add_vars(nommu_save.old_vars);
  6805. #endif
  6806. free(argv_expanded);
  6807. argv_expanded = NULL;
  6808. if (command->pid < 0) { /* [v]fork failed */
  6809. /* Clearly indicate, was it fork or vfork */
  6810. bb_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
  6811. } else {
  6812. pi->alive_cmds++;
  6813. #if ENABLE_HUSH_JOB
  6814. /* Second and next children need to know pid of first one */
  6815. if (pi->pgrp < 0)
  6816. pi->pgrp = command->pid;
  6817. #endif
  6818. }
  6819. if (cmd_no > 1)
  6820. close(next_infd);
  6821. if (cmd_no < pi->num_cmds)
  6822. close(pipefds.wr);
  6823. /* Pass read (output) pipe end to next iteration */
  6824. next_infd = pipefds.rd;
  6825. }
  6826. if (!pi->alive_cmds) {
  6827. debug_leave();
  6828. debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
  6829. return 1;
  6830. }
  6831. debug_leave();
  6832. debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
  6833. return -1;
  6834. }
  6835. /* NB: called by pseudo_exec, and therefore must not modify any
  6836. * global data until exec/_exit (we can be a child after vfork!) */
  6837. static int run_list(struct pipe *pi)
  6838. {
  6839. #if ENABLE_HUSH_CASE
  6840. char *case_word = NULL;
  6841. #endif
  6842. #if ENABLE_HUSH_LOOPS
  6843. struct pipe *loop_top = NULL;
  6844. char **for_lcur = NULL;
  6845. char **for_list = NULL;
  6846. #endif
  6847. smallint last_followup;
  6848. smalluint rcode;
  6849. #if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
  6850. smalluint cond_code = 0;
  6851. #else
  6852. enum { cond_code = 0 };
  6853. #endif
  6854. #if HAS_KEYWORDS
  6855. smallint rword; /* RES_foo */
  6856. smallint last_rword; /* ditto */
  6857. #endif
  6858. debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
  6859. debug_enter();
  6860. #if ENABLE_HUSH_LOOPS
  6861. /* Check syntax for "for" */
  6862. {
  6863. struct pipe *cpipe;
  6864. for (cpipe = pi; cpipe; cpipe = cpipe->next) {
  6865. if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
  6866. continue;
  6867. /* current word is FOR or IN (BOLD in comments below) */
  6868. if (cpipe->next == NULL) {
  6869. syntax_error("malformed for");
  6870. debug_leave();
  6871. debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
  6872. return 1;
  6873. }
  6874. /* "FOR v; do ..." and "for v IN a b; do..." are ok */
  6875. if (cpipe->next->res_word == RES_DO)
  6876. continue;
  6877. /* next word is not "do". It must be "in" then ("FOR v in ...") */
  6878. if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
  6879. || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
  6880. ) {
  6881. syntax_error("malformed for");
  6882. debug_leave();
  6883. debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
  6884. return 1;
  6885. }
  6886. }
  6887. }
  6888. #endif
  6889. /* Past this point, all code paths should jump to ret: label
  6890. * in order to return, no direct "return" statements please.
  6891. * This helps to ensure that no memory is leaked. */
  6892. #if ENABLE_HUSH_JOB
  6893. G.run_list_level++;
  6894. #endif
  6895. #if HAS_KEYWORDS
  6896. rword = RES_NONE;
  6897. last_rword = RES_XXXX;
  6898. #endif
  6899. last_followup = PIPE_SEQ;
  6900. rcode = G.last_exitcode;
  6901. /* Go through list of pipes, (maybe) executing them. */
  6902. for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
  6903. if (G.flag_SIGINT)
  6904. break;
  6905. IF_HAS_KEYWORDS(rword = pi->res_word;)
  6906. debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
  6907. rword, cond_code, last_rword);
  6908. #if ENABLE_HUSH_LOOPS
  6909. if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
  6910. && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
  6911. ) {
  6912. /* start of a loop: remember where loop starts */
  6913. loop_top = pi;
  6914. G.depth_of_loop++;
  6915. }
  6916. #endif
  6917. /* Still in the same "if...", "then..." or "do..." branch? */
  6918. if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
  6919. if ((rcode == 0 && last_followup == PIPE_OR)
  6920. || (rcode != 0 && last_followup == PIPE_AND)
  6921. ) {
  6922. /* It is "<true> || CMD" or "<false> && CMD"
  6923. * and we should not execute CMD */
  6924. debug_printf_exec("skipped cmd because of || or &&\n");
  6925. last_followup = pi->followup;
  6926. goto dont_check_jobs_but_continue;
  6927. }
  6928. }
  6929. last_followup = pi->followup;
  6930. IF_HAS_KEYWORDS(last_rword = rword;)
  6931. #if ENABLE_HUSH_IF
  6932. if (cond_code) {
  6933. if (rword == RES_THEN) {
  6934. /* if false; then ... fi has exitcode 0! */
  6935. G.last_exitcode = rcode = EXIT_SUCCESS;
  6936. /* "if <false> THEN cmd": skip cmd */
  6937. continue;
  6938. }
  6939. } else {
  6940. if (rword == RES_ELSE || rword == RES_ELIF) {
  6941. /* "if <true> then ... ELSE/ELIF cmd":
  6942. * skip cmd and all following ones */
  6943. break;
  6944. }
  6945. }
  6946. #endif
  6947. #if ENABLE_HUSH_LOOPS
  6948. if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
  6949. if (!for_lcur) {
  6950. /* first loop through for */
  6951. static const char encoded_dollar_at[] ALIGN1 = {
  6952. SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
  6953. }; /* encoded representation of "$@" */
  6954. static const char *const encoded_dollar_at_argv[] = {
  6955. encoded_dollar_at, NULL
  6956. }; /* argv list with one element: "$@" */
  6957. char **vals;
  6958. vals = (char**)encoded_dollar_at_argv;
  6959. if (pi->next->res_word == RES_IN) {
  6960. /* if no variable values after "in" we skip "for" */
  6961. if (!pi->next->cmds[0].argv) {
  6962. G.last_exitcode = rcode = EXIT_SUCCESS;
  6963. debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
  6964. break;
  6965. }
  6966. vals = pi->next->cmds[0].argv;
  6967. } /* else: "for var; do..." -> assume "$@" list */
  6968. /* create list of variable values */
  6969. debug_print_strings("for_list made from", vals);
  6970. for_list = expand_strvec_to_strvec(vals);
  6971. for_lcur = for_list;
  6972. debug_print_strings("for_list", for_list);
  6973. }
  6974. if (!*for_lcur) {
  6975. /* "for" loop is over, clean up */
  6976. free(for_list);
  6977. for_list = NULL;
  6978. for_lcur = NULL;
  6979. break;
  6980. }
  6981. /* Insert next value from for_lcur */
  6982. /* note: *for_lcur already has quotes removed, $var expanded, etc */
  6983. set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ 0);
  6984. continue;
  6985. }
  6986. if (rword == RES_IN) {
  6987. continue; /* "for v IN list;..." - "in" has no cmds anyway */
  6988. }
  6989. if (rword == RES_DONE) {
  6990. continue; /* "done" has no cmds too */
  6991. }
  6992. #endif
  6993. #if ENABLE_HUSH_CASE
  6994. if (rword == RES_CASE) {
  6995. case_word = expand_strvec_to_string(pi->cmds->argv);
  6996. continue;
  6997. }
  6998. if (rword == RES_MATCH) {
  6999. char **argv;
  7000. if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
  7001. break;
  7002. /* all prev words didn't match, does this one match? */
  7003. argv = pi->cmds->argv;
  7004. while (*argv) {
  7005. char *pattern = expand_string_to_string(*argv, /*unbackslash:*/ 1);
  7006. /* TODO: which FNM_xxx flags to use? */
  7007. cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
  7008. free(pattern);
  7009. if (cond_code == 0) { /* match! we will execute this branch */
  7010. free(case_word); /* make future "word)" stop */
  7011. case_word = NULL;
  7012. break;
  7013. }
  7014. argv++;
  7015. }
  7016. continue;
  7017. }
  7018. if (rword == RES_CASE_BODY) { /* inside of a case branch */
  7019. if (cond_code != 0)
  7020. continue; /* not matched yet, skip this pipe */
  7021. }
  7022. #endif
  7023. /* Just pressing <enter> in shell should check for jobs.
  7024. * OTOH, in non-interactive shell this is useless
  7025. * and only leads to extra job checks */
  7026. if (pi->num_cmds == 0) {
  7027. if (G_interactive_fd)
  7028. goto check_jobs_and_continue;
  7029. continue;
  7030. }
  7031. /* After analyzing all keywords and conditions, we decided
  7032. * to execute this pipe. NB: have to do checkjobs(NULL)
  7033. * after run_pipe to collect any background children,
  7034. * even if list execution is to be stopped. */
  7035. debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
  7036. {
  7037. int r;
  7038. #if ENABLE_HUSH_LOOPS
  7039. G.flag_break_continue = 0;
  7040. #endif
  7041. rcode = r = run_pipe(pi); /* NB: rcode is a smallint */
  7042. if (r != -1) {
  7043. /* We ran a builtin, function, or group.
  7044. * rcode is already known
  7045. * and we don't need to wait for anything. */
  7046. G.last_exitcode = rcode;
  7047. debug_printf_exec(": builtin/func exitcode %d\n", rcode);
  7048. check_and_run_traps();
  7049. #if ENABLE_HUSH_LOOPS
  7050. /* Was it "break" or "continue"? */
  7051. if (G.flag_break_continue) {
  7052. smallint fbc = G.flag_break_continue;
  7053. /* We might fall into outer *loop*,
  7054. * don't want to break it too */
  7055. if (loop_top) {
  7056. G.depth_break_continue--;
  7057. if (G.depth_break_continue == 0)
  7058. G.flag_break_continue = 0;
  7059. /* else: e.g. "continue 2" should *break* once, *then* continue */
  7060. } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
  7061. if (G.depth_break_continue != 0 || fbc == BC_BREAK) {
  7062. checkjobs(NULL);
  7063. break;
  7064. }
  7065. /* "continue": simulate end of loop */
  7066. rword = RES_DONE;
  7067. continue;
  7068. }
  7069. #endif
  7070. #if ENABLE_HUSH_FUNCTIONS
  7071. if (G.flag_return_in_progress == 1) {
  7072. checkjobs(NULL);
  7073. break;
  7074. }
  7075. #endif
  7076. } else if (pi->followup == PIPE_BG) {
  7077. /* What does bash do with attempts to background builtins? */
  7078. /* even bash 3.2 doesn't do that well with nested bg:
  7079. * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
  7080. * I'm NOT treating inner &'s as jobs */
  7081. check_and_run_traps();
  7082. #if ENABLE_HUSH_JOB
  7083. if (G.run_list_level == 1)
  7084. insert_bg_job(pi);
  7085. #endif
  7086. /* Last command's pid goes to $! */
  7087. G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
  7088. G.last_exitcode = rcode = EXIT_SUCCESS;
  7089. debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
  7090. } else {
  7091. #if ENABLE_HUSH_JOB
  7092. if (G.run_list_level == 1 && G_interactive_fd) {
  7093. /* Waits for completion, then fg's main shell */
  7094. rcode = checkjobs_and_fg_shell(pi);
  7095. debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
  7096. check_and_run_traps();
  7097. } else
  7098. #endif
  7099. { /* This one just waits for completion */
  7100. rcode = checkjobs(pi);
  7101. debug_printf_exec(": checkjobs exitcode %d\n", rcode);
  7102. check_and_run_traps();
  7103. }
  7104. G.last_exitcode = rcode;
  7105. }
  7106. }
  7107. /* Analyze how result affects subsequent commands */
  7108. #if ENABLE_HUSH_IF
  7109. if (rword == RES_IF || rword == RES_ELIF)
  7110. cond_code = rcode;
  7111. #endif
  7112. check_jobs_and_continue:
  7113. checkjobs(NULL);
  7114. dont_check_jobs_but_continue: ;
  7115. #if ENABLE_HUSH_LOOPS
  7116. /* Beware of "while false; true; do ..."! */
  7117. if (pi->next
  7118. && (pi->next->res_word == RES_DO || pi->next->res_word == RES_DONE)
  7119. /* check for RES_DONE is needed for "while ...; do \n done" case */
  7120. ) {
  7121. if (rword == RES_WHILE) {
  7122. if (rcode) {
  7123. /* "while false; do...done" - exitcode 0 */
  7124. G.last_exitcode = rcode = EXIT_SUCCESS;
  7125. debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
  7126. break;
  7127. }
  7128. }
  7129. if (rword == RES_UNTIL) {
  7130. if (!rcode) {
  7131. debug_printf_exec(": until expr is true: breaking\n");
  7132. break;
  7133. }
  7134. }
  7135. }
  7136. #endif
  7137. } /* for (pi) */
  7138. #if ENABLE_HUSH_JOB
  7139. G.run_list_level--;
  7140. #endif
  7141. #if ENABLE_HUSH_LOOPS
  7142. if (loop_top)
  7143. G.depth_of_loop--;
  7144. free(for_list);
  7145. #endif
  7146. #if ENABLE_HUSH_CASE
  7147. free(case_word);
  7148. #endif
  7149. debug_leave();
  7150. debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
  7151. return rcode;
  7152. }
  7153. /* Select which version we will use */
  7154. static int run_and_free_list(struct pipe *pi)
  7155. {
  7156. int rcode = 0;
  7157. debug_printf_exec("run_and_free_list entered\n");
  7158. if (!G.o_opt[OPT_O_NOEXEC]) {
  7159. debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
  7160. rcode = run_list(pi);
  7161. }
  7162. /* free_pipe_list has the side effect of clearing memory.
  7163. * In the long run that function can be merged with run_list,
  7164. * but doing that now would hobble the debugging effort. */
  7165. free_pipe_list(pi);
  7166. debug_printf_exec("run_and_free_list return %d\n", rcode);
  7167. return rcode;
  7168. }
  7169. static void install_sighandlers(unsigned mask)
  7170. {
  7171. sighandler_t old_handler;
  7172. unsigned sig = 0;
  7173. while ((mask >>= 1) != 0) {
  7174. sig++;
  7175. if (!(mask & 1))
  7176. continue;
  7177. old_handler = install_sighandler(sig, pick_sighandler(sig));
  7178. /* POSIX allows shell to re-enable SIGCHLD
  7179. * even if it was SIG_IGN on entry.
  7180. * Therefore we skip IGN check for it:
  7181. */
  7182. if (sig == SIGCHLD)
  7183. continue;
  7184. if (old_handler == SIG_IGN) {
  7185. /* oops... restore back to IGN, and record this fact */
  7186. install_sighandler(sig, old_handler);
  7187. if (!G.traps)
  7188. G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
  7189. free(G.traps[sig]);
  7190. G.traps[sig] = xzalloc(1); /* == xstrdup(""); */
  7191. }
  7192. }
  7193. }
  7194. /* Called a few times only (or even once if "sh -c") */
  7195. static void install_special_sighandlers(void)
  7196. {
  7197. unsigned mask;
  7198. /* Which signals are shell-special? */
  7199. mask = (1 << SIGQUIT) | (1 << SIGCHLD);
  7200. if (G_interactive_fd) {
  7201. mask |= SPECIAL_INTERACTIVE_SIGS;
  7202. if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
  7203. mask |= SPECIAL_JOBSTOP_SIGS;
  7204. }
  7205. /* Careful, do not re-install handlers we already installed */
  7206. if (G.special_sig_mask != mask) {
  7207. unsigned diff = mask & ~G.special_sig_mask;
  7208. G.special_sig_mask = mask;
  7209. install_sighandlers(diff);
  7210. }
  7211. }
  7212. #if ENABLE_HUSH_JOB
  7213. /* helper */
  7214. /* Set handlers to restore tty pgrp and exit */
  7215. static void install_fatal_sighandlers(void)
  7216. {
  7217. unsigned mask;
  7218. /* We will restore tty pgrp on these signals */
  7219. mask = 0
  7220. + (1 << SIGILL ) * HUSH_DEBUG
  7221. + (1 << SIGFPE ) * HUSH_DEBUG
  7222. + (1 << SIGBUS ) * HUSH_DEBUG
  7223. + (1 << SIGSEGV) * HUSH_DEBUG
  7224. + (1 << SIGTRAP) * HUSH_DEBUG
  7225. + (1 << SIGABRT)
  7226. /* bash 3.2 seems to handle these just like 'fatal' ones */
  7227. + (1 << SIGPIPE)
  7228. + (1 << SIGALRM)
  7229. /* if we are interactive, SIGHUP, SIGTERM and SIGINT are special sigs.
  7230. * if we aren't interactive... but in this case
  7231. * we never want to restore pgrp on exit, and this fn is not called
  7232. */
  7233. /*+ (1 << SIGHUP )*/
  7234. /*+ (1 << SIGTERM)*/
  7235. /*+ (1 << SIGINT )*/
  7236. ;
  7237. G_fatal_sig_mask = mask;
  7238. install_sighandlers(mask);
  7239. }
  7240. #endif
  7241. static int set_mode(int state, char mode, const char *o_opt)
  7242. {
  7243. int idx;
  7244. switch (mode) {
  7245. case 'n':
  7246. G.o_opt[OPT_O_NOEXEC] = state;
  7247. break;
  7248. case 'x':
  7249. IF_HUSH_MODE_X(G_x_mode = state;)
  7250. break;
  7251. case 'o':
  7252. if (!o_opt) {
  7253. /* "set -+o" without parameter.
  7254. * in bash, set -o produces this output:
  7255. * pipefail off
  7256. * and set +o:
  7257. * set +o pipefail
  7258. * We always use the second form.
  7259. */
  7260. const char *p = o_opt_strings;
  7261. idx = 0;
  7262. while (*p) {
  7263. printf("set %co %s\n", (G.o_opt[idx] ? '-' : '+'), p);
  7264. idx++;
  7265. p += strlen(p) + 1;
  7266. }
  7267. break;
  7268. }
  7269. idx = index_in_strings(o_opt_strings, o_opt);
  7270. if (idx >= 0) {
  7271. G.o_opt[idx] = state;
  7272. break;
  7273. }
  7274. default:
  7275. return EXIT_FAILURE;
  7276. }
  7277. return EXIT_SUCCESS;
  7278. }
  7279. int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  7280. int hush_main(int argc, char **argv)
  7281. {
  7282. enum {
  7283. OPT_login = (1 << 0),
  7284. };
  7285. unsigned flags;
  7286. int opt;
  7287. unsigned builtin_argc;
  7288. char **e;
  7289. struct variable *cur_var;
  7290. struct variable *shell_ver;
  7291. INIT_G();
  7292. if (EXIT_SUCCESS != 0) /* if EXIT_SUCCESS == 0, it is already done */
  7293. G.last_exitcode = EXIT_SUCCESS;
  7294. #if ENABLE_HUSH_FAST
  7295. G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
  7296. #endif
  7297. #if !BB_MMU
  7298. G.argv0_for_re_execing = argv[0];
  7299. #endif
  7300. /* Deal with HUSH_VERSION */
  7301. shell_ver = xzalloc(sizeof(*shell_ver));
  7302. shell_ver->flg_export = 1;
  7303. shell_ver->flg_read_only = 1;
  7304. /* Code which handles ${var<op>...} needs writable values for all variables,
  7305. * therefore we xstrdup: */
  7306. shell_ver->varstr = xstrdup(hush_version_str);
  7307. /* Create shell local variables from the values
  7308. * currently living in the environment */
  7309. debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
  7310. unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
  7311. G.top_var = shell_ver;
  7312. cur_var = G.top_var;
  7313. e = environ;
  7314. if (e) while (*e) {
  7315. char *value = strchr(*e, '=');
  7316. if (value) { /* paranoia */
  7317. cur_var->next = xzalloc(sizeof(*cur_var));
  7318. cur_var = cur_var->next;
  7319. cur_var->varstr = *e;
  7320. cur_var->max_len = strlen(*e);
  7321. cur_var->flg_export = 1;
  7322. }
  7323. e++;
  7324. }
  7325. /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
  7326. debug_printf_env("putenv '%s'\n", shell_ver->varstr);
  7327. putenv(shell_ver->varstr);
  7328. /* Export PWD */
  7329. set_pwd_var(/*exp:*/ 1);
  7330. #if ENABLE_HUSH_BASH_COMPAT
  7331. /* Set (but not export) HOSTNAME unless already set */
  7332. if (!get_local_var_value("HOSTNAME")) {
  7333. struct utsname uts;
  7334. uname(&uts);
  7335. set_local_var_from_halves("HOSTNAME", uts.nodename);
  7336. }
  7337. /* bash also exports SHLVL and _,
  7338. * and sets (but doesn't export) the following variables:
  7339. * BASH=/bin/bash
  7340. * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
  7341. * BASH_VERSION='3.2.0(1)-release'
  7342. * HOSTTYPE=i386
  7343. * MACHTYPE=i386-pc-linux-gnu
  7344. * OSTYPE=linux-gnu
  7345. * PPID=<NNNNN> - we also do it elsewhere
  7346. * EUID=<NNNNN>
  7347. * UID=<NNNNN>
  7348. * GROUPS=()
  7349. * LINES=<NNN>
  7350. * COLUMNS=<NNN>
  7351. * BASH_ARGC=()
  7352. * BASH_ARGV=()
  7353. * BASH_LINENO=()
  7354. * BASH_SOURCE=()
  7355. * DIRSTACK=()
  7356. * PIPESTATUS=([0]="0")
  7357. * HISTFILE=/<xxx>/.bash_history
  7358. * HISTFILESIZE=500
  7359. * HISTSIZE=500
  7360. * MAILCHECK=60
  7361. * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
  7362. * SHELL=/bin/bash
  7363. * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
  7364. * TERM=dumb
  7365. * OPTERR=1
  7366. * OPTIND=1
  7367. * IFS=$' \t\n'
  7368. * PS1='\s-\v\$ '
  7369. * PS2='> '
  7370. * PS4='+ '
  7371. */
  7372. #endif
  7373. #if ENABLE_FEATURE_EDITING
  7374. G.line_input_state = new_line_input_t(FOR_SHELL);
  7375. #endif
  7376. /* Initialize some more globals to non-zero values */
  7377. cmdedit_update_prompt();
  7378. die_func = restore_ttypgrp_and__exit;
  7379. /* Shell is non-interactive at first. We need to call
  7380. * install_special_sighandlers() if we are going to execute "sh <script>",
  7381. * "sh -c <cmds>" or login shell's /etc/profile and friends.
  7382. * If we later decide that we are interactive, we run install_special_sighandlers()
  7383. * in order to intercept (more) signals.
  7384. */
  7385. /* Parse options */
  7386. /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
  7387. flags = (argv[0] && argv[0][0] == '-') ? OPT_login : 0;
  7388. builtin_argc = 0;
  7389. while (1) {
  7390. opt = getopt(argc, argv, "+c:xinsl"
  7391. #if !BB_MMU
  7392. "<:$:R:V:"
  7393. # if ENABLE_HUSH_FUNCTIONS
  7394. "F:"
  7395. # endif
  7396. #endif
  7397. );
  7398. if (opt <= 0)
  7399. break;
  7400. switch (opt) {
  7401. case 'c':
  7402. /* Possibilities:
  7403. * sh ... -c 'script'
  7404. * sh ... -c 'script' ARG0 [ARG1...]
  7405. * On NOMMU, if builtin_argc != 0,
  7406. * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
  7407. * "" needs to be replaced with NULL
  7408. * and BARGV vector fed to builtin function.
  7409. * Note: the form without ARG0 never happens:
  7410. * sh ... -c 'builtin' BARGV... ""
  7411. */
  7412. if (!G.root_pid) {
  7413. G.root_pid = getpid();
  7414. G.root_ppid = getppid();
  7415. }
  7416. G.global_argv = argv + optind;
  7417. G.global_argc = argc - optind;
  7418. if (builtin_argc) {
  7419. /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
  7420. const struct built_in_command *x;
  7421. install_special_sighandlers();
  7422. x = find_builtin(optarg);
  7423. if (x) { /* paranoia */
  7424. G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
  7425. G.global_argv += builtin_argc;
  7426. G.global_argv[-1] = NULL; /* replace "" */
  7427. fflush_all();
  7428. G.last_exitcode = x->b_function(argv + optind - 1);
  7429. }
  7430. goto final_return;
  7431. }
  7432. if (!G.global_argv[0]) {
  7433. /* -c 'script' (no params): prevent empty $0 */
  7434. G.global_argv--; /* points to argv[i] of 'script' */
  7435. G.global_argv[0] = argv[0];
  7436. G.global_argc++;
  7437. } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
  7438. install_special_sighandlers();
  7439. parse_and_run_string(optarg);
  7440. goto final_return;
  7441. case 'i':
  7442. /* Well, we cannot just declare interactiveness,
  7443. * we have to have some stuff (ctty, etc) */
  7444. /* G_interactive_fd++; */
  7445. break;
  7446. case 's':
  7447. /* "-s" means "read from stdin", but this is how we always
  7448. * operate, so simply do nothing here. */
  7449. break;
  7450. case 'l':
  7451. flags |= OPT_login;
  7452. break;
  7453. #if !BB_MMU
  7454. case '<': /* "big heredoc" support */
  7455. full_write1_str(optarg);
  7456. _exit(0);
  7457. case '$': {
  7458. unsigned long long empty_trap_mask;
  7459. G.root_pid = bb_strtou(optarg, &optarg, 16);
  7460. optarg++;
  7461. G.root_ppid = bb_strtou(optarg, &optarg, 16);
  7462. optarg++;
  7463. G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
  7464. optarg++;
  7465. G.last_exitcode = bb_strtou(optarg, &optarg, 16);
  7466. optarg++;
  7467. builtin_argc = bb_strtou(optarg, &optarg, 16);
  7468. optarg++;
  7469. empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
  7470. if (empty_trap_mask != 0) {
  7471. int sig;
  7472. install_special_sighandlers();
  7473. G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
  7474. for (sig = 1; sig < NSIG; sig++) {
  7475. if (empty_trap_mask & (1LL << sig)) {
  7476. G.traps[sig] = xzalloc(1); /* == xstrdup(""); */
  7477. install_sighandler(sig, SIG_IGN);
  7478. }
  7479. }
  7480. }
  7481. # if ENABLE_HUSH_LOOPS
  7482. optarg++;
  7483. G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
  7484. # endif
  7485. break;
  7486. }
  7487. case 'R':
  7488. case 'V':
  7489. set_local_var(xstrdup(optarg), /*exp:*/ 0, /*lvl:*/ 0, /*ro:*/ opt == 'R');
  7490. break;
  7491. # if ENABLE_HUSH_FUNCTIONS
  7492. case 'F': {
  7493. struct function *funcp = new_function(optarg);
  7494. /* funcp->name is already set to optarg */
  7495. /* funcp->body is set to NULL. It's a special case. */
  7496. funcp->body_as_string = argv[optind];
  7497. optind++;
  7498. break;
  7499. }
  7500. # endif
  7501. #endif
  7502. case 'n':
  7503. case 'x':
  7504. if (set_mode(1, opt, NULL) == 0) /* no error */
  7505. break;
  7506. default:
  7507. #ifndef BB_VER
  7508. fprintf(stderr, "Usage: sh [FILE]...\n"
  7509. " or: sh -c command [args]...\n\n");
  7510. exit(EXIT_FAILURE);
  7511. #else
  7512. bb_show_usage();
  7513. #endif
  7514. }
  7515. } /* option parsing loop */
  7516. /* Skip options. Try "hush -l": $1 should not be "-l"! */
  7517. G.global_argc = argc - (optind - 1);
  7518. G.global_argv = argv + (optind - 1);
  7519. G.global_argv[0] = argv[0];
  7520. if (!G.root_pid) {
  7521. G.root_pid = getpid();
  7522. G.root_ppid = getppid();
  7523. }
  7524. /* If we are login shell... */
  7525. if (flags & OPT_login) {
  7526. FILE *input;
  7527. debug_printf("sourcing /etc/profile\n");
  7528. input = fopen_for_read("/etc/profile");
  7529. if (input != NULL) {
  7530. close_on_exec_on(fileno(input));
  7531. install_special_sighandlers();
  7532. parse_and_run_file(input);
  7533. fclose(input);
  7534. }
  7535. /* bash: after sourcing /etc/profile,
  7536. * tries to source (in the given order):
  7537. * ~/.bash_profile, ~/.bash_login, ~/.profile,
  7538. * stopping on first found. --noprofile turns this off.
  7539. * bash also sources ~/.bash_logout on exit.
  7540. * If called as sh, skips .bash_XXX files.
  7541. */
  7542. }
  7543. if (G.global_argv[1]) {
  7544. FILE *input;
  7545. /*
  7546. * "bash <script>" (which is never interactive (unless -i?))
  7547. * sources $BASH_ENV here (without scanning $PATH).
  7548. * If called as sh, does the same but with $ENV.
  7549. */
  7550. G.global_argc--;
  7551. G.global_argv++;
  7552. debug_printf("running script '%s'\n", G.global_argv[0]);
  7553. input = xfopen_for_read(G.global_argv[0]);
  7554. close_on_exec_on(fileno(input));
  7555. install_special_sighandlers();
  7556. parse_and_run_file(input);
  7557. #if ENABLE_FEATURE_CLEAN_UP
  7558. fclose(input);
  7559. #endif
  7560. goto final_return;
  7561. }
  7562. /* Up to here, shell was non-interactive. Now it may become one.
  7563. * NB: don't forget to (re)run install_special_sighandlers() as needed.
  7564. */
  7565. /* A shell is interactive if the '-i' flag was given,
  7566. * or if all of the following conditions are met:
  7567. * no -c command
  7568. * no arguments remaining or the -s flag given
  7569. * standard input is a terminal
  7570. * standard output is a terminal
  7571. * Refer to Posix.2, the description of the 'sh' utility.
  7572. */
  7573. #if ENABLE_HUSH_JOB
  7574. if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
  7575. G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
  7576. debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
  7577. if (G_saved_tty_pgrp < 0)
  7578. G_saved_tty_pgrp = 0;
  7579. /* try to dup stdin to high fd#, >= 255 */
  7580. G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
  7581. if (G_interactive_fd < 0) {
  7582. /* try to dup to any fd */
  7583. G_interactive_fd = dup(STDIN_FILENO);
  7584. if (G_interactive_fd < 0) {
  7585. /* give up */
  7586. G_interactive_fd = 0;
  7587. G_saved_tty_pgrp = 0;
  7588. }
  7589. }
  7590. // TODO: track & disallow any attempts of user
  7591. // to (inadvertently) close/redirect G_interactive_fd
  7592. }
  7593. debug_printf("interactive_fd:%d\n", G_interactive_fd);
  7594. if (G_interactive_fd) {
  7595. close_on_exec_on(G_interactive_fd);
  7596. if (G_saved_tty_pgrp) {
  7597. /* If we were run as 'hush &', sleep until we are
  7598. * in the foreground (tty pgrp == our pgrp).
  7599. * If we get started under a job aware app (like bash),
  7600. * make sure we are now in charge so we don't fight over
  7601. * who gets the foreground */
  7602. while (1) {
  7603. pid_t shell_pgrp = getpgrp();
  7604. G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
  7605. if (G_saved_tty_pgrp == shell_pgrp)
  7606. break;
  7607. /* send TTIN to ourself (should stop us) */
  7608. kill(- shell_pgrp, SIGTTIN);
  7609. }
  7610. }
  7611. /* Install more signal handlers */
  7612. install_special_sighandlers();
  7613. if (G_saved_tty_pgrp) {
  7614. /* Set other signals to restore saved_tty_pgrp */
  7615. install_fatal_sighandlers();
  7616. /* Put ourselves in our own process group
  7617. * (bash, too, does this only if ctty is available) */
  7618. bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
  7619. /* Grab control of the terminal */
  7620. tcsetpgrp(G_interactive_fd, getpid());
  7621. }
  7622. enable_restore_tty_pgrp_on_exit();
  7623. # if ENABLE_HUSH_SAVEHISTORY && MAX_HISTORY > 0
  7624. {
  7625. const char *hp = get_local_var_value("HISTFILE");
  7626. if (!hp) {
  7627. hp = get_local_var_value("HOME");
  7628. if (hp)
  7629. hp = concat_path_file(hp, ".hush_history");
  7630. } else {
  7631. hp = xstrdup(hp);
  7632. }
  7633. if (hp) {
  7634. G.line_input_state->hist_file = hp;
  7635. //set_local_var(xasprintf("HISTFILE=%s", ...));
  7636. }
  7637. # if ENABLE_FEATURE_SH_HISTFILESIZE
  7638. hp = get_local_var_value("HISTFILESIZE");
  7639. G.line_input_state->max_history = size_from_HISTFILESIZE(hp);
  7640. # endif
  7641. }
  7642. # endif
  7643. } else {
  7644. install_special_sighandlers();
  7645. }
  7646. #elif ENABLE_HUSH_INTERACTIVE
  7647. /* No job control compiled in, only prompt/line editing */
  7648. if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
  7649. G_interactive_fd = fcntl(STDIN_FILENO, F_DUPFD, 255);
  7650. if (G_interactive_fd < 0) {
  7651. /* try to dup to any fd */
  7652. G_interactive_fd = dup(STDIN_FILENO);
  7653. if (G_interactive_fd < 0)
  7654. /* give up */
  7655. G_interactive_fd = 0;
  7656. }
  7657. }
  7658. if (G_interactive_fd) {
  7659. close_on_exec_on(G_interactive_fd);
  7660. }
  7661. install_special_sighandlers();
  7662. #else
  7663. /* We have interactiveness code disabled */
  7664. install_special_sighandlers();
  7665. #endif
  7666. /* bash:
  7667. * if interactive but not a login shell, sources ~/.bashrc
  7668. * (--norc turns this off, --rcfile <file> overrides)
  7669. */
  7670. if (!ENABLE_FEATURE_SH_EXTRA_QUIET && G_interactive_fd) {
  7671. /* note: ash and hush share this string */
  7672. printf("\n\n%s %s\n"
  7673. IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
  7674. "\n",
  7675. bb_banner,
  7676. "hush - the humble shell"
  7677. );
  7678. }
  7679. parse_and_run_file(stdin);
  7680. final_return:
  7681. hush_exit(G.last_exitcode);
  7682. }
  7683. #if ENABLE_MSH
  7684. int msh_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  7685. int msh_main(int argc, char **argv)
  7686. {
  7687. //bb_error_msg("msh is deprecated, please use hush instead");
  7688. return hush_main(argc, argv);
  7689. }
  7690. #endif
  7691. /*
  7692. * Built-ins
  7693. */
  7694. static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
  7695. {
  7696. return 0;
  7697. }
  7698. static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
  7699. {
  7700. int argc = 0;
  7701. while (*argv) {
  7702. argc++;
  7703. argv++;
  7704. }
  7705. return applet_main_func(argc, argv - argc);
  7706. }
  7707. static int FAST_FUNC builtin_test(char **argv)
  7708. {
  7709. return run_applet_main(argv, test_main);
  7710. }
  7711. static int FAST_FUNC builtin_echo(char **argv)
  7712. {
  7713. return run_applet_main(argv, echo_main);
  7714. }
  7715. #if ENABLE_PRINTF
  7716. static int FAST_FUNC builtin_printf(char **argv)
  7717. {
  7718. return run_applet_main(argv, printf_main);
  7719. }
  7720. #endif
  7721. static char **skip_dash_dash(char **argv)
  7722. {
  7723. argv++;
  7724. if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
  7725. argv++;
  7726. return argv;
  7727. }
  7728. static int FAST_FUNC builtin_eval(char **argv)
  7729. {
  7730. int rcode = EXIT_SUCCESS;
  7731. argv = skip_dash_dash(argv);
  7732. if (*argv) {
  7733. char *str = expand_strvec_to_string(argv);
  7734. /* bash:
  7735. * eval "echo Hi; done" ("done" is syntax error):
  7736. * "echo Hi" will not execute too.
  7737. */
  7738. parse_and_run_string(str);
  7739. free(str);
  7740. rcode = G.last_exitcode;
  7741. }
  7742. return rcode;
  7743. }
  7744. static int FAST_FUNC builtin_cd(char **argv)
  7745. {
  7746. const char *newdir;
  7747. argv = skip_dash_dash(argv);
  7748. newdir = argv[0];
  7749. if (newdir == NULL) {
  7750. /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
  7751. * bash says "bash: cd: HOME not set" and does nothing
  7752. * (exitcode 1)
  7753. */
  7754. const char *home = get_local_var_value("HOME");
  7755. newdir = home ? home : "/";
  7756. }
  7757. if (chdir(newdir)) {
  7758. /* Mimic bash message exactly */
  7759. bb_perror_msg("cd: %s", newdir);
  7760. return EXIT_FAILURE;
  7761. }
  7762. /* Read current dir (get_cwd(1) is inside) and set PWD.
  7763. * Note: do not enforce exporting. If PWD was unset or unexported,
  7764. * set it again, but do not export. bash does the same.
  7765. */
  7766. set_pwd_var(/*exp:*/ 0);
  7767. return EXIT_SUCCESS;
  7768. }
  7769. static int FAST_FUNC builtin_exec(char **argv)
  7770. {
  7771. argv = skip_dash_dash(argv);
  7772. if (argv[0] == NULL)
  7773. return EXIT_SUCCESS; /* bash does this */
  7774. /* Careful: we can end up here after [v]fork. Do not restore
  7775. * tty pgrp then, only top-level shell process does that */
  7776. if (G_saved_tty_pgrp && getpid() == G.root_pid)
  7777. tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
  7778. /* TODO: if exec fails, bash does NOT exit! We do.
  7779. * We'll need to undo trap cleanup (it's inside execvp_or_die)
  7780. * and tcsetpgrp, and this is inherently racy.
  7781. */
  7782. execvp_or_die(argv);
  7783. }
  7784. static int FAST_FUNC builtin_exit(char **argv)
  7785. {
  7786. debug_printf_exec("%s()\n", __func__);
  7787. /* interactive bash:
  7788. * # trap "echo EEE" EXIT
  7789. * # exit
  7790. * exit
  7791. * There are stopped jobs.
  7792. * (if there are _stopped_ jobs, running ones don't count)
  7793. * # exit
  7794. * exit
  7795. * EEE (then bash exits)
  7796. *
  7797. * TODO: we can use G.exiting = -1 as indicator "last cmd was exit"
  7798. */
  7799. /* note: EXIT trap is run by hush_exit */
  7800. argv = skip_dash_dash(argv);
  7801. if (argv[0] == NULL)
  7802. hush_exit(G.last_exitcode);
  7803. /* mimic bash: exit 123abc == exit 255 + error msg */
  7804. xfunc_error_retval = 255;
  7805. /* bash: exit -2 == exit 254, no error msg */
  7806. hush_exit(xatoi(argv[0]) & 0xff);
  7807. }
  7808. static void print_escaped(const char *s)
  7809. {
  7810. if (*s == '\'')
  7811. goto squote;
  7812. do {
  7813. const char *p = strchrnul(s, '\'');
  7814. /* print 'xxxx', possibly just '' */
  7815. printf("'%.*s'", (int)(p - s), s);
  7816. if (*p == '\0')
  7817. break;
  7818. s = p;
  7819. squote:
  7820. /* s points to '; print "'''...'''" */
  7821. putchar('"');
  7822. do putchar('\''); while (*++s == '\'');
  7823. putchar('"');
  7824. } while (*s);
  7825. }
  7826. #if !ENABLE_HUSH_LOCAL
  7827. #define helper_export_local(argv, exp, lvl) \
  7828. helper_export_local(argv, exp)
  7829. #endif
  7830. static void helper_export_local(char **argv, int exp, int lvl)
  7831. {
  7832. do {
  7833. char *name = *argv;
  7834. char *name_end = strchrnul(name, '=');
  7835. /* So far we do not check that name is valid (TODO?) */
  7836. if (*name_end == '\0') {
  7837. struct variable *var, **vpp;
  7838. vpp = get_ptr_to_local_var(name, name_end - name);
  7839. var = vpp ? *vpp : NULL;
  7840. if (exp == -1) { /* unexporting? */
  7841. /* export -n NAME (without =VALUE) */
  7842. if (var) {
  7843. var->flg_export = 0;
  7844. debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
  7845. unsetenv(name);
  7846. } /* else: export -n NOT_EXISTING_VAR: no-op */
  7847. continue;
  7848. }
  7849. if (exp == 1) { /* exporting? */
  7850. /* export NAME (without =VALUE) */
  7851. if (var) {
  7852. var->flg_export = 1;
  7853. debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
  7854. putenv(var->varstr);
  7855. continue;
  7856. }
  7857. }
  7858. /* Exporting non-existing variable.
  7859. * bash does not put it in environment,
  7860. * but remembers that it is exported,
  7861. * and does put it in env when it is set later.
  7862. * We just set it to "" and export. */
  7863. /* Or, it's "local NAME" (without =VALUE).
  7864. * bash sets the value to "". */
  7865. name = xasprintf("%s=", name);
  7866. } else {
  7867. /* (Un)exporting/making local NAME=VALUE */
  7868. name = xstrdup(name);
  7869. }
  7870. set_local_var(name, /*exp:*/ exp, /*lvl:*/ lvl, /*ro:*/ 0);
  7871. } while (*++argv);
  7872. }
  7873. static int FAST_FUNC builtin_export(char **argv)
  7874. {
  7875. unsigned opt_unexport;
  7876. #if ENABLE_HUSH_EXPORT_N
  7877. /* "!": do not abort on errors */
  7878. opt_unexport = getopt32(argv, "!n");
  7879. if (opt_unexport == (uint32_t)-1)
  7880. return EXIT_FAILURE;
  7881. argv += optind;
  7882. #else
  7883. opt_unexport = 0;
  7884. argv++;
  7885. #endif
  7886. if (argv[0] == NULL) {
  7887. char **e = environ;
  7888. if (e) {
  7889. while (*e) {
  7890. #if 0
  7891. puts(*e++);
  7892. #else
  7893. /* ash emits: export VAR='VAL'
  7894. * bash: declare -x VAR="VAL"
  7895. * we follow ash example */
  7896. const char *s = *e++;
  7897. const char *p = strchr(s, '=');
  7898. if (!p) /* wtf? take next variable */
  7899. continue;
  7900. /* export var= */
  7901. printf("export %.*s", (int)(p - s) + 1, s);
  7902. print_escaped(p + 1);
  7903. putchar('\n');
  7904. #endif
  7905. }
  7906. /*fflush_all(); - done after each builtin anyway */
  7907. }
  7908. return EXIT_SUCCESS;
  7909. }
  7910. helper_export_local(argv, (opt_unexport ? -1 : 1), 0);
  7911. return EXIT_SUCCESS;
  7912. }
  7913. #if ENABLE_HUSH_LOCAL
  7914. static int FAST_FUNC builtin_local(char **argv)
  7915. {
  7916. if (G.func_nest_level == 0) {
  7917. bb_error_msg("%s: not in a function", argv[0]);
  7918. return EXIT_FAILURE; /* bash compat */
  7919. }
  7920. helper_export_local(argv, 0, G.func_nest_level);
  7921. return EXIT_SUCCESS;
  7922. }
  7923. #endif
  7924. static int FAST_FUNC builtin_trap(char **argv)
  7925. {
  7926. int sig;
  7927. char *new_cmd;
  7928. if (!G.traps)
  7929. G.traps = xzalloc(sizeof(G.traps[0]) * NSIG);
  7930. argv++;
  7931. if (!*argv) {
  7932. int i;
  7933. /* No args: print all trapped */
  7934. for (i = 0; i < NSIG; ++i) {
  7935. if (G.traps[i]) {
  7936. printf("trap -- ");
  7937. print_escaped(G.traps[i]);
  7938. /* note: bash adds "SIG", but only if invoked
  7939. * as "bash". If called as "sh", or if set -o posix,
  7940. * then it prints short signal names.
  7941. * We are printing short names: */
  7942. printf(" %s\n", get_signame(i));
  7943. }
  7944. }
  7945. /*fflush_all(); - done after each builtin anyway */
  7946. return EXIT_SUCCESS;
  7947. }
  7948. new_cmd = NULL;
  7949. /* If first arg is a number: reset all specified signals */
  7950. sig = bb_strtou(*argv, NULL, 10);
  7951. if (errno == 0) {
  7952. int ret;
  7953. process_sig_list:
  7954. ret = EXIT_SUCCESS;
  7955. while (*argv) {
  7956. sighandler_t handler;
  7957. sig = get_signum(*argv++);
  7958. if (sig < 0 || sig >= NSIG) {
  7959. ret = EXIT_FAILURE;
  7960. /* Mimic bash message exactly */
  7961. bb_perror_msg("trap: %s: invalid signal specification", argv[-1]);
  7962. continue;
  7963. }
  7964. free(G.traps[sig]);
  7965. G.traps[sig] = xstrdup(new_cmd);
  7966. debug_printf("trap: setting SIG%s (%i) to '%s'\n",
  7967. get_signame(sig), sig, G.traps[sig]);
  7968. /* There is no signal for 0 (EXIT) */
  7969. if (sig == 0)
  7970. continue;
  7971. if (new_cmd)
  7972. handler = (new_cmd[0] ? record_pending_signo : SIG_IGN);
  7973. else
  7974. /* We are removing trap handler */
  7975. handler = pick_sighandler(sig);
  7976. install_sighandler(sig, handler);
  7977. }
  7978. return ret;
  7979. }
  7980. if (!argv[1]) { /* no second arg */
  7981. bb_error_msg("trap: invalid arguments");
  7982. return EXIT_FAILURE;
  7983. }
  7984. /* First arg is "-": reset all specified to default */
  7985. /* First arg is "--": skip it, the rest is "handler SIGs..." */
  7986. /* Everything else: set arg as signal handler
  7987. * (includes "" case, which ignores signal) */
  7988. if (argv[0][0] == '-') {
  7989. if (argv[0][1] == '\0') { /* "-" */
  7990. /* new_cmd remains NULL: "reset these sigs" */
  7991. goto reset_traps;
  7992. }
  7993. if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
  7994. argv++;
  7995. }
  7996. /* else: "-something", no special meaning */
  7997. }
  7998. new_cmd = *argv;
  7999. reset_traps:
  8000. argv++;
  8001. goto process_sig_list;
  8002. }
  8003. /* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
  8004. static int FAST_FUNC builtin_type(char **argv)
  8005. {
  8006. int ret = EXIT_SUCCESS;
  8007. while (*++argv) {
  8008. const char *type;
  8009. char *path = NULL;
  8010. if (0) {} /* make conditional compile easier below */
  8011. /*else if (find_alias(*argv))
  8012. type = "an alias";*/
  8013. #if ENABLE_HUSH_FUNCTIONS
  8014. else if (find_function(*argv))
  8015. type = "a function";
  8016. #endif
  8017. else if (find_builtin(*argv))
  8018. type = "a shell builtin";
  8019. else if ((path = find_in_path(*argv)) != NULL)
  8020. type = path;
  8021. else {
  8022. bb_error_msg("type: %s: not found", *argv);
  8023. ret = EXIT_FAILURE;
  8024. continue;
  8025. }
  8026. printf("%s is %s\n", *argv, type);
  8027. free(path);
  8028. }
  8029. return ret;
  8030. }
  8031. #if ENABLE_HUSH_JOB
  8032. /* built-in 'fg' and 'bg' handler */
  8033. static int FAST_FUNC builtin_fg_bg(char **argv)
  8034. {
  8035. int i, jobnum;
  8036. struct pipe *pi;
  8037. if (!G_interactive_fd)
  8038. return EXIT_FAILURE;
  8039. /* If they gave us no args, assume they want the last backgrounded task */
  8040. if (!argv[1]) {
  8041. for (pi = G.job_list; pi; pi = pi->next) {
  8042. if (pi->jobid == G.last_jobid) {
  8043. goto found;
  8044. }
  8045. }
  8046. bb_error_msg("%s: no current job", argv[0]);
  8047. return EXIT_FAILURE;
  8048. }
  8049. if (sscanf(argv[1], "%%%d", &jobnum) != 1) {
  8050. bb_error_msg("%s: bad argument '%s'", argv[0], argv[1]);
  8051. return EXIT_FAILURE;
  8052. }
  8053. for (pi = G.job_list; pi; pi = pi->next) {
  8054. if (pi->jobid == jobnum) {
  8055. goto found;
  8056. }
  8057. }
  8058. bb_error_msg("%s: %d: no such job", argv[0], jobnum);
  8059. return EXIT_FAILURE;
  8060. found:
  8061. /* TODO: bash prints a string representation
  8062. * of job being foregrounded (like "sleep 1 | cat") */
  8063. if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
  8064. /* Put the job into the foreground. */
  8065. tcsetpgrp(G_interactive_fd, pi->pgrp);
  8066. }
  8067. /* Restart the processes in the job */
  8068. debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
  8069. for (i = 0; i < pi->num_cmds; i++) {
  8070. debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
  8071. }
  8072. pi->stopped_cmds = 0;
  8073. i = kill(- pi->pgrp, SIGCONT);
  8074. if (i < 0) {
  8075. if (errno == ESRCH) {
  8076. delete_finished_bg_job(pi);
  8077. return EXIT_SUCCESS;
  8078. }
  8079. bb_perror_msg("kill (SIGCONT)");
  8080. }
  8081. if (argv[0][0] == 'f') {
  8082. remove_bg_job(pi);
  8083. return checkjobs_and_fg_shell(pi);
  8084. }
  8085. return EXIT_SUCCESS;
  8086. }
  8087. #endif
  8088. #if ENABLE_HUSH_HELP
  8089. static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
  8090. {
  8091. const struct built_in_command *x;
  8092. printf(
  8093. "Built-in commands:\n"
  8094. "------------------\n");
  8095. for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
  8096. if (x->b_descr)
  8097. printf("%-10s%s\n", x->b_cmd, x->b_descr);
  8098. }
  8099. bb_putchar('\n');
  8100. return EXIT_SUCCESS;
  8101. }
  8102. #endif
  8103. #if MAX_HISTORY && ENABLE_FEATURE_EDITING
  8104. static int FAST_FUNC builtin_history(char **argv UNUSED_PARAM)
  8105. {
  8106. show_history(G.line_input_state);
  8107. return EXIT_SUCCESS;
  8108. }
  8109. #endif
  8110. #if ENABLE_HUSH_JOB
  8111. static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
  8112. {
  8113. struct pipe *job;
  8114. const char *status_string;
  8115. for (job = G.job_list; job; job = job->next) {
  8116. if (job->alive_cmds == job->stopped_cmds)
  8117. status_string = "Stopped";
  8118. else
  8119. status_string = "Running";
  8120. printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
  8121. }
  8122. return EXIT_SUCCESS;
  8123. }
  8124. #endif
  8125. #if HUSH_DEBUG
  8126. static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
  8127. {
  8128. void *p;
  8129. unsigned long l;
  8130. # ifdef M_TRIM_THRESHOLD
  8131. /* Optional. Reduces probability of false positives */
  8132. malloc_trim(0);
  8133. # endif
  8134. /* Crude attempt to find where "free memory" starts,
  8135. * sans fragmentation. */
  8136. p = malloc(240);
  8137. l = (unsigned long)p;
  8138. free(p);
  8139. p = malloc(3400);
  8140. if (l < (unsigned long)p) l = (unsigned long)p;
  8141. free(p);
  8142. if (!G.memleak_value)
  8143. G.memleak_value = l;
  8144. l -= G.memleak_value;
  8145. if ((long)l < 0)
  8146. l = 0;
  8147. l /= 1024;
  8148. if (l > 127)
  8149. l = 127;
  8150. /* Exitcode is "how many kilobytes we leaked since 1st call" */
  8151. return l;
  8152. }
  8153. #endif
  8154. static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
  8155. {
  8156. puts(get_cwd(0));
  8157. return EXIT_SUCCESS;
  8158. }
  8159. /* Interruptibility of read builtin in bash
  8160. * (tested on bash-4.2.8 by sending signals (not by ^C)):
  8161. *
  8162. * Empty trap makes read ignore corresponding signal, for any signal.
  8163. *
  8164. * SIGINT:
  8165. * - terminates non-interactive shell;
  8166. * - interrupts read in interactive shell;
  8167. * if it has non-empty trap:
  8168. * - executes trap and returns to command prompt in interactive shell;
  8169. * - executes trap and returns to read in non-interactive shell;
  8170. * SIGTERM:
  8171. * - is ignored (does not interrupt) read in interactive shell;
  8172. * - terminates non-interactive shell;
  8173. * if it has non-empty trap:
  8174. * - executes trap and returns to read;
  8175. * SIGHUP:
  8176. * - terminates shell (regardless of interactivity);
  8177. * if it has non-empty trap:
  8178. * - executes trap and returns to read;
  8179. */
  8180. static int FAST_FUNC builtin_read(char **argv)
  8181. {
  8182. const char *r;
  8183. char *opt_n = NULL;
  8184. char *opt_p = NULL;
  8185. char *opt_t = NULL;
  8186. char *opt_u = NULL;
  8187. const char *ifs;
  8188. int read_flags;
  8189. /* "!": do not abort on errors.
  8190. * Option string must start with "sr" to match BUILTIN_READ_xxx
  8191. */
  8192. read_flags = getopt32(argv, "!srn:p:t:u:", &opt_n, &opt_p, &opt_t, &opt_u);
  8193. if (read_flags == (uint32_t)-1)
  8194. return EXIT_FAILURE;
  8195. argv += optind;
  8196. ifs = get_local_var_value("IFS"); /* can be NULL */
  8197. again:
  8198. r = shell_builtin_read(set_local_var_from_halves,
  8199. argv,
  8200. ifs,
  8201. read_flags,
  8202. opt_n,
  8203. opt_p,
  8204. opt_t,
  8205. opt_u
  8206. );
  8207. if ((uintptr_t)r == 1 && errno == EINTR) {
  8208. unsigned sig = check_and_run_traps();
  8209. if (sig && sig != SIGINT)
  8210. goto again;
  8211. }
  8212. if ((uintptr_t)r > 1) {
  8213. bb_error_msg("%s", r);
  8214. r = (char*)(uintptr_t)1;
  8215. }
  8216. return (uintptr_t)r;
  8217. }
  8218. /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
  8219. * built-in 'set' handler
  8220. * SUSv3 says:
  8221. * set [-abCefhmnuvx] [-o option] [argument...]
  8222. * set [+abCefhmnuvx] [+o option] [argument...]
  8223. * set -- [argument...]
  8224. * set -o
  8225. * set +o
  8226. * Implementations shall support the options in both their hyphen and
  8227. * plus-sign forms. These options can also be specified as options to sh.
  8228. * Examples:
  8229. * Write out all variables and their values: set
  8230. * Set $1, $2, and $3 and set "$#" to 3: set c a b
  8231. * Turn on the -x and -v options: set -xv
  8232. * Unset all positional parameters: set --
  8233. * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
  8234. * Set the positional parameters to the expansion of x, even if x expands
  8235. * with a leading '-' or '+': set -- $x
  8236. *
  8237. * So far, we only support "set -- [argument...]" and some of the short names.
  8238. */
  8239. static int FAST_FUNC builtin_set(char **argv)
  8240. {
  8241. int n;
  8242. char **pp, **g_argv;
  8243. char *arg = *++argv;
  8244. if (arg == NULL) {
  8245. struct variable *e;
  8246. for (e = G.top_var; e; e = e->next)
  8247. puts(e->varstr);
  8248. return EXIT_SUCCESS;
  8249. }
  8250. do {
  8251. if (strcmp(arg, "--") == 0) {
  8252. ++argv;
  8253. goto set_argv;
  8254. }
  8255. if (arg[0] != '+' && arg[0] != '-')
  8256. break;
  8257. for (n = 1; arg[n]; ++n) {
  8258. if (set_mode((arg[0] == '-'), arg[n], argv[1]))
  8259. goto error;
  8260. if (arg[n] == 'o' && argv[1])
  8261. argv++;
  8262. }
  8263. } while ((arg = *++argv) != NULL);
  8264. /* Now argv[0] is 1st argument */
  8265. if (arg == NULL)
  8266. return EXIT_SUCCESS;
  8267. set_argv:
  8268. /* NB: G.global_argv[0] ($0) is never freed/changed */
  8269. g_argv = G.global_argv;
  8270. if (G.global_args_malloced) {
  8271. pp = g_argv;
  8272. while (*++pp)
  8273. free(*pp);
  8274. g_argv[1] = NULL;
  8275. } else {
  8276. G.global_args_malloced = 1;
  8277. pp = xzalloc(sizeof(pp[0]) * 2);
  8278. pp[0] = g_argv[0]; /* retain $0 */
  8279. g_argv = pp;
  8280. }
  8281. /* This realloc's G.global_argv */
  8282. G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
  8283. n = 1;
  8284. while (*++pp)
  8285. n++;
  8286. G.global_argc = n;
  8287. return EXIT_SUCCESS;
  8288. /* Nothing known, so abort */
  8289. error:
  8290. bb_error_msg("set: %s: invalid option", arg);
  8291. return EXIT_FAILURE;
  8292. }
  8293. static int FAST_FUNC builtin_shift(char **argv)
  8294. {
  8295. int n = 1;
  8296. argv = skip_dash_dash(argv);
  8297. if (argv[0]) {
  8298. n = atoi(argv[0]);
  8299. }
  8300. if (n >= 0 && n < G.global_argc) {
  8301. if (G.global_args_malloced) {
  8302. int m = 1;
  8303. while (m <= n)
  8304. free(G.global_argv[m++]);
  8305. }
  8306. G.global_argc -= n;
  8307. memmove(&G.global_argv[1], &G.global_argv[n+1],
  8308. G.global_argc * sizeof(G.global_argv[0]));
  8309. return EXIT_SUCCESS;
  8310. }
  8311. return EXIT_FAILURE;
  8312. }
  8313. static int FAST_FUNC builtin_source(char **argv)
  8314. {
  8315. char *arg_path, *filename;
  8316. FILE *input;
  8317. save_arg_t sv;
  8318. #if ENABLE_HUSH_FUNCTIONS
  8319. smallint sv_flg;
  8320. #endif
  8321. argv = skip_dash_dash(argv);
  8322. filename = argv[0];
  8323. if (!filename) {
  8324. /* bash says: "bash: .: filename argument required" */
  8325. return 2; /* bash compat */
  8326. }
  8327. arg_path = NULL;
  8328. if (!strchr(filename, '/')) {
  8329. arg_path = find_in_path(filename);
  8330. if (arg_path)
  8331. filename = arg_path;
  8332. }
  8333. input = fopen_or_warn(filename, "r");
  8334. free(arg_path);
  8335. if (!input) {
  8336. /* bb_perror_msg("%s", *argv); - done by fopen_or_warn */
  8337. /* POSIX: non-interactive shell should abort here,
  8338. * not merely fail. So far no one complained :)
  8339. */
  8340. return EXIT_FAILURE;
  8341. }
  8342. close_on_exec_on(fileno(input));
  8343. #if ENABLE_HUSH_FUNCTIONS
  8344. sv_flg = G.flag_return_in_progress;
  8345. /* "we are inside sourced file, ok to use return" */
  8346. G.flag_return_in_progress = -1;
  8347. #endif
  8348. if (argv[1])
  8349. save_and_replace_G_args(&sv, argv);
  8350. parse_and_run_file(input);
  8351. fclose(input);
  8352. if (argv[1])
  8353. restore_G_args(&sv, argv);
  8354. #if ENABLE_HUSH_FUNCTIONS
  8355. G.flag_return_in_progress = sv_flg;
  8356. #endif
  8357. return G.last_exitcode;
  8358. }
  8359. static int FAST_FUNC builtin_umask(char **argv)
  8360. {
  8361. int rc;
  8362. mode_t mask;
  8363. rc = 1;
  8364. mask = umask(0);
  8365. argv = skip_dash_dash(argv);
  8366. if (argv[0]) {
  8367. mode_t old_mask = mask;
  8368. /* numeric umasks are taken as-is */
  8369. /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
  8370. if (!isdigit(argv[0][0]))
  8371. mask ^= 0777;
  8372. mask = bb_parse_mode(argv[0], mask);
  8373. if (!isdigit(argv[0][0]))
  8374. mask ^= 0777;
  8375. if ((unsigned)mask > 0777) {
  8376. mask = old_mask;
  8377. /* bash messages:
  8378. * bash: umask: 'q': invalid symbolic mode operator
  8379. * bash: umask: 999: octal number out of range
  8380. */
  8381. bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
  8382. rc = 0;
  8383. }
  8384. } else {
  8385. /* Mimic bash */
  8386. printf("%04o\n", (unsigned) mask);
  8387. /* fall through and restore mask which we set to 0 */
  8388. }
  8389. umask(mask);
  8390. return !rc; /* rc != 0 - success */
  8391. }
  8392. /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
  8393. static int FAST_FUNC builtin_unset(char **argv)
  8394. {
  8395. int ret;
  8396. unsigned opts;
  8397. /* "!": do not abort on errors */
  8398. /* "+": stop at 1st non-option */
  8399. opts = getopt32(argv, "!+vf");
  8400. if (opts == (unsigned)-1)
  8401. return EXIT_FAILURE;
  8402. if (opts == 3) {
  8403. bb_error_msg("unset: -v and -f are exclusive");
  8404. return EXIT_FAILURE;
  8405. }
  8406. argv += optind;
  8407. ret = EXIT_SUCCESS;
  8408. while (*argv) {
  8409. if (!(opts & 2)) { /* not -f */
  8410. if (unset_local_var(*argv)) {
  8411. /* unset <nonexistent_var> doesn't fail.
  8412. * Error is when one tries to unset RO var.
  8413. * Message was printed by unset_local_var. */
  8414. ret = EXIT_FAILURE;
  8415. }
  8416. }
  8417. #if ENABLE_HUSH_FUNCTIONS
  8418. else {
  8419. unset_func(*argv);
  8420. }
  8421. #endif
  8422. argv++;
  8423. }
  8424. return ret;
  8425. }
  8426. /* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
  8427. static int FAST_FUNC builtin_wait(char **argv)
  8428. {
  8429. int ret = EXIT_SUCCESS;
  8430. int status;
  8431. argv = skip_dash_dash(argv);
  8432. if (argv[0] == NULL) {
  8433. /* Don't care about wait results */
  8434. /* Note 1: must wait until there are no more children */
  8435. /* Note 2: must be interruptible */
  8436. /* Examples:
  8437. * $ sleep 3 & sleep 6 & wait
  8438. * [1] 30934 sleep 3
  8439. * [2] 30935 sleep 6
  8440. * [1] Done sleep 3
  8441. * [2] Done sleep 6
  8442. * $ sleep 3 & sleep 6 & wait
  8443. * [1] 30936 sleep 3
  8444. * [2] 30937 sleep 6
  8445. * [1] Done sleep 3
  8446. * ^C <-- after ~4 sec from keyboard
  8447. * $
  8448. */
  8449. while (1) {
  8450. int sig;
  8451. sigset_t oldset, allsigs;
  8452. /* waitpid is not interruptible by SA_RESTARTed
  8453. * signals which we use. Thus, this ugly dance:
  8454. */
  8455. /* Make sure possible SIGCHLD is stored in kernel's
  8456. * pending signal mask before we call waitpid.
  8457. * Or else we may race with SIGCHLD, lose it,
  8458. * and get stuck in sigwaitinfo...
  8459. */
  8460. sigfillset(&allsigs);
  8461. sigprocmask(SIG_SETMASK, &allsigs, &oldset);
  8462. if (!sigisemptyset(&G.pending_set)) {
  8463. /* Crap! we raced with some signal! */
  8464. // sig = 0;
  8465. goto restore;
  8466. }
  8467. checkjobs(NULL); /* waitpid(WNOHANG) inside */
  8468. if (errno == ECHILD) {
  8469. sigprocmask(SIG_SETMASK, &oldset, NULL);
  8470. break;
  8471. }
  8472. /* Wait for SIGCHLD or any other signal */
  8473. //sig = sigwaitinfo(&allsigs, NULL);
  8474. /* It is vitally important for sigsuspend that SIGCHLD has non-DFL handler! */
  8475. /* Note: sigsuspend invokes signal handler */
  8476. sigsuspend(&oldset);
  8477. restore:
  8478. sigprocmask(SIG_SETMASK, &oldset, NULL);
  8479. /* So, did we get a signal? */
  8480. //if (sig > 0)
  8481. // raise(sig); /* run handler */
  8482. sig = check_and_run_traps();
  8483. if (sig /*&& sig != SIGCHLD - always true */) {
  8484. /* see note 2 */
  8485. ret = 128 + sig;
  8486. break;
  8487. }
  8488. /* SIGCHLD, or no signal, or ignored one, such as SIGQUIT. Repeat */
  8489. }
  8490. return ret;
  8491. }
  8492. /* This is probably buggy wrt interruptible-ness */
  8493. while (*argv) {
  8494. pid_t pid = bb_strtou(*argv, NULL, 10);
  8495. if (errno) {
  8496. /* mimic bash message */
  8497. bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
  8498. return EXIT_FAILURE;
  8499. }
  8500. if (waitpid(pid, &status, 0) == pid) {
  8501. ret = WEXITSTATUS(status);
  8502. if (WIFSIGNALED(status))
  8503. ret = 128 + WTERMSIG(status);
  8504. } else {
  8505. bb_perror_msg("wait %s", *argv);
  8506. ret = 127;
  8507. }
  8508. argv++;
  8509. }
  8510. return ret;
  8511. }
  8512. #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
  8513. static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
  8514. {
  8515. if (argv[1]) {
  8516. def = bb_strtou(argv[1], NULL, 10);
  8517. if (errno || def < def_min || argv[2]) {
  8518. bb_error_msg("%s: bad arguments", argv[0]);
  8519. def = UINT_MAX;
  8520. }
  8521. }
  8522. return def;
  8523. }
  8524. #endif
  8525. #if ENABLE_HUSH_LOOPS
  8526. static int FAST_FUNC builtin_break(char **argv)
  8527. {
  8528. unsigned depth;
  8529. if (G.depth_of_loop == 0) {
  8530. bb_error_msg("%s: only meaningful in a loop", argv[0]);
  8531. return EXIT_SUCCESS; /* bash compat */
  8532. }
  8533. G.flag_break_continue++; /* BC_BREAK = 1 */
  8534. G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
  8535. if (depth == UINT_MAX)
  8536. G.flag_break_continue = BC_BREAK;
  8537. if (G.depth_of_loop < depth)
  8538. G.depth_break_continue = G.depth_of_loop;
  8539. return EXIT_SUCCESS;
  8540. }
  8541. static int FAST_FUNC builtin_continue(char **argv)
  8542. {
  8543. G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
  8544. return builtin_break(argv);
  8545. }
  8546. #endif
  8547. #if ENABLE_HUSH_FUNCTIONS
  8548. static int FAST_FUNC builtin_return(char **argv)
  8549. {
  8550. int rc;
  8551. if (G.flag_return_in_progress != -1) {
  8552. bb_error_msg("%s: not in a function or sourced script", argv[0]);
  8553. return EXIT_FAILURE; /* bash compat */
  8554. }
  8555. G.flag_return_in_progress = 1;
  8556. /* bash:
  8557. * out of range: wraps around at 256, does not error out
  8558. * non-numeric param:
  8559. * f() { false; return qwe; }; f; echo $?
  8560. * bash: return: qwe: numeric argument required <== we do this
  8561. * 255 <== we also do this
  8562. */
  8563. rc = parse_numeric_argv1(argv, G.last_exitcode, 0);
  8564. return rc;
  8565. }
  8566. #endif