hush.c 250 KB

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