3
0

hush.c 249 KB

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