hush.c 250 KB

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