hush.c 248 KB

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