3
0

hush.c 326 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883
  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. * make complex ${var%...} constructs support optional
  45. * make here documents optional
  46. * special variables (done: PWD, PPID, RANDOM)
  47. * follow IFS rules more precisely, including update semantics
  48. * tilde expansion
  49. * aliases
  50. * "command" missing features:
  51. * command -p CMD: run CMD using default $PATH
  52. * (can use this to override standalone shell as well?)
  53. * command BLTIN: disables special-ness (e.g. errors do not abort)
  54. * command -V CMD1 CMD2 CMD3 (multiple args) (not in standard)
  55. * builtins mandated by standards we don't support:
  56. * [un]alias, fc:
  57. * fc -l[nr] [BEG] [END]: list range of commands in history
  58. * fc [-e EDITOR] [BEG] [END]: edit/rerun range of commands
  59. * fc -s [PAT=REP] [CMD]: rerun CMD, replacing PAT with REP
  60. *
  61. * Bash compat TODO:
  62. * redirection of stdout+stderr: &> and >&
  63. * reserved words: function select
  64. * advanced test: [[ ]]
  65. * process substitution: <(list) and >(list)
  66. * =~: regex operator
  67. * let EXPR [EXPR...]
  68. * Each EXPR is an arithmetic expression (ARITHMETIC EVALUATION)
  69. * If the last arg evaluates to 0, let returns 1; 0 otherwise.
  70. * NB: let `echo 'a=a + 1'` - error (IOW: multi-word expansion is used)
  71. * ((EXPR))
  72. * The EXPR is evaluated according to ARITHMETIC EVALUATION.
  73. * This is exactly equivalent to let "EXPR".
  74. * $[EXPR]: synonym for $((EXPR))
  75. * indirect expansion: ${!VAR}
  76. * substring op on @: ${@:n:m}
  77. *
  78. * Won't do:
  79. * Some builtins mandated by standards:
  80. * newgrp [GRP]: not a builtin in bash but a suid binary
  81. * which spawns a new shell with new group ID
  82. *
  83. * Status of [[ support:
  84. * [[ args ]] are CMD_SINGLEWORD_NOGLOB:
  85. * v='a b'; [[ $v = 'a b' ]]; echo 0:$?
  86. * [[ /bin/n* ]]; echo 0:$?
  87. * TODO:
  88. * &&/|| are AND/OR ops, -a/-o are not
  89. * quoting needs to be considered (-f is an operator, "-f" and ""-f are not; etc)
  90. * = is glob match operator, not equality operator: STR = GLOB
  91. * (in GLOB, quoting is significant on char-by-char basis: a*cd"*")
  92. * == same as =
  93. * add =~ regex match operator: STR =~ REGEX
  94. */
  95. //config:config HUSH
  96. //config: bool "hush (68 kb)"
  97. //config: default y
  98. //config: help
  99. //config: hush is a small shell. It handles the normal flow control
  100. //config: constructs such as if/then/elif/else/fi, for/in/do/done, while loops,
  101. //config: case/esac. Redirections, here documents, $((arithmetic))
  102. //config: and functions are supported.
  103. //config:
  104. //config: It will compile and work on no-mmu systems.
  105. //config:
  106. //config: It does not handle select, aliases, tilde expansion,
  107. //config: &>file and >&file redirection of stdout+stderr.
  108. //config:
  109. //config:config HUSH_BASH_COMPAT
  110. //config: bool "bash-compatible extensions"
  111. //config: default y
  112. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  113. //config:
  114. //config:config HUSH_BRACE_EXPANSION
  115. //config: bool "Brace expansion"
  116. //config: default y
  117. //config: depends on HUSH_BASH_COMPAT
  118. //config: help
  119. //config: Enable {abc,def} extension.
  120. //config:
  121. //config:config HUSH_LINENO_VAR
  122. //config: bool "$LINENO variable"
  123. //config: default y
  124. //config: depends on HUSH_BASH_COMPAT
  125. //config:
  126. //config:config HUSH_BASH_SOURCE_CURDIR
  127. //config: bool "'source' and '.' builtins search current directory after $PATH"
  128. //config: default n # do not encourage non-standard behavior
  129. //config: depends on HUSH_BASH_COMPAT
  130. //config: help
  131. //config: This is not compliant with standards. Avoid if possible.
  132. //config:
  133. //config:config HUSH_INTERACTIVE
  134. //config: bool "Interactive mode"
  135. //config: default y
  136. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  137. //config: help
  138. //config: Enable interactive mode (prompt and command editing).
  139. //config: Without this, hush simply reads and executes commands
  140. //config: from stdin just like a shell script from a file.
  141. //config: No prompt, no PS1/PS2 magic shell variables.
  142. //config:
  143. //config:config HUSH_SAVEHISTORY
  144. //config: bool "Save command history to .hush_history"
  145. //config: default y
  146. //config: depends on HUSH_INTERACTIVE && FEATURE_EDITING_SAVEHISTORY
  147. //config:
  148. //config:config HUSH_JOB
  149. //config: bool "Job control"
  150. //config: default y
  151. //config: depends on HUSH_INTERACTIVE
  152. //config: help
  153. //config: Enable job control: Ctrl-Z backgrounds, Ctrl-C interrupts current
  154. //config: command (not entire shell), fg/bg builtins work. Without this option,
  155. //config: "cmd &" still works by simply spawning a process and immediately
  156. //config: prompting for next command (or executing next command in a script),
  157. //config: but no separate process group is formed.
  158. //config:
  159. //config:config HUSH_TICK
  160. //config: bool "Support command substitution"
  161. //config: default y
  162. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  163. //config: help
  164. //config: Enable `command` and $(command).
  165. //config:
  166. //config:config HUSH_IF
  167. //config: bool "Support if/then/elif/else/fi"
  168. //config: default y
  169. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  170. //config:
  171. //config:config HUSH_LOOPS
  172. //config: bool "Support for, while and until loops"
  173. //config: default y
  174. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  175. //config:
  176. //config:config HUSH_CASE
  177. //config: bool "Support case ... esac statement"
  178. //config: default y
  179. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  180. //config: help
  181. //config: Enable case ... esac statement. +400 bytes.
  182. //config:
  183. //config:config HUSH_FUNCTIONS
  184. //config: bool "Support funcname() { commands; } syntax"
  185. //config: default y
  186. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  187. //config: help
  188. //config: Enable support for shell functions. +800 bytes.
  189. //config:
  190. //config:config HUSH_LOCAL
  191. //config: bool "local builtin"
  192. //config: default y
  193. //config: depends on HUSH_FUNCTIONS
  194. //config: help
  195. //config: Enable support for local variables in functions.
  196. //config:
  197. //config:config HUSH_RANDOM_SUPPORT
  198. //config: bool "Pseudorandom generator and $RANDOM variable"
  199. //config: default y
  200. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  201. //config: help
  202. //config: Enable pseudorandom generator and dynamic variable "$RANDOM".
  203. //config: Each read of "$RANDOM" will generate a new pseudorandom value.
  204. //config:
  205. //config:config HUSH_MODE_X
  206. //config: bool "Support 'hush -x' option and 'set -x' command"
  207. //config: default y
  208. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  209. //config: help
  210. //config: This instructs hush to print commands before execution.
  211. //config: Adds ~300 bytes.
  212. //config:
  213. //config:config HUSH_ECHO
  214. //config: bool "echo builtin"
  215. //config: default y
  216. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  217. //config:
  218. //config:config HUSH_PRINTF
  219. //config: bool "printf builtin"
  220. //config: default y
  221. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  222. //config:
  223. //config:config HUSH_TEST
  224. //config: bool "test builtin"
  225. //config: default y
  226. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  227. //config:
  228. //config:config HUSH_HELP
  229. //config: bool "help builtin"
  230. //config: default y
  231. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  232. //config:
  233. //config:config HUSH_EXPORT
  234. //config: bool "export builtin"
  235. //config: default y
  236. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  237. //config:
  238. //config:config HUSH_EXPORT_N
  239. //config: bool "Support 'export -n' option"
  240. //config: default y
  241. //config: depends on HUSH_EXPORT
  242. //config: help
  243. //config: export -n unexports variables. It is a bash extension.
  244. //config:
  245. //config:config HUSH_READONLY
  246. //config: bool "readonly builtin"
  247. //config: default y
  248. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  249. //config: help
  250. //config: Enable support for read-only variables.
  251. //config:
  252. //config:config HUSH_KILL
  253. //config: bool "kill builtin (supports kill %jobspec)"
  254. //config: default y
  255. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  256. //config:
  257. //config:config HUSH_WAIT
  258. //config: bool "wait builtin"
  259. //config: default y
  260. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  261. //config:
  262. //config:config HUSH_COMMAND
  263. //config: bool "command builtin"
  264. //config: default y
  265. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  266. //config:
  267. //config:config HUSH_TRAP
  268. //config: bool "trap builtin"
  269. //config: default y
  270. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  271. //config:
  272. //config:config HUSH_TYPE
  273. //config: bool "type builtin"
  274. //config: default y
  275. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  276. //config:
  277. //config:config HUSH_TIMES
  278. //config: bool "times builtin"
  279. //config: default y
  280. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  281. //config:
  282. //config:config HUSH_READ
  283. //config: bool "read builtin"
  284. //config: default y
  285. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  286. //config:
  287. //config:config HUSH_SET
  288. //config: bool "set builtin"
  289. //config: default y
  290. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  291. //config:
  292. //config:config HUSH_UNSET
  293. //config: bool "unset builtin"
  294. //config: default y
  295. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  296. //config:
  297. //config:config HUSH_ULIMIT
  298. //config: bool "ulimit builtin"
  299. //config: default y
  300. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  301. //config:
  302. //config:config HUSH_UMASK
  303. //config: bool "umask builtin"
  304. //config: default y
  305. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  306. //config:
  307. //config:config HUSH_GETOPTS
  308. //config: bool "getopts builtin"
  309. //config: default y
  310. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  311. //config:
  312. //config:config HUSH_MEMLEAK
  313. //config: bool "memleak builtin (debugging)"
  314. //config: default n
  315. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  316. //applet:IF_HUSH(APPLET(hush, BB_DIR_BIN, BB_SUID_DROP))
  317. // APPLET_ODDNAME:name main location suid_type help
  318. //applet:IF_SH_IS_HUSH( APPLET_ODDNAME(sh, hush, BB_DIR_BIN, BB_SUID_DROP, hush))
  319. //applet:IF_BASH_IS_HUSH(APPLET_ODDNAME(bash, hush, BB_DIR_BIN, BB_SUID_DROP, hush))
  320. //kbuild:lib-$(CONFIG_HUSH) += hush.o match.o shell_common.o
  321. //kbuild:lib-$(CONFIG_SH_IS_HUSH) += hush.o match.o shell_common.o
  322. //kbuild:lib-$(CONFIG_BASH_IS_HUSH) += hush.o match.o shell_common.o
  323. //kbuild:lib-$(CONFIG_HUSH_RANDOM_SUPPORT) += random.o
  324. /* -i (interactive) is also accepted,
  325. * but does nothing, therefore not shown in help.
  326. * NOMMU-specific options are not meant to be used by users,
  327. * therefore we don't show them either.
  328. */
  329. //usage:#define hush_trivial_usage
  330. //usage: "[-enxl] [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS] / -s [ARGS]]"
  331. //usage:#define hush_full_usage "\n\n"
  332. //usage: "Unix shell interpreter"
  333. #if !(defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) \
  334. || defined(__APPLE__) \
  335. )
  336. # include <malloc.h> /* for malloc_trim */
  337. #endif
  338. #include <glob.h>
  339. /* #include <dmalloc.h> */
  340. #if ENABLE_HUSH_CASE
  341. # include <fnmatch.h>
  342. #endif
  343. #include <sys/times.h>
  344. #include <sys/utsname.h> /* for setting $HOSTNAME */
  345. #include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
  346. #include "unicode.h"
  347. #include "shell_common.h"
  348. #include "math.h"
  349. #include "match.h"
  350. #if ENABLE_HUSH_RANDOM_SUPPORT
  351. # include "random.h"
  352. #else
  353. # define CLEAR_RANDOM_T(rnd) ((void)0)
  354. #endif
  355. #ifndef O_CLOEXEC
  356. # define O_CLOEXEC 0
  357. #endif
  358. #ifndef F_DUPFD_CLOEXEC
  359. # define F_DUPFD_CLOEXEC F_DUPFD
  360. #endif
  361. #if ENABLE_FEATURE_SH_EMBEDDED_SCRIPTS && !(ENABLE_ASH || ENABLE_SH_IS_ASH || ENABLE_BASH_IS_ASH)
  362. # include "embedded_scripts.h"
  363. #else
  364. # define NUM_SCRIPTS 0
  365. #endif
  366. /* So far, all bash compat is controlled by one config option */
  367. /* Separate defines document which part of code implements what */
  368. #define BASH_PATTERN_SUBST ENABLE_HUSH_BASH_COMPAT
  369. #define BASH_SUBSTR ENABLE_HUSH_BASH_COMPAT
  370. #define BASH_SOURCE ENABLE_HUSH_BASH_COMPAT
  371. #define BASH_HOSTNAME_VAR ENABLE_HUSH_BASH_COMPAT
  372. #define BASH_EPOCH_VARS ENABLE_HUSH_BASH_COMPAT
  373. #define BASH_TEST2 (ENABLE_HUSH_BASH_COMPAT && ENABLE_HUSH_TEST)
  374. #define BASH_READ_D ENABLE_HUSH_BASH_COMPAT
  375. /* Build knobs */
  376. #define LEAK_HUNTING 0
  377. #define BUILD_AS_NOMMU 0
  378. /* Enable/disable sanity checks. Ok to enable in production,
  379. * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
  380. * Keeping 1 for now even in released versions.
  381. */
  382. #define HUSH_DEBUG 1
  383. /* Slightly bigger (+200 bytes), but faster hush.
  384. * So far it only enables a trick with counting SIGCHLDs and forks,
  385. * which allows us to do fewer waitpid's.
  386. * (we can detect a case where neither forks were done nor SIGCHLDs happened
  387. * and therefore waitpid will return the same result as last time)
  388. */
  389. #define ENABLE_HUSH_FAST 0
  390. /* TODO: implement simplified code for users which do not need ${var%...} ops
  391. * So far ${var%...} ops are always enabled:
  392. */
  393. #define ENABLE_HUSH_DOLLAR_OPS 1
  394. #if BUILD_AS_NOMMU
  395. # undef BB_MMU
  396. # undef USE_FOR_NOMMU
  397. # undef USE_FOR_MMU
  398. # define BB_MMU 0
  399. # define USE_FOR_NOMMU(...) __VA_ARGS__
  400. # define USE_FOR_MMU(...)
  401. #endif
  402. #include "NUM_APPLETS.h"
  403. #if NUM_APPLETS == 1
  404. /* STANDALONE does not make sense, and won't compile */
  405. # undef CONFIG_FEATURE_SH_STANDALONE
  406. # undef ENABLE_FEATURE_SH_STANDALONE
  407. # undef IF_FEATURE_SH_STANDALONE
  408. # undef IF_NOT_FEATURE_SH_STANDALONE
  409. # define ENABLE_FEATURE_SH_STANDALONE 0
  410. # define IF_FEATURE_SH_STANDALONE(...)
  411. # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
  412. #endif
  413. #if !ENABLE_HUSH_INTERACTIVE
  414. # undef ENABLE_FEATURE_EDITING
  415. # define ENABLE_FEATURE_EDITING 0
  416. # undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
  417. # define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
  418. # undef ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
  419. # define ENABLE_FEATURE_EDITING_SAVE_ON_EXIT 0
  420. #endif
  421. /* Do we support ANY keywords? */
  422. #if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
  423. # define HAS_KEYWORDS 1
  424. # define IF_HAS_KEYWORDS(...) __VA_ARGS__
  425. # define IF_HAS_NO_KEYWORDS(...)
  426. #else
  427. # define HAS_KEYWORDS 0
  428. # define IF_HAS_KEYWORDS(...)
  429. # define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
  430. #endif
  431. /* If you comment out one of these below, it will be #defined later
  432. * to perform debug printfs to stderr: */
  433. #define debug_printf(...) do {} while (0)
  434. /* Finer-grained debug switches */
  435. #define debug_printf_parse(...) do {} while (0)
  436. #define debug_printf_heredoc(...) do {} while (0)
  437. #define debug_print_tree(a, b) do {} while (0)
  438. #define debug_printf_exec(...) do {} while (0)
  439. #define debug_printf_env(...) do {} while (0)
  440. #define debug_printf_jobs(...) do {} while (0)
  441. #define debug_printf_expand(...) do {} while (0)
  442. #define debug_printf_varexp(...) do {} while (0)
  443. #define debug_printf_glob(...) do {} while (0)
  444. #define debug_printf_redir(...) do {} while (0)
  445. #define debug_printf_list(...) do {} while (0)
  446. #define debug_printf_subst(...) do {} while (0)
  447. #define debug_printf_prompt(...) do {} while (0)
  448. #define debug_printf_clean(...) do {} while (0)
  449. #define ERR_PTR ((void*)(long)1)
  450. #define JOB_STATUS_FORMAT "[%u] %-22s %.40s\n"
  451. #define _SPECIAL_VARS_STR "_*@$!?#-"
  452. #define SPECIAL_VARS_STR ("_*@$!?#-" + 1)
  453. #define NUMERIC_SPECVARS_STR ("_*@$!?#-" + 3)
  454. #if BASH_PATTERN_SUBST
  455. /* Support / and // replace ops */
  456. /* Note that // is stored as \ in "encoded" string representation */
  457. # define VAR_ENCODED_SUBST_OPS "\\/%#:-=+?"
  458. # define VAR_SUBST_OPS ("\\/%#:-=+?" + 1)
  459. # define MINUS_PLUS_EQUAL_QUESTION ("\\/%#:-=+?" + 5)
  460. #else
  461. # define VAR_ENCODED_SUBST_OPS "%#:-=+?"
  462. # define VAR_SUBST_OPS "%#:-=+?"
  463. # define MINUS_PLUS_EQUAL_QUESTION ("%#:-=+?" + 3)
  464. #endif
  465. #define SPECIAL_VAR_SYMBOL_STR "\3"
  466. #define SPECIAL_VAR_SYMBOL 3
  467. /* The "variable" with name "\1" emits string "\3". Testcase: "echo ^C" */
  468. #define SPECIAL_VAR_QUOTED_SVS 1
  469. struct variable;
  470. static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
  471. /* This supports saving pointers malloced in vfork child,
  472. * to be freed in the parent.
  473. */
  474. #if !BB_MMU
  475. typedef struct nommu_save_t {
  476. struct variable *old_vars;
  477. char **argv;
  478. char **argv_from_re_execing;
  479. } nommu_save_t;
  480. #endif
  481. enum {
  482. RES_NONE = 0,
  483. #if ENABLE_HUSH_IF
  484. RES_IF ,
  485. RES_THEN ,
  486. RES_ELIF ,
  487. RES_ELSE ,
  488. RES_FI ,
  489. #endif
  490. #if ENABLE_HUSH_LOOPS
  491. RES_FOR ,
  492. RES_WHILE ,
  493. RES_UNTIL ,
  494. RES_DO ,
  495. RES_DONE ,
  496. #endif
  497. #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
  498. RES_IN ,
  499. #endif
  500. #if ENABLE_HUSH_CASE
  501. RES_CASE ,
  502. /* three pseudo-keywords support contrived "case" syntax: */
  503. RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
  504. RES_MATCH , /* "word)" */
  505. RES_CASE_BODY, /* "this command is inside CASE" */
  506. RES_ESAC ,
  507. #endif
  508. RES_XXXX ,
  509. RES_SNTX
  510. };
  511. typedef struct o_string {
  512. char *data;
  513. int length; /* position where data is appended */
  514. int maxlen;
  515. int o_expflags;
  516. /* At least some part of the string was inside '' or "",
  517. * possibly empty one: word"", wo''rd etc. */
  518. smallint has_quoted_part;
  519. smallint has_empty_slot;
  520. smallint ended_in_ifs;
  521. } o_string;
  522. enum {
  523. EXP_FLAG_SINGLEWORD = 0x80, /* must be 0x80 */
  524. EXP_FLAG_GLOB = 0x2,
  525. /* Protect newly added chars against globbing
  526. * by prepending \ to *, ?, [, \ */
  527. EXP_FLAG_ESC_GLOB_CHARS = 0x1,
  528. };
  529. /* Used for initialization: o_string foo = NULL_O_STRING; */
  530. #define NULL_O_STRING { NULL }
  531. #ifndef debug_printf_parse
  532. static const char *const assignment_flag[] = {
  533. "MAYBE_ASSIGNMENT",
  534. "DEFINITELY_ASSIGNMENT",
  535. "NOT_ASSIGNMENT",
  536. "WORD_IS_KEYWORD",
  537. };
  538. #endif
  539. /* We almost can use standard FILE api, but we need an ability to move
  540. * its fd when redirects coincide with it. No api exists for that
  541. * (RFE for it at https://sourceware.org/bugzilla/show_bug.cgi?id=21902).
  542. * HFILE is our internal alternative. Only supports reading.
  543. * Since we now can, we incorporate linked list of all opened HFILEs
  544. * into the struct (used to be a separate mini-list).
  545. */
  546. typedef struct HFILE {
  547. char *cur;
  548. char *end;
  549. struct HFILE *next_hfile;
  550. int fd;
  551. char buf[1024];
  552. } HFILE;
  553. typedef struct in_str {
  554. const char *p;
  555. int peek_buf[2];
  556. int last_char;
  557. HFILE *file;
  558. } in_str;
  559. /* The descrip member of this structure is only used to make
  560. * debugging output pretty */
  561. static const struct {
  562. int mode;
  563. signed char default_fd;
  564. char descrip[3];
  565. } redir_table[] = {
  566. { O_RDONLY, 0, "<" },
  567. { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
  568. { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
  569. { O_CREAT|O_RDWR, 1, "<>" },
  570. { O_RDONLY, 0, "<<" },
  571. /* Should not be needed. Bogus default_fd helps in debugging */
  572. /* { O_RDONLY, 77, "<<" }, */
  573. };
  574. struct redir_struct {
  575. struct redir_struct *next;
  576. char *rd_filename; /* filename */
  577. int rd_fd; /* fd to redirect */
  578. /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
  579. int rd_dup;
  580. smallint rd_type; /* (enum redir_type) */
  581. /* note: for heredocs, rd_filename contains heredoc delimiter,
  582. * and subsequently heredoc itself; and rd_dup is a bitmask:
  583. * bit 0: do we need to trim leading tabs?
  584. * bit 1: is heredoc quoted (<<'delim' syntax) ?
  585. */
  586. };
  587. typedef enum redir_type {
  588. REDIRECT_INPUT = 0,
  589. REDIRECT_OVERWRITE = 1,
  590. REDIRECT_APPEND = 2,
  591. REDIRECT_IO = 3,
  592. REDIRECT_HEREDOC = 4,
  593. REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
  594. REDIRFD_CLOSE = -3,
  595. REDIRFD_SYNTAX_ERR = -2,
  596. REDIRFD_TO_FILE = -1,
  597. /* otherwise, rd_fd is redirected to rd_dup */
  598. HEREDOC_SKIPTABS = 1,
  599. HEREDOC_QUOTED = 2,
  600. } redir_type;
  601. struct command {
  602. pid_t pid; /* 0 if exited */
  603. unsigned assignment_cnt; /* how many argv[i] are assignments? */
  604. #if ENABLE_HUSH_LINENO_VAR
  605. unsigned lineno;
  606. #endif
  607. smallint cmd_type; /* CMD_xxx */
  608. #define CMD_NORMAL 0
  609. #define CMD_SUBSHELL 1
  610. #if BASH_TEST2 || ENABLE_HUSH_LOCAL || ENABLE_HUSH_EXPORT || ENABLE_HUSH_READONLY
  611. /* used for "[[ EXPR ]]", and to prevent word splitting and globbing in
  612. * "export v=t*"
  613. */
  614. # define CMD_SINGLEWORD_NOGLOB 2
  615. #endif
  616. #if ENABLE_HUSH_FUNCTIONS
  617. # define CMD_FUNCDEF 3
  618. #endif
  619. smalluint cmd_exitcode;
  620. /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
  621. struct pipe *group;
  622. #if !BB_MMU
  623. char *group_as_string;
  624. #endif
  625. #if ENABLE_HUSH_FUNCTIONS
  626. struct function *child_func;
  627. /* This field is used to prevent a bug here:
  628. * while...do f1() {a;}; f1; f1() {b;}; f1; done
  629. * When we execute "f1() {a;}" cmd, we create new function and clear
  630. * cmd->group, cmd->group_as_string, cmd->argv[0].
  631. * When we execute "f1() {b;}", we notice that f1 exists,
  632. * and that its "parent cmd" struct is still "alive",
  633. * we put those fields back into cmd->xxx
  634. * (struct function has ->parent_cmd ptr to facilitate that).
  635. * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
  636. * Without this trick, loop would execute a;b;b;b;...
  637. * instead of correct sequence a;b;a;b;...
  638. * When command is freed, it severs the link
  639. * (sets ->child_func->parent_cmd to NULL).
  640. */
  641. #endif
  642. char **argv; /* command name and arguments */
  643. /* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
  644. * and on execution these are substituted with their values.
  645. * Substitution can make _several_ words out of one argv[n]!
  646. * Example: argv[0]=='.^C*^C.' here: echo .$*.
  647. * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
  648. */
  649. struct redir_struct *redirects; /* I/O redirections */
  650. };
  651. /* Is there anything in this command at all? */
  652. #define IS_NULL_CMD(cmd) \
  653. (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
  654. struct pipe {
  655. struct pipe *next;
  656. int num_cmds; /* total number of commands in pipe */
  657. int alive_cmds; /* number of commands running (not exited) */
  658. int stopped_cmds; /* number of commands alive, but stopped */
  659. #if ENABLE_HUSH_JOB
  660. unsigned jobid; /* job number */
  661. pid_t pgrp; /* process group ID for the job */
  662. char *cmdtext; /* name of job */
  663. #endif
  664. struct command *cmds; /* array of commands in pipe */
  665. smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
  666. IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
  667. IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
  668. };
  669. typedef enum pipe_style {
  670. PIPE_SEQ = 0,
  671. PIPE_AND = 1,
  672. PIPE_OR = 2,
  673. PIPE_BG = 3,
  674. } pipe_style;
  675. /* Is there anything in this pipe at all? */
  676. #define IS_NULL_PIPE(pi) \
  677. ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
  678. /* This holds pointers to the various results of parsing */
  679. struct parse_context {
  680. /* linked list of pipes */
  681. struct pipe *list_head;
  682. /* last pipe (being constructed right now) */
  683. struct pipe *pipe;
  684. /* last command in pipe (being constructed right now) */
  685. struct command *command;
  686. /* last redirect in command->redirects list */
  687. struct redir_struct *pending_redirect;
  688. o_string word;
  689. #if !BB_MMU
  690. o_string as_string;
  691. #endif
  692. smallint is_assignment; /* 0:maybe, 1:yes, 2:no, 3:keyword */
  693. #if HAS_KEYWORDS
  694. smallint ctx_res_w;
  695. smallint ctx_inverted; /* "! cmd | cmd" */
  696. #if ENABLE_HUSH_CASE
  697. smallint ctx_dsemicolon; /* ";;" seen */
  698. #endif
  699. /* bitmask of FLAG_xxx, for figuring out valid reserved words */
  700. int old_flag;
  701. /* group we are enclosed in:
  702. * example: "if pipe1; pipe2; then pipe3; fi"
  703. * when we see "if" or "then", we malloc and copy current context,
  704. * and make ->stack point to it. then we parse pipeN.
  705. * when closing "then" / fi" / whatever is found,
  706. * we move list_head into ->stack->command->group,
  707. * copy ->stack into current context, and delete ->stack.
  708. * (parsing of { list } and ( list ) doesn't use this method)
  709. */
  710. struct parse_context *stack;
  711. #endif
  712. };
  713. enum {
  714. MAYBE_ASSIGNMENT = 0,
  715. DEFINITELY_ASSIGNMENT = 1,
  716. NOT_ASSIGNMENT = 2,
  717. /* Not an assignment, but next word may be: "if v=xyz cmd;" */
  718. WORD_IS_KEYWORD = 3,
  719. };
  720. /* On program start, environ points to initial environment.
  721. * putenv adds new pointers into it, unsetenv removes them.
  722. * Neither of these (de)allocates the strings.
  723. * setenv allocates new strings in malloc space and does putenv,
  724. * and thus setenv is unusable (leaky) for shell's purposes */
  725. #define setenv(...) setenv_is_leaky_dont_use()
  726. struct variable {
  727. struct variable *next;
  728. char *varstr; /* points to "name=" portion */
  729. int max_len; /* if > 0, name is part of initial env; else name is malloced */
  730. uint16_t var_nest_level;
  731. smallint flg_export; /* putenv should be done on this var */
  732. smallint flg_read_only;
  733. };
  734. enum {
  735. BC_BREAK = 1,
  736. BC_CONTINUE = 2,
  737. };
  738. #if ENABLE_HUSH_FUNCTIONS
  739. struct function {
  740. struct function *next;
  741. char *name;
  742. struct command *parent_cmd;
  743. struct pipe *body;
  744. # if !BB_MMU
  745. char *body_as_string;
  746. # endif
  747. };
  748. #endif
  749. /* set -/+o OPT support. (TODO: make it optional)
  750. * bash supports the following opts:
  751. * allexport off
  752. * braceexpand on
  753. * emacs on
  754. * errexit off
  755. * errtrace off
  756. * functrace off
  757. * hashall on
  758. * histexpand off
  759. * history on
  760. * ignoreeof off
  761. * interactive-comments on
  762. * keyword off
  763. * monitor on
  764. * noclobber off
  765. * noexec off
  766. * noglob off
  767. * nolog off
  768. * notify off
  769. * nounset off
  770. * onecmd off
  771. * physical off
  772. * pipefail off
  773. * posix off
  774. * privileged off
  775. * verbose off
  776. * vi off
  777. * xtrace off
  778. */
  779. static const char o_opt_strings[] ALIGN1 =
  780. "pipefail\0"
  781. "noexec\0"
  782. "errexit\0"
  783. #if ENABLE_HUSH_MODE_X
  784. "xtrace\0"
  785. #endif
  786. ;
  787. enum {
  788. OPT_O_PIPEFAIL,
  789. OPT_O_NOEXEC,
  790. OPT_O_ERREXIT,
  791. #if ENABLE_HUSH_MODE_X
  792. OPT_O_XTRACE,
  793. #endif
  794. NUM_OPT_O
  795. };
  796. /* "Globals" within this file */
  797. /* Sorted roughly by size (smaller offsets == smaller code) */
  798. struct globals {
  799. /* interactive_fd != 0 means we are an interactive shell.
  800. * If we are, then saved_tty_pgrp can also be != 0, meaning
  801. * that controlling tty is available. With saved_tty_pgrp == 0,
  802. * job control still works, but terminal signals
  803. * (^C, ^Z, ^Y, ^\) won't work at all, and background
  804. * process groups can only be created with "cmd &".
  805. * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
  806. * to give tty to the foreground process group,
  807. * and will take it back when the group is stopped (^Z)
  808. * or killed (^C).
  809. */
  810. #if ENABLE_HUSH_INTERACTIVE
  811. /* 'interactive_fd' is a fd# open to ctty, if we have one
  812. * _AND_ if we decided to act interactively */
  813. int interactive_fd;
  814. IF_NOT_FEATURE_EDITING_FANCY_PROMPT(char *PS1;)
  815. # define G_interactive_fd (G.interactive_fd)
  816. #else
  817. # define G_interactive_fd 0
  818. #endif
  819. #if ENABLE_FEATURE_EDITING
  820. line_input_t *line_input_state;
  821. #endif
  822. pid_t root_pid;
  823. pid_t root_ppid;
  824. pid_t last_bg_pid;
  825. #if ENABLE_HUSH_RANDOM_SUPPORT
  826. random_t random_gen;
  827. #endif
  828. #if ENABLE_HUSH_JOB
  829. int run_list_level;
  830. unsigned last_jobid;
  831. pid_t saved_tty_pgrp;
  832. struct pipe *job_list;
  833. # define G_saved_tty_pgrp (G.saved_tty_pgrp)
  834. #else
  835. # define G_saved_tty_pgrp 0
  836. #endif
  837. /* How deeply are we in context where "set -e" is ignored */
  838. int errexit_depth;
  839. /* "set -e" rules (do we follow them correctly?):
  840. * Exit if pipe, list, or compound command exits with a non-zero status.
  841. * Shell does not exit if failed command is part of condition in
  842. * if/while, part of && or || list except the last command, any command
  843. * in a pipe but the last, or if the command's return value is being
  844. * inverted with !. If a compound command other than a subshell returns a
  845. * non-zero status because a command failed while -e was being ignored, the
  846. * shell does not exit. A trap on ERR, if set, is executed before the shell
  847. * exits [ERR is a bashism].
  848. *
  849. * If a compound command or function executes in a context where -e is
  850. * ignored, none of the commands executed within are affected by the -e
  851. * setting. If a compound command or function sets -e while executing in a
  852. * context where -e is ignored, that setting does not have any effect until
  853. * the compound command or the command containing the function call completes.
  854. */
  855. char o_opt[NUM_OPT_O];
  856. #if ENABLE_HUSH_MODE_X
  857. # define G_x_mode (G.o_opt[OPT_O_XTRACE])
  858. #else
  859. # define G_x_mode 0
  860. #endif
  861. char opt_s;
  862. char opt_c;
  863. #if ENABLE_HUSH_INTERACTIVE
  864. smallint promptmode; /* 0: PS1, 1: PS2 */
  865. #endif
  866. smallint flag_SIGINT;
  867. #if ENABLE_HUSH_LOOPS
  868. smallint flag_break_continue;
  869. #endif
  870. #if ENABLE_HUSH_FUNCTIONS
  871. /* 0: outside of a function (or sourced file)
  872. * -1: inside of a function, ok to use return builtin
  873. * 1: return is invoked, skip all till end of func
  874. */
  875. smallint flag_return_in_progress;
  876. # define G_flag_return_in_progress (G.flag_return_in_progress)
  877. #else
  878. # define G_flag_return_in_progress 0
  879. #endif
  880. smallint exiting; /* used to prevent EXIT trap recursion */
  881. /* These support $? */
  882. smalluint last_exitcode;
  883. smalluint expand_exitcode;
  884. smalluint last_bg_pid_exitcode;
  885. #if ENABLE_HUSH_SET
  886. /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
  887. smalluint global_args_malloced;
  888. # define G_global_args_malloced (G.global_args_malloced)
  889. #else
  890. # define G_global_args_malloced 0
  891. #endif
  892. #if ENABLE_HUSH_BASH_COMPAT
  893. int dead_job_exitcode; /* for "wait -n" */
  894. #endif
  895. /* how many non-NULL argv's we have. NB: $# + 1 */
  896. int global_argc;
  897. char **global_argv;
  898. #if !BB_MMU
  899. char *argv0_for_re_execing;
  900. #endif
  901. #if ENABLE_HUSH_LOOPS
  902. unsigned depth_break_continue;
  903. unsigned depth_of_loop;
  904. #endif
  905. #if ENABLE_HUSH_GETOPTS
  906. unsigned getopt_count;
  907. #endif
  908. const char *ifs;
  909. char *ifs_whitespace; /* = G.ifs or malloced */
  910. const char *cwd;
  911. struct variable *top_var;
  912. char **expanded_assignments;
  913. struct variable **shadowed_vars_pp;
  914. unsigned var_nest_level;
  915. #if ENABLE_HUSH_FUNCTIONS
  916. # if ENABLE_HUSH_LOCAL
  917. unsigned func_nest_level; /* solely to prevent "local v" in non-functions */
  918. # endif
  919. struct function *top_func;
  920. #endif
  921. /* Signal and trap handling */
  922. #if ENABLE_HUSH_FAST
  923. unsigned count_SIGCHLD;
  924. unsigned handled_SIGCHLD;
  925. smallint we_have_children;
  926. #endif
  927. #if ENABLE_HUSH_LINENO_VAR
  928. unsigned parse_lineno;
  929. unsigned execute_lineno;
  930. #endif
  931. HFILE *HFILE_list;
  932. HFILE *HFILE_stdin;
  933. /* Which signals have non-DFL handler (even with no traps set)?
  934. * Set at the start to:
  935. * (SIGQUIT + maybe SPECIAL_INTERACTIVE_SIGS + maybe SPECIAL_JOBSTOP_SIGS)
  936. * SPECIAL_INTERACTIVE_SIGS are cleared after fork.
  937. * The rest is cleared right before execv syscalls.
  938. * Other than these two times, never modified.
  939. */
  940. unsigned special_sig_mask;
  941. #if ENABLE_HUSH_JOB
  942. unsigned fatal_sig_mask;
  943. # define G_fatal_sig_mask (G.fatal_sig_mask)
  944. #else
  945. # define G_fatal_sig_mask 0
  946. #endif
  947. #if ENABLE_HUSH_TRAP
  948. int pre_trap_exitcode;
  949. # if ENABLE_HUSH_FUNCTIONS
  950. int return_exitcode;
  951. # endif
  952. char **traps; /* char *traps[NSIG] */
  953. # define G_traps G.traps
  954. #else
  955. # define G_traps ((char**)NULL)
  956. #endif
  957. sigset_t pending_set;
  958. #if ENABLE_HUSH_MEMLEAK
  959. unsigned long memleak_value;
  960. #endif
  961. #if ENABLE_HUSH_MODE_X
  962. unsigned x_mode_depth;
  963. /* "set -x" output should not be redirectable with subsequent 2>FILE.
  964. * We dup fd#2 to x_mode_fd when "set -x" is executed, and use it
  965. * for all subsequent output.
  966. */
  967. int x_mode_fd;
  968. o_string x_mode_buf;
  969. #endif
  970. #if HUSH_DEBUG >= 2
  971. int debug_indent;
  972. #endif
  973. struct sigaction sa;
  974. char optstring_buf[sizeof("eixcs")];
  975. #if BASH_EPOCH_VARS
  976. char epoch_buf[sizeof("%lu.nnnnnn") + sizeof(long)*3];
  977. #endif
  978. #if ENABLE_FEATURE_EDITING
  979. char user_input_buf[CONFIG_FEATURE_EDITING_MAX_LEN];
  980. #endif
  981. };
  982. #define G (*ptr_to_globals)
  983. /* Not #defining name to G.name - this quickly gets unwieldy
  984. * (too many defines). Also, I actually prefer to see when a variable
  985. * is global, thus "G." prefix is a useful hint */
  986. #define INIT_G() do { \
  987. SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
  988. /* memset(&G.sa, 0, sizeof(G.sa)); */ \
  989. sigfillset(&G.sa.sa_mask); \
  990. G.sa.sa_flags = SA_RESTART; \
  991. } while (0)
  992. /* Function prototypes for builtins */
  993. static int builtin_cd(char **argv) FAST_FUNC;
  994. #if ENABLE_HUSH_ECHO
  995. static int builtin_echo(char **argv) FAST_FUNC;
  996. #endif
  997. static int builtin_eval(char **argv) FAST_FUNC;
  998. static int builtin_exec(char **argv) FAST_FUNC;
  999. static int builtin_exit(char **argv) FAST_FUNC;
  1000. #if ENABLE_HUSH_EXPORT
  1001. static int builtin_export(char **argv) FAST_FUNC;
  1002. #endif
  1003. #if ENABLE_HUSH_READONLY
  1004. static int builtin_readonly(char **argv) FAST_FUNC;
  1005. #endif
  1006. #if ENABLE_HUSH_JOB
  1007. static int builtin_fg_bg(char **argv) FAST_FUNC;
  1008. static int builtin_jobs(char **argv) FAST_FUNC;
  1009. #endif
  1010. #if ENABLE_HUSH_GETOPTS
  1011. static int builtin_getopts(char **argv) FAST_FUNC;
  1012. #endif
  1013. #if ENABLE_HUSH_HELP
  1014. static int builtin_help(char **argv) FAST_FUNC;
  1015. #endif
  1016. #if MAX_HISTORY && ENABLE_FEATURE_EDITING
  1017. static int builtin_history(char **argv) FAST_FUNC;
  1018. #endif
  1019. #if ENABLE_HUSH_LOCAL
  1020. static int builtin_local(char **argv) FAST_FUNC;
  1021. #endif
  1022. #if ENABLE_HUSH_MEMLEAK
  1023. static int builtin_memleak(char **argv) FAST_FUNC;
  1024. #endif
  1025. #if ENABLE_HUSH_PRINTF
  1026. static int builtin_printf(char **argv) FAST_FUNC;
  1027. #endif
  1028. static int builtin_pwd(char **argv) FAST_FUNC;
  1029. #if ENABLE_HUSH_READ
  1030. static int builtin_read(char **argv) FAST_FUNC;
  1031. #endif
  1032. #if ENABLE_HUSH_SET
  1033. static int builtin_set(char **argv) FAST_FUNC;
  1034. #endif
  1035. static int builtin_shift(char **argv) FAST_FUNC;
  1036. static int builtin_source(char **argv) FAST_FUNC;
  1037. #if ENABLE_HUSH_TEST || BASH_TEST2
  1038. static int builtin_test(char **argv) FAST_FUNC;
  1039. #endif
  1040. #if ENABLE_HUSH_TRAP
  1041. static int builtin_trap(char **argv) FAST_FUNC;
  1042. #endif
  1043. #if ENABLE_HUSH_TYPE
  1044. static int builtin_type(char **argv) FAST_FUNC;
  1045. #endif
  1046. #if ENABLE_HUSH_TIMES
  1047. static int builtin_times(char **argv) FAST_FUNC;
  1048. #endif
  1049. static int builtin_true(char **argv) FAST_FUNC;
  1050. #if ENABLE_HUSH_UMASK
  1051. static int builtin_umask(char **argv) FAST_FUNC;
  1052. #endif
  1053. #if ENABLE_HUSH_UNSET
  1054. static int builtin_unset(char **argv) FAST_FUNC;
  1055. #endif
  1056. #if ENABLE_HUSH_KILL
  1057. static int builtin_kill(char **argv) FAST_FUNC;
  1058. #endif
  1059. #if ENABLE_HUSH_WAIT
  1060. static int builtin_wait(char **argv) FAST_FUNC;
  1061. #endif
  1062. #if ENABLE_HUSH_LOOPS
  1063. static int builtin_break(char **argv) FAST_FUNC;
  1064. static int builtin_continue(char **argv) FAST_FUNC;
  1065. #endif
  1066. #if ENABLE_HUSH_FUNCTIONS
  1067. static int builtin_return(char **argv) FAST_FUNC;
  1068. #endif
  1069. /* Table of built-in functions. They can be forked or not, depending on
  1070. * context: within pipes, they fork. As simple commands, they do not.
  1071. * When used in non-forking context, they can change global variables
  1072. * in the parent shell process. If forked, of course they cannot.
  1073. * For example, 'unset foo | whatever' will parse and run, but foo will
  1074. * still be set at the end. */
  1075. struct built_in_command {
  1076. const char *b_cmd;
  1077. int (*b_function)(char **argv) FAST_FUNC;
  1078. #if ENABLE_HUSH_HELP
  1079. const char *b_descr;
  1080. # define BLTIN(cmd, func, help) { cmd, func, help }
  1081. #else
  1082. # define BLTIN(cmd, func, help) { cmd, func }
  1083. #endif
  1084. };
  1085. static const struct built_in_command bltins1[] = {
  1086. BLTIN("." , builtin_source , "Run commands in file"),
  1087. BLTIN(":" , builtin_true , NULL),
  1088. #if ENABLE_HUSH_JOB
  1089. BLTIN("bg" , builtin_fg_bg , "Resume job in background"),
  1090. #endif
  1091. #if ENABLE_HUSH_LOOPS
  1092. BLTIN("break" , builtin_break , "Exit loop"),
  1093. #endif
  1094. BLTIN("cd" , builtin_cd , "Change directory"),
  1095. #if ENABLE_HUSH_LOOPS
  1096. BLTIN("continue" , builtin_continue, "Start new loop iteration"),
  1097. #endif
  1098. BLTIN("eval" , builtin_eval , "Construct and run shell command"),
  1099. BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
  1100. BLTIN("exit" , builtin_exit , NULL),
  1101. #if ENABLE_HUSH_EXPORT
  1102. BLTIN("export" , builtin_export , "Set environment variables"),
  1103. #endif
  1104. #if ENABLE_HUSH_JOB
  1105. BLTIN("fg" , builtin_fg_bg , "Bring job to foreground"),
  1106. #endif
  1107. #if ENABLE_HUSH_GETOPTS
  1108. BLTIN("getopts" , builtin_getopts , NULL),
  1109. #endif
  1110. #if ENABLE_HUSH_HELP
  1111. BLTIN("help" , builtin_help , NULL),
  1112. #endif
  1113. #if MAX_HISTORY && ENABLE_FEATURE_EDITING
  1114. BLTIN("history" , builtin_history , "Show history"),
  1115. #endif
  1116. #if ENABLE_HUSH_JOB
  1117. BLTIN("jobs" , builtin_jobs , "List jobs"),
  1118. #endif
  1119. #if ENABLE_HUSH_KILL
  1120. BLTIN("kill" , builtin_kill , "Send signals to processes"),
  1121. #endif
  1122. #if ENABLE_HUSH_LOCAL
  1123. BLTIN("local" , builtin_local , "Set local variables"),
  1124. #endif
  1125. #if ENABLE_HUSH_MEMLEAK
  1126. BLTIN("memleak" , builtin_memleak , NULL),
  1127. #endif
  1128. #if ENABLE_HUSH_READ
  1129. BLTIN("read" , builtin_read , "Input into variable"),
  1130. #endif
  1131. #if ENABLE_HUSH_READONLY
  1132. BLTIN("readonly" , builtin_readonly, "Make variables read-only"),
  1133. #endif
  1134. #if ENABLE_HUSH_FUNCTIONS
  1135. BLTIN("return" , builtin_return , "Return from function"),
  1136. #endif
  1137. #if ENABLE_HUSH_SET
  1138. BLTIN("set" , builtin_set , "Set positional parameters"),
  1139. #endif
  1140. BLTIN("shift" , builtin_shift , "Shift positional parameters"),
  1141. #if BASH_SOURCE
  1142. BLTIN("source" , builtin_source , NULL),
  1143. #endif
  1144. #if ENABLE_HUSH_TIMES
  1145. BLTIN("times" , builtin_times , NULL),
  1146. #endif
  1147. #if ENABLE_HUSH_TRAP
  1148. BLTIN("trap" , builtin_trap , "Trap signals"),
  1149. #endif
  1150. BLTIN("true" , builtin_true , NULL),
  1151. #if ENABLE_HUSH_TYPE
  1152. BLTIN("type" , builtin_type , "Show command type"),
  1153. #endif
  1154. #if ENABLE_HUSH_ULIMIT
  1155. BLTIN("ulimit" , shell_builtin_ulimit, "Control resource limits"),
  1156. #endif
  1157. #if ENABLE_HUSH_UMASK
  1158. BLTIN("umask" , builtin_umask , "Set file creation mask"),
  1159. #endif
  1160. #if ENABLE_HUSH_UNSET
  1161. BLTIN("unset" , builtin_unset , "Unset variables"),
  1162. #endif
  1163. #if ENABLE_HUSH_WAIT
  1164. BLTIN("wait" , builtin_wait , "Wait for process to finish"),
  1165. #endif
  1166. };
  1167. /* These builtins won't be used if we are on NOMMU and need to re-exec
  1168. * (it's cheaper to run an external program in this case):
  1169. */
  1170. static const struct built_in_command bltins2[] = {
  1171. #if ENABLE_HUSH_TEST
  1172. BLTIN("[" , builtin_test , NULL),
  1173. #endif
  1174. #if BASH_TEST2
  1175. BLTIN("[[" , builtin_test , NULL),
  1176. #endif
  1177. #if ENABLE_HUSH_ECHO
  1178. BLTIN("echo" , builtin_echo , NULL),
  1179. #endif
  1180. #if ENABLE_HUSH_PRINTF
  1181. BLTIN("printf" , builtin_printf , NULL),
  1182. #endif
  1183. BLTIN("pwd" , builtin_pwd , NULL),
  1184. #if ENABLE_HUSH_TEST
  1185. BLTIN("test" , builtin_test , NULL),
  1186. #endif
  1187. };
  1188. /* Debug printouts.
  1189. */
  1190. #if HUSH_DEBUG >= 2
  1191. /* prevent disasters with G.debug_indent < 0 */
  1192. # define indent() fdprintf(2, "%*s", (G.debug_indent * 2) & 0xff, "")
  1193. # define debug_enter() (G.debug_indent++)
  1194. # define debug_leave() (G.debug_indent--)
  1195. #else
  1196. # define indent() ((void)0)
  1197. # define debug_enter() ((void)0)
  1198. # define debug_leave() ((void)0)
  1199. #endif
  1200. #ifndef debug_printf
  1201. # define debug_printf(...) (indent(), fdprintf(2, __VA_ARGS__))
  1202. #endif
  1203. #ifndef debug_printf_parse
  1204. # define debug_printf_parse(...) (indent(), fdprintf(2, __VA_ARGS__))
  1205. #endif
  1206. #ifndef debug_printf_heredoc
  1207. # define debug_printf_heredoc(...) (indent(), fdprintf(2, __VA_ARGS__))
  1208. #endif
  1209. #ifndef debug_printf_exec
  1210. #define debug_printf_exec(...) (indent(), fdprintf(2, __VA_ARGS__))
  1211. #endif
  1212. #ifndef debug_printf_env
  1213. # define debug_printf_env(...) (indent(), fdprintf(2, __VA_ARGS__))
  1214. #endif
  1215. #ifndef debug_printf_jobs
  1216. # define debug_printf_jobs(...) (indent(), fdprintf(2, __VA_ARGS__))
  1217. # define DEBUG_JOBS 1
  1218. #else
  1219. # define DEBUG_JOBS 0
  1220. #endif
  1221. #ifndef debug_printf_expand
  1222. # define debug_printf_expand(...) (indent(), fdprintf(2, __VA_ARGS__))
  1223. # define DEBUG_EXPAND 1
  1224. #else
  1225. # define DEBUG_EXPAND 0
  1226. #endif
  1227. #ifndef debug_printf_varexp
  1228. # define debug_printf_varexp(...) (indent(), fdprintf(2, __VA_ARGS__))
  1229. #endif
  1230. #ifndef debug_printf_glob
  1231. # define debug_printf_glob(...) (indent(), fdprintf(2, __VA_ARGS__))
  1232. # define DEBUG_GLOB 1
  1233. #else
  1234. # define DEBUG_GLOB 0
  1235. #endif
  1236. #ifndef debug_printf_redir
  1237. # define debug_printf_redir(...) (indent(), fdprintf(2, __VA_ARGS__))
  1238. #endif
  1239. #ifndef debug_printf_list
  1240. # define debug_printf_list(...) (indent(), fdprintf(2, __VA_ARGS__))
  1241. #endif
  1242. #ifndef debug_printf_subst
  1243. # define debug_printf_subst(...) (indent(), fdprintf(2, __VA_ARGS__))
  1244. #endif
  1245. #ifndef debug_printf_prompt
  1246. # define debug_printf_prompt(...) (indent(), fdprintf(2, __VA_ARGS__))
  1247. #endif
  1248. #ifndef debug_printf_clean
  1249. # define debug_printf_clean(...) (indent(), fdprintf(2, __VA_ARGS__))
  1250. # define DEBUG_CLEAN 1
  1251. #else
  1252. # define DEBUG_CLEAN 0
  1253. #endif
  1254. #if DEBUG_EXPAND
  1255. static void debug_print_strings(const char *prefix, char **vv)
  1256. {
  1257. indent();
  1258. fdprintf(2, "%s:\n", prefix);
  1259. while (*vv)
  1260. fdprintf(2, " '%s'\n", *vv++);
  1261. }
  1262. #else
  1263. # define debug_print_strings(prefix, vv) ((void)0)
  1264. #endif
  1265. /* Leak hunting. Use hush_leaktool.sh for post-processing.
  1266. */
  1267. #if LEAK_HUNTING
  1268. static void *xxmalloc(int lineno, size_t size)
  1269. {
  1270. void *ptr = xmalloc((size + 0xff) & ~0xff);
  1271. fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
  1272. return ptr;
  1273. }
  1274. static void *xxrealloc(int lineno, void *ptr, size_t size)
  1275. {
  1276. ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
  1277. fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
  1278. return ptr;
  1279. }
  1280. static char *xxstrdup(int lineno, const char *str)
  1281. {
  1282. char *ptr = xstrdup(str);
  1283. fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
  1284. return ptr;
  1285. }
  1286. static void xxfree(void *ptr)
  1287. {
  1288. fdprintf(2, "free %p\n", ptr);
  1289. free(ptr);
  1290. }
  1291. # define xmalloc(s) xxmalloc(__LINE__, s)
  1292. # define xrealloc(p, s) xxrealloc(__LINE__, p, s)
  1293. # define xstrdup(s) xxstrdup(__LINE__, s)
  1294. # define free(p) xxfree(p)
  1295. #endif
  1296. /* Syntax and runtime errors. They always abort scripts.
  1297. * In interactive use they usually discard unparsed and/or unexecuted commands
  1298. * and return to the prompt.
  1299. * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
  1300. */
  1301. #if HUSH_DEBUG < 2
  1302. # define msg_and_die_if_script(lineno, ...) msg_and_die_if_script(__VA_ARGS__)
  1303. # define syntax_error(lineno, msg) syntax_error(msg)
  1304. # define syntax_error_at(lineno, msg) syntax_error_at(msg)
  1305. # define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
  1306. # define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
  1307. # define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
  1308. #endif
  1309. static void die_if_script(void)
  1310. {
  1311. if (!G_interactive_fd) {
  1312. if (G.last_exitcode) /* sometines it's 2, not 1 (bash compat) */
  1313. xfunc_error_retval = G.last_exitcode;
  1314. xfunc_die();
  1315. }
  1316. }
  1317. static void msg_and_die_if_script(unsigned lineno, const char *fmt, ...)
  1318. {
  1319. va_list p;
  1320. #if HUSH_DEBUG >= 2
  1321. bb_error_msg("hush.c:%u", lineno);
  1322. #endif
  1323. va_start(p, fmt);
  1324. bb_verror_msg(fmt, p, NULL);
  1325. va_end(p);
  1326. die_if_script();
  1327. }
  1328. static void syntax_error(unsigned lineno UNUSED_PARAM, const char *msg)
  1329. {
  1330. if (msg)
  1331. bb_error_msg("syntax error: %s", msg);
  1332. else
  1333. bb_simple_error_msg("syntax error");
  1334. die_if_script();
  1335. }
  1336. static void syntax_error_at(unsigned lineno UNUSED_PARAM, const char *msg)
  1337. {
  1338. bb_error_msg("syntax error at '%s'", msg);
  1339. die_if_script();
  1340. }
  1341. static void syntax_error_unterm_str(unsigned lineno UNUSED_PARAM, const char *s)
  1342. {
  1343. bb_error_msg("syntax error: unterminated %s", s);
  1344. //? source4.tests fails: in bash, echo ${^} in script does not terminate the script
  1345. // die_if_script();
  1346. }
  1347. static void syntax_error_unterm_ch(unsigned lineno, char ch)
  1348. {
  1349. char msg[2] = { ch, '\0' };
  1350. syntax_error_unterm_str(lineno, msg);
  1351. }
  1352. static void syntax_error_unexpected_ch(unsigned lineno UNUSED_PARAM, int ch)
  1353. {
  1354. char msg[2];
  1355. msg[0] = ch;
  1356. msg[1] = '\0';
  1357. #if HUSH_DEBUG >= 2
  1358. bb_error_msg("hush.c:%u", lineno);
  1359. #endif
  1360. bb_error_msg("syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
  1361. die_if_script();
  1362. }
  1363. #if HUSH_DEBUG < 2
  1364. # undef msg_and_die_if_script
  1365. # undef syntax_error
  1366. # undef syntax_error_at
  1367. # undef syntax_error_unterm_ch
  1368. # undef syntax_error_unterm_str
  1369. # undef syntax_error_unexpected_ch
  1370. #else
  1371. # define msg_and_die_if_script(...) msg_and_die_if_script(__LINE__, __VA_ARGS__)
  1372. # define syntax_error(msg) syntax_error(__LINE__, msg)
  1373. # define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
  1374. # define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
  1375. # define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
  1376. # define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
  1377. #endif
  1378. /* Utility functions
  1379. */
  1380. /* Replace each \x with x in place, return ptr past NUL. */
  1381. static char *unbackslash(char *src)
  1382. {
  1383. char *dst = src = strchrnul(src, '\\');
  1384. while (1) {
  1385. if (*src == '\\') {
  1386. src++;
  1387. if (*src != '\0') {
  1388. /* \x -> x */
  1389. *dst++ = *src++;
  1390. continue;
  1391. }
  1392. /* else: "\<nul>". Do not delete this backslash.
  1393. * Testcase: eval 'echo ok\'
  1394. */
  1395. *dst++ = '\\';
  1396. /* fallthrough */
  1397. }
  1398. if ((*dst++ = *src++) == '\0')
  1399. break;
  1400. }
  1401. return dst;
  1402. }
  1403. static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
  1404. {
  1405. int i;
  1406. unsigned count1;
  1407. unsigned count2;
  1408. char **v;
  1409. v = strings;
  1410. count1 = 0;
  1411. if (v) {
  1412. while (*v) {
  1413. count1++;
  1414. v++;
  1415. }
  1416. }
  1417. count2 = 0;
  1418. v = add;
  1419. while (*v) {
  1420. count2++;
  1421. v++;
  1422. }
  1423. v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
  1424. v[count1 + count2] = NULL;
  1425. i = count2;
  1426. while (--i >= 0)
  1427. v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
  1428. return v;
  1429. }
  1430. #if LEAK_HUNTING
  1431. static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
  1432. {
  1433. char **ptr = add_strings_to_strings(strings, add, need_to_dup);
  1434. fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
  1435. return ptr;
  1436. }
  1437. #define add_strings_to_strings(strings, add, need_to_dup) \
  1438. xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
  1439. #endif
  1440. /* Note: takes ownership of "add" ptr (it is not strdup'ed) */
  1441. static char **add_string_to_strings(char **strings, char *add)
  1442. {
  1443. char *v[2];
  1444. v[0] = add;
  1445. v[1] = NULL;
  1446. return add_strings_to_strings(strings, v, /*dup:*/ 0);
  1447. }
  1448. #if LEAK_HUNTING
  1449. static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
  1450. {
  1451. char **ptr = add_string_to_strings(strings, add);
  1452. fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
  1453. return ptr;
  1454. }
  1455. #define add_string_to_strings(strings, add) \
  1456. xx_add_string_to_strings(__LINE__, strings, add)
  1457. #endif
  1458. static void free_strings(char **strings)
  1459. {
  1460. char **v;
  1461. if (!strings)
  1462. return;
  1463. v = strings;
  1464. while (*v) {
  1465. free(*v);
  1466. v++;
  1467. }
  1468. free(strings);
  1469. }
  1470. static int dup_CLOEXEC(int fd, int avoid_fd)
  1471. {
  1472. int newfd;
  1473. repeat:
  1474. newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
  1475. if (newfd >= 0) {
  1476. if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
  1477. fcntl(newfd, F_SETFD, FD_CLOEXEC);
  1478. } else { /* newfd < 0 */
  1479. if (errno == EBUSY)
  1480. goto repeat;
  1481. if (errno == EINTR)
  1482. goto repeat;
  1483. }
  1484. return newfd;
  1485. }
  1486. static int xdup_CLOEXEC_and_close(int fd, int avoid_fd)
  1487. {
  1488. int newfd;
  1489. repeat:
  1490. newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
  1491. if (newfd < 0) {
  1492. if (errno == EBUSY)
  1493. goto repeat;
  1494. if (errno == EINTR)
  1495. goto repeat;
  1496. /* fd was not open? */
  1497. if (errno == EBADF)
  1498. return fd;
  1499. xfunc_die();
  1500. }
  1501. if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
  1502. fcntl(newfd, F_SETFD, FD_CLOEXEC);
  1503. close(fd);
  1504. return newfd;
  1505. }
  1506. /* Manipulating HFILEs */
  1507. static HFILE *hfopen(const char *name)
  1508. {
  1509. HFILE *fp;
  1510. int fd;
  1511. fd = STDIN_FILENO;
  1512. if (name) {
  1513. fd = open(name, O_RDONLY | O_CLOEXEC);
  1514. if (fd < 0)
  1515. return NULL;
  1516. if (O_CLOEXEC == 0) /* ancient libc */
  1517. close_on_exec_on(fd);
  1518. }
  1519. fp = xmalloc(sizeof(*fp));
  1520. if (name == NULL)
  1521. G.HFILE_stdin = fp;
  1522. fp->fd = fd;
  1523. fp->cur = fp->end = fp->buf;
  1524. fp->next_hfile = G.HFILE_list;
  1525. G.HFILE_list = fp;
  1526. return fp;
  1527. }
  1528. static void hfclose(HFILE *fp)
  1529. {
  1530. HFILE **pp = &G.HFILE_list;
  1531. while (*pp) {
  1532. HFILE *cur = *pp;
  1533. if (cur == fp) {
  1534. *pp = cur->next_hfile;
  1535. break;
  1536. }
  1537. pp = &cur->next_hfile;
  1538. }
  1539. if (fp->fd >= 0)
  1540. close(fp->fd);
  1541. free(fp);
  1542. }
  1543. static int refill_HFILE_and_getc(HFILE *fp)
  1544. {
  1545. int n;
  1546. if (fp->fd < 0) {
  1547. /* Already saw EOF */
  1548. return EOF;
  1549. }
  1550. /* Try to buffer more input */
  1551. fp->cur = fp->buf;
  1552. n = safe_read(fp->fd, fp->buf, sizeof(fp->buf));
  1553. if (n < 0) {
  1554. bb_simple_perror_msg("read error");
  1555. n = 0;
  1556. }
  1557. fp->end = fp->buf + n;
  1558. if (n == 0) {
  1559. /* EOF/error */
  1560. close(fp->fd);
  1561. fp->fd = -1;
  1562. return EOF;
  1563. }
  1564. return (unsigned char)(*fp->cur++);
  1565. }
  1566. /* Inlined for common case of non-empty buffer.
  1567. */
  1568. static ALWAYS_INLINE int hfgetc(HFILE *fp)
  1569. {
  1570. if (fp->cur < fp->end)
  1571. return (unsigned char)(*fp->cur++);
  1572. /* Buffer empty */
  1573. return refill_HFILE_and_getc(fp);
  1574. }
  1575. static int move_HFILEs_on_redirect(int fd, int avoid_fd)
  1576. {
  1577. HFILE *fl = G.HFILE_list;
  1578. while (fl) {
  1579. if (fd == fl->fd) {
  1580. /* We use it only on script files, they are all CLOEXEC */
  1581. fl->fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
  1582. debug_printf_redir("redirect_fd %d: matches a script fd, moving it to %d\n", fd, fl->fd);
  1583. return 1; /* "found and moved" */
  1584. }
  1585. fl = fl->next_hfile;
  1586. }
  1587. #if ENABLE_HUSH_MODE_X
  1588. if (G.x_mode_fd > 0 && fd == G.x_mode_fd) {
  1589. G.x_mode_fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
  1590. return 1; /* "found and moved" */
  1591. }
  1592. #endif
  1593. return 0; /* "not in the list" */
  1594. }
  1595. #if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
  1596. static void close_all_HFILE_list(void)
  1597. {
  1598. HFILE *fl = G.HFILE_list;
  1599. while (fl) {
  1600. /* hfclose would also free HFILE object.
  1601. * It is disastrous if we share memory with a vforked parent.
  1602. * I'm not sure we never come here after vfork.
  1603. * Therefore just close fd, nothing more.
  1604. *
  1605. * ">" instead of ">=": we don't close fd#0,
  1606. * interactive shell uses hfopen(NULL) as stdin input
  1607. * which has fl->fd == 0, but fd#0 gets redirected in pipes.
  1608. * If we'd close it here, then e.g. interactive "set | sort"
  1609. * with NOFORKed sort, would have sort's input fd closed.
  1610. */
  1611. if (fl->fd > 0)
  1612. /*hfclose(fl); - unsafe */
  1613. close(fl->fd);
  1614. fl = fl->next_hfile;
  1615. }
  1616. }
  1617. #endif
  1618. static int fd_in_HFILEs(int fd)
  1619. {
  1620. HFILE *fl = G.HFILE_list;
  1621. while (fl) {
  1622. if (fl->fd == fd)
  1623. return 1;
  1624. fl = fl->next_hfile;
  1625. }
  1626. return 0;
  1627. }
  1628. /* Helpers for setting new $n and restoring them back
  1629. */
  1630. typedef struct save_arg_t {
  1631. char *sv_argv0;
  1632. char **sv_g_argv;
  1633. int sv_g_argc;
  1634. IF_HUSH_SET(smallint sv_g_malloced;)
  1635. } save_arg_t;
  1636. static void save_and_replace_G_args(save_arg_t *sv, char **argv)
  1637. {
  1638. sv->sv_argv0 = argv[0];
  1639. sv->sv_g_argv = G.global_argv;
  1640. sv->sv_g_argc = G.global_argc;
  1641. IF_HUSH_SET(sv->sv_g_malloced = G.global_args_malloced;)
  1642. argv[0] = G.global_argv[0]; /* retain $0 */
  1643. G.global_argv = argv;
  1644. IF_HUSH_SET(G.global_args_malloced = 0;)
  1645. G.global_argc = 1 + string_array_len(argv + 1);
  1646. }
  1647. static void restore_G_args(save_arg_t *sv, char **argv)
  1648. {
  1649. #if ENABLE_HUSH_SET
  1650. if (G.global_args_malloced) {
  1651. /* someone ran "set -- arg1 arg2 ...", undo */
  1652. char **pp = G.global_argv;
  1653. while (*++pp) /* note: does not free $0 */
  1654. free(*pp);
  1655. free(G.global_argv);
  1656. }
  1657. #endif
  1658. argv[0] = sv->sv_argv0;
  1659. G.global_argv = sv->sv_g_argv;
  1660. G.global_argc = sv->sv_g_argc;
  1661. IF_HUSH_SET(G.global_args_malloced = sv->sv_g_malloced;)
  1662. }
  1663. /* Basic theory of signal handling in shell
  1664. * ========================================
  1665. * This does not describe what hush does, rather, it is current understanding
  1666. * what it _should_ do. If it doesn't, it's a bug.
  1667. * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
  1668. *
  1669. * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
  1670. * is finished or backgrounded. It is the same in interactive and
  1671. * non-interactive shells, and is the same regardless of whether
  1672. * a user trap handler is installed or a shell special one is in effect.
  1673. * ^C or ^Z from keyboard seems to execute "at once" because it usually
  1674. * backgrounds (i.e. stops) or kills all members of currently running
  1675. * pipe.
  1676. *
  1677. * Wait builtin is interruptible by signals for which user trap is set
  1678. * or by SIGINT in interactive shell.
  1679. *
  1680. * Trap handlers will execute even within trap handlers. (right?)
  1681. *
  1682. * User trap handlers are forgotten when subshell ("(cmd)") is entered,
  1683. * except for handlers set to '' (empty string).
  1684. *
  1685. * If job control is off, backgrounded commands ("cmd &")
  1686. * have SIGINT, SIGQUIT set to SIG_IGN.
  1687. *
  1688. * Commands which are run in command substitution ("`cmd`")
  1689. * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
  1690. *
  1691. * Ordinary commands have signals set to SIG_IGN/DFL as inherited
  1692. * by the shell from its parent.
  1693. *
  1694. * Signals which differ from SIG_DFL action
  1695. * (note: child (i.e., [v]forked) shell is not an interactive shell):
  1696. *
  1697. * SIGQUIT: ignore
  1698. * SIGTERM (interactive): ignore
  1699. * SIGHUP (interactive):
  1700. * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
  1701. * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
  1702. * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
  1703. * that all pipe members are stopped. Try this in bash:
  1704. * while :; do :; done - ^Z does not background it
  1705. * (while :; do :; done) - ^Z backgrounds it
  1706. * SIGINT (interactive): wait for last pipe, ignore the rest
  1707. * of the command line, show prompt. NB: ^C does not send SIGINT
  1708. * to interactive shell while shell is waiting for a pipe,
  1709. * since shell is bg'ed (is not in foreground process group).
  1710. * Example 1: this waits 5 sec, but does not execute ls:
  1711. * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
  1712. * Example 2: this does not wait and does not execute ls:
  1713. * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
  1714. * Example 3: this does not wait 5 sec, but executes ls:
  1715. * "sleep 5; ls -l" + press ^C
  1716. * Example 4: this does not wait and does not execute ls:
  1717. * "sleep 5 & wait; ls -l" + press ^C
  1718. *
  1719. * (What happens to signals which are IGN on shell start?)
  1720. * (What happens with signal mask on shell start?)
  1721. *
  1722. * Old implementation
  1723. * ==================
  1724. * We use in-kernel pending signal mask to determine which signals were sent.
  1725. * We block all signals which we don't want to take action immediately,
  1726. * i.e. we block all signals which need to have special handling as described
  1727. * above, and all signals which have traps set.
  1728. * After each pipe execution, we extract any pending signals via sigtimedwait()
  1729. * and act on them.
  1730. *
  1731. * unsigned special_sig_mask: a mask of such "special" signals
  1732. * sigset_t blocked_set: current blocked signal set
  1733. *
  1734. * "trap - SIGxxx":
  1735. * clear bit in blocked_set unless it is also in special_sig_mask
  1736. * "trap 'cmd' SIGxxx":
  1737. * set bit in blocked_set (even if 'cmd' is '')
  1738. * after [v]fork, if we plan to be a shell:
  1739. * unblock signals with special interactive handling
  1740. * (child shell is not interactive),
  1741. * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
  1742. * after [v]fork, if we plan to exec:
  1743. * POSIX says fork clears pending signal mask in child - no need to clear it.
  1744. * Restore blocked signal set to one inherited by shell just prior to exec.
  1745. *
  1746. * Note: as a result, we do not use signal handlers much. The only uses
  1747. * are to count SIGCHLDs
  1748. * and to restore tty pgrp on signal-induced exit.
  1749. *
  1750. * Note 2 (compat):
  1751. * Standard says "When a subshell is entered, traps that are not being ignored
  1752. * are set to the default actions". bash interprets it so that traps which
  1753. * are set to '' (ignore) are NOT reset to defaults. We do the same.
  1754. *
  1755. * Problem: the above approach makes it unwieldy to catch signals while
  1756. * we are in read builtin, or while we read commands from stdin:
  1757. * masked signals are not visible!
  1758. *
  1759. * New implementation
  1760. * ==================
  1761. * We record each signal we are interested in by installing signal handler
  1762. * for them - a bit like emulating kernel pending signal mask in userspace.
  1763. * We are interested in: signals which need to have special handling
  1764. * as described above, and all signals which have traps set.
  1765. * Signals are recorded in pending_set.
  1766. * After each pipe execution, we extract any pending signals
  1767. * and act on them.
  1768. *
  1769. * unsigned special_sig_mask: a mask of shell-special signals.
  1770. * unsigned fatal_sig_mask: a mask of signals on which we restore tty pgrp.
  1771. * char *traps[sig] if trap for sig is set (even if it's '').
  1772. * sigset_t pending_set: set of sigs we received.
  1773. *
  1774. * "trap - SIGxxx":
  1775. * if sig is in special_sig_mask, set handler back to:
  1776. * record_pending_signo, or to IGN if it's a tty stop signal
  1777. * if sig is in fatal_sig_mask, set handler back to sigexit.
  1778. * else: set handler back to SIG_DFL
  1779. * "trap 'cmd' SIGxxx":
  1780. * set handler to record_pending_signo.
  1781. * "trap '' SIGxxx":
  1782. * set handler to SIG_IGN.
  1783. * after [v]fork, if we plan to be a shell:
  1784. * set signals with special interactive handling to SIG_DFL
  1785. * (because child shell is not interactive),
  1786. * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
  1787. * after [v]fork, if we plan to exec:
  1788. * POSIX says fork clears pending signal mask in child - no need to clear it.
  1789. *
  1790. * To make wait builtin interruptible, we handle SIGCHLD as special signal,
  1791. * otherwise (if we leave it SIG_DFL) sigsuspend in wait builtin will not wake up on it.
  1792. *
  1793. * Note (compat):
  1794. * Standard says "When a subshell is entered, traps that are not being ignored
  1795. * are set to the default actions". bash interprets it so that traps which
  1796. * are set to '' (ignore) are NOT reset to defaults. We do the same.
  1797. */
  1798. enum {
  1799. SPECIAL_INTERACTIVE_SIGS = 0
  1800. | (1 << SIGTERM)
  1801. | (1 << SIGINT)
  1802. | (1 << SIGHUP)
  1803. ,
  1804. SPECIAL_JOBSTOP_SIGS = 0
  1805. #if ENABLE_HUSH_JOB
  1806. | (1 << SIGTTIN)
  1807. | (1 << SIGTTOU)
  1808. | (1 << SIGTSTP)
  1809. #endif
  1810. ,
  1811. };
  1812. static void record_pending_signo(int sig)
  1813. {
  1814. sigaddset(&G.pending_set, sig);
  1815. #if ENABLE_HUSH_FAST
  1816. if (sig == SIGCHLD) {
  1817. G.count_SIGCHLD++;
  1818. //bb_error_msg("[%d] SIGCHLD_handler: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
  1819. }
  1820. #endif
  1821. }
  1822. static sighandler_t install_sighandler(int sig, sighandler_t handler)
  1823. {
  1824. struct sigaction old_sa;
  1825. /* We could use signal() to install handlers... almost:
  1826. * except that we need to mask ALL signals while handlers run.
  1827. * I saw signal nesting in strace, race window isn't small.
  1828. * SA_RESTART is also needed, but in Linux, signal()
  1829. * sets SA_RESTART too.
  1830. */
  1831. /* memset(&G.sa, 0, sizeof(G.sa)); - already done */
  1832. /* sigfillset(&G.sa.sa_mask); - already done */
  1833. /* G.sa.sa_flags = SA_RESTART; - already done */
  1834. G.sa.sa_handler = handler;
  1835. sigaction(sig, &G.sa, &old_sa);
  1836. return old_sa.sa_handler;
  1837. }
  1838. static void hush_exit(int exitcode) NORETURN;
  1839. static void restore_ttypgrp_and__exit(void) NORETURN;
  1840. static void restore_ttypgrp_and__exit(void)
  1841. {
  1842. /* xfunc has failed! die die die */
  1843. /* no EXIT traps, this is an escape hatch! */
  1844. G.exiting = 1;
  1845. hush_exit(xfunc_error_retval);
  1846. }
  1847. #if ENABLE_HUSH_JOB
  1848. /* Needed only on some libc:
  1849. * It was observed that on exit(), fgetc'ed buffered data
  1850. * gets "unwound" via lseek(fd, -NUM, SEEK_CUR).
  1851. * With the net effect that even after fork(), not vfork(),
  1852. * exit() in NOEXECed applet in "sh SCRIPT":
  1853. * noexec_applet_here
  1854. * echo END_OF_SCRIPT
  1855. * lseeks fd in input FILE object from EOF to "e" in "echo END_OF_SCRIPT".
  1856. * This makes "echo END_OF_SCRIPT" executed twice.
  1857. * Similar problems can be seen with msg_and_die_if_script() -> xfunc_die()
  1858. * and in `cmd` handling.
  1859. * If set as die_func(), this makes xfunc_die() exit via _exit(), not exit():
  1860. */
  1861. static void fflush_and__exit(void) NORETURN;
  1862. static void fflush_and__exit(void)
  1863. {
  1864. fflush_all();
  1865. _exit(xfunc_error_retval);
  1866. }
  1867. /* After [v]fork, in child: do not restore tty pgrp on xfunc death */
  1868. # define disable_restore_tty_pgrp_on_exit() (die_func = fflush_and__exit)
  1869. /* After [v]fork, in parent: restore tty pgrp on xfunc death */
  1870. # define enable_restore_tty_pgrp_on_exit() (die_func = restore_ttypgrp_and__exit)
  1871. /* Restores tty foreground process group, and exits.
  1872. * May be called as signal handler for fatal signal
  1873. * (will resend signal to itself, producing correct exit state)
  1874. * or called directly with -EXITCODE.
  1875. * We also call it if xfunc is exiting.
  1876. */
  1877. static void sigexit(int sig) NORETURN;
  1878. static void sigexit(int sig)
  1879. {
  1880. /* Careful: we can end up here after [v]fork. Do not restore
  1881. * tty pgrp then, only top-level shell process does that */
  1882. if (G_saved_tty_pgrp && getpid() == G.root_pid) {
  1883. /* Disable all signals: job control, SIGPIPE, etc.
  1884. * Mostly paranoid measure, to prevent infinite SIGTTOU.
  1885. */
  1886. sigprocmask_allsigs(SIG_BLOCK);
  1887. tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
  1888. }
  1889. /* Not a signal, just exit */
  1890. if (sig <= 0)
  1891. _exit(- sig);
  1892. kill_myself_with_sig(sig); /* does not return */
  1893. }
  1894. #else
  1895. # define disable_restore_tty_pgrp_on_exit() ((void)0)
  1896. # define enable_restore_tty_pgrp_on_exit() ((void)0)
  1897. #endif
  1898. static sighandler_t pick_sighandler(unsigned sig)
  1899. {
  1900. sighandler_t handler = SIG_DFL;
  1901. if (sig < sizeof(unsigned)*8) {
  1902. unsigned sigmask = (1 << sig);
  1903. #if ENABLE_HUSH_JOB
  1904. /* is sig fatal? */
  1905. if (G_fatal_sig_mask & sigmask)
  1906. handler = sigexit;
  1907. else
  1908. #endif
  1909. /* sig has special handling? */
  1910. if (G.special_sig_mask & sigmask) {
  1911. handler = record_pending_signo;
  1912. /* TTIN/TTOU/TSTP can't be set to record_pending_signo
  1913. * in order to ignore them: they will be raised
  1914. * in an endless loop when we try to do some
  1915. * terminal ioctls! We do have to _ignore_ these.
  1916. */
  1917. if (SPECIAL_JOBSTOP_SIGS & sigmask)
  1918. handler = SIG_IGN;
  1919. }
  1920. }
  1921. return handler;
  1922. }
  1923. /* Restores tty foreground process group, and exits. */
  1924. static void hush_exit(int exitcode)
  1925. {
  1926. #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
  1927. if (G.line_input_state)
  1928. save_history(G.line_input_state);
  1929. #endif
  1930. fflush_all();
  1931. if (G.exiting <= 0 && G_traps && G_traps[0] && G_traps[0][0]) {
  1932. char *argv[3];
  1933. /* argv[0] is unused */
  1934. argv[1] = xstrdup(G_traps[0]); /* copy, since EXIT trap handler may modify G_traps[0] */
  1935. argv[2] = NULL;
  1936. G.exiting = 1; /* prevent EXIT trap recursion */
  1937. /* Note: G_traps[0] is not cleared!
  1938. * "trap" will still show it, if executed
  1939. * in the handler */
  1940. builtin_eval(argv);
  1941. }
  1942. #if ENABLE_FEATURE_CLEAN_UP
  1943. {
  1944. struct variable *cur_var;
  1945. if (G.cwd != bb_msg_unknown)
  1946. free((char*)G.cwd);
  1947. cur_var = G.top_var;
  1948. while (cur_var) {
  1949. struct variable *tmp = cur_var;
  1950. if (!cur_var->max_len)
  1951. free(cur_var->varstr);
  1952. cur_var = cur_var->next;
  1953. free(tmp);
  1954. }
  1955. }
  1956. #endif
  1957. fflush_all();
  1958. #if ENABLE_HUSH_JOB
  1959. sigexit(- (exitcode & 0xff));
  1960. #else
  1961. _exit(exitcode);
  1962. #endif
  1963. }
  1964. //TODO: return a mask of ALL handled sigs?
  1965. static int check_and_run_traps(void)
  1966. {
  1967. int last_sig = 0;
  1968. while (1) {
  1969. int sig;
  1970. if (sigisemptyset(&G.pending_set))
  1971. break;
  1972. sig = 0;
  1973. do {
  1974. sig++;
  1975. if (sigismember(&G.pending_set, sig)) {
  1976. sigdelset(&G.pending_set, sig);
  1977. goto got_sig;
  1978. }
  1979. } while (sig < NSIG);
  1980. break;
  1981. got_sig:
  1982. #if ENABLE_HUSH_TRAP
  1983. if (G_traps && G_traps[sig]) {
  1984. debug_printf_exec("%s: sig:%d handler:'%s'\n", __func__, sig, G.traps[sig]);
  1985. if (G_traps[sig][0]) {
  1986. /* We have user-defined handler */
  1987. smalluint save_rcode;
  1988. int save_pre;
  1989. char *argv[3];
  1990. /* argv[0] is unused */
  1991. argv[1] = xstrdup(G_traps[sig]);
  1992. /* why strdup? trap can modify itself: trap 'trap "echo oops" INT' INT */
  1993. argv[2] = NULL;
  1994. save_pre = G.pre_trap_exitcode;
  1995. G.pre_trap_exitcode = save_rcode = G.last_exitcode;
  1996. builtin_eval(argv);
  1997. free(argv[1]);
  1998. G.pre_trap_exitcode = save_pre;
  1999. G.last_exitcode = save_rcode;
  2000. # if ENABLE_HUSH_FUNCTIONS
  2001. if (G.return_exitcode >= 0) {
  2002. debug_printf_exec("trap exitcode:%d\n", G.return_exitcode);
  2003. G.last_exitcode = G.return_exitcode;
  2004. }
  2005. # endif
  2006. last_sig = sig;
  2007. } /* else: "" trap, ignoring signal */
  2008. continue;
  2009. }
  2010. #endif
  2011. /* not a trap: special action */
  2012. switch (sig) {
  2013. case SIGINT:
  2014. debug_printf_exec("%s: sig:%d default SIGINT handler\n", __func__, sig);
  2015. G.flag_SIGINT = 1;
  2016. last_sig = sig;
  2017. break;
  2018. #if ENABLE_HUSH_JOB
  2019. case SIGHUP: {
  2020. //TODO: why are we doing this? ash and dash don't do this,
  2021. //they have no handler for SIGHUP at all,
  2022. //they rely on kernel to send SIGHUP+SIGCONT to orphaned process groups
  2023. struct pipe *job;
  2024. debug_printf_exec("%s: sig:%d default SIGHUP handler\n", __func__, sig);
  2025. /* bash is observed to signal whole process groups,
  2026. * not individual processes */
  2027. for (job = G.job_list; job; job = job->next) {
  2028. if (job->pgrp <= 0)
  2029. continue;
  2030. debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
  2031. if (kill(- job->pgrp, SIGHUP) == 0)
  2032. kill(- job->pgrp, SIGCONT);
  2033. }
  2034. sigexit(SIGHUP);
  2035. }
  2036. #endif
  2037. #if ENABLE_HUSH_FAST
  2038. case SIGCHLD:
  2039. debug_printf_exec("%s: sig:%d default SIGCHLD handler\n", __func__, sig);
  2040. G.count_SIGCHLD++;
  2041. //bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
  2042. /* Note:
  2043. * We don't do 'last_sig = sig' here -> NOT returning this sig.
  2044. * This simplifies wait builtin a bit.
  2045. */
  2046. break;
  2047. #endif
  2048. default: /* ignored: */
  2049. debug_printf_exec("%s: sig:%d default handling is to ignore\n", __func__, sig);
  2050. /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
  2051. /* Note:
  2052. * We don't do 'last_sig = sig' here -> NOT returning this sig.
  2053. * Example: wait is not interrupted by TERM
  2054. * in interactive shell, because TERM is ignored.
  2055. */
  2056. break;
  2057. }
  2058. }
  2059. return last_sig;
  2060. }
  2061. static const char *get_cwd(int force)
  2062. {
  2063. if (force || G.cwd == NULL) {
  2064. /* xrealloc_getcwd_or_warn(arg) calls free(arg),
  2065. * we must not try to free(bb_msg_unknown) */
  2066. if (G.cwd == bb_msg_unknown)
  2067. G.cwd = NULL;
  2068. G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
  2069. if (!G.cwd)
  2070. G.cwd = bb_msg_unknown;
  2071. }
  2072. return G.cwd;
  2073. }
  2074. /*
  2075. * Shell and environment variable support
  2076. */
  2077. static struct variable **get_ptr_to_local_var(const char *name, unsigned len)
  2078. {
  2079. struct variable **pp;
  2080. struct variable *cur;
  2081. pp = &G.top_var;
  2082. while ((cur = *pp) != NULL) {
  2083. if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
  2084. return pp;
  2085. pp = &cur->next;
  2086. }
  2087. return NULL;
  2088. }
  2089. static const char* FAST_FUNC get_local_var_value(const char *name)
  2090. {
  2091. struct variable **vpp;
  2092. unsigned len = strlen(name);
  2093. if (G.expanded_assignments) {
  2094. char **cpp = G.expanded_assignments;
  2095. while (*cpp) {
  2096. char *cp = *cpp;
  2097. if (strncmp(cp, name, len) == 0 && cp[len] == '=')
  2098. return cp + len + 1;
  2099. cpp++;
  2100. }
  2101. }
  2102. vpp = get_ptr_to_local_var(name, len);
  2103. if (vpp)
  2104. return (*vpp)->varstr + len + 1;
  2105. if (strcmp(name, "PPID") == 0)
  2106. return utoa(G.root_ppid);
  2107. // bash compat: UID? EUID?
  2108. #if ENABLE_HUSH_RANDOM_SUPPORT
  2109. if (strcmp(name, "RANDOM") == 0)
  2110. return utoa(next_random(&G.random_gen));
  2111. #endif
  2112. #if ENABLE_HUSH_LINENO_VAR
  2113. if (strcmp(name, "LINENO") == 0)
  2114. return utoa(G.execute_lineno);
  2115. #endif
  2116. #if BASH_EPOCH_VARS
  2117. {
  2118. const char *fmt = NULL;
  2119. if (strcmp(name, "EPOCHSECONDS") == 0)
  2120. fmt = "%lu";
  2121. else if (strcmp(name, "EPOCHREALTIME") == 0)
  2122. fmt = "%lu.%06u";
  2123. if (fmt) {
  2124. struct timeval tv;
  2125. gettimeofday(&tv, NULL);
  2126. sprintf(G.epoch_buf, fmt, (unsigned long)tv.tv_sec,
  2127. (unsigned)tv.tv_usec);
  2128. return G.epoch_buf;
  2129. }
  2130. }
  2131. #endif
  2132. return NULL;
  2133. }
  2134. #if ENABLE_HUSH_GETOPTS
  2135. static void handle_changed_special_names(const char *name, unsigned name_len)
  2136. {
  2137. if (name_len == 6) {
  2138. if (strncmp(name, "OPTIND", 6) == 0) {
  2139. G.getopt_count = 0;
  2140. return;
  2141. }
  2142. }
  2143. }
  2144. #else
  2145. /* Do not even bother evaluating arguments */
  2146. # define handle_changed_special_names(...) ((void)0)
  2147. #endif
  2148. /* str holds "NAME=VAL" and is expected to be malloced.
  2149. * We take ownership of it.
  2150. */
  2151. #define SETFLAG_EXPORT (1 << 0)
  2152. #define SETFLAG_UNEXPORT (1 << 1)
  2153. #define SETFLAG_MAKE_RO (1 << 2)
  2154. #define SETFLAG_VARLVL_SHIFT 3
  2155. static int set_local_var(char *str, unsigned flags)
  2156. {
  2157. struct variable **cur_pp;
  2158. struct variable *cur;
  2159. char *free_me = NULL;
  2160. char *eq_sign;
  2161. int name_len;
  2162. int retval;
  2163. unsigned local_lvl = (flags >> SETFLAG_VARLVL_SHIFT);
  2164. eq_sign = strchr(str, '=');
  2165. if (HUSH_DEBUG && !eq_sign)
  2166. bb_simple_error_msg_and_die("BUG in setvar");
  2167. name_len = eq_sign - str + 1; /* including '=' */
  2168. cur_pp = &G.top_var;
  2169. while ((cur = *cur_pp) != NULL) {
  2170. if (strncmp(cur->varstr, str, name_len) != 0) {
  2171. cur_pp = &cur->next;
  2172. continue;
  2173. }
  2174. /* We found an existing var with this name */
  2175. if (cur->flg_read_only) {
  2176. bb_error_msg("%s: readonly variable", str);
  2177. free(str);
  2178. //NOTE: in bash, assignment in "export READONLY_VAR=Z" fails, and sets $?=1,
  2179. //but export per se succeeds (does put the var in env). We don't mimic that.
  2180. return -1;
  2181. }
  2182. if (flags & SETFLAG_UNEXPORT) { // && cur->flg_export ?
  2183. debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
  2184. *eq_sign = '\0';
  2185. unsetenv(str);
  2186. *eq_sign = '=';
  2187. }
  2188. if (cur->var_nest_level < local_lvl) {
  2189. /* bash 3.2.33(1) and exported vars:
  2190. * # export z=z
  2191. * # f() { local z=a; env | grep ^z; }
  2192. * # f
  2193. * z=a
  2194. * # env | grep ^z
  2195. * z=z
  2196. */
  2197. if (cur->flg_export)
  2198. flags |= SETFLAG_EXPORT;
  2199. /* New variable is local ("local VAR=VAL" or
  2200. * "VAR=VAL cmd")
  2201. * and existing one is global, or local
  2202. * on a lower level that new one.
  2203. * Remove it from global variable list:
  2204. */
  2205. *cur_pp = cur->next;
  2206. if (G.shadowed_vars_pp) {
  2207. /* Save in "shadowed" list */
  2208. debug_printf_env("shadowing %s'%s'/%u by '%s'/%u\n",
  2209. cur->flg_export ? "exported " : "",
  2210. cur->varstr, cur->var_nest_level, str, local_lvl
  2211. );
  2212. cur->next = *G.shadowed_vars_pp;
  2213. *G.shadowed_vars_pp = cur;
  2214. } else {
  2215. /* Came from pseudo_exec_argv(), no need to save: delete it */
  2216. debug_printf_env("shadow-deleting %s'%s'/%u by '%s'/%u\n",
  2217. cur->flg_export ? "exported " : "",
  2218. cur->varstr, cur->var_nest_level, str, local_lvl
  2219. );
  2220. if (cur->max_len == 0) /* allocated "VAR=VAL"? */
  2221. free_me = cur->varstr; /* then free it later */
  2222. free(cur);
  2223. }
  2224. break;
  2225. }
  2226. if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
  2227. debug_printf_env("assignement '%s' does not change anything\n", str);
  2228. free_and_exp:
  2229. free(str);
  2230. goto exp;
  2231. }
  2232. /* Replace the value in the found "struct variable" */
  2233. if (cur->max_len != 0) {
  2234. if (cur->max_len >= strnlen(str, cur->max_len + 1)) {
  2235. /* This one is from startup env, reuse space */
  2236. debug_printf_env("reusing startup env for '%s'\n", str);
  2237. strcpy(cur->varstr, str);
  2238. goto free_and_exp;
  2239. }
  2240. /* Can't reuse */
  2241. cur->max_len = 0;
  2242. goto set_str_and_exp;
  2243. }
  2244. /* max_len == 0 signifies "malloced" var, which we can
  2245. * (and have to) free. But we can't free(cur->varstr) here:
  2246. * if cur->flg_export is 1, it is in the environment.
  2247. * We should either unsetenv+free, or wait until putenv,
  2248. * then putenv(new)+free(old).
  2249. */
  2250. free_me = cur->varstr;
  2251. goto set_str_and_exp;
  2252. }
  2253. /* Not found or shadowed - create new variable struct */
  2254. debug_printf_env("%s: alloc new var '%s'/%u\n", __func__, str, local_lvl);
  2255. cur = xzalloc(sizeof(*cur));
  2256. cur->var_nest_level = local_lvl;
  2257. cur->next = *cur_pp;
  2258. *cur_pp = cur;
  2259. set_str_and_exp:
  2260. cur->varstr = str;
  2261. exp:
  2262. #if !BB_MMU || ENABLE_HUSH_READONLY
  2263. if (flags & SETFLAG_MAKE_RO) {
  2264. cur->flg_read_only = 1;
  2265. }
  2266. #endif
  2267. if (flags & SETFLAG_EXPORT)
  2268. cur->flg_export = 1;
  2269. retval = 0;
  2270. if (cur->flg_export) {
  2271. if (flags & SETFLAG_UNEXPORT) {
  2272. cur->flg_export = 0;
  2273. /* unsetenv was already done */
  2274. } else {
  2275. debug_printf_env("%s: putenv '%s'/%u\n", __func__, cur->varstr, cur->var_nest_level);
  2276. retval = putenv(cur->varstr);
  2277. /* fall through to "free(free_me)" -
  2278. * only now we can free old exported malloced string
  2279. */
  2280. }
  2281. }
  2282. free(free_me);
  2283. handle_changed_special_names(cur->varstr, name_len - 1);
  2284. return retval;
  2285. }
  2286. static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
  2287. {
  2288. char *var = xasprintf("%s=%s", name, val);
  2289. set_local_var(var, /*flag:*/ 0);
  2290. }
  2291. /* Used at startup and after each cd */
  2292. static void set_pwd_var(unsigned flag)
  2293. {
  2294. set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)), flag);
  2295. }
  2296. #if ENABLE_HUSH_UNSET || ENABLE_HUSH_GETOPTS
  2297. static int unset_local_var_len(const char *name, int name_len)
  2298. {
  2299. struct variable *cur;
  2300. struct variable **cur_pp;
  2301. cur_pp = &G.top_var;
  2302. while ((cur = *cur_pp) != NULL) {
  2303. if (strncmp(cur->varstr, name, name_len) == 0
  2304. && cur->varstr[name_len] == '='
  2305. ) {
  2306. if (cur->flg_read_only) {
  2307. bb_error_msg("%s: readonly variable", name);
  2308. return EXIT_FAILURE;
  2309. }
  2310. *cur_pp = cur->next;
  2311. debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
  2312. bb_unsetenv(cur->varstr);
  2313. if (!cur->max_len)
  2314. free(cur->varstr);
  2315. free(cur);
  2316. break;
  2317. }
  2318. cur_pp = &cur->next;
  2319. }
  2320. /* Handle "unset LINENO" et al even if did not find the variable to unset */
  2321. handle_changed_special_names(name, name_len);
  2322. return EXIT_SUCCESS;
  2323. }
  2324. static int unset_local_var(const char *name)
  2325. {
  2326. return unset_local_var_len(name, strlen(name));
  2327. }
  2328. #endif
  2329. /*
  2330. * Helpers for "var1=val1 var2=val2 cmd" feature
  2331. */
  2332. static void add_vars(struct variable *var)
  2333. {
  2334. struct variable *next;
  2335. while (var) {
  2336. next = var->next;
  2337. var->next = G.top_var;
  2338. G.top_var = var;
  2339. if (var->flg_export) {
  2340. debug_printf_env("%s: restoring exported '%s'/%u\n", __func__, var->varstr, var->var_nest_level);
  2341. putenv(var->varstr);
  2342. } else {
  2343. debug_printf_env("%s: restoring variable '%s'/%u\n", __func__, var->varstr, var->var_nest_level);
  2344. }
  2345. var = next;
  2346. }
  2347. }
  2348. /* We put strings[i] into variable table and possibly putenv them.
  2349. * If variable is read only, we can free the strings[i]
  2350. * which attempts to overwrite it.
  2351. * The strings[] vector itself is freed.
  2352. */
  2353. static void set_vars_and_save_old(char **strings)
  2354. {
  2355. char **s;
  2356. if (!strings)
  2357. return;
  2358. s = strings;
  2359. while (*s) {
  2360. struct variable *var_p;
  2361. struct variable **var_pp;
  2362. char *eq;
  2363. eq = strchr(*s, '=');
  2364. if (HUSH_DEBUG && !eq)
  2365. bb_simple_error_msg_and_die("BUG in varexp4");
  2366. var_pp = get_ptr_to_local_var(*s, eq - *s);
  2367. if (var_pp) {
  2368. var_p = *var_pp;
  2369. if (var_p->flg_read_only) {
  2370. char **p;
  2371. bb_error_msg("%s: readonly variable", *s);
  2372. /*
  2373. * "VAR=V BLTIN" unsets VARs after BLTIN completes.
  2374. * If VAR is readonly, leaving it in the list
  2375. * after asssignment error (msg above)
  2376. * causes doubled error message later, on unset.
  2377. */
  2378. debug_printf_env("removing/freeing '%s' element\n", *s);
  2379. free(*s);
  2380. p = s;
  2381. do { *p = p[1]; p++; } while (*p);
  2382. goto next;
  2383. }
  2384. /* below, set_local_var() with nest level will
  2385. * "shadow" (remove) this variable from
  2386. * global linked list.
  2387. */
  2388. }
  2389. debug_printf_env("%s: env override '%s'/%u\n", __func__, *s, G.var_nest_level);
  2390. set_local_var(*s, (G.var_nest_level << SETFLAG_VARLVL_SHIFT) | SETFLAG_EXPORT);
  2391. s++;
  2392. next: ;
  2393. }
  2394. free(strings);
  2395. }
  2396. /*
  2397. * Unicode helper
  2398. */
  2399. static void reinit_unicode_for_hush(void)
  2400. {
  2401. /* Unicode support should be activated even if LANG is set
  2402. * _during_ shell execution, not only if it was set when
  2403. * shell was started. Therefore, re-check LANG every time:
  2404. */
  2405. if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
  2406. || ENABLE_UNICODE_USING_LOCALE
  2407. ) {
  2408. const char *s = get_local_var_value("LC_ALL");
  2409. if (!s) s = get_local_var_value("LC_CTYPE");
  2410. if (!s) s = get_local_var_value("LANG");
  2411. reinit_unicode(s);
  2412. }
  2413. }
  2414. /*
  2415. * in_str support (strings, and "strings" read from files).
  2416. */
  2417. #if ENABLE_HUSH_INTERACTIVE
  2418. /* To test correct lineedit/interactive behavior, type from command line:
  2419. * echo $P\
  2420. * \
  2421. * AT\
  2422. * H\
  2423. * \
  2424. * It exercises a lot of corner cases.
  2425. */
  2426. static const char *setup_prompt_string(void)
  2427. {
  2428. const char *prompt_str;
  2429. debug_printf_prompt("%s promptmode:%d\n", __func__, G.promptmode);
  2430. # if ENABLE_FEATURE_EDITING_FANCY_PROMPT
  2431. prompt_str = get_local_var_value(G.promptmode == 0 ? "PS1" : "PS2");
  2432. if (!prompt_str)
  2433. prompt_str = "";
  2434. # else
  2435. prompt_str = "> "; /* if PS2, else... */
  2436. if (G.promptmode == 0) { /* PS1 */
  2437. /* No fancy prompts supported, (re)generate "CURDIR $ " by hand */
  2438. free(G.PS1);
  2439. /* bash uses $PWD value, even if it is set by user.
  2440. * It uses current dir only if PWD is unset.
  2441. * We always use current dir. */
  2442. G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
  2443. }
  2444. # endif
  2445. debug_printf("prompt_str '%s'\n", prompt_str);
  2446. return prompt_str;
  2447. }
  2448. static int get_user_input(struct in_str *i)
  2449. {
  2450. int r;
  2451. const char *prompt_str;
  2452. prompt_str = setup_prompt_string();
  2453. # if ENABLE_FEATURE_EDITING
  2454. for (;;) {
  2455. reinit_unicode_for_hush();
  2456. if (G.flag_SIGINT) {
  2457. /* There was ^C'ed, make it look prettier: */
  2458. bb_putchar('\n');
  2459. G.flag_SIGINT = 0;
  2460. }
  2461. /* buglet: SIGINT will not make new prompt to appear _at once_,
  2462. * only after <Enter>. (^C works immediately) */
  2463. r = read_line_input(G.line_input_state, prompt_str,
  2464. G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1
  2465. );
  2466. /* read_line_input intercepts ^C, "convert" it to SIGINT */
  2467. if (r == 0)
  2468. raise(SIGINT);
  2469. check_and_run_traps();
  2470. if (r != 0 && !G.flag_SIGINT)
  2471. break;
  2472. /* ^C or SIGINT: repeat */
  2473. /* bash prints ^C even on real SIGINT (non-kbd generated) */
  2474. write(STDOUT_FILENO, "^C", 2);
  2475. G.last_exitcode = 128 + SIGINT;
  2476. }
  2477. if (r < 0) {
  2478. /* EOF/error detected */
  2479. i->p = NULL;
  2480. i->peek_buf[0] = r = EOF;
  2481. return r;
  2482. }
  2483. i->p = G.user_input_buf;
  2484. return (unsigned char)*i->p++;
  2485. # else
  2486. for (;;) {
  2487. G.flag_SIGINT = 0;
  2488. if (i->last_char == '\0' || i->last_char == '\n') {
  2489. /* Why check_and_run_traps here? Try this interactively:
  2490. * $ trap 'echo INT' INT; (sleep 2; kill -INT $$) &
  2491. * $ <[enter], repeatedly...>
  2492. * Without check_and_run_traps, handler never runs.
  2493. */
  2494. check_and_run_traps();
  2495. fputs(prompt_str, stdout);
  2496. }
  2497. fflush_all();
  2498. //FIXME: here ^C or SIGINT will have effect only after <Enter>
  2499. r = hfgetc(i->file);
  2500. /* In !ENABLE_FEATURE_EDITING we don't use read_line_input,
  2501. * no ^C masking happens during fgetc, no special code for ^C:
  2502. * it generates SIGINT as usual.
  2503. */
  2504. check_and_run_traps();
  2505. if (G.flag_SIGINT)
  2506. G.last_exitcode = 128 + SIGINT;
  2507. if (r != '\0')
  2508. break;
  2509. }
  2510. return r;
  2511. # endif
  2512. }
  2513. /* This is the magic location that prints prompts
  2514. * and gets data back from the user */
  2515. static int fgetc_interactive(struct in_str *i)
  2516. {
  2517. int ch;
  2518. /* If it's interactive stdin, get new line. */
  2519. if (G_interactive_fd && i->file == G.HFILE_stdin) {
  2520. /* Returns first char (or EOF), the rest is in i->p[] */
  2521. ch = get_user_input(i);
  2522. G.promptmode = 1; /* PS2 */
  2523. debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
  2524. } else {
  2525. /* Not stdin: script file, sourced file, etc */
  2526. do ch = hfgetc(i->file); while (ch == '\0');
  2527. }
  2528. return ch;
  2529. }
  2530. #else
  2531. static ALWAYS_INLINE int fgetc_interactive(struct in_str *i)
  2532. {
  2533. int ch;
  2534. do ch = hfgetc(i->file); while (ch == '\0');
  2535. return ch;
  2536. }
  2537. #endif /* INTERACTIVE */
  2538. static int i_getch(struct in_str *i)
  2539. {
  2540. int ch;
  2541. if (!i->file) {
  2542. /* string-based in_str */
  2543. ch = (unsigned char)*i->p;
  2544. if (ch != '\0') {
  2545. i->p++;
  2546. i->last_char = ch;
  2547. return ch;
  2548. }
  2549. return EOF;
  2550. }
  2551. /* FILE-based in_str */
  2552. #if ENABLE_FEATURE_EDITING
  2553. /* This can be stdin, check line editing char[] buffer */
  2554. if (i->p && *i->p != '\0') {
  2555. ch = (unsigned char)*i->p++;
  2556. goto out;
  2557. }
  2558. #endif
  2559. /* peek_buf[] is an int array, not char. Can contain EOF. */
  2560. ch = i->peek_buf[0];
  2561. if (ch != 0) {
  2562. int ch2 = i->peek_buf[1];
  2563. i->peek_buf[0] = ch2;
  2564. if (ch2 == 0) /* very likely, avoid redundant write */
  2565. goto out;
  2566. i->peek_buf[1] = 0;
  2567. goto out;
  2568. }
  2569. ch = fgetc_interactive(i);
  2570. out:
  2571. debug_printf("file_get: got '%c' %d\n", ch, ch);
  2572. i->last_char = ch;
  2573. #if ENABLE_HUSH_LINENO_VAR
  2574. if (ch == '\n') {
  2575. G.parse_lineno++;
  2576. debug_printf_parse("G.parse_lineno++ = %u\n", G.parse_lineno);
  2577. }
  2578. #endif
  2579. return ch;
  2580. }
  2581. static int i_peek(struct in_str *i)
  2582. {
  2583. int ch;
  2584. if (!i->file) {
  2585. /* string-based in_str */
  2586. /* Doesn't report EOF on NUL. None of the callers care. */
  2587. return (unsigned char)*i->p;
  2588. }
  2589. /* FILE-based in_str */
  2590. #if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
  2591. /* This can be stdin, check line editing char[] buffer */
  2592. if (i->p && *i->p != '\0')
  2593. return (unsigned char)*i->p;
  2594. #endif
  2595. /* peek_buf[] is an int array, not char. Can contain EOF. */
  2596. ch = i->peek_buf[0];
  2597. if (ch != 0)
  2598. return ch;
  2599. /* Need to get a new char */
  2600. ch = fgetc_interactive(i);
  2601. debug_printf("file_peek: got '%c' %d\n", ch, ch);
  2602. /* Save it by either rolling back line editing buffer, or in i->peek_buf[0] */
  2603. #if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
  2604. if (i->p) {
  2605. i->p -= 1;
  2606. return ch;
  2607. }
  2608. #endif
  2609. i->peek_buf[0] = ch;
  2610. /*i->peek_buf[1] = 0; - already is */
  2611. return ch;
  2612. }
  2613. /* Only ever called if i_peek() was called, and did not return EOF.
  2614. * IOW: we know the previous peek saw an ordinary char, not EOF, not NUL,
  2615. * not end-of-line. Therefore we never need to read a new editing line here.
  2616. */
  2617. static int i_peek2(struct in_str *i)
  2618. {
  2619. int ch;
  2620. /* There are two cases when i->p[] buffer exists.
  2621. * (1) it's a string in_str.
  2622. * (2) It's a file, and we have a saved line editing buffer.
  2623. * In both cases, we know that i->p[0] exists and not NUL, and
  2624. * the peek2 result is in i->p[1].
  2625. */
  2626. if (i->p)
  2627. return (unsigned char)i->p[1];
  2628. /* Now we know it is a file-based in_str. */
  2629. /* peek_buf[] is an int array, not char. Can contain EOF. */
  2630. /* Is there 2nd char? */
  2631. ch = i->peek_buf[1];
  2632. if (ch == 0) {
  2633. /* We did not read it yet, get it now */
  2634. do ch = hfgetc(i->file); while (ch == '\0');
  2635. i->peek_buf[1] = ch;
  2636. }
  2637. debug_printf("file_peek2: got '%c' %d\n", ch, ch);
  2638. return ch;
  2639. }
  2640. static int i_getch_and_eat_bkslash_nl(struct in_str *input)
  2641. {
  2642. for (;;) {
  2643. int ch, ch2;
  2644. ch = i_getch(input);
  2645. if (ch != '\\')
  2646. return ch;
  2647. ch2 = i_peek(input);
  2648. if (ch2 != '\n')
  2649. return ch;
  2650. /* backslash+newline, skip it */
  2651. i_getch(input);
  2652. }
  2653. }
  2654. /* Note: this function _eats_ \<newline> pairs, safe to use plain
  2655. * i_getch() after it instead of i_getch_and_eat_bkslash_nl().
  2656. */
  2657. static int i_peek_and_eat_bkslash_nl(struct in_str *input)
  2658. {
  2659. for (;;) {
  2660. int ch, ch2;
  2661. ch = i_peek(input);
  2662. if (ch != '\\')
  2663. return ch;
  2664. ch2 = i_peek2(input);
  2665. if (ch2 != '\n')
  2666. return ch;
  2667. /* backslash+newline, skip it */
  2668. i_getch(input);
  2669. i_getch(input);
  2670. }
  2671. }
  2672. static void setup_file_in_str(struct in_str *i, HFILE *fp)
  2673. {
  2674. memset(i, 0, sizeof(*i));
  2675. i->file = fp;
  2676. /* i->p = NULL; */
  2677. }
  2678. static void setup_string_in_str(struct in_str *i, const char *s)
  2679. {
  2680. memset(i, 0, sizeof(*i));
  2681. /*i->file = NULL */;
  2682. i->p = s;
  2683. }
  2684. /*
  2685. * o_string support
  2686. */
  2687. #define B_CHUNK (32 * sizeof(char*))
  2688. static void o_reset_to_empty_unquoted(o_string *o)
  2689. {
  2690. o->length = 0;
  2691. o->has_quoted_part = 0;
  2692. if (o->data)
  2693. o->data[0] = '\0';
  2694. }
  2695. static void o_free_and_set_NULL(o_string *o)
  2696. {
  2697. free(o->data);
  2698. memset(o, 0, sizeof(*o));
  2699. }
  2700. static ALWAYS_INLINE void o_free(o_string *o)
  2701. {
  2702. free(o->data);
  2703. }
  2704. static void o_grow_by(o_string *o, int len)
  2705. {
  2706. if (o->length + len > o->maxlen) {
  2707. o->maxlen += (2 * len) | (B_CHUNK-1);
  2708. o->data = xrealloc(o->data, 1 + o->maxlen);
  2709. }
  2710. }
  2711. static void o_addchr(o_string *o, int ch)
  2712. {
  2713. debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
  2714. if (o->length < o->maxlen) {
  2715. /* likely. avoid o_grow_by() call */
  2716. add:
  2717. o->data[o->length] = ch;
  2718. o->length++;
  2719. o->data[o->length] = '\0';
  2720. return;
  2721. }
  2722. o_grow_by(o, 1);
  2723. goto add;
  2724. }
  2725. #if 0
  2726. /* Valid only if we know o_string is not empty */
  2727. static void o_delchr(o_string *o)
  2728. {
  2729. o->length--;
  2730. o->data[o->length] = '\0';
  2731. }
  2732. #endif
  2733. static void o_addblock(o_string *o, const char *str, int len)
  2734. {
  2735. o_grow_by(o, len);
  2736. ((char*)mempcpy(&o->data[o->length], str, len))[0] = '\0';
  2737. o->length += len;
  2738. }
  2739. static void o_addstr(o_string *o, const char *str)
  2740. {
  2741. o_addblock(o, str, strlen(str));
  2742. }
  2743. static void o_addstr_with_NUL(o_string *o, const char *str)
  2744. {
  2745. o_addblock(o, str, strlen(str) + 1);
  2746. }
  2747. #if !BB_MMU
  2748. static void nommu_addchr(o_string *o, int ch)
  2749. {
  2750. if (o)
  2751. o_addchr(o, ch);
  2752. }
  2753. #else
  2754. # define nommu_addchr(o, str) ((void)0)
  2755. #endif
  2756. #if ENABLE_HUSH_MODE_X
  2757. static void x_mode_addchr(int ch)
  2758. {
  2759. o_addchr(&G.x_mode_buf, ch);
  2760. }
  2761. static void x_mode_addstr(const char *str)
  2762. {
  2763. o_addstr(&G.x_mode_buf, str);
  2764. }
  2765. static void x_mode_addblock(const char *str, int len)
  2766. {
  2767. o_addblock(&G.x_mode_buf, str, len);
  2768. }
  2769. static void x_mode_prefix(void)
  2770. {
  2771. int n = G.x_mode_depth;
  2772. do x_mode_addchr('+'); while (--n >= 0);
  2773. }
  2774. static void x_mode_flush(void)
  2775. {
  2776. int len = G.x_mode_buf.length;
  2777. if (len <= 0)
  2778. return;
  2779. if (G.x_mode_fd > 0) {
  2780. G.x_mode_buf.data[len] = '\n';
  2781. full_write(G.x_mode_fd, G.x_mode_buf.data, len + 1);
  2782. }
  2783. G.x_mode_buf.length = 0;
  2784. }
  2785. #endif
  2786. /*
  2787. * HUSH_BRACE_EXPANSION code needs corresponding quoting on variable expansion side.
  2788. * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
  2789. * Apparently, on unquoted $v bash still does globbing
  2790. * ("v='*.txt'; echo $v" prints all .txt files),
  2791. * but NOT brace expansion! Thus, there should be TWO independent
  2792. * quoting mechanisms on $v expansion side: one protects
  2793. * $v from brace expansion, and other additionally protects "$v" against globbing.
  2794. * We have only second one.
  2795. */
  2796. #if ENABLE_HUSH_BRACE_EXPANSION
  2797. # define MAYBE_BRACES "{}"
  2798. #else
  2799. # define MAYBE_BRACES ""
  2800. #endif
  2801. /* My analysis of quoting semantics tells me that state information
  2802. * is associated with a destination, not a source.
  2803. */
  2804. static void o_addqchr(o_string *o, int ch)
  2805. {
  2806. int sz = 1;
  2807. /* '-' is included because of this case:
  2808. * >filename0 >filename1 >filename9; v='-'; echo filename[0"$v"9]
  2809. */
  2810. char *found = strchr("*?[-\\" MAYBE_BRACES, ch);
  2811. if (found)
  2812. sz++;
  2813. o_grow_by(o, sz);
  2814. if (found) {
  2815. o->data[o->length] = '\\';
  2816. o->length++;
  2817. }
  2818. o->data[o->length] = ch;
  2819. o->length++;
  2820. o->data[o->length] = '\0';
  2821. }
  2822. static void o_addQchr(o_string *o, int ch)
  2823. {
  2824. int sz = 1;
  2825. if ((o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)
  2826. && strchr("*?[-\\" MAYBE_BRACES, ch)
  2827. ) {
  2828. sz++;
  2829. o->data[o->length] = '\\';
  2830. o->length++;
  2831. }
  2832. o_grow_by(o, sz);
  2833. o->data[o->length] = ch;
  2834. o->length++;
  2835. o->data[o->length] = '\0';
  2836. }
  2837. static void o_addqblock(o_string *o, const char *str, int len)
  2838. {
  2839. while (len) {
  2840. char ch;
  2841. int sz;
  2842. int ordinary_cnt = strcspn(str, "*?[-\\" MAYBE_BRACES);
  2843. if (ordinary_cnt > len) /* paranoia */
  2844. ordinary_cnt = len;
  2845. o_addblock(o, str, ordinary_cnt);
  2846. if (ordinary_cnt == len)
  2847. return; /* NUL is already added by o_addblock */
  2848. str += ordinary_cnt;
  2849. len -= ordinary_cnt + 1; /* we are processing + 1 char below */
  2850. ch = *str++;
  2851. sz = 1;
  2852. if (ch) { /* it is necessarily one of "*?[-\\" MAYBE_BRACES */
  2853. sz++;
  2854. o->data[o->length] = '\\';
  2855. o->length++;
  2856. }
  2857. o_grow_by(o, sz);
  2858. o->data[o->length] = ch;
  2859. o->length++;
  2860. }
  2861. o->data[o->length] = '\0';
  2862. }
  2863. static void o_addQblock(o_string *o, const char *str, int len)
  2864. {
  2865. if (!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)) {
  2866. o_addblock(o, str, len);
  2867. return;
  2868. }
  2869. o_addqblock(o, str, len);
  2870. }
  2871. static void o_addQstr(o_string *o, const char *str)
  2872. {
  2873. o_addQblock(o, str, strlen(str));
  2874. }
  2875. /* A special kind of o_string for $VAR and `cmd` expansion.
  2876. * It contains char* list[] at the beginning, which is grown in 16 element
  2877. * increments. Actual string data starts at the next multiple of 16 * (char*).
  2878. * list[i] contains an INDEX (int!) into this string data.
  2879. * It means that if list[] needs to grow, data needs to be moved higher up
  2880. * but list[i]'s need not be modified.
  2881. * NB: remembering how many list[i]'s you have there is crucial.
  2882. * o_finalize_list() operation post-processes this structure - calculates
  2883. * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
  2884. */
  2885. #if DEBUG_EXPAND || DEBUG_GLOB
  2886. static void debug_print_list(const char *prefix, o_string *o, int n)
  2887. {
  2888. char **list = (char**)o->data;
  2889. int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
  2890. int i = 0;
  2891. indent();
  2892. fdprintf(2, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d glob:%d quoted:%d escape:%d\n",
  2893. prefix, list, n, string_start, o->length, o->maxlen,
  2894. !!(o->o_expflags & EXP_FLAG_GLOB),
  2895. o->has_quoted_part,
  2896. !!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
  2897. while (i < n) {
  2898. indent();
  2899. fdprintf(2, " list[%d]=%d '%s' %p\n", i, (int)(uintptr_t)list[i],
  2900. o->data + (int)(uintptr_t)list[i] + string_start,
  2901. o->data + (int)(uintptr_t)list[i] + string_start);
  2902. i++;
  2903. }
  2904. if (n) {
  2905. const char *p = o->data + (int)(uintptr_t)list[n - 1] + string_start;
  2906. indent();
  2907. fdprintf(2, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
  2908. }
  2909. }
  2910. #else
  2911. # define debug_print_list(prefix, o, n) ((void)0)
  2912. #endif
  2913. /* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
  2914. * in list[n] so that it points past last stored byte so far.
  2915. * It returns n+1. */
  2916. static int o_save_ptr_helper(o_string *o, int n)
  2917. {
  2918. char **list = (char**)o->data;
  2919. int string_start;
  2920. int string_len;
  2921. if (!o->has_empty_slot) {
  2922. string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
  2923. string_len = o->length - string_start;
  2924. if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
  2925. debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
  2926. /* list[n] points to string_start, make space for 16 more pointers */
  2927. o->maxlen += 0x10 * sizeof(list[0]);
  2928. o->data = xrealloc(o->data, o->maxlen + 1);
  2929. list = (char**)o->data;
  2930. memmove(list + n + 0x10, list + n, string_len);
  2931. /*
  2932. * expand_on_ifs() has a "previous argv[] ends in IFS?"
  2933. * check. (grep for -prev-ifs-check-).
  2934. * Ensure that argv[-1][last] is not garbage
  2935. * but zero bytes, to save index check there.
  2936. */
  2937. list[n + 0x10 - 1] = 0;
  2938. o->length += 0x10 * sizeof(list[0]);
  2939. } else {
  2940. debug_printf_list("list[%d]=%d string_start=%d\n",
  2941. n, string_len, string_start);
  2942. }
  2943. } else {
  2944. /* We have empty slot at list[n], reuse without growth */
  2945. string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
  2946. string_len = o->length - string_start;
  2947. debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
  2948. n, string_len, string_start);
  2949. o->has_empty_slot = 0;
  2950. }
  2951. o->has_quoted_part = 0;
  2952. list[n] = (char*)(uintptr_t)string_len;
  2953. return n + 1;
  2954. }
  2955. /* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
  2956. static int o_get_last_ptr(o_string *o, int n)
  2957. {
  2958. char **list = (char**)o->data;
  2959. int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
  2960. return ((int)(uintptr_t)list[n-1]) + string_start;
  2961. }
  2962. /*
  2963. * Globbing routines.
  2964. *
  2965. * Most words in commands need to be globbed, even ones which are
  2966. * (single or double) quoted. This stems from the possiblity of
  2967. * constructs like "abc"* and 'abc'* - these should be globbed.
  2968. * Having a different code path for fully-quoted strings ("abc",
  2969. * 'abc') would only help performance-wise, but we still need
  2970. * code for partially-quoted strings.
  2971. *
  2972. * Unfortunately, if we want to match bash and ash behavior in all cases,
  2973. * the logic can't be "shell-syntax argument is first transformed
  2974. * to a string, then globbed, and if globbing does not match anything,
  2975. * it is used verbatim". Here are two examples where it fails:
  2976. *
  2977. * echo 'b\*'?
  2978. *
  2979. * The globbing can't be avoided (because of '?' at the end).
  2980. * The glob pattern is: b\\\*? - IOW, both \ and * are literals
  2981. * and are glob-escaped. If this does not match, bash/ash print b\*?
  2982. * - IOW: they "unbackslash" the glob pattern.
  2983. * Now, look at this:
  2984. *
  2985. * v='\\\*'; echo b$v?
  2986. *
  2987. * The glob pattern is the same here: b\\\*? - the unquoted $v expansion
  2988. * should be used as glob pattern with no changes. However, if glob
  2989. * does not match, bash/ash print b\\\*? - NOT THE SAME as first example!
  2990. *
  2991. * ash implements this by having an encoded representation of the word
  2992. * to glob, which IS NOT THE SAME as the glob pattern - it has more data.
  2993. * Glob pattern is derived from it. If glob fails, the decision what result
  2994. * should be is made using that encoded representation. Not glob pattern.
  2995. */
  2996. #if ENABLE_HUSH_BRACE_EXPANSION
  2997. /* There in a GNU extension, GLOB_BRACE, but it is not usable:
  2998. * first, it processes even {a} (no commas), second,
  2999. * I didn't manage to make it return strings when they don't match
  3000. * existing files. Need to re-implement it.
  3001. */
  3002. /* Helper */
  3003. static int glob_needed(const char *s)
  3004. {
  3005. while (*s) {
  3006. if (*s == '\\') {
  3007. if (!s[1])
  3008. return 0;
  3009. s += 2;
  3010. continue;
  3011. }
  3012. if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
  3013. return 1;
  3014. s++;
  3015. }
  3016. return 0;
  3017. }
  3018. /* Return pointer to next closing brace or to comma */
  3019. static const char *next_brace_sub(const char *cp)
  3020. {
  3021. unsigned depth = 0;
  3022. cp++;
  3023. while (*cp != '\0') {
  3024. if (*cp == '\\') {
  3025. if (*++cp == '\0')
  3026. break;
  3027. cp++;
  3028. continue;
  3029. }
  3030. if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
  3031. break;
  3032. if (*cp++ == '{')
  3033. depth++;
  3034. }
  3035. return *cp != '\0' ? cp : NULL;
  3036. }
  3037. /* Recursive brace globber. Note: may garble pattern[]. */
  3038. static int glob_brace(char *pattern, o_string *o, int n)
  3039. {
  3040. char *new_pattern_buf;
  3041. const char *begin;
  3042. const char *next;
  3043. const char *rest;
  3044. const char *p;
  3045. size_t rest_len;
  3046. debug_printf_glob("glob_brace('%s')\n", pattern);
  3047. begin = pattern;
  3048. while (1) {
  3049. if (*begin == '\0')
  3050. goto simple_glob;
  3051. if (*begin == '{') {
  3052. /* Find the first sub-pattern and at the same time
  3053. * find the rest after the closing brace */
  3054. next = next_brace_sub(begin);
  3055. if (next == NULL) {
  3056. /* An illegal expression */
  3057. goto simple_glob;
  3058. }
  3059. if (*next == '}') {
  3060. /* "{abc}" with no commas - illegal
  3061. * brace expr, disregard and skip it */
  3062. begin = next + 1;
  3063. continue;
  3064. }
  3065. break;
  3066. }
  3067. if (*begin == '\\' && begin[1] != '\0')
  3068. begin++;
  3069. begin++;
  3070. }
  3071. debug_printf_glob("begin:%s\n", begin);
  3072. debug_printf_glob("next:%s\n", next);
  3073. /* Now find the end of the whole brace expression */
  3074. rest = next;
  3075. while (*rest != '}') {
  3076. rest = next_brace_sub(rest);
  3077. if (rest == NULL) {
  3078. /* An illegal expression */
  3079. goto simple_glob;
  3080. }
  3081. debug_printf_glob("rest:%s\n", rest);
  3082. }
  3083. rest_len = strlen(++rest) + 1;
  3084. /* We are sure the brace expression is well-formed */
  3085. /* Allocate working buffer large enough for our work */
  3086. new_pattern_buf = xmalloc(strlen(pattern));
  3087. /* We have a brace expression. BEGIN points to the opening {,
  3088. * NEXT points past the terminator of the first element, and REST
  3089. * points past the final }. We will accumulate result names from
  3090. * recursive runs for each brace alternative in the buffer using
  3091. * GLOB_APPEND. */
  3092. p = begin + 1;
  3093. while (1) {
  3094. /* Construct the new glob expression */
  3095. memcpy(
  3096. mempcpy(
  3097. mempcpy(new_pattern_buf,
  3098. /* We know the prefix for all sub-patterns */
  3099. pattern, begin - pattern),
  3100. p, next - p),
  3101. rest, rest_len);
  3102. /* Note: glob_brace() may garble new_pattern_buf[].
  3103. * That's why we re-copy prefix every time (1st memcpy above).
  3104. */
  3105. n = glob_brace(new_pattern_buf, o, n);
  3106. if (*next == '}') {
  3107. /* We saw the last entry */
  3108. break;
  3109. }
  3110. p = next + 1;
  3111. next = next_brace_sub(next);
  3112. }
  3113. free(new_pattern_buf);
  3114. return n;
  3115. simple_glob:
  3116. {
  3117. int gr;
  3118. glob_t globdata;
  3119. memset(&globdata, 0, sizeof(globdata));
  3120. gr = glob(pattern, 0, NULL, &globdata);
  3121. debug_printf_glob("glob('%s'):%d\n", pattern, gr);
  3122. if (gr != 0) {
  3123. if (gr == GLOB_NOMATCH) {
  3124. globfree(&globdata);
  3125. /* NB: garbles parameter */
  3126. unbackslash(pattern);
  3127. o_addstr_with_NUL(o, pattern);
  3128. debug_printf_glob("glob pattern '%s' is literal\n", pattern);
  3129. return o_save_ptr_helper(o, n);
  3130. }
  3131. if (gr == GLOB_NOSPACE)
  3132. bb_die_memory_exhausted();
  3133. /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
  3134. * but we didn't specify it. Paranoia again. */
  3135. bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
  3136. }
  3137. if (globdata.gl_pathv && globdata.gl_pathv[0]) {
  3138. char **argv = globdata.gl_pathv;
  3139. while (1) {
  3140. o_addstr_with_NUL(o, *argv);
  3141. n = o_save_ptr_helper(o, n);
  3142. argv++;
  3143. if (!*argv)
  3144. break;
  3145. }
  3146. }
  3147. globfree(&globdata);
  3148. }
  3149. return n;
  3150. }
  3151. /* Performs globbing on last list[],
  3152. * saving each result as a new list[].
  3153. */
  3154. static int perform_glob(o_string *o, int n)
  3155. {
  3156. char *pattern, *copy;
  3157. debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
  3158. if (!o->data)
  3159. return o_save_ptr_helper(o, n);
  3160. pattern = o->data + o_get_last_ptr(o, n);
  3161. debug_printf_glob("glob pattern '%s'\n", pattern);
  3162. if (!glob_needed(pattern)) {
  3163. /* unbackslash last string in o in place, fix length */
  3164. o->length = unbackslash(pattern) - o->data;
  3165. debug_printf_glob("glob pattern '%s' is literal\n", pattern);
  3166. return o_save_ptr_helper(o, n);
  3167. }
  3168. copy = xstrdup(pattern);
  3169. /* "forget" pattern in o */
  3170. o->length = pattern - o->data;
  3171. n = glob_brace(copy, o, n);
  3172. free(copy);
  3173. if (DEBUG_GLOB)
  3174. debug_print_list("perform_glob returning", o, n);
  3175. return n;
  3176. }
  3177. #else /* !HUSH_BRACE_EXPANSION */
  3178. /* Helper */
  3179. static int glob_needed(const char *s)
  3180. {
  3181. while (*s) {
  3182. if (*s == '\\') {
  3183. if (!s[1])
  3184. return 0;
  3185. s += 2;
  3186. continue;
  3187. }
  3188. if (*s == '*' || *s == '[' || *s == '?')
  3189. return 1;
  3190. s++;
  3191. }
  3192. return 0;
  3193. }
  3194. /* Performs globbing on last list[],
  3195. * saving each result as a new list[].
  3196. */
  3197. static int perform_glob(o_string *o, int n)
  3198. {
  3199. glob_t globdata;
  3200. int gr;
  3201. char *pattern;
  3202. debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
  3203. if (!o->data)
  3204. return o_save_ptr_helper(o, n);
  3205. pattern = o->data + o_get_last_ptr(o, n);
  3206. debug_printf_glob("glob pattern '%s'\n", pattern);
  3207. if (!glob_needed(pattern)) {
  3208. literal:
  3209. /* unbackslash last string in o in place, fix length */
  3210. o->length = unbackslash(pattern) - o->data;
  3211. debug_printf_glob("glob pattern '%s' is literal\n", pattern);
  3212. return o_save_ptr_helper(o, n);
  3213. }
  3214. memset(&globdata, 0, sizeof(globdata));
  3215. /* Can't use GLOB_NOCHECK: it does not unescape the string.
  3216. * If we glob "*.\*" and don't find anything, we need
  3217. * to fall back to using literal "*.*", but GLOB_NOCHECK
  3218. * will return "*.\*"!
  3219. */
  3220. gr = glob(pattern, 0, NULL, &globdata);
  3221. debug_printf_glob("glob('%s'):%d\n", pattern, gr);
  3222. if (gr != 0) {
  3223. if (gr == GLOB_NOMATCH) {
  3224. globfree(&globdata);
  3225. goto literal;
  3226. }
  3227. if (gr == GLOB_NOSPACE)
  3228. bb_die_memory_exhausted();
  3229. /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
  3230. * but we didn't specify it. Paranoia again. */
  3231. bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
  3232. }
  3233. if (globdata.gl_pathv && globdata.gl_pathv[0]) {
  3234. char **argv = globdata.gl_pathv;
  3235. /* "forget" pattern in o */
  3236. o->length = pattern - o->data;
  3237. while (1) {
  3238. o_addstr_with_NUL(o, *argv);
  3239. n = o_save_ptr_helper(o, n);
  3240. argv++;
  3241. if (!*argv)
  3242. break;
  3243. }
  3244. }
  3245. globfree(&globdata);
  3246. if (DEBUG_GLOB)
  3247. debug_print_list("perform_glob returning", o, n);
  3248. return n;
  3249. }
  3250. #endif /* !HUSH_BRACE_EXPANSION */
  3251. /* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered.
  3252. * Otherwise, just finish current list[] and start new */
  3253. static int o_save_ptr(o_string *o, int n)
  3254. {
  3255. if (o->o_expflags & EXP_FLAG_GLOB) {
  3256. /* If o->has_empty_slot, list[n] was already globbed
  3257. * (if it was requested back then when it was filled)
  3258. * so don't do that again! */
  3259. if (!o->has_empty_slot)
  3260. return perform_glob(o, n); /* o_save_ptr_helper is inside */
  3261. }
  3262. return o_save_ptr_helper(o, n);
  3263. }
  3264. /* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
  3265. static char **o_finalize_list(o_string *o, int n)
  3266. {
  3267. char **list;
  3268. int string_start;
  3269. if (DEBUG_EXPAND)
  3270. debug_print_list("finalized", o, n);
  3271. debug_printf_expand("finalized n:%d\n", n);
  3272. list = (char**)o->data;
  3273. string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
  3274. list[--n] = NULL;
  3275. while (n) {
  3276. n--;
  3277. list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
  3278. }
  3279. return list;
  3280. }
  3281. static void free_pipe_list(struct pipe *pi);
  3282. /* Returns pi->next - next pipe in the list */
  3283. static struct pipe *free_pipe(struct pipe *pi)
  3284. {
  3285. struct pipe *next;
  3286. int i;
  3287. debug_printf_clean("free_pipe (pid %d)\n", getpid());
  3288. for (i = 0; i < pi->num_cmds; i++) {
  3289. struct command *command;
  3290. struct redir_struct *r, *rnext;
  3291. command = &pi->cmds[i];
  3292. debug_printf_clean(" command %d:\n", i);
  3293. if (command->argv) {
  3294. if (DEBUG_CLEAN) {
  3295. int a;
  3296. char **p;
  3297. for (a = 0, p = command->argv; *p; a++, p++) {
  3298. debug_printf_clean(" argv[%d] = %s\n", a, *p);
  3299. }
  3300. }
  3301. free_strings(command->argv);
  3302. //command->argv = NULL;
  3303. }
  3304. /* not "else if": on syntax error, we may have both! */
  3305. if (command->group) {
  3306. debug_printf_clean(" begin group (cmd_type:%d)\n",
  3307. command->cmd_type);
  3308. free_pipe_list(command->group);
  3309. debug_printf_clean(" end group\n");
  3310. //command->group = NULL;
  3311. }
  3312. /* else is crucial here.
  3313. * If group != NULL, child_func is meaningless */
  3314. #if ENABLE_HUSH_FUNCTIONS
  3315. else if (command->child_func) {
  3316. debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
  3317. command->child_func->parent_cmd = NULL;
  3318. }
  3319. #endif
  3320. #if !BB_MMU
  3321. free(command->group_as_string);
  3322. //command->group_as_string = NULL;
  3323. #endif
  3324. for (r = command->redirects; r; r = rnext) {
  3325. debug_printf_clean(" redirect %d%s",
  3326. r->rd_fd, redir_table[r->rd_type].descrip);
  3327. /* guard against the case >$FOO, where foo is unset or blank */
  3328. if (r->rd_filename) {
  3329. debug_printf_clean(" fname:'%s'\n", r->rd_filename);
  3330. free(r->rd_filename);
  3331. //r->rd_filename = NULL;
  3332. }
  3333. debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
  3334. rnext = r->next;
  3335. free(r);
  3336. }
  3337. //command->redirects = NULL;
  3338. }
  3339. free(pi->cmds); /* children are an array, they get freed all at once */
  3340. //pi->cmds = NULL;
  3341. #if ENABLE_HUSH_JOB
  3342. free(pi->cmdtext);
  3343. //pi->cmdtext = NULL;
  3344. #endif
  3345. next = pi->next;
  3346. free(pi);
  3347. return next;
  3348. }
  3349. static void free_pipe_list(struct pipe *pi)
  3350. {
  3351. while (pi) {
  3352. #if HAS_KEYWORDS
  3353. debug_printf_clean("pipe reserved word %d\n", pi->res_word);
  3354. #endif
  3355. debug_printf_clean("pipe followup code %d\n", pi->followup);
  3356. pi = free_pipe(pi);
  3357. }
  3358. }
  3359. /*** Parsing routines ***/
  3360. #ifndef debug_print_tree
  3361. static void debug_print_tree(struct pipe *pi, int lvl)
  3362. {
  3363. static const char *const PIPE[] = {
  3364. [PIPE_SEQ] = "SEQ",
  3365. [PIPE_AND] = "AND",
  3366. [PIPE_OR ] = "OR" ,
  3367. [PIPE_BG ] = "BG" ,
  3368. };
  3369. static const char *RES[] = {
  3370. [RES_NONE ] = "NONE" ,
  3371. # if ENABLE_HUSH_IF
  3372. [RES_IF ] = "IF" ,
  3373. [RES_THEN ] = "THEN" ,
  3374. [RES_ELIF ] = "ELIF" ,
  3375. [RES_ELSE ] = "ELSE" ,
  3376. [RES_FI ] = "FI" ,
  3377. # endif
  3378. # if ENABLE_HUSH_LOOPS
  3379. [RES_FOR ] = "FOR" ,
  3380. [RES_WHILE] = "WHILE",
  3381. [RES_UNTIL] = "UNTIL",
  3382. [RES_DO ] = "DO" ,
  3383. [RES_DONE ] = "DONE" ,
  3384. # endif
  3385. # if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
  3386. [RES_IN ] = "IN" ,
  3387. # endif
  3388. # if ENABLE_HUSH_CASE
  3389. [RES_CASE ] = "CASE" ,
  3390. [RES_CASE_IN ] = "CASE_IN" ,
  3391. [RES_MATCH] = "MATCH",
  3392. [RES_CASE_BODY] = "CASE_BODY",
  3393. [RES_ESAC ] = "ESAC" ,
  3394. # endif
  3395. [RES_XXXX ] = "XXXX" ,
  3396. [RES_SNTX ] = "SNTX" ,
  3397. };
  3398. static const char *const CMDTYPE[] = {
  3399. "{}",
  3400. "()",
  3401. "[noglob]",
  3402. # if ENABLE_HUSH_FUNCTIONS
  3403. "func()",
  3404. # endif
  3405. };
  3406. int pin, prn;
  3407. pin = 0;
  3408. while (pi) {
  3409. fdprintf(2, "%*spipe %d %sres_word=%s followup=%d %s\n",
  3410. lvl*2, "",
  3411. pin,
  3412. (IF_HAS_KEYWORDS(pi->pi_inverted ? "! " :) ""),
  3413. RES[pi->res_word],
  3414. pi->followup, PIPE[pi->followup]
  3415. );
  3416. prn = 0;
  3417. while (prn < pi->num_cmds) {
  3418. struct command *command = &pi->cmds[prn];
  3419. char **argv = command->argv;
  3420. fdprintf(2, "%*s cmd %d assignment_cnt:%d",
  3421. lvl*2, "", prn,
  3422. command->assignment_cnt);
  3423. # if ENABLE_HUSH_LINENO_VAR
  3424. fdprintf(2, " LINENO:%u", command->lineno);
  3425. # endif
  3426. if (command->group) {
  3427. fdprintf(2, " group %s: (argv=%p)%s%s\n",
  3428. CMDTYPE[command->cmd_type],
  3429. argv
  3430. # if !BB_MMU
  3431. , " group_as_string:", command->group_as_string
  3432. # else
  3433. , "", ""
  3434. # endif
  3435. );
  3436. debug_print_tree(command->group, lvl+1);
  3437. prn++;
  3438. continue;
  3439. }
  3440. if (argv) while (*argv) {
  3441. fdprintf(2, " '%s'", *argv);
  3442. argv++;
  3443. }
  3444. if (command->redirects)
  3445. fdprintf(2, " {redir}");
  3446. fdprintf(2, "\n");
  3447. prn++;
  3448. }
  3449. pi = pi->next;
  3450. pin++;
  3451. }
  3452. }
  3453. #endif /* debug_print_tree */
  3454. static struct pipe *new_pipe(void)
  3455. {
  3456. struct pipe *pi;
  3457. pi = xzalloc(sizeof(struct pipe));
  3458. /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
  3459. return pi;
  3460. }
  3461. /* Command (member of a pipe) is complete, or we start a new pipe
  3462. * if ctx->command is NULL.
  3463. * No errors possible here.
  3464. */
  3465. static int done_command(struct parse_context *ctx)
  3466. {
  3467. /* The command is really already in the pipe structure, so
  3468. * advance the pipe counter and make a new, null command. */
  3469. struct pipe *pi = ctx->pipe;
  3470. struct command *command = ctx->command;
  3471. #if 0 /* Instead we emit error message at run time */
  3472. if (ctx->pending_redirect) {
  3473. /* For example, "cmd >" (no filename to redirect to) */
  3474. syntax_error("invalid redirect");
  3475. ctx->pending_redirect = NULL;
  3476. }
  3477. #endif
  3478. if (command) {
  3479. if (IS_NULL_CMD(command)) {
  3480. debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
  3481. goto clear_and_ret;
  3482. }
  3483. pi->num_cmds++;
  3484. debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
  3485. //debug_print_tree(ctx->list_head, 20);
  3486. } else {
  3487. debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
  3488. }
  3489. /* Only real trickiness here is that the uncommitted
  3490. * command structure is not counted in pi->num_cmds. */
  3491. pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
  3492. ctx->command = command = &pi->cmds[pi->num_cmds];
  3493. clear_and_ret:
  3494. memset(command, 0, sizeof(*command));
  3495. #if ENABLE_HUSH_LINENO_VAR
  3496. command->lineno = G.parse_lineno;
  3497. debug_printf_parse("command->lineno = G.parse_lineno (%u)\n", G.parse_lineno);
  3498. #endif
  3499. return pi->num_cmds; /* used only for 0/nonzero check */
  3500. }
  3501. static void done_pipe(struct parse_context *ctx, pipe_style type)
  3502. {
  3503. int not_null;
  3504. debug_printf_parse("done_pipe entered, followup %d\n", type);
  3505. /* Close previous command */
  3506. not_null = done_command(ctx);
  3507. #if HAS_KEYWORDS
  3508. ctx->pipe->pi_inverted = ctx->ctx_inverted;
  3509. ctx->ctx_inverted = 0;
  3510. ctx->pipe->res_word = ctx->ctx_res_w;
  3511. #endif
  3512. if (type == PIPE_BG && ctx->list_head != ctx->pipe) {
  3513. /* Necessary since && and || have precedence over &:
  3514. * "cmd1 && cmd2 &" must spawn both cmds, not only cmd2,
  3515. * in a backgrounded subshell.
  3516. */
  3517. struct pipe *pi;
  3518. struct command *command;
  3519. /* Is this actually this construct, all pipes end with && or ||? */
  3520. pi = ctx->list_head;
  3521. while (pi != ctx->pipe) {
  3522. if (pi->followup != PIPE_AND && pi->followup != PIPE_OR)
  3523. goto no_conv;
  3524. pi = pi->next;
  3525. }
  3526. debug_printf_parse("BG with more than one pipe, converting to { p1 &&...pN; } &\n");
  3527. pi->followup = PIPE_SEQ; /* close pN _not_ with "&"! */
  3528. pi = xzalloc(sizeof(*pi));
  3529. pi->followup = PIPE_BG;
  3530. pi->num_cmds = 1;
  3531. pi->cmds = xzalloc(sizeof(pi->cmds[0]));
  3532. command = &pi->cmds[0];
  3533. if (CMD_NORMAL != 0) /* "if xzalloc didn't do that already" */
  3534. command->cmd_type = CMD_NORMAL;
  3535. command->group = ctx->list_head;
  3536. #if !BB_MMU
  3537. command->group_as_string = xstrndup(
  3538. ctx->as_string.data,
  3539. ctx->as_string.length - 1 /* do not copy last char, "&" */
  3540. );
  3541. #endif
  3542. /* Replace all pipes in ctx with one newly created */
  3543. ctx->list_head = ctx->pipe = pi;
  3544. } else {
  3545. no_conv:
  3546. ctx->pipe->followup = type;
  3547. }
  3548. /* Without this check, even just <enter> on command line generates
  3549. * tree of three NOPs (!). Which is harmless but annoying.
  3550. * IOW: it is safe to do it unconditionally. */
  3551. if (not_null
  3552. #if ENABLE_HUSH_IF
  3553. || ctx->ctx_res_w == RES_FI
  3554. #endif
  3555. #if ENABLE_HUSH_LOOPS
  3556. || ctx->ctx_res_w == RES_DONE
  3557. || ctx->ctx_res_w == RES_FOR
  3558. || ctx->ctx_res_w == RES_IN
  3559. #endif
  3560. #if ENABLE_HUSH_CASE
  3561. || ctx->ctx_res_w == RES_ESAC
  3562. #endif
  3563. ) {
  3564. struct pipe *new_p;
  3565. debug_printf_parse("done_pipe: adding new pipe: "
  3566. "not_null:%d ctx->ctx_res_w:%d\n",
  3567. not_null, ctx->ctx_res_w);
  3568. new_p = new_pipe();
  3569. ctx->pipe->next = new_p;
  3570. ctx->pipe = new_p;
  3571. /* RES_THEN, RES_DO etc are "sticky" -
  3572. * they remain set for pipes inside if/while.
  3573. * This is used to control execution.
  3574. * RES_FOR and RES_IN are NOT sticky (needed to support
  3575. * cases where variable or value happens to match a keyword):
  3576. */
  3577. #if ENABLE_HUSH_LOOPS
  3578. if (ctx->ctx_res_w == RES_FOR
  3579. || ctx->ctx_res_w == RES_IN)
  3580. ctx->ctx_res_w = RES_NONE;
  3581. #endif
  3582. #if ENABLE_HUSH_CASE
  3583. if (ctx->ctx_res_w == RES_MATCH)
  3584. ctx->ctx_res_w = RES_CASE_BODY;
  3585. if (ctx->ctx_res_w == RES_CASE)
  3586. ctx->ctx_res_w = RES_CASE_IN;
  3587. #endif
  3588. ctx->command = NULL; /* trick done_command below */
  3589. /* Create the memory for command, roughly:
  3590. * ctx->pipe->cmds = new struct command;
  3591. * ctx->command = &ctx->pipe->cmds[0];
  3592. */
  3593. done_command(ctx);
  3594. //debug_print_tree(ctx->list_head, 10);
  3595. }
  3596. debug_printf_parse("done_pipe return\n");
  3597. }
  3598. static void initialize_context(struct parse_context *ctx)
  3599. {
  3600. memset(ctx, 0, sizeof(*ctx));
  3601. if (MAYBE_ASSIGNMENT != 0)
  3602. ctx->is_assignment = MAYBE_ASSIGNMENT;
  3603. ctx->pipe = ctx->list_head = new_pipe();
  3604. /* Create the memory for command, roughly:
  3605. * ctx->pipe->cmds = new struct command;
  3606. * ctx->command = &ctx->pipe->cmds[0];
  3607. */
  3608. done_command(ctx);
  3609. }
  3610. /* If a reserved word is found and processed, parse context is modified
  3611. * and 1 is returned.
  3612. */
  3613. #if HAS_KEYWORDS
  3614. struct reserved_combo {
  3615. char literal[6];
  3616. unsigned char res;
  3617. unsigned char assignment_flag;
  3618. int flag;
  3619. };
  3620. enum {
  3621. FLAG_END = (1 << RES_NONE ),
  3622. # if ENABLE_HUSH_IF
  3623. FLAG_IF = (1 << RES_IF ),
  3624. FLAG_THEN = (1 << RES_THEN ),
  3625. FLAG_ELIF = (1 << RES_ELIF ),
  3626. FLAG_ELSE = (1 << RES_ELSE ),
  3627. FLAG_FI = (1 << RES_FI ),
  3628. # endif
  3629. # if ENABLE_HUSH_LOOPS
  3630. FLAG_FOR = (1 << RES_FOR ),
  3631. FLAG_WHILE = (1 << RES_WHILE),
  3632. FLAG_UNTIL = (1 << RES_UNTIL),
  3633. FLAG_DO = (1 << RES_DO ),
  3634. FLAG_DONE = (1 << RES_DONE ),
  3635. FLAG_IN = (1 << RES_IN ),
  3636. # endif
  3637. # if ENABLE_HUSH_CASE
  3638. FLAG_MATCH = (1 << RES_MATCH),
  3639. FLAG_ESAC = (1 << RES_ESAC ),
  3640. # endif
  3641. FLAG_START = (1 << RES_XXXX ),
  3642. };
  3643. static const struct reserved_combo* match_reserved_word(o_string *word)
  3644. {
  3645. /* Mostly a list of accepted follow-up reserved words.
  3646. * FLAG_END means we are done with the sequence, and are ready
  3647. * to turn the compound list into a command.
  3648. * FLAG_START means the word must start a new compound list.
  3649. */
  3650. static const struct reserved_combo reserved_list[] = {
  3651. # if ENABLE_HUSH_IF
  3652. { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
  3653. { "if", RES_IF, MAYBE_ASSIGNMENT, FLAG_THEN | FLAG_START },
  3654. { "then", RES_THEN, MAYBE_ASSIGNMENT, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
  3655. { "elif", RES_ELIF, MAYBE_ASSIGNMENT, FLAG_THEN },
  3656. { "else", RES_ELSE, MAYBE_ASSIGNMENT, FLAG_FI },
  3657. { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
  3658. # endif
  3659. # if ENABLE_HUSH_LOOPS
  3660. { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
  3661. { "while", RES_WHILE, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
  3662. { "until", RES_UNTIL, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
  3663. { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
  3664. { "do", RES_DO, MAYBE_ASSIGNMENT, FLAG_DONE },
  3665. { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
  3666. # endif
  3667. # if ENABLE_HUSH_CASE
  3668. { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
  3669. { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
  3670. # endif
  3671. };
  3672. const struct reserved_combo *r;
  3673. for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
  3674. if (strcmp(word->data, r->literal) == 0)
  3675. return r;
  3676. }
  3677. return NULL;
  3678. }
  3679. /* Return NULL: not a keyword, else: keyword
  3680. */
  3681. static const struct reserved_combo* reserved_word(struct parse_context *ctx)
  3682. {
  3683. # if ENABLE_HUSH_CASE
  3684. static const struct reserved_combo reserved_match = {
  3685. "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
  3686. };
  3687. # endif
  3688. const struct reserved_combo *r;
  3689. if (ctx->word.has_quoted_part)
  3690. return 0;
  3691. r = match_reserved_word(&ctx->word);
  3692. if (!r)
  3693. return r; /* NULL */
  3694. debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
  3695. # if ENABLE_HUSH_CASE
  3696. if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
  3697. /* "case word IN ..." - IN part starts first MATCH part */
  3698. r = &reserved_match;
  3699. } else
  3700. # endif
  3701. if (r->flag == 0) { /* '!' */
  3702. if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
  3703. syntax_error("! ! command");
  3704. ctx->ctx_res_w = RES_SNTX;
  3705. }
  3706. ctx->ctx_inverted = 1;
  3707. return r;
  3708. }
  3709. if (r->flag & FLAG_START) {
  3710. struct parse_context *old;
  3711. old = xmemdup(ctx, sizeof(*ctx));
  3712. debug_printf_parse("push stack %p\n", old);
  3713. initialize_context(ctx);
  3714. ctx->stack = old;
  3715. } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
  3716. syntax_error_at(ctx->word.data);
  3717. ctx->ctx_res_w = RES_SNTX;
  3718. return r;
  3719. } else {
  3720. /* "{...} fi" is ok. "{...} if" is not
  3721. * Example:
  3722. * if { echo foo; } then { echo bar; } fi */
  3723. if (ctx->command->group)
  3724. done_pipe(ctx, PIPE_SEQ);
  3725. }
  3726. ctx->ctx_res_w = r->res;
  3727. ctx->old_flag = r->flag;
  3728. ctx->is_assignment = r->assignment_flag;
  3729. debug_printf_parse("ctx->is_assignment='%s'\n", assignment_flag[ctx->is_assignment]);
  3730. if (ctx->old_flag & FLAG_END) {
  3731. struct parse_context *old;
  3732. done_pipe(ctx, PIPE_SEQ);
  3733. debug_printf_parse("pop stack %p\n", ctx->stack);
  3734. old = ctx->stack;
  3735. old->command->group = ctx->list_head;
  3736. old->command->cmd_type = CMD_NORMAL;
  3737. # if !BB_MMU
  3738. /* At this point, the compound command's string is in
  3739. * ctx->as_string... except for the leading keyword!
  3740. * Consider this example: "echo a | if true; then echo a; fi"
  3741. * ctx->as_string will contain "true; then echo a; fi",
  3742. * with "if " remaining in old->as_string!
  3743. */
  3744. {
  3745. char *str;
  3746. int len = old->as_string.length;
  3747. /* Concatenate halves */
  3748. o_addstr(&old->as_string, ctx->as_string.data);
  3749. o_free(&ctx->as_string);
  3750. /* Find where leading keyword starts in first half */
  3751. str = old->as_string.data + len;
  3752. if (str > old->as_string.data)
  3753. str--; /* skip whitespace after keyword */
  3754. while (str > old->as_string.data && isalpha(str[-1]))
  3755. str--;
  3756. /* Ugh, we're done with this horrid hack */
  3757. old->command->group_as_string = xstrdup(str);
  3758. debug_printf_parse("pop, remembering as:'%s'\n",
  3759. old->command->group_as_string);
  3760. }
  3761. # endif
  3762. *ctx = *old; /* physical copy */
  3763. free(old);
  3764. }
  3765. return r;
  3766. }
  3767. #endif /* HAS_KEYWORDS */
  3768. /* Word is complete, look at it and update parsing context.
  3769. * Normal return is 0. Syntax errors return 1.
  3770. * Note: on return, word is reset, but not o_free'd!
  3771. */
  3772. static int done_word(struct parse_context *ctx)
  3773. {
  3774. struct command *command = ctx->command;
  3775. debug_printf_parse("done_word entered: '%s' %p\n", ctx->word.data, command);
  3776. if (ctx->word.length == 0 && !ctx->word.has_quoted_part) {
  3777. debug_printf_parse("done_word return 0: true null, ignored\n");
  3778. return 0;
  3779. }
  3780. if (ctx->pending_redirect) {
  3781. /* We do not glob in e.g. >*.tmp case. bash seems to glob here
  3782. * only if run as "bash", not "sh" */
  3783. /* http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
  3784. * "2.7 Redirection
  3785. * If the redirection operator is "<<" or "<<-", the word
  3786. * that follows the redirection operator shall be
  3787. * subjected to quote removal; it is unspecified whether
  3788. * any of the other expansions occur. For the other
  3789. * redirection operators, the word that follows the
  3790. * redirection operator shall be subjected to tilde
  3791. * expansion, parameter expansion, command substitution,
  3792. * arithmetic expansion, and quote removal.
  3793. * Pathname expansion shall not be performed
  3794. * on the word by a non-interactive shell; an interactive
  3795. * shell may perform it, but shall do so only when
  3796. * the expansion would result in one word."
  3797. */
  3798. //bash does not do parameter/command substitution or arithmetic expansion
  3799. //for _heredoc_ redirection word: these constructs look for exact eof marker
  3800. // as written:
  3801. // <<EOF$t
  3802. // <<EOF$((1))
  3803. // <<EOF`true` [this case also makes heredoc "quoted", a-la <<"EOF". Probably bash-4.3.43 bug]
  3804. ctx->pending_redirect->rd_filename = xstrdup(ctx->word.data);
  3805. /* Cater for >\file case:
  3806. * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
  3807. * Same with heredocs:
  3808. * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
  3809. */
  3810. if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
  3811. unbackslash(ctx->pending_redirect->rd_filename);
  3812. /* Is it <<"HEREDOC"? */
  3813. if (ctx->word.has_quoted_part) {
  3814. ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
  3815. }
  3816. }
  3817. debug_printf_parse("word stored in rd_filename: '%s'\n", ctx->word.data);
  3818. ctx->pending_redirect = NULL;
  3819. } else {
  3820. #if HAS_KEYWORDS
  3821. # if ENABLE_HUSH_CASE
  3822. if (ctx->ctx_dsemicolon
  3823. && strcmp(ctx->word.data, "esac") != 0 /* not "... pattern) cmd;; esac" */
  3824. ) {
  3825. /* already done when ctx_dsemicolon was set to 1: */
  3826. /* ctx->ctx_res_w = RES_MATCH; */
  3827. ctx->ctx_dsemicolon = 0;
  3828. } else
  3829. # endif
  3830. if (!command->argv /* if it's the first word... */
  3831. # if ENABLE_HUSH_LOOPS
  3832. && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
  3833. && ctx->ctx_res_w != RES_IN
  3834. # endif
  3835. # if ENABLE_HUSH_CASE
  3836. && ctx->ctx_res_w != RES_CASE
  3837. # endif
  3838. ) {
  3839. const struct reserved_combo *reserved;
  3840. reserved = reserved_word(ctx);
  3841. debug_printf_parse("checking for reserved-ness: %d\n", !!reserved);
  3842. if (reserved) {
  3843. # if ENABLE_HUSH_LINENO_VAR
  3844. /* Case:
  3845. * "while ...; do
  3846. * cmd ..."
  3847. * If we don't close the pipe _now_, immediately after "do", lineno logic
  3848. * sees "cmd" as starting at "do" - i.e., at the previous line.
  3849. */
  3850. if (0
  3851. IF_HUSH_IF(|| reserved->res == RES_THEN)
  3852. IF_HUSH_IF(|| reserved->res == RES_ELIF)
  3853. IF_HUSH_IF(|| reserved->res == RES_ELSE)
  3854. IF_HUSH_LOOPS(|| reserved->res == RES_DO)
  3855. ) {
  3856. done_pipe(ctx, PIPE_SEQ);
  3857. }
  3858. # endif
  3859. o_reset_to_empty_unquoted(&ctx->word);
  3860. debug_printf_parse("done_word return %d\n",
  3861. (ctx->ctx_res_w == RES_SNTX));
  3862. return (ctx->ctx_res_w == RES_SNTX);
  3863. }
  3864. # if defined(CMD_SINGLEWORD_NOGLOB)
  3865. if (0
  3866. # if BASH_TEST2
  3867. || strcmp(ctx->word.data, "[[") == 0
  3868. # endif
  3869. /* In bash, local/export/readonly are special, args
  3870. * are assignments and therefore expansion of them
  3871. * should be "one-word" expansion:
  3872. * $ export i=`echo 'a b'` # one arg: "i=a b"
  3873. * compare with:
  3874. * $ ls i=`echo 'a b'` # two args: "i=a" and "b"
  3875. * ls: cannot access i=a: No such file or directory
  3876. * ls: cannot access b: No such file or directory
  3877. * Note: bash 3.2.33(1) does this only if export word
  3878. * itself is not quoted:
  3879. * $ export i=`echo 'aaa bbb'`; echo "$i"
  3880. * aaa bbb
  3881. * $ "export" i=`echo 'aaa bbb'`; echo "$i"
  3882. * aaa
  3883. */
  3884. IF_HUSH_LOCAL( || strcmp(ctx->word.data, "local") == 0)
  3885. IF_HUSH_EXPORT( || strcmp(ctx->word.data, "export") == 0)
  3886. IF_HUSH_READONLY(|| strcmp(ctx->word.data, "readonly") == 0)
  3887. ) {
  3888. command->cmd_type = CMD_SINGLEWORD_NOGLOB;
  3889. }
  3890. /* fall through */
  3891. # endif
  3892. }
  3893. #endif /* HAS_KEYWORDS */
  3894. if (command->group) {
  3895. /* "{ echo foo; } echo bar" - bad */
  3896. syntax_error_at(ctx->word.data);
  3897. debug_printf_parse("done_word return 1: syntax error, "
  3898. "groups and arglists don't mix\n");
  3899. return 1;
  3900. }
  3901. /* If this word wasn't an assignment, next ones definitely
  3902. * can't be assignments. Even if they look like ones. */
  3903. if (ctx->is_assignment != DEFINITELY_ASSIGNMENT
  3904. && ctx->is_assignment != WORD_IS_KEYWORD
  3905. ) {
  3906. ctx->is_assignment = NOT_ASSIGNMENT;
  3907. } else {
  3908. if (ctx->is_assignment == DEFINITELY_ASSIGNMENT) {
  3909. command->assignment_cnt++;
  3910. debug_printf_parse("++assignment_cnt=%d\n", command->assignment_cnt);
  3911. }
  3912. debug_printf_parse("ctx->is_assignment was:'%s'\n", assignment_flag[ctx->is_assignment]);
  3913. ctx->is_assignment = MAYBE_ASSIGNMENT;
  3914. }
  3915. debug_printf_parse("ctx->is_assignment='%s'\n", assignment_flag[ctx->is_assignment]);
  3916. command->argv = add_string_to_strings(command->argv, xstrdup(ctx->word.data));
  3917. debug_print_strings("word appended to argv", command->argv);
  3918. }
  3919. #if ENABLE_HUSH_LOOPS
  3920. if (ctx->ctx_res_w == RES_FOR) {
  3921. if (ctx->word.has_quoted_part
  3922. || endofname(command->argv[0])[0] != '\0'
  3923. ) {
  3924. /* bash says just "not a valid identifier" */
  3925. syntax_error("not a valid identifier in for");
  3926. return 1;
  3927. }
  3928. /* Force FOR to have just one word (variable name) */
  3929. /* NB: basically, this makes hush see "for v in ..."
  3930. * syntax as if it is "for v; in ...". FOR and IN become
  3931. * two pipe structs in parse tree. */
  3932. done_pipe(ctx, PIPE_SEQ);
  3933. }
  3934. #endif
  3935. #if ENABLE_HUSH_CASE
  3936. /* Force CASE to have just one word */
  3937. if (ctx->ctx_res_w == RES_CASE) {
  3938. done_pipe(ctx, PIPE_SEQ);
  3939. }
  3940. #endif
  3941. o_reset_to_empty_unquoted(&ctx->word);
  3942. debug_printf_parse("done_word return 0\n");
  3943. return 0;
  3944. }
  3945. /* Peek ahead in the input to find out if we have a "&n" construct,
  3946. * as in "2>&1", that represents duplicating a file descriptor.
  3947. * Return:
  3948. * REDIRFD_CLOSE if >&- "close fd" construct is seen,
  3949. * REDIRFD_SYNTAX_ERR if syntax error,
  3950. * REDIRFD_TO_FILE if no & was seen,
  3951. * or the number found.
  3952. */
  3953. #if BB_MMU
  3954. #define parse_redir_right_fd(as_string, input) \
  3955. parse_redir_right_fd(input)
  3956. #endif
  3957. static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
  3958. {
  3959. int ch, d, ok;
  3960. ch = i_peek(input);
  3961. if (ch != '&')
  3962. return REDIRFD_TO_FILE;
  3963. ch = i_getch(input); /* get the & */
  3964. nommu_addchr(as_string, ch);
  3965. ch = i_peek(input);
  3966. if (ch == '-') {
  3967. ch = i_getch(input);
  3968. nommu_addchr(as_string, ch);
  3969. return REDIRFD_CLOSE;
  3970. }
  3971. d = 0;
  3972. ok = 0;
  3973. while (ch != EOF && isdigit(ch)) {
  3974. d = d*10 + (ch-'0');
  3975. ok = 1;
  3976. ch = i_getch(input);
  3977. nommu_addchr(as_string, ch);
  3978. ch = i_peek(input);
  3979. }
  3980. if (ok) return d;
  3981. //TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
  3982. bb_simple_error_msg("ambiguous redirect");
  3983. return REDIRFD_SYNTAX_ERR;
  3984. }
  3985. /* Return code is 0 normal, 1 if a syntax error is detected
  3986. */
  3987. static int parse_redirect(struct parse_context *ctx,
  3988. int fd,
  3989. redir_type style,
  3990. struct in_str *input)
  3991. {
  3992. struct command *command = ctx->command;
  3993. struct redir_struct *redir;
  3994. struct redir_struct **redirp;
  3995. int dup_num;
  3996. dup_num = REDIRFD_TO_FILE;
  3997. if (style != REDIRECT_HEREDOC) {
  3998. /* Check for a '>&1' type redirect */
  3999. dup_num = parse_redir_right_fd(&ctx->as_string, input);
  4000. if (dup_num == REDIRFD_SYNTAX_ERR)
  4001. return 1;
  4002. } else {
  4003. int ch = i_peek_and_eat_bkslash_nl(input);
  4004. dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
  4005. if (dup_num) { /* <<-... */
  4006. ch = i_getch(input);
  4007. nommu_addchr(&ctx->as_string, ch);
  4008. ch = i_peek(input);
  4009. }
  4010. }
  4011. if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
  4012. int ch = i_peek_and_eat_bkslash_nl(input);
  4013. if (ch == '|') {
  4014. /* >|FILE redirect ("clobbering" >).
  4015. * Since we do not support "set -o noclobber" yet,
  4016. * >| and > are the same for now. Just eat |.
  4017. */
  4018. ch = i_getch(input);
  4019. nommu_addchr(&ctx->as_string, ch);
  4020. }
  4021. }
  4022. /* Create a new redir_struct and append it to the linked list */
  4023. redirp = &command->redirects;
  4024. while ((redir = *redirp) != NULL) {
  4025. redirp = &(redir->next);
  4026. }
  4027. *redirp = redir = xzalloc(sizeof(*redir));
  4028. /* redir->next = NULL; */
  4029. /* redir->rd_filename = NULL; */
  4030. redir->rd_type = style;
  4031. redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
  4032. debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
  4033. redir_table[style].descrip);
  4034. redir->rd_dup = dup_num;
  4035. if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
  4036. /* Erik had a check here that the file descriptor in question
  4037. * is legit; I postpone that to "run time"
  4038. * A "-" representation of "close me" shows up as a -3 here */
  4039. debug_printf_parse("duplicating redirect '%d>&%d'\n",
  4040. redir->rd_fd, redir->rd_dup);
  4041. } else {
  4042. #if 0 /* Instead we emit error message at run time */
  4043. if (ctx->pending_redirect) {
  4044. /* For example, "cmd > <file" */
  4045. syntax_error("invalid redirect");
  4046. }
  4047. #endif
  4048. /* Set ctx->pending_redirect, so we know what to do at the
  4049. * end of the next parsed word. */
  4050. ctx->pending_redirect = redir;
  4051. }
  4052. return 0;
  4053. }
  4054. /* If a redirect is immediately preceded by a number, that number is
  4055. * supposed to tell which file descriptor to redirect. This routine
  4056. * looks for such preceding numbers. In an ideal world this routine
  4057. * needs to handle all the following classes of redirects...
  4058. * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
  4059. * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
  4060. * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
  4061. * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
  4062. *
  4063. * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
  4064. * "2.7 Redirection
  4065. * ... If n is quoted, the number shall not be recognized as part of
  4066. * the redirection expression. For example:
  4067. * echo \2>a
  4068. * writes the character 2 into file a"
  4069. * We are getting it right by setting ->has_quoted_part on any \<char>
  4070. *
  4071. * A -1 return means no valid number was found,
  4072. * the caller should use the appropriate default for this redirection.
  4073. */
  4074. static int redirect_opt_num(o_string *o)
  4075. {
  4076. int num;
  4077. if (o->data == NULL)
  4078. return -1;
  4079. num = bb_strtou(o->data, NULL, 10);
  4080. if (errno || num < 0)
  4081. return -1;
  4082. o_reset_to_empty_unquoted(o);
  4083. return num;
  4084. }
  4085. #if BB_MMU
  4086. #define fetch_till_str(as_string, input, word, skip_tabs) \
  4087. fetch_till_str(input, word, skip_tabs)
  4088. #endif
  4089. static char *fetch_till_str(o_string *as_string,
  4090. struct in_str *input,
  4091. const char *word,
  4092. int heredoc_flags)
  4093. {
  4094. o_string heredoc = NULL_O_STRING;
  4095. unsigned past_EOL;
  4096. int prev = 0; /* not \ */
  4097. int ch;
  4098. /* Starting with "" is necessary for this case:
  4099. * cat <<EOF
  4100. *
  4101. * xxx
  4102. * EOF
  4103. */
  4104. heredoc.data = xzalloc(1); /* start as "", not as NULL */
  4105. goto jump_in;
  4106. while (1) {
  4107. ch = i_getch(input);
  4108. if (ch != EOF)
  4109. nommu_addchr(as_string, ch);
  4110. if (ch == '\n' || ch == EOF) {
  4111. check_heredoc_end:
  4112. if ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\') {
  4113. /* End-of-line, and not a line continuation */
  4114. if (strcmp(heredoc.data + past_EOL, word) == 0) {
  4115. heredoc.data[past_EOL] = '\0';
  4116. debug_printf_heredoc("parsed '%s' heredoc '%s'\n", word, heredoc.data);
  4117. return heredoc.data;
  4118. }
  4119. if (ch == '\n') {
  4120. /* This is a new line.
  4121. * Remember position and backslash-escaping status.
  4122. */
  4123. o_addchr(&heredoc, ch);
  4124. prev = ch;
  4125. jump_in:
  4126. past_EOL = heredoc.length;
  4127. /* Get 1st char of next line, possibly skipping leading tabs */
  4128. do {
  4129. ch = i_getch(input);
  4130. if (ch != EOF)
  4131. nommu_addchr(as_string, ch);
  4132. } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
  4133. /* If this immediately ended the line,
  4134. * go back to end-of-line checks.
  4135. */
  4136. if (ch == '\n')
  4137. goto check_heredoc_end;
  4138. }
  4139. } else {
  4140. /* Backslash-line continuation in an unquoted
  4141. * heredoc. This does not need special handling
  4142. * for heredoc body (unquoted heredocs are
  4143. * expanded on "execution" and that would take
  4144. * care of this case too), but not the case
  4145. * of line continuation *in terminator*:
  4146. * cat <<EOF
  4147. * Ok1
  4148. * EO\
  4149. * F
  4150. */
  4151. heredoc.data[--heredoc.length] = '\0';
  4152. prev = 0; /* not '\' */
  4153. continue;
  4154. }
  4155. }
  4156. if (ch == EOF) {
  4157. o_free(&heredoc);
  4158. return NULL; /* error */
  4159. }
  4160. o_addchr(&heredoc, ch);
  4161. nommu_addchr(as_string, ch);
  4162. if (prev == '\\' && ch == '\\')
  4163. /* Correctly handle foo\\<eol> (not a line cont.) */
  4164. prev = 0; /* not '\' */
  4165. else
  4166. prev = ch;
  4167. }
  4168. }
  4169. /* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
  4170. * and load them all. There should be exactly heredoc_cnt of them.
  4171. */
  4172. #if BB_MMU
  4173. #define fetch_heredocs(as_string, pi, heredoc_cnt, input) \
  4174. fetch_heredocs(pi, heredoc_cnt, input)
  4175. #endif
  4176. static int fetch_heredocs(o_string *as_string, struct pipe *pi, int heredoc_cnt, struct in_str *input)
  4177. {
  4178. while (pi && heredoc_cnt) {
  4179. int i;
  4180. struct command *cmd = pi->cmds;
  4181. debug_printf_heredoc("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
  4182. pi->num_cmds,
  4183. cmd->argv ? cmd->argv[0] : "NONE"
  4184. );
  4185. for (i = 0; i < pi->num_cmds; i++) {
  4186. struct redir_struct *redir = cmd->redirects;
  4187. debug_printf_heredoc("fetch_heredocs: %d cmd argv0:'%s'\n",
  4188. i, cmd->argv ? cmd->argv[0] : "NONE");
  4189. while (redir) {
  4190. if (redir->rd_type == REDIRECT_HEREDOC) {
  4191. char *p;
  4192. redir->rd_type = REDIRECT_HEREDOC2;
  4193. /* redir->rd_dup is (ab)used to indicate <<- */
  4194. p = fetch_till_str(as_string, input,
  4195. redir->rd_filename, redir->rd_dup);
  4196. if (!p) {
  4197. syntax_error("unexpected EOF in here document");
  4198. return -1;
  4199. }
  4200. free(redir->rd_filename);
  4201. redir->rd_filename = p;
  4202. heredoc_cnt--;
  4203. }
  4204. redir = redir->next;
  4205. }
  4206. if (cmd->group) {
  4207. //bb_error_msg("%s:%u heredoc_cnt:%d", __func__, __LINE__, heredoc_cnt);
  4208. heredoc_cnt = fetch_heredocs(as_string, cmd->group, heredoc_cnt, input);
  4209. //bb_error_msg("%s:%u heredoc_cnt:%d", __func__, __LINE__, heredoc_cnt);
  4210. if (heredoc_cnt < 0)
  4211. return heredoc_cnt; /* error */
  4212. }
  4213. cmd++;
  4214. }
  4215. pi = pi->next;
  4216. }
  4217. return heredoc_cnt;
  4218. }
  4219. static int run_list(struct pipe *pi);
  4220. #if BB_MMU
  4221. #define parse_stream(pstring, heredoc_cnt_ptr, input, end_trigger) \
  4222. parse_stream(heredoc_cnt_ptr, input, end_trigger)
  4223. #endif
  4224. static struct pipe *parse_stream(char **pstring,
  4225. int *heredoc_cnt_ptr,
  4226. struct in_str *input,
  4227. int end_trigger);
  4228. /* Returns number of heredocs not yet consumed,
  4229. * or -1 on error.
  4230. */
  4231. static int parse_group(struct parse_context *ctx,
  4232. struct in_str *input, int ch)
  4233. {
  4234. /* ctx->word contains characters seen prior to ( or {.
  4235. * Typically it's empty, but for function defs,
  4236. * it contains function name (without '()'). */
  4237. #if BB_MMU
  4238. # define as_string NULL
  4239. #else
  4240. char *as_string = NULL;
  4241. #endif
  4242. struct pipe *pipe_list;
  4243. int heredoc_cnt = 0;
  4244. int endch;
  4245. struct command *command = ctx->command;
  4246. debug_printf_parse("parse_group entered\n");
  4247. #if ENABLE_HUSH_FUNCTIONS
  4248. if (ch == '(' && !ctx->word.has_quoted_part) {
  4249. if (ctx->word.length)
  4250. if (done_word(ctx))
  4251. return -1;
  4252. if (!command->argv)
  4253. goto skip; /* (... */
  4254. if (command->argv[1]) { /* word word ... (... */
  4255. syntax_error_unexpected_ch('(');
  4256. return -1;
  4257. }
  4258. /* it is "word(..." or "word (..." */
  4259. do
  4260. ch = i_getch(input);
  4261. while (ch == ' ' || ch == '\t');
  4262. if (ch != ')') {
  4263. syntax_error_unexpected_ch(ch);
  4264. return -1;
  4265. }
  4266. nommu_addchr(&ctx->as_string, ch);
  4267. do
  4268. ch = i_getch(input);
  4269. while (ch == ' ' || ch == '\t' || ch == '\n');
  4270. if (ch != '{' && ch != '(') {
  4271. syntax_error_unexpected_ch(ch);
  4272. return -1;
  4273. }
  4274. nommu_addchr(&ctx->as_string, ch);
  4275. command->cmd_type = CMD_FUNCDEF;
  4276. goto skip;
  4277. }
  4278. #endif
  4279. #if 0 /* Prevented by caller */
  4280. if (command->argv /* word [word]{... */
  4281. || ctx->word.length /* word{... */
  4282. || ctx->word.has_quoted_part /* ""{... */
  4283. ) {
  4284. syntax_error(NULL);
  4285. debug_printf_parse("parse_group return -1: "
  4286. "syntax error, groups and arglists don't mix\n");
  4287. return -1;
  4288. }
  4289. #endif
  4290. IF_HUSH_FUNCTIONS(skip:)
  4291. endch = '}';
  4292. if (ch == '(') {
  4293. endch = ')';
  4294. IF_HUSH_FUNCTIONS(if (command->cmd_type != CMD_FUNCDEF))
  4295. command->cmd_type = CMD_SUBSHELL;
  4296. } else {
  4297. /* bash does not allow "{echo...", requires whitespace */
  4298. ch = i_peek(input);
  4299. if (ch != ' ' && ch != '\t' && ch != '\n'
  4300. && ch != '(' /* but "{(..." is allowed (without whitespace) */
  4301. ) {
  4302. syntax_error_unexpected_ch(ch);
  4303. return -1;
  4304. }
  4305. if (ch != '(') {
  4306. ch = i_getch(input);
  4307. nommu_addchr(&ctx->as_string, ch);
  4308. }
  4309. }
  4310. debug_printf_heredoc("calling parse_stream, heredoc_cnt:%d\n", heredoc_cnt);
  4311. pipe_list = parse_stream(&as_string, &heredoc_cnt, input, endch);
  4312. debug_printf_heredoc("parse_stream returned: heredoc_cnt:%d\n", heredoc_cnt);
  4313. #if !BB_MMU
  4314. if (as_string)
  4315. o_addstr(&ctx->as_string, as_string);
  4316. #endif
  4317. /* empty ()/{} or parse error? */
  4318. if (!pipe_list || pipe_list == ERR_PTR) {
  4319. /* parse_stream already emitted error msg */
  4320. if (!BB_MMU)
  4321. free(as_string);
  4322. debug_printf_parse("parse_group return -1: "
  4323. "parse_stream returned %p\n", pipe_list);
  4324. return -1;
  4325. }
  4326. #if !BB_MMU
  4327. as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
  4328. command->group_as_string = as_string;
  4329. debug_printf_parse("end of group, remembering as:'%s'\n",
  4330. command->group_as_string);
  4331. #endif
  4332. #if ENABLE_HUSH_FUNCTIONS
  4333. /* Convert "f() (cmds)" to "f() {(cmds)}" */
  4334. if (command->cmd_type == CMD_FUNCDEF && endch == ')') {
  4335. struct command *cmd2;
  4336. cmd2 = xzalloc(sizeof(*cmd2));
  4337. cmd2->cmd_type = CMD_SUBSHELL;
  4338. cmd2->group = pipe_list;
  4339. # if !BB_MMU
  4340. //UNTESTED!
  4341. cmd2->group_as_string = command->group_as_string;
  4342. command->group_as_string = xasprintf("(%s)", command->group_as_string);
  4343. # endif
  4344. pipe_list = new_pipe();
  4345. pipe_list->cmds = cmd2;
  4346. pipe_list->num_cmds = 1;
  4347. }
  4348. #endif
  4349. command->group = pipe_list;
  4350. debug_printf_parse("parse_group return %d\n", heredoc_cnt);
  4351. return heredoc_cnt;
  4352. /* command remains "open", available for possible redirects */
  4353. #undef as_string
  4354. }
  4355. #if ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS
  4356. /* Subroutines for copying $(...) and `...` things */
  4357. /* '...' */
  4358. static int add_till_single_quote(o_string *dest, struct in_str *input)
  4359. {
  4360. while (1) {
  4361. int ch = i_getch(input);
  4362. if (ch == EOF) {
  4363. syntax_error_unterm_ch('\'');
  4364. return 0;
  4365. }
  4366. if (ch == '\'')
  4367. return 1;
  4368. o_addchr(dest, ch);
  4369. }
  4370. }
  4371. static int add_till_single_quote_dquoted(o_string *dest, struct in_str *input)
  4372. {
  4373. while (1) {
  4374. int ch = i_getch(input);
  4375. if (ch == EOF) {
  4376. syntax_error_unterm_ch('\'');
  4377. return 0;
  4378. }
  4379. if (ch == '\'')
  4380. return 1;
  4381. o_addqchr(dest, ch);
  4382. }
  4383. }
  4384. /* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
  4385. static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote);
  4386. static int add_till_double_quote(o_string *dest, struct in_str *input)
  4387. {
  4388. while (1) {
  4389. int ch = i_getch(input);
  4390. if (ch == EOF) {
  4391. syntax_error_unterm_ch('"');
  4392. return 0;
  4393. }
  4394. if (ch == '"')
  4395. return 1;
  4396. if (ch == '\\') { /* \x. Copy both chars. */
  4397. o_addchr(dest, ch);
  4398. ch = i_getch(input);
  4399. }
  4400. o_addchr(dest, ch);
  4401. if (ch == '`') {
  4402. if (!add_till_backquote(dest, input, /*in_dquote:*/ 1))
  4403. return 0;
  4404. o_addchr(dest, ch);
  4405. continue;
  4406. }
  4407. //if (ch == '$') ...
  4408. }
  4409. }
  4410. /* Process `cmd` - copy contents until "`" is seen. Complicated by
  4411. * \` quoting.
  4412. * "Within the backquoted style of command substitution, backslash
  4413. * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
  4414. * The search for the matching backquote shall be satisfied by the first
  4415. * backquote found without a preceding backslash; during this search,
  4416. * if a non-escaped backquote is encountered within a shell comment,
  4417. * a here-document, an embedded command substitution of the $(command)
  4418. * form, or a quoted string, undefined results occur. A single-quoted
  4419. * or double-quoted string that begins, but does not end, within the
  4420. * "`...`" sequence produces undefined results."
  4421. * Example Output
  4422. * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
  4423. */
  4424. static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote)
  4425. {
  4426. while (1) {
  4427. int ch = i_getch(input);
  4428. if (ch == '`')
  4429. return 1;
  4430. if (ch == '\\') {
  4431. /* \x. Copy both unless it is \`, \$, \\ and maybe \" */
  4432. ch = i_getch(input);
  4433. if (ch != '`'
  4434. && ch != '$'
  4435. && ch != '\\'
  4436. && (!in_dquote || ch != '"')
  4437. ) {
  4438. o_addchr(dest, '\\');
  4439. }
  4440. }
  4441. if (ch == EOF) {
  4442. syntax_error_unterm_ch('`');
  4443. return 0;
  4444. }
  4445. o_addchr(dest, ch);
  4446. }
  4447. }
  4448. /* Process $(cmd) - copy contents until ")" is seen. Complicated by
  4449. * quoting and nested ()s.
  4450. * "With the $(command) style of command substitution, all characters
  4451. * following the open parenthesis to the matching closing parenthesis
  4452. * constitute the command. Any valid shell script can be used for command,
  4453. * except a script consisting solely of redirections which produces
  4454. * unspecified results."
  4455. * Example Output
  4456. * echo $(echo '(TEST)' BEST) (TEST) BEST
  4457. * echo $(echo 'TEST)' BEST) TEST) BEST
  4458. * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
  4459. *
  4460. * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
  4461. * can contain arbitrary constructs, just like $(cmd).
  4462. * In bash compat mode, it needs to also be able to stop on ':' or '/'
  4463. * for ${var:N[:M]} and ${var/P[/R]} parsing.
  4464. */
  4465. #define DOUBLE_CLOSE_CHAR_FLAG 0x80
  4466. static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
  4467. {
  4468. int ch;
  4469. char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
  4470. # if BASH_SUBSTR || BASH_PATTERN_SUBST
  4471. char end_char2 = end_ch >> 8;
  4472. # endif
  4473. end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
  4474. # if ENABLE_HUSH_INTERACTIVE
  4475. G.promptmode = 1; /* PS2 */
  4476. # endif
  4477. debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
  4478. while (1) {
  4479. ch = i_getch(input);
  4480. if (ch == EOF) {
  4481. syntax_error_unterm_ch(end_ch);
  4482. return 0;
  4483. }
  4484. if (ch == end_ch
  4485. # if BASH_SUBSTR || BASH_PATTERN_SUBST
  4486. || ch == end_char2
  4487. # endif
  4488. ) {
  4489. if (!dbl)
  4490. break;
  4491. /* we look for closing )) of $((EXPR)) */
  4492. if (i_peek_and_eat_bkslash_nl(input) == end_ch) {
  4493. i_getch(input); /* eat second ')' */
  4494. break;
  4495. }
  4496. }
  4497. o_addchr(dest, ch);
  4498. //bb_error_msg("%s:o_addchr('%c')", __func__, ch);
  4499. if (ch == '(' || ch == '{') {
  4500. ch = (ch == '(' ? ')' : '}');
  4501. if (!add_till_closing_bracket(dest, input, ch))
  4502. return 0;
  4503. o_addchr(dest, ch);
  4504. continue;
  4505. }
  4506. if (ch == '\'') {
  4507. if (!add_till_single_quote(dest, input))
  4508. return 0;
  4509. o_addchr(dest, ch);
  4510. continue;
  4511. }
  4512. if (ch == '"') {
  4513. if (!add_till_double_quote(dest, input))
  4514. return 0;
  4515. o_addchr(dest, ch);
  4516. continue;
  4517. }
  4518. if (ch == '`') {
  4519. if (!add_till_backquote(dest, input, /*in_dquote:*/ 0))
  4520. return 0;
  4521. o_addchr(dest, ch);
  4522. continue;
  4523. }
  4524. if (ch == '\\') {
  4525. /* \x. Copy verbatim. Important for \(, \) */
  4526. ch = i_getch(input);
  4527. if (ch == EOF) {
  4528. syntax_error_unterm_ch(end_ch);
  4529. return 0;
  4530. }
  4531. # if 0
  4532. if (ch == '\n') {
  4533. /* "backslash+newline", ignore both */
  4534. o_delchr(dest); /* undo insertion of '\' */
  4535. continue;
  4536. }
  4537. # endif
  4538. o_addchr(dest, ch);
  4539. //bb_error_msg("%s:o_addchr('%c') after '\\'", __func__, ch);
  4540. continue;
  4541. }
  4542. }
  4543. debug_printf_parse("%s return '%s' ch:'%c'\n", __func__, dest->data, ch);
  4544. return ch;
  4545. }
  4546. #endif /* ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS */
  4547. /* Return code: 0 for OK, 1 for syntax error */
  4548. #if BB_MMU
  4549. #define parse_dollar(as_string, dest, input, quote_mask) \
  4550. parse_dollar(dest, input, quote_mask)
  4551. #define as_string NULL
  4552. #endif
  4553. static int parse_dollar(o_string *as_string,
  4554. o_string *dest,
  4555. struct in_str *input, unsigned char quote_mask)
  4556. {
  4557. int ch = i_peek_and_eat_bkslash_nl(input); /* first character after the $ */
  4558. debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
  4559. if (isalpha(ch)) {
  4560. make_var:
  4561. ch = i_getch(input);
  4562. nommu_addchr(as_string, ch);
  4563. /*make_var1:*/
  4564. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4565. while (1) {
  4566. debug_printf_parse(": '%c'\n", ch);
  4567. o_addchr(dest, ch | quote_mask);
  4568. quote_mask = 0;
  4569. ch = i_peek_and_eat_bkslash_nl(input);
  4570. if (!isalnum(ch) && ch != '_') {
  4571. /* End of variable name reached */
  4572. break;
  4573. }
  4574. ch = i_getch(input);
  4575. nommu_addchr(as_string, ch);
  4576. }
  4577. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4578. } else if (isdigit(ch)) {
  4579. make_one_char_var:
  4580. ch = i_getch(input);
  4581. nommu_addchr(as_string, ch);
  4582. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4583. debug_printf_parse(": '%c'\n", ch);
  4584. o_addchr(dest, ch | quote_mask);
  4585. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4586. } else switch (ch) {
  4587. case '$': /* pid */
  4588. case '!': /* last bg pid */
  4589. case '?': /* last exit code */
  4590. case '#': /* number of args */
  4591. case '*': /* args */
  4592. case '@': /* args */
  4593. case '-': /* $- option flags set by set builtin or shell options (-i etc) */
  4594. goto make_one_char_var;
  4595. case '{': {
  4596. char len_single_ch;
  4597. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4598. ch = i_getch(input); /* eat '{' */
  4599. nommu_addchr(as_string, ch);
  4600. ch = i_getch_and_eat_bkslash_nl(input); /* first char after '{' */
  4601. /* It should be ${?}, or ${#var},
  4602. * or even ${?+subst} - operator acting on a special variable,
  4603. * or the beginning of variable name.
  4604. */
  4605. if (ch == EOF
  4606. || (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) /* not one of those */
  4607. ) {
  4608. bad_dollar_syntax:
  4609. syntax_error_unterm_str("${name}");
  4610. debug_printf_parse("parse_dollar return 0: unterminated ${name}\n");
  4611. return 0;
  4612. }
  4613. nommu_addchr(as_string, ch);
  4614. len_single_ch = ch;
  4615. ch |= quote_mask;
  4616. /* It's possible to just call add_till_closing_bracket() at this point.
  4617. * However, this regresses some of our testsuite cases
  4618. * which check invalid constructs like ${%}.
  4619. * Oh well... let's check that the var name part is fine... */
  4620. while (1) {
  4621. unsigned pos;
  4622. o_addchr(dest, ch);
  4623. debug_printf_parse(": '%c'\n", ch);
  4624. ch = i_getch(input);
  4625. nommu_addchr(as_string, ch);
  4626. if (ch == '}')
  4627. break;
  4628. if (!isalnum(ch) && ch != '_') {
  4629. unsigned end_ch;
  4630. unsigned char last_ch;
  4631. /* handle parameter expansions
  4632. * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
  4633. */
  4634. if (!strchr(VAR_SUBST_OPS, ch)) { /* ${var<bad_char>... */
  4635. if (len_single_ch != '#'
  4636. /*|| !strchr(SPECIAL_VARS_STR, ch) - disallow errors like ${#+} ? */
  4637. || i_peek(input) != '}'
  4638. ) {
  4639. goto bad_dollar_syntax;
  4640. }
  4641. /* else: it's "length of C" ${#C} op,
  4642. * where C is a single char
  4643. * special var name, e.g. ${#!}.
  4644. */
  4645. }
  4646. /* Eat everything until closing '}' (or ':') */
  4647. end_ch = '}';
  4648. if (BASH_SUBSTR
  4649. && ch == ':'
  4650. && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
  4651. ) {
  4652. /* It's ${var:N[:M]} thing */
  4653. end_ch = '}' * 0x100 + ':';
  4654. }
  4655. if (BASH_PATTERN_SUBST
  4656. && ch == '/'
  4657. ) {
  4658. /* It's ${var/[/]pattern[/repl]} thing */
  4659. if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
  4660. i_getch(input);
  4661. nommu_addchr(as_string, '/');
  4662. ch = '\\';
  4663. }
  4664. end_ch = '}' * 0x100 + '/';
  4665. }
  4666. o_addchr(dest, ch);
  4667. /* The pattern can't be empty.
  4668. * IOW: if the first char after "${v//" is a slash,
  4669. * it does not terminate the pattern - it's the first char of the pattern:
  4670. * v=/dev/ram; echo ${v////-} prints -dev-ram (pattern is "/")
  4671. * v=/dev/ram; echo ${v///r/-} prints /dev-am (pattern is "/r")
  4672. */
  4673. if (i_peek(input) == '/') {
  4674. o_addchr(dest, i_getch(input));
  4675. }
  4676. again:
  4677. if (!BB_MMU)
  4678. pos = dest->length;
  4679. #if ENABLE_HUSH_DOLLAR_OPS
  4680. last_ch = add_till_closing_bracket(dest, input, end_ch);
  4681. if (last_ch == 0) /* error? */
  4682. return 0;
  4683. #else
  4684. # error Simple code to only allow ${var} is not implemented
  4685. #endif
  4686. if (as_string) {
  4687. o_addstr(as_string, dest->data + pos);
  4688. o_addchr(as_string, last_ch);
  4689. }
  4690. if ((BASH_SUBSTR || BASH_PATTERN_SUBST)
  4691. && (end_ch & 0xff00)
  4692. ) {
  4693. /* close the first block: */
  4694. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4695. /* while parsing N from ${var:N[:M]}
  4696. * or pattern from ${var/[/]pattern[/repl]} */
  4697. if ((end_ch & 0xff) == last_ch) {
  4698. /* got ':' or '/'- parse the rest */
  4699. end_ch = '}';
  4700. goto again;
  4701. }
  4702. /* got '}' */
  4703. if (BASH_SUBSTR && end_ch == '}' * 0x100 + ':') {
  4704. /* it's ${var:N} - emulate :999999999 */
  4705. o_addstr(dest, "999999999");
  4706. } /* else: it's ${var/[/]pattern} */
  4707. }
  4708. break;
  4709. }
  4710. len_single_ch = 0; /* it can't be ${#C} op */
  4711. }
  4712. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4713. break;
  4714. }
  4715. #if ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_TICK
  4716. case '(': {
  4717. unsigned pos;
  4718. ch = i_getch(input);
  4719. nommu_addchr(as_string, ch);
  4720. # if ENABLE_FEATURE_SH_MATH
  4721. if (i_peek_and_eat_bkslash_nl(input) == '(') {
  4722. ch = i_getch(input);
  4723. nommu_addchr(as_string, ch);
  4724. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4725. o_addchr(dest, quote_mask | '+');
  4726. if (!BB_MMU)
  4727. pos = dest->length;
  4728. if (!add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG))
  4729. return 0; /* error */
  4730. if (as_string) {
  4731. o_addstr(as_string, dest->data + pos);
  4732. o_addchr(as_string, ')');
  4733. o_addchr(as_string, ')');
  4734. }
  4735. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4736. break;
  4737. }
  4738. # endif
  4739. # if ENABLE_HUSH_TICK
  4740. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4741. o_addchr(dest, quote_mask | '`');
  4742. if (!BB_MMU)
  4743. pos = dest->length;
  4744. if (!add_till_closing_bracket(dest, input, ')'))
  4745. return 0; /* error */
  4746. if (as_string) {
  4747. o_addstr(as_string, dest->data + pos);
  4748. o_addchr(as_string, ')');
  4749. }
  4750. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4751. # endif
  4752. break;
  4753. }
  4754. #endif
  4755. case '_':
  4756. goto make_var;
  4757. #if 0
  4758. /* TODO: $_: */
  4759. /* $_ Shell or shell script name; or last argument of last command
  4760. * (if last command wasn't a pipe; if it was, bash sets $_ to "");
  4761. * but in command's env, set to full pathname used to invoke it */
  4762. ch = i_getch(input);
  4763. nommu_addchr(as_string, ch);
  4764. ch = i_peek_and_eat_bkslash_nl(input);
  4765. if (isalnum(ch)) { /* it's $_name or $_123 */
  4766. ch = '_';
  4767. goto make_var1;
  4768. }
  4769. /* else: it's $_ */
  4770. #endif
  4771. default:
  4772. o_addQchr(dest, '$');
  4773. }
  4774. debug_printf_parse("parse_dollar return 1 (ok)\n");
  4775. return 1;
  4776. #undef as_string
  4777. }
  4778. #if BB_MMU
  4779. #define encode_string(as_string, dest, input, dquote_end) \
  4780. encode_string(dest, input, dquote_end)
  4781. #define as_string NULL
  4782. #endif
  4783. static int encode_string(o_string *as_string,
  4784. o_string *dest,
  4785. struct in_str *input,
  4786. int dquote_end)
  4787. {
  4788. int ch;
  4789. int next;
  4790. again:
  4791. ch = i_getch(input);
  4792. if (ch != EOF)
  4793. nommu_addchr(as_string, ch);
  4794. if (ch == dquote_end) { /* may be only '"' or EOF */
  4795. debug_printf_parse("encode_string return 1 (ok)\n");
  4796. return 1;
  4797. }
  4798. /* note: can't move it above ch == dquote_end check! */
  4799. if (ch == EOF) {
  4800. syntax_error_unterm_ch('"');
  4801. return 0; /* error */
  4802. }
  4803. next = '\0';
  4804. if (ch != '\n') {
  4805. next = i_peek(input);
  4806. }
  4807. debug_printf_parse("\" ch=%c (%d) escape=%d\n",
  4808. ch, ch, !!(dest->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
  4809. if (ch == '\\') {
  4810. if (next == EOF) {
  4811. /* Testcase: in interactive shell a file with
  4812. * echo "unterminated string\<eof>
  4813. * is sourced.
  4814. */
  4815. syntax_error_unterm_ch('"');
  4816. return 0; /* error */
  4817. }
  4818. /* bash:
  4819. * "The backslash retains its special meaning [in "..."]
  4820. * only when followed by one of the following characters:
  4821. * $, `, ", \, or <newline>. A double quote may be quoted
  4822. * within double quotes by preceding it with a backslash."
  4823. * NB: in (unquoted) heredoc, above does not apply to ",
  4824. * therefore we check for it by "next == dquote_end" cond.
  4825. */
  4826. if (next == dquote_end || strchr("$`\\\n", next)) {
  4827. ch = i_getch(input); /* eat next */
  4828. if (ch == '\n')
  4829. goto again; /* skip \<newline> */
  4830. } /* else: ch remains == '\\', and we double it below: */
  4831. o_addqchr(dest, ch); /* \c if c is a glob char, else just c */
  4832. nommu_addchr(as_string, ch);
  4833. goto again;
  4834. }
  4835. if (ch == '$') {
  4836. if (!parse_dollar(as_string, dest, input, /*quote_mask:*/ 0x80)) {
  4837. debug_printf_parse("encode_string return 0: "
  4838. "parse_dollar returned 0 (error)\n");
  4839. return 0;
  4840. }
  4841. goto again;
  4842. }
  4843. #if ENABLE_HUSH_TICK
  4844. if (ch == '`') {
  4845. //unsigned pos = dest->length;
  4846. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4847. o_addchr(dest, 0x80 | '`');
  4848. if (!add_till_backquote(dest, input, /*in_dquote:*/ dquote_end == '"'))
  4849. return 0; /* error */
  4850. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4851. //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
  4852. goto again;
  4853. }
  4854. #endif
  4855. o_addQchr(dest, ch);
  4856. goto again;
  4857. #undef as_string
  4858. }
  4859. /*
  4860. * Scan input until EOF or end_trigger char.
  4861. * Return a list of pipes to execute, or NULL on EOF
  4862. * or if end_trigger character is met.
  4863. * On syntax error, exit if shell is not interactive,
  4864. * reset parsing machinery and start parsing anew,
  4865. * or return ERR_PTR.
  4866. */
  4867. static struct pipe *parse_stream(char **pstring,
  4868. int *heredoc_cnt_ptr,
  4869. struct in_str *input,
  4870. int end_trigger)
  4871. {
  4872. struct parse_context ctx;
  4873. int heredoc_cnt;
  4874. /* Single-quote triggers a bypass of the main loop until its mate is
  4875. * found. When recursing, quote state is passed in via ctx.word.o_expflags.
  4876. */
  4877. debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
  4878. end_trigger ? end_trigger : 'X');
  4879. debug_enter();
  4880. initialize_context(&ctx);
  4881. /* If very first arg is "" or '', ctx.word.data may end up NULL.
  4882. * Preventing this:
  4883. */
  4884. ctx.word.data = xzalloc(1); /* start as "", not as NULL */
  4885. /* We used to separate words on $IFS here. This was wrong.
  4886. * $IFS is used only for word splitting when $var is expanded,
  4887. * here we should use blank chars as separators, not $IFS
  4888. */
  4889. heredoc_cnt = 0;
  4890. while (1) {
  4891. const char *is_blank;
  4892. const char *is_special;
  4893. int ch;
  4894. int next;
  4895. int redir_fd;
  4896. redir_type redir_style;
  4897. ch = i_getch(input);
  4898. debug_printf_parse(": ch=%c (%d) escape=%d\n",
  4899. ch, ch, !!(ctx.word.o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
  4900. if (ch == EOF) {
  4901. struct pipe *pi;
  4902. if (heredoc_cnt) {
  4903. syntax_error_unterm_str("here document");
  4904. goto parse_error;
  4905. }
  4906. if (end_trigger == ')') {
  4907. syntax_error_unterm_ch('(');
  4908. goto parse_error;
  4909. }
  4910. if (end_trigger == '}') {
  4911. syntax_error_unterm_ch('{');
  4912. goto parse_error;
  4913. }
  4914. if (done_word(&ctx)) {
  4915. goto parse_error;
  4916. }
  4917. o_free_and_set_NULL(&ctx.word);
  4918. done_pipe(&ctx, PIPE_SEQ);
  4919. pi = ctx.list_head;
  4920. /* If we got nothing... */
  4921. /* (this makes bare "&" cmd a no-op.
  4922. * bash says: "syntax error near unexpected token '&'") */
  4923. if (pi->num_cmds == 0
  4924. IF_HAS_KEYWORDS(&& pi->res_word == RES_NONE)
  4925. ) {
  4926. free_pipe_list(pi);
  4927. pi = NULL;
  4928. }
  4929. #if !BB_MMU
  4930. debug_printf_parse("as_string1 '%s'\n", ctx.as_string.data);
  4931. if (pstring)
  4932. *pstring = ctx.as_string.data;
  4933. else
  4934. o_free(&ctx.as_string);
  4935. #endif
  4936. // heredoc_cnt must be 0 here anyway
  4937. //if (heredoc_cnt_ptr)
  4938. // *heredoc_cnt_ptr = heredoc_cnt;
  4939. debug_leave();
  4940. debug_printf_heredoc("parse_stream return heredoc_cnt:%d\n", heredoc_cnt);
  4941. debug_printf_parse("parse_stream return %p\n", pi);
  4942. return pi;
  4943. }
  4944. /* Handle "'" and "\" first, as they won't play nice with
  4945. * i_peek_and_eat_bkslash_nl() anyway:
  4946. * echo z\\
  4947. * and
  4948. * echo '\
  4949. * '
  4950. * would break.
  4951. */
  4952. if (ch == '\\') {
  4953. ch = i_getch(input);
  4954. if (ch == '\n')
  4955. continue; /* drop \<newline>, get next char */
  4956. nommu_addchr(&ctx.as_string, '\\');
  4957. o_addchr(&ctx.word, '\\');
  4958. if (ch == EOF) {
  4959. /* Testcase: eval 'echo Ok\' */
  4960. /* bash-4.3.43 was removing backslash,
  4961. * but 4.4.19 retains it, most other shells too
  4962. */
  4963. continue; /* get next char */
  4964. }
  4965. /* Example: echo Hello \2>file
  4966. * we need to know that word 2 is quoted
  4967. */
  4968. ctx.word.has_quoted_part = 1;
  4969. nommu_addchr(&ctx.as_string, ch);
  4970. o_addchr(&ctx.word, ch);
  4971. continue; /* get next char */
  4972. }
  4973. nommu_addchr(&ctx.as_string, ch);
  4974. if (ch == '\'') {
  4975. ctx.word.has_quoted_part = 1;
  4976. next = i_getch(input);
  4977. if (next == '\'' && !ctx.pending_redirect)
  4978. goto insert_empty_quoted_str_marker;
  4979. ch = next;
  4980. while (1) {
  4981. if (ch == EOF) {
  4982. syntax_error_unterm_ch('\'');
  4983. goto parse_error;
  4984. }
  4985. nommu_addchr(&ctx.as_string, ch);
  4986. if (ch == '\'')
  4987. break;
  4988. if (ch == SPECIAL_VAR_SYMBOL) {
  4989. /* Convert raw ^C to corresponding special variable reference */
  4990. o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
  4991. o_addchr(&ctx.word, SPECIAL_VAR_QUOTED_SVS);
  4992. }
  4993. o_addqchr(&ctx.word, ch);
  4994. ch = i_getch(input);
  4995. }
  4996. continue; /* get next char */
  4997. }
  4998. next = '\0';
  4999. if (ch != '\n')
  5000. next = i_peek_and_eat_bkslash_nl(input);
  5001. is_special = "{}<>;&|()#" /* special outside of "str" */
  5002. "$\"" IF_HUSH_TICK("`") /* always special */
  5003. SPECIAL_VAR_SYMBOL_STR;
  5004. /* Are { and } special here? */
  5005. if (ctx.command->argv /* word [word]{... - non-special */
  5006. || ctx.word.length /* word{... - non-special */
  5007. || ctx.word.has_quoted_part /* ""{... - non-special */
  5008. || (next != ';' /* }; - special */
  5009. && next != ')' /* }) - special */
  5010. && next != '(' /* {( - special */
  5011. && next != '&' /* }& and }&& ... - special */
  5012. && next != '|' /* }|| ... - special */
  5013. && !strchr(defifs, next) /* {word - non-special */
  5014. )
  5015. ) {
  5016. /* They are not special, skip "{}" */
  5017. is_special += 2;
  5018. }
  5019. is_special = strchr(is_special, ch);
  5020. is_blank = strchr(defifs, ch);
  5021. if (!is_special && !is_blank) { /* ordinary char */
  5022. ordinary_char:
  5023. o_addQchr(&ctx.word, ch);
  5024. if ((ctx.is_assignment == MAYBE_ASSIGNMENT
  5025. || ctx.is_assignment == WORD_IS_KEYWORD)
  5026. && ch == '='
  5027. && endofname(ctx.word.data)[0] == '='
  5028. ) {
  5029. ctx.is_assignment = DEFINITELY_ASSIGNMENT;
  5030. debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
  5031. }
  5032. continue;
  5033. }
  5034. if (is_blank) {
  5035. #if ENABLE_HUSH_LINENO_VAR
  5036. /* Case:
  5037. * "while ...; do<whitespace><newline>
  5038. * cmd ..."
  5039. * would think that "cmd" starts in <whitespace> -
  5040. * i.e., at the previous line.
  5041. * We need to skip all whitespace before newlines.
  5042. */
  5043. while (ch != '\n') {
  5044. next = i_peek(input);
  5045. if (next != ' ' && next != '\t' && next != '\n')
  5046. break; /* next char is not ws */
  5047. ch = i_getch(input);
  5048. }
  5049. /* ch == last eaten whitespace char */
  5050. #endif
  5051. if (done_word(&ctx)) {
  5052. goto parse_error;
  5053. }
  5054. if (ch == '\n') {
  5055. /* Is this a case when newline is simply ignored?
  5056. * Some examples:
  5057. * "cmd | <newline> cmd ..."
  5058. * "case ... in <newline> word) ..."
  5059. */
  5060. if (IS_NULL_CMD(ctx.command)
  5061. && ctx.word.length == 0
  5062. && !ctx.word.has_quoted_part
  5063. && heredoc_cnt == 0
  5064. ) {
  5065. /* This newline can be ignored. But...
  5066. * Without check #1, interactive shell
  5067. * ignores even bare <newline>,
  5068. * and shows the continuation prompt:
  5069. * ps1_prompt$ <enter>
  5070. * ps2> _ <=== wrong, should be ps1
  5071. * Without check #2, "cmd & <newline>"
  5072. * is similarly mistreated.
  5073. * (BTW, this makes "cmd & cmd"
  5074. * and "cmd && cmd" non-orthogonal.
  5075. * Really, ask yourself, why
  5076. * "cmd && <newline>" doesn't start
  5077. * cmd but waits for more input?
  5078. * The only reason is that it might be
  5079. * a "cmd1 && <nl> cmd2 &" construct,
  5080. * cmd1 may need to run in BG).
  5081. */
  5082. struct pipe *pi = ctx.list_head;
  5083. if (pi->num_cmds != 0 /* check #1 */
  5084. && pi->followup != PIPE_BG /* check #2 */
  5085. ) {
  5086. continue;
  5087. }
  5088. }
  5089. /* Treat newline as a command separator. */
  5090. done_pipe(&ctx, PIPE_SEQ);
  5091. debug_printf_heredoc("heredoc_cnt:%d\n", heredoc_cnt);
  5092. if (heredoc_cnt) {
  5093. heredoc_cnt = fetch_heredocs(&ctx.as_string, ctx.list_head, heredoc_cnt, input);
  5094. if (heredoc_cnt != 0)
  5095. goto parse_error;
  5096. }
  5097. ctx.is_assignment = MAYBE_ASSIGNMENT;
  5098. debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
  5099. ch = ';';
  5100. /* note: if (is_blank) continue;
  5101. * will still trigger for us */
  5102. }
  5103. }
  5104. /* "cmd}" or "cmd }..." without semicolon or &:
  5105. * } is an ordinary char in this case, even inside { cmd; }
  5106. * Pathological example: { ""}; } should exec "}" cmd
  5107. */
  5108. if (ch == '}') {
  5109. if (ctx.word.length != 0 /* word} */
  5110. || ctx.word.has_quoted_part /* ""} */
  5111. ) {
  5112. goto ordinary_char;
  5113. }
  5114. if (!IS_NULL_CMD(ctx.command)) { /* cmd } */
  5115. /* Generally, there should be semicolon: "cmd; }"
  5116. * However, bash allows to omit it if "cmd" is
  5117. * a group. Examples:
  5118. * { { echo 1; } }
  5119. * {(echo 1)}
  5120. * { echo 0 >&2 | { echo 1; } }
  5121. * { while false; do :; done }
  5122. * { case a in b) ;; esac }
  5123. */
  5124. if (ctx.command->group)
  5125. goto term_group;
  5126. goto ordinary_char;
  5127. }
  5128. if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
  5129. /* Can't be an end of {cmd}, skip the check */
  5130. goto skip_end_trigger;
  5131. /* else: } does terminate a group */
  5132. }
  5133. term_group:
  5134. if (end_trigger && end_trigger == ch
  5135. && (ch != ';' || heredoc_cnt == 0)
  5136. #if ENABLE_HUSH_CASE
  5137. && (ch != ')'
  5138. || ctx.ctx_res_w != RES_MATCH
  5139. || (!ctx.word.has_quoted_part && strcmp(ctx.word.data, "esac") == 0)
  5140. )
  5141. #endif
  5142. ) {
  5143. if (done_word(&ctx)) {
  5144. goto parse_error;
  5145. }
  5146. done_pipe(&ctx, PIPE_SEQ);
  5147. ctx.is_assignment = MAYBE_ASSIGNMENT;
  5148. debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
  5149. /* Do we sit outside of any if's, loops or case's? */
  5150. if (!HAS_KEYWORDS
  5151. IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
  5152. ) {
  5153. o_free_and_set_NULL(&ctx.word);
  5154. #if !BB_MMU
  5155. debug_printf_parse("as_string2 '%s'\n", ctx.as_string.data);
  5156. if (pstring)
  5157. *pstring = ctx.as_string.data;
  5158. else
  5159. o_free(&ctx.as_string);
  5160. #endif
  5161. if (ch != ';' && IS_NULL_PIPE(ctx.list_head)) {
  5162. /* Example: bare "{ }", "()" */
  5163. G.last_exitcode = 2; /* bash compat */
  5164. syntax_error_unexpected_ch(ch);
  5165. goto parse_error2;
  5166. }
  5167. if (heredoc_cnt_ptr)
  5168. *heredoc_cnt_ptr = heredoc_cnt;
  5169. debug_printf_heredoc("parse_stream return heredoc_cnt:%d\n", heredoc_cnt);
  5170. debug_printf_parse("parse_stream return %p: "
  5171. "end_trigger char found\n",
  5172. ctx.list_head);
  5173. debug_leave();
  5174. return ctx.list_head;
  5175. }
  5176. }
  5177. if (is_blank)
  5178. continue;
  5179. /* Catch <, > before deciding whether this word is
  5180. * an assignment. a=1 2>z b=2: b=2 is still assignment */
  5181. switch (ch) {
  5182. case '>':
  5183. redir_fd = redirect_opt_num(&ctx.word);
  5184. if (done_word(&ctx)) {
  5185. goto parse_error;
  5186. }
  5187. redir_style = REDIRECT_OVERWRITE;
  5188. if (next == '>') {
  5189. redir_style = REDIRECT_APPEND;
  5190. ch = i_getch(input);
  5191. nommu_addchr(&ctx.as_string, ch);
  5192. }
  5193. #if 0
  5194. else if (next == '(') {
  5195. syntax_error(">(process) not supported");
  5196. goto parse_error;
  5197. }
  5198. #endif
  5199. if (parse_redirect(&ctx, redir_fd, redir_style, input))
  5200. goto parse_error;
  5201. continue; /* get next char */
  5202. case '<':
  5203. redir_fd = redirect_opt_num(&ctx.word);
  5204. if (done_word(&ctx)) {
  5205. goto parse_error;
  5206. }
  5207. redir_style = REDIRECT_INPUT;
  5208. if (next == '<') {
  5209. redir_style = REDIRECT_HEREDOC;
  5210. heredoc_cnt++;
  5211. debug_printf_heredoc("++heredoc_cnt=%d\n", heredoc_cnt);
  5212. ch = i_getch(input);
  5213. nommu_addchr(&ctx.as_string, ch);
  5214. } else if (next == '>') {
  5215. redir_style = REDIRECT_IO;
  5216. ch = i_getch(input);
  5217. nommu_addchr(&ctx.as_string, ch);
  5218. }
  5219. #if 0
  5220. else if (next == '(') {
  5221. syntax_error("<(process) not supported");
  5222. goto parse_error;
  5223. }
  5224. #endif
  5225. if (parse_redirect(&ctx, redir_fd, redir_style, input))
  5226. goto parse_error;
  5227. continue; /* get next char */
  5228. case '#':
  5229. if (ctx.word.length == 0 && !ctx.word.has_quoted_part) {
  5230. /* skip "#comment" */
  5231. /* note: we do not add it to &ctx.as_string */
  5232. /* TODO: in bash:
  5233. * comment inside $() goes to the next \n, even inside quoted string (!):
  5234. * cmd "$(cmd2 #comment)" - syntax error
  5235. * cmd "`cmd2 #comment`" - ok
  5236. * We accept both (comment ends where command subst ends, in both cases).
  5237. */
  5238. while (1) {
  5239. ch = i_peek(input);
  5240. if (ch == '\n') {
  5241. nommu_addchr(&ctx.as_string, '\n');
  5242. break;
  5243. }
  5244. ch = i_getch(input);
  5245. if (ch == EOF)
  5246. break;
  5247. }
  5248. continue; /* get next char */
  5249. }
  5250. break;
  5251. }
  5252. skip_end_trigger:
  5253. if (ctx.is_assignment == MAYBE_ASSIGNMENT
  5254. /* check that we are not in word in "a=1 2>word b=1": */
  5255. && !ctx.pending_redirect
  5256. ) {
  5257. /* ch is a special char and thus this word
  5258. * cannot be an assignment */
  5259. ctx.is_assignment = NOT_ASSIGNMENT;
  5260. debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
  5261. }
  5262. /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
  5263. switch (ch) {
  5264. case SPECIAL_VAR_SYMBOL:
  5265. /* Convert raw ^C to corresponding special variable reference */
  5266. o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
  5267. o_addchr(&ctx.word, SPECIAL_VAR_QUOTED_SVS);
  5268. /* fall through */
  5269. case '#':
  5270. /* non-comment #: "echo a#b" etc */
  5271. o_addchr(&ctx.word, ch);
  5272. continue; /* get next char */
  5273. case '$':
  5274. if (!parse_dollar(&ctx.as_string, &ctx.word, input, /*quote_mask:*/ 0)) {
  5275. debug_printf_parse("parse_stream parse error: "
  5276. "parse_dollar returned 0 (error)\n");
  5277. goto parse_error;
  5278. }
  5279. continue; /* get next char */
  5280. case '"':
  5281. ctx.word.has_quoted_part = 1;
  5282. if (next == '"' && !ctx.pending_redirect) {
  5283. i_getch(input); /* eat second " */
  5284. insert_empty_quoted_str_marker:
  5285. nommu_addchr(&ctx.as_string, next);
  5286. o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
  5287. o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
  5288. continue; /* get next char */
  5289. }
  5290. if (ctx.is_assignment == NOT_ASSIGNMENT)
  5291. ctx.word.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
  5292. if (!encode_string(&ctx.as_string, &ctx.word, input, '"'))
  5293. goto parse_error;
  5294. ctx.word.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
  5295. continue; /* get next char */
  5296. #if ENABLE_HUSH_TICK
  5297. case '`': {
  5298. USE_FOR_NOMMU(unsigned pos;)
  5299. o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
  5300. o_addchr(&ctx.word, '`');
  5301. USE_FOR_NOMMU(pos = ctx.word.length;)
  5302. if (!add_till_backquote(&ctx.word, input, /*in_dquote:*/ 0))
  5303. goto parse_error;
  5304. # if !BB_MMU
  5305. o_addstr(&ctx.as_string, ctx.word.data + pos);
  5306. o_addchr(&ctx.as_string, '`');
  5307. # endif
  5308. o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
  5309. //debug_printf_subst("SUBST RES3 '%s'\n", ctx.word.data + pos);
  5310. continue; /* get next char */
  5311. }
  5312. #endif
  5313. case ';':
  5314. #if ENABLE_HUSH_CASE
  5315. case_semi:
  5316. #endif
  5317. if (done_word(&ctx)) {
  5318. goto parse_error;
  5319. }
  5320. done_pipe(&ctx, PIPE_SEQ);
  5321. #if ENABLE_HUSH_CASE
  5322. /* Eat multiple semicolons, detect
  5323. * whether it means something special */
  5324. while (1) {
  5325. ch = i_peek_and_eat_bkslash_nl(input);
  5326. if (ch != ';')
  5327. break;
  5328. ch = i_getch(input);
  5329. nommu_addchr(&ctx.as_string, ch);
  5330. if (ctx.ctx_res_w == RES_CASE_BODY) {
  5331. ctx.ctx_dsemicolon = 1;
  5332. ctx.ctx_res_w = RES_MATCH;
  5333. break;
  5334. }
  5335. }
  5336. #endif
  5337. new_cmd:
  5338. /* We just finished a cmd. New one may start
  5339. * with an assignment */
  5340. ctx.is_assignment = MAYBE_ASSIGNMENT;
  5341. debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
  5342. continue; /* get next char */
  5343. case '&':
  5344. if (done_word(&ctx)) {
  5345. goto parse_error;
  5346. }
  5347. if (next == '&') {
  5348. ch = i_getch(input);
  5349. nommu_addchr(&ctx.as_string, ch);
  5350. done_pipe(&ctx, PIPE_AND);
  5351. } else {
  5352. done_pipe(&ctx, PIPE_BG);
  5353. }
  5354. goto new_cmd;
  5355. case '|':
  5356. if (done_word(&ctx)) {
  5357. goto parse_error;
  5358. }
  5359. #if ENABLE_HUSH_CASE
  5360. if (ctx.ctx_res_w == RES_MATCH)
  5361. break; /* we are in case's "word | word)" */
  5362. #endif
  5363. if (next == '|') { /* || */
  5364. ch = i_getch(input);
  5365. nommu_addchr(&ctx.as_string, ch);
  5366. done_pipe(&ctx, PIPE_OR);
  5367. } else {
  5368. /* we could pick up a file descriptor choice here
  5369. * with redirect_opt_num(), but bash doesn't do it.
  5370. * "echo foo 2| cat" yields "foo 2". */
  5371. done_command(&ctx);
  5372. }
  5373. goto new_cmd;
  5374. case '(':
  5375. #if ENABLE_HUSH_CASE
  5376. /* "case... in [(]word)..." - skip '(' */
  5377. if (ctx.ctx_res_w == RES_MATCH
  5378. && ctx.command->argv == NULL /* not (word|(... */
  5379. && ctx.word.length == 0 /* not word(... */
  5380. && ctx.word.has_quoted_part == 0 /* not ""(... */
  5381. ) {
  5382. continue; /* get next char */
  5383. }
  5384. #endif
  5385. /* fall through */
  5386. case '{': {
  5387. int n = parse_group(&ctx, input, ch);
  5388. if (n < 0) {
  5389. goto parse_error;
  5390. }
  5391. debug_printf_heredoc("parse_group done, needs heredocs:%d\n", n);
  5392. heredoc_cnt += n;
  5393. goto new_cmd;
  5394. }
  5395. case ')':
  5396. #if ENABLE_HUSH_CASE
  5397. if (ctx.ctx_res_w == RES_MATCH)
  5398. goto case_semi;
  5399. #endif
  5400. case '}':
  5401. /* proper use of this character is caught by end_trigger:
  5402. * if we see {, we call parse_group(..., end_trigger='}')
  5403. * and it will match } earlier (not here). */
  5404. G.last_exitcode = 2;
  5405. syntax_error_unexpected_ch(ch);
  5406. goto parse_error2;
  5407. default:
  5408. if (HUSH_DEBUG)
  5409. bb_error_msg_and_die("BUG: unexpected %c", ch);
  5410. }
  5411. } /* while (1) */
  5412. parse_error:
  5413. G.last_exitcode = 1;
  5414. parse_error2:
  5415. {
  5416. struct parse_context *pctx;
  5417. IF_HAS_KEYWORDS(struct parse_context *p2;)
  5418. /* Clean up allocated tree.
  5419. * Sample for finding leaks on syntax error recovery path.
  5420. * Run it from interactive shell, watch pmap `pidof hush`.
  5421. * while if false; then false; fi; do break; fi
  5422. * Samples to catch leaks at execution:
  5423. * while if (true | { true;}); then echo ok; fi; do break; done
  5424. * while if (true | { true;}); then echo ok; fi; do (if echo ok; break; then :; fi) | cat; break; done
  5425. */
  5426. pctx = &ctx;
  5427. do {
  5428. /* Update pipe/command counts,
  5429. * otherwise freeing may miss some */
  5430. done_pipe(pctx, PIPE_SEQ);
  5431. debug_printf_clean("freeing list %p from ctx %p\n",
  5432. pctx->list_head, pctx);
  5433. debug_print_tree(pctx->list_head, 0);
  5434. free_pipe_list(pctx->list_head);
  5435. debug_printf_clean("freed list %p\n", pctx->list_head);
  5436. #if !BB_MMU
  5437. o_free(&pctx->as_string);
  5438. #endif
  5439. IF_HAS_KEYWORDS(p2 = pctx->stack;)
  5440. if (pctx != &ctx) {
  5441. free(pctx);
  5442. }
  5443. IF_HAS_KEYWORDS(pctx = p2;)
  5444. } while (HAS_KEYWORDS && pctx);
  5445. o_free(&ctx.word);
  5446. #if !BB_MMU
  5447. if (pstring)
  5448. *pstring = NULL;
  5449. #endif
  5450. debug_leave();
  5451. return ERR_PTR;
  5452. }
  5453. }
  5454. /*** Execution routines ***/
  5455. /* Expansion can recurse, need forward decls: */
  5456. #if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
  5457. #define expand_string_to_string(str, EXP_flags, do_unbackslash) \
  5458. expand_string_to_string(str)
  5459. #endif
  5460. static char *expand_string_to_string(const char *str, int EXP_flags, int do_unbackslash);
  5461. #if ENABLE_HUSH_TICK
  5462. static int process_command_subs(o_string *dest, const char *s);
  5463. #endif
  5464. static int expand_vars_to_list(o_string *output, int n, char *arg);
  5465. /* expand_strvec_to_strvec() takes a list of strings, expands
  5466. * all variable references within and returns a pointer to
  5467. * a list of expanded strings, possibly with larger number
  5468. * of strings. (Think VAR="a b"; echo $VAR).
  5469. * This new list is allocated as a single malloc block.
  5470. * NULL-terminated list of char* pointers is at the beginning of it,
  5471. * followed by strings themselves.
  5472. * Caller can deallocate entire list by single free(list). */
  5473. /* A horde of its helpers come first: */
  5474. static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
  5475. {
  5476. while (--len >= 0) {
  5477. char c = *str++;
  5478. #if ENABLE_HUSH_BRACE_EXPANSION
  5479. if (c == '{' || c == '}') {
  5480. /* { -> \{, } -> \} */
  5481. o_addchr(o, '\\');
  5482. /* And now we want to add { or } and continue:
  5483. * o_addchr(o, c);
  5484. * continue;
  5485. * luckily, just falling through achieves this.
  5486. */
  5487. }
  5488. #endif
  5489. o_addchr(o, c);
  5490. if (c == '\\') {
  5491. /* \z -> \\\z; \<eol> -> \\<eol> */
  5492. o_addchr(o, '\\');
  5493. if (len) {
  5494. len--;
  5495. o_addchr(o, '\\');
  5496. o_addchr(o, *str++);
  5497. }
  5498. }
  5499. }
  5500. }
  5501. /* Store given string, finalizing the word and starting new one whenever
  5502. * we encounter IFS char(s). This is used for expanding variable values.
  5503. * End-of-string does NOT finalize word: think about 'echo -$VAR-'.
  5504. * Return in output->ended_in_ifs:
  5505. * 1 - ended with IFS char, else 0 (this includes case of empty str).
  5506. */
  5507. static int expand_on_ifs(o_string *output, int n, const char *str)
  5508. {
  5509. int last_is_ifs = 0;
  5510. while (1) {
  5511. int word_len;
  5512. if (!*str) /* EOL - do not finalize word */
  5513. break;
  5514. word_len = strcspn(str, G.ifs);
  5515. if (word_len) {
  5516. /* We have WORD_LEN leading non-IFS chars */
  5517. if (!(output->o_expflags & EXP_FLAG_GLOB)) {
  5518. o_addblock(output, str, word_len);
  5519. } else {
  5520. /* Protect backslashes against globbing up :)
  5521. * Example: "v='\*'; echo b$v" prints "b\*"
  5522. * (and does not try to glob on "*")
  5523. */
  5524. o_addblock_duplicate_backslash(output, str, word_len);
  5525. /*/ Why can't we do it easier? */
  5526. /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
  5527. /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
  5528. }
  5529. last_is_ifs = 0;
  5530. str += word_len;
  5531. if (!*str) /* EOL - do not finalize word */
  5532. break;
  5533. }
  5534. /* We know str here points to at least one IFS char */
  5535. last_is_ifs = 1;
  5536. str += strspn(str, G.ifs_whitespace); /* skip IFS whitespace chars */
  5537. if (!*str) /* EOL - do not finalize word */
  5538. break;
  5539. if (G.ifs_whitespace != G.ifs /* usually false ($IFS is usually all whitespace), */
  5540. && strchr(G.ifs, *str) /* the second check would fail */
  5541. ) {
  5542. /* This is a non-whitespace $IFS char */
  5543. /* Skip it and IFS whitespace chars, start new word */
  5544. str++;
  5545. str += strspn(str, G.ifs_whitespace);
  5546. goto new_word;
  5547. }
  5548. /* Start new word... but not always! */
  5549. /* Case "v=' a'; echo ''$v": we do need to finalize empty word: */
  5550. if (output->has_quoted_part
  5551. /*
  5552. * Case "v=' a'; echo $v":
  5553. * here nothing precedes the space in $v expansion,
  5554. * therefore we should not finish the word
  5555. * (IOW: if there *is* word to finalize, only then do it):
  5556. * It's okay if this accesses the byte before first argv[]:
  5557. * past call to o_save_ptr() cleared it to zero byte
  5558. * (grep for -prev-ifs-check-).
  5559. */
  5560. || output->data[output->length - 1]
  5561. ) {
  5562. new_word:
  5563. o_addchr(output, '\0');
  5564. debug_print_list("expand_on_ifs", output, n);
  5565. n = o_save_ptr(output, n);
  5566. }
  5567. }
  5568. output->ended_in_ifs = last_is_ifs;
  5569. debug_print_list("expand_on_ifs[1]", output, n);
  5570. return n;
  5571. }
  5572. /* Helper to expand $((...)) and heredoc body. These act as if
  5573. * they are in double quotes, with the exception that they are not :).
  5574. * Just the rules are similar: "expand only $var and `cmd`"
  5575. *
  5576. * Returns malloced string.
  5577. * As an optimization, we return NULL if expansion is not needed.
  5578. */
  5579. static char *encode_then_expand_string(const char *str)
  5580. {
  5581. char *exp_str;
  5582. struct in_str input;
  5583. o_string dest = NULL_O_STRING;
  5584. const char *cp;
  5585. cp = str;
  5586. for (;;) {
  5587. if (!*cp) return NULL; /* string has no special chars */
  5588. if (*cp == '$') break;
  5589. if (*cp == '\\') break;
  5590. #if ENABLE_HUSH_TICK
  5591. if (*cp == '`') break;
  5592. #endif
  5593. cp++;
  5594. }
  5595. /* We need to expand. Example:
  5596. * echo $(($a + `echo 1`)) $((1 + $((2)) ))
  5597. */
  5598. setup_string_in_str(&input, str);
  5599. encode_string(NULL, &dest, &input, EOF);
  5600. //TODO: error check (encode_string returns 0 on error)?
  5601. //bb_error_msg("'%s' -> '%s'", str, dest.data);
  5602. exp_str = expand_string_to_string(dest.data,
  5603. EXP_FLAG_ESC_GLOB_CHARS,
  5604. /*unbackslash:*/ 1
  5605. );
  5606. //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
  5607. o_free(&dest);
  5608. return exp_str;
  5609. }
  5610. static const char *first_special_char_in_vararg(const char *cp)
  5611. {
  5612. for (;;) {
  5613. if (!*cp) return NULL; /* string has no special chars */
  5614. if (*cp == '$') return cp;
  5615. if (*cp == '\\') return cp;
  5616. if (*cp == '\'') return cp;
  5617. if (*cp == '"') return cp;
  5618. #if ENABLE_HUSH_TICK
  5619. if (*cp == '`') return cp;
  5620. #endif
  5621. /* dquoted "${x:+ARG}" should not glob, therefore
  5622. * '*' et al require some non-literal processing: */
  5623. if (*cp == '*') return cp;
  5624. if (*cp == '?') return cp;
  5625. if (*cp == '[') return cp;
  5626. cp++;
  5627. }
  5628. }
  5629. /* Expanding ARG in ${var#ARG}, ${var%ARG}, or ${var/ARG/ARG}.
  5630. * These can contain single- and double-quoted strings,
  5631. * and treated as if the ARG string is initially unquoted. IOW:
  5632. * ${var#ARG} and "${var#ARG}" treat ARG the same (ARG can even be
  5633. * a dquoted string: "${var#"zz"}"), the difference only comes later
  5634. * (word splitting and globbing of the ${var...} result).
  5635. */
  5636. #if !BASH_PATTERN_SUBST
  5637. #define encode_then_expand_vararg(str, handle_squotes, do_unbackslash) \
  5638. encode_then_expand_vararg(str, handle_squotes)
  5639. #endif
  5640. static char *encode_then_expand_vararg(const char *str, int handle_squotes, int do_unbackslash)
  5641. {
  5642. #if !BASH_PATTERN_SUBST && ENABLE_HUSH_CASE
  5643. const int do_unbackslash = 0;
  5644. #endif
  5645. char *exp_str;
  5646. struct in_str input;
  5647. o_string dest = NULL_O_STRING;
  5648. if (!first_special_char_in_vararg(str)) {
  5649. /* string has no special chars */
  5650. return NULL;
  5651. }
  5652. setup_string_in_str(&input, str);
  5653. dest.data = xzalloc(1); /* start as "", not as NULL */
  5654. exp_str = NULL;
  5655. for (;;) {
  5656. int ch;
  5657. ch = i_getch(&input);
  5658. debug_printf_parse("%s: ch=%c (%d) escape=%d\n",
  5659. __func__, ch, ch, !!dest.o_expflags);
  5660. if (!dest.o_expflags) {
  5661. if (ch == EOF)
  5662. break;
  5663. if (handle_squotes && ch == '\'') {
  5664. if (!add_till_single_quote_dquoted(&dest, &input))
  5665. goto ret; /* error */
  5666. continue;
  5667. }
  5668. }
  5669. if (ch == EOF) {
  5670. syntax_error_unterm_ch('"');
  5671. goto ret; /* error */
  5672. }
  5673. if (ch == '"') {
  5674. dest.o_expflags ^= EXP_FLAG_ESC_GLOB_CHARS;
  5675. continue;
  5676. }
  5677. if (ch == '\\') {
  5678. ch = i_getch(&input);
  5679. if (ch == EOF) {
  5680. //example? error message? syntax_error_unterm_ch('"');
  5681. debug_printf_parse("%s: error: \\<eof>\n", __func__);
  5682. goto ret;
  5683. }
  5684. o_addqchr(&dest, ch);
  5685. continue;
  5686. }
  5687. if (ch == '$') {
  5688. if (!parse_dollar(NULL, &dest, &input, /*quote_mask:*/ 0x80)) {
  5689. debug_printf_parse("%s: error: parse_dollar returned 0 (error)\n", __func__);
  5690. goto ret;
  5691. }
  5692. continue;
  5693. }
  5694. #if ENABLE_HUSH_TICK
  5695. if (ch == '`') {
  5696. //unsigned pos = dest->length;
  5697. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  5698. o_addchr(&dest, 0x80 | '`');
  5699. if (!add_till_backquote(&dest, &input,
  5700. /*in_dquote:*/ dest.o_expflags /* nonzero if EXP_FLAG_ESC_GLOB_CHARS set */
  5701. )
  5702. ) {
  5703. goto ret; /* error */
  5704. }
  5705. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  5706. //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
  5707. continue;
  5708. }
  5709. #endif
  5710. o_addQchr(&dest, ch);
  5711. } /* for (;;) */
  5712. debug_printf_parse("encode: '%s' -> '%s'\n", str, dest.data);
  5713. exp_str = expand_string_to_string(dest.data,
  5714. do_unbackslash ? EXP_FLAG_ESC_GLOB_CHARS : 0,
  5715. do_unbackslash
  5716. );
  5717. ret:
  5718. debug_printf_parse("expand: '%s' -> '%s'\n", dest.data, exp_str);
  5719. o_free(&dest);
  5720. return exp_str;
  5721. }
  5722. /* Expanding ARG in ${var+ARG}, ${var-ARG}
  5723. */
  5724. static int encode_then_append_var_plusminus(o_string *output, int n,
  5725. char *str, int dquoted)
  5726. {
  5727. struct in_str input;
  5728. o_string dest = NULL_O_STRING;
  5729. if (!first_special_char_in_vararg(str)
  5730. && '\0' == str[strcspn(str, G.ifs)]
  5731. ) {
  5732. /* string has no special chars
  5733. * && string has no $IFS chars
  5734. */
  5735. if (dquoted) {
  5736. /* Prints 1 (quoted expansion is a "" word, not nothing):
  5737. * set -- "${notexist-}"; echo $#
  5738. */
  5739. output->has_quoted_part = 1;
  5740. }
  5741. return expand_vars_to_list(output, n, str);
  5742. }
  5743. setup_string_in_str(&input, str);
  5744. for (;;) {
  5745. int ch;
  5746. ch = i_getch(&input);
  5747. debug_printf_parse("%s: ch=%c (%d) escape=%x\n",
  5748. __func__, ch, ch, dest.o_expflags);
  5749. if (!dest.o_expflags) {
  5750. if (ch == EOF)
  5751. break;
  5752. if (!dquoted && strchr(G.ifs, ch)) {
  5753. /* PREFIX${x:d${e}f ...} and we met space: expand "d${e}f" and start new word.
  5754. * do not assume we are at the start of the word (PREFIX above).
  5755. */
  5756. if (dest.data) {
  5757. n = expand_vars_to_list(output, n, dest.data);
  5758. o_free_and_set_NULL(&dest);
  5759. o_addchr(output, '\0');
  5760. n = o_save_ptr(output, n); /* create next word */
  5761. } else
  5762. if (output->length != o_get_last_ptr(output, n)
  5763. || output->has_quoted_part
  5764. ) {
  5765. /* For these cases:
  5766. * f() { for i; do echo "|$i|"; done; }; x=x
  5767. * f a${x:+ }b # 1st condition
  5768. * |a|
  5769. * |b|
  5770. * f ""${x:+ }b # 2nd condition
  5771. * ||
  5772. * |b|
  5773. */
  5774. o_addchr(output, '\0');
  5775. n = o_save_ptr(output, n); /* create next word */
  5776. }
  5777. continue;
  5778. }
  5779. if (!dquoted && ch == '\'') {
  5780. if (!add_till_single_quote_dquoted(&dest, &input))
  5781. goto ret; /* error */
  5782. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  5783. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  5784. continue;
  5785. }
  5786. }
  5787. if (ch == EOF) {
  5788. syntax_error_unterm_ch('"');
  5789. goto ret; /* error */
  5790. }
  5791. if (ch == '"') {
  5792. dest.o_expflags ^= EXP_FLAG_ESC_GLOB_CHARS;
  5793. if (dest.o_expflags) {
  5794. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  5795. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  5796. }
  5797. continue;
  5798. }
  5799. if (ch == '\\') {
  5800. ch = i_getch(&input);
  5801. if (ch == EOF) {
  5802. //example? error message? syntax_error_unterm_ch('"');
  5803. debug_printf_parse("%s: error: \\<eof>\n", __func__);
  5804. goto ret;
  5805. }
  5806. o_addqchr(&dest, ch);
  5807. continue;
  5808. }
  5809. if (ch == '$') {
  5810. if (!parse_dollar(NULL, &dest, &input, /*quote_mask:*/ (dest.o_expflags || dquoted) ? 0x80 : 0)) {
  5811. debug_printf_parse("%s: error: parse_dollar returned 0 (error)\n", __func__);
  5812. goto ret;
  5813. }
  5814. continue;
  5815. }
  5816. #if ENABLE_HUSH_TICK
  5817. if (ch == '`') {
  5818. //unsigned pos = dest->length;
  5819. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  5820. o_addchr(&dest, (dest.o_expflags || dquoted) ? 0x80 | '`' : '`');
  5821. if (!add_till_backquote(&dest, &input,
  5822. /*in_dquote:*/ dest.o_expflags /* nonzero if EXP_FLAG_ESC_GLOB_CHARS set */
  5823. )
  5824. ) {
  5825. goto ret; /* error */
  5826. }
  5827. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  5828. //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
  5829. continue;
  5830. }
  5831. #endif
  5832. if (dquoted) {
  5833. /* Always glob-protect if in dquotes:
  5834. * x=x; echo "${x:+/bin/c*}" - prints: /bin/c*
  5835. * x=x; echo "${x:+"/bin/c*"}" - prints: /bin/c*
  5836. */
  5837. o_addqchr(&dest, ch);
  5838. } else {
  5839. /* Glob-protect only if char is quoted:
  5840. * x=x; echo ${x:+/bin/c*} - prints many filenames
  5841. * x=x; echo ${x:+"/bin/c*"} - prints: /bin/c*
  5842. */
  5843. o_addQchr(&dest, ch);
  5844. }
  5845. } /* for (;;) */
  5846. if (dest.data) {
  5847. n = expand_vars_to_list(output, n, dest.data);
  5848. }
  5849. ret:
  5850. o_free(&dest);
  5851. return n;
  5852. }
  5853. #if ENABLE_FEATURE_SH_MATH
  5854. static arith_t expand_and_evaluate_arith(const char *arg, const char **errmsg_p)
  5855. {
  5856. arith_state_t math_state;
  5857. arith_t res;
  5858. char *exp_str;
  5859. math_state.lookupvar = get_local_var_value;
  5860. math_state.setvar = set_local_var_from_halves;
  5861. //math_state.endofname = endofname;
  5862. exp_str = encode_then_expand_string(arg);
  5863. res = arith(&math_state, exp_str ? exp_str : arg);
  5864. free(exp_str);
  5865. if (errmsg_p)
  5866. *errmsg_p = math_state.errmsg;
  5867. if (math_state.errmsg)
  5868. msg_and_die_if_script(math_state.errmsg);
  5869. return res;
  5870. }
  5871. #endif
  5872. #if BASH_PATTERN_SUBST
  5873. /* ${var/[/]pattern[/repl]} helpers */
  5874. static char *strstr_pattern(char *val, const char *pattern, int *size)
  5875. {
  5876. while (1) {
  5877. char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
  5878. debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
  5879. if (end) {
  5880. *size = end - val;
  5881. return val;
  5882. }
  5883. if (*val == '\0')
  5884. return NULL;
  5885. /* Optimization: if "*pat" did not match the start of "string",
  5886. * we know that "tring", "ring" etc will not match too:
  5887. */
  5888. if (pattern[0] == '*')
  5889. return NULL;
  5890. val++;
  5891. }
  5892. }
  5893. static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
  5894. {
  5895. char *result = NULL;
  5896. unsigned res_len = 0;
  5897. unsigned repl_len = strlen(repl);
  5898. /* Null pattern never matches, including if "var" is empty */
  5899. if (!pattern[0])
  5900. return result; /* NULL, no replaces happened */
  5901. while (1) {
  5902. int size;
  5903. char *s = strstr_pattern(val, pattern, &size);
  5904. if (!s)
  5905. break;
  5906. result = xrealloc(result, res_len + (s - val) + repl_len + 1);
  5907. strcpy(mempcpy(result + res_len, val, s - val), repl);
  5908. res_len += (s - val) + repl_len;
  5909. debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
  5910. val = s + size;
  5911. if (exp_op == '/')
  5912. break;
  5913. }
  5914. if (*val && result) {
  5915. result = xrealloc(result, res_len + strlen(val) + 1);
  5916. strcpy(result + res_len, val);
  5917. debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
  5918. }
  5919. debug_printf_varexp("result:'%s'\n", result);
  5920. return result;
  5921. }
  5922. #endif /* BASH_PATTERN_SUBST */
  5923. static int append_str_maybe_ifs_split(o_string *output, int n,
  5924. int first_ch, const char *val)
  5925. {
  5926. if (!(first_ch & 0x80)) { /* unquoted $VAR */
  5927. debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val,
  5928. !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
  5929. if (val && val[0])
  5930. n = expand_on_ifs(output, n, val);
  5931. } else { /* quoted "$VAR" */
  5932. output->has_quoted_part = 1;
  5933. debug_printf_expand("quoted '%s', output->o_escape:%d\n", val,
  5934. !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
  5935. if (val && val[0])
  5936. o_addQstr(output, val);
  5937. }
  5938. return n;
  5939. }
  5940. /* Handle <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
  5941. */
  5942. static NOINLINE int expand_one_var(o_string *output, int n,
  5943. int first_ch, char *arg, char **pp)
  5944. {
  5945. const char *val;
  5946. char *to_be_freed;
  5947. char *p;
  5948. char *var;
  5949. char exp_op;
  5950. char exp_save = exp_save; /* for compiler */
  5951. char *exp_saveptr; /* points to expansion operator */
  5952. char *exp_word = exp_word; /* for compiler */
  5953. char arg0;
  5954. val = NULL;
  5955. to_be_freed = NULL;
  5956. p = *pp;
  5957. *p = '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
  5958. var = arg;
  5959. exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
  5960. arg0 = arg[0];
  5961. arg[0] = (arg0 & 0x7f);
  5962. exp_op = 0;
  5963. if (arg[0] == '#' && arg[1] /* ${#...} but not ${#} */
  5964. && (!exp_saveptr /* and ( not(${#<op_char>...}) */
  5965. || (arg[2] == '\0' && strchr(SPECIAL_VARS_STR, arg[1])) /* or ${#C} "len of $C" ) */
  5966. ) /* NB: skipping ^^^specvar check mishandles ${#::2} */
  5967. ) {
  5968. /* It must be length operator: ${#var} */
  5969. var++;
  5970. exp_op = 'L';
  5971. } else {
  5972. /* Maybe handle parameter expansion */
  5973. if (exp_saveptr /* if 2nd char is one of expansion operators */
  5974. && strchr(NUMERIC_SPECVARS_STR, arg[0]) /* 1st char is special variable */
  5975. ) {
  5976. /* ${?:0}, ${#[:]%0} etc */
  5977. exp_saveptr = var + 1;
  5978. } else {
  5979. /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
  5980. exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
  5981. }
  5982. exp_op = exp_save = *exp_saveptr;
  5983. if (exp_op) {
  5984. exp_word = exp_saveptr + 1;
  5985. if (exp_op == ':') {
  5986. exp_op = *exp_word++;
  5987. //TODO: try ${var:} and ${var:bogus} in non-bash config
  5988. if (BASH_SUBSTR
  5989. && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
  5990. ) {
  5991. /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
  5992. exp_op = ':';
  5993. exp_word--;
  5994. }
  5995. }
  5996. *exp_saveptr = '\0';
  5997. } /* else: it's not an expansion op, but bare ${var} */
  5998. }
  5999. /* Look up the variable in question */
  6000. if (isdigit(var[0])) {
  6001. /* parse_dollar should have vetted var for us */
  6002. int nn = xatoi_positive(var);
  6003. if (nn < G.global_argc)
  6004. val = G.global_argv[nn];
  6005. /* else val remains NULL: $N with too big N */
  6006. } else {
  6007. switch (var[0]) {
  6008. case '$': /* pid */
  6009. val = utoa(G.root_pid);
  6010. break;
  6011. case '!': /* bg pid */
  6012. val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
  6013. break;
  6014. case '?': /* exitcode */
  6015. val = utoa(G.last_exitcode);
  6016. break;
  6017. case '#': /* argc */
  6018. val = utoa(G.global_argc ? G.global_argc-1 : 0);
  6019. break;
  6020. case '-': { /* active options */
  6021. /* Check set_mode() to see what option chars we support */
  6022. char *cp;
  6023. val = cp = G.optstring_buf;
  6024. if (G.o_opt[OPT_O_ERREXIT])
  6025. *cp++ = 'e';
  6026. if (G_interactive_fd)
  6027. *cp++ = 'i';
  6028. if (G_x_mode)
  6029. *cp++ = 'x';
  6030. /* If G.o_opt[OPT_O_NOEXEC] is true,
  6031. * commands read but are not executed,
  6032. * so $- can not execute too, 'n' is never seen in $-.
  6033. */
  6034. if (G.opt_c)
  6035. *cp++ = 'c';
  6036. if (G.opt_s)
  6037. *cp++ = 's';
  6038. *cp = '\0';
  6039. break;
  6040. }
  6041. default:
  6042. val = get_local_var_value(var);
  6043. }
  6044. }
  6045. /* Handle any expansions */
  6046. if (exp_op == 'L') {
  6047. reinit_unicode_for_hush();
  6048. debug_printf_expand("expand: length(%s)=", val);
  6049. val = utoa(val ? unicode_strlen(val) : 0);
  6050. debug_printf_expand("%s\n", val);
  6051. } else if (exp_op) {
  6052. if (exp_op == '%' || exp_op == '#') {
  6053. /* Standard-mandated substring removal ops:
  6054. * ${parameter%word} - remove smallest suffix pattern
  6055. * ${parameter%%word} - remove largest suffix pattern
  6056. * ${parameter#word} - remove smallest prefix pattern
  6057. * ${parameter##word} - remove largest prefix pattern
  6058. *
  6059. * Word is expanded to produce a glob pattern.
  6060. * Then var's value is matched to it and matching part removed.
  6061. */
  6062. //FIXME: ${x#...${...}...}
  6063. //should evaluate inner ${...} even if x is "" and no shrinking of it is possible -
  6064. //inner ${...} may have side effects!
  6065. if (val && val[0]) {
  6066. char *t;
  6067. char *exp_exp_word;
  6068. char *loc;
  6069. unsigned scan_flags = pick_scan(exp_op, *exp_word);
  6070. if (exp_op == *exp_word) /* ## or %% */
  6071. exp_word++;
  6072. debug_printf_expand("expand: exp_word:'%s'\n", exp_word);
  6073. exp_exp_word = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 0);
  6074. if (exp_exp_word)
  6075. exp_word = exp_exp_word;
  6076. debug_printf_expand("expand: exp_word:'%s'\n", exp_word);
  6077. /*
  6078. * HACK ALERT. We depend here on the fact that
  6079. * G.global_argv and results of utoa and get_local_var_value
  6080. * are actually in writable memory:
  6081. * scan_and_match momentarily stores NULs there.
  6082. */
  6083. t = (char*)val;
  6084. loc = scan_and_match(t, exp_word, scan_flags);
  6085. debug_printf_expand("op:%c str:'%s' pat:'%s' res:'%s'\n", exp_op, t, exp_word, loc);
  6086. free(exp_exp_word);
  6087. if (loc) { /* match was found */
  6088. if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
  6089. val = loc; /* take right part */
  6090. else /* %[%] */
  6091. val = to_be_freed = xstrndup(val, loc - val); /* left */
  6092. }
  6093. }
  6094. }
  6095. #if BASH_PATTERN_SUBST
  6096. else if (exp_op == '/' || exp_op == '\\') {
  6097. /* It's ${var/[/]pattern[/repl]} thing.
  6098. * Note that in encoded form it has TWO parts:
  6099. * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
  6100. * and if // is used, it is encoded as \:
  6101. * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
  6102. */
  6103. if (val && val[0]) {
  6104. /* pattern uses non-standard expansion.
  6105. * repl should be unbackslashed and globbed
  6106. * by the usual expansion rules:
  6107. * >az >bz
  6108. * v='a bz'; echo "${v/a*z/a*z}" #prints "a*z"
  6109. * v='a bz'; echo "${v/a*z/\z}" #prints "z"
  6110. * v='a bz'; echo ${v/a*z/a*z} #prints "az"
  6111. * v='a bz'; echo ${v/a*z/\z} #prints "z"
  6112. * (note that a*z _pattern_ is never globbed!)
  6113. */
  6114. char *pattern, *repl, *t;
  6115. pattern = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 0);
  6116. if (!pattern)
  6117. pattern = xstrdup(exp_word);
  6118. debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
  6119. *p++ = SPECIAL_VAR_SYMBOL;
  6120. exp_word = p;
  6121. p = strchr(p, SPECIAL_VAR_SYMBOL);
  6122. *p = '\0';
  6123. repl = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 1);
  6124. debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
  6125. /* HACK ALERT. We depend here on the fact that
  6126. * G.global_argv and results of utoa and get_local_var_value
  6127. * are actually in writable memory:
  6128. * replace_pattern momentarily stores NULs there. */
  6129. t = (char*)val;
  6130. to_be_freed = replace_pattern(t,
  6131. pattern,
  6132. (repl ? repl : exp_word),
  6133. exp_op);
  6134. if (to_be_freed) /* at least one replace happened */
  6135. val = to_be_freed;
  6136. free(pattern);
  6137. free(repl);
  6138. } else {
  6139. /* Empty variable always gives nothing */
  6140. // "v=''; echo ${v/*/w}" prints "", not "w"
  6141. /* Just skip "replace" part */
  6142. *p++ = SPECIAL_VAR_SYMBOL;
  6143. p = strchr(p, SPECIAL_VAR_SYMBOL);
  6144. *p = '\0';
  6145. }
  6146. }
  6147. #endif /* BASH_PATTERN_SUBST */
  6148. else if (exp_op == ':') {
  6149. #if BASH_SUBSTR && ENABLE_FEATURE_SH_MATH
  6150. /* It's ${var:N[:M]} bashism.
  6151. * Note that in encoded form it has TWO parts:
  6152. * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
  6153. */
  6154. arith_t beg, len;
  6155. const char *errmsg;
  6156. beg = expand_and_evaluate_arith(exp_word, &errmsg);
  6157. if (errmsg)
  6158. goto arith_err;
  6159. debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
  6160. *p++ = SPECIAL_VAR_SYMBOL;
  6161. exp_word = p;
  6162. p = strchr(p, SPECIAL_VAR_SYMBOL);
  6163. *p = '\0';
  6164. len = expand_and_evaluate_arith(exp_word, &errmsg);
  6165. if (errmsg)
  6166. goto arith_err;
  6167. debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
  6168. if (beg < 0) {
  6169. /* negative beg counts from the end */
  6170. beg = (arith_t)strlen(val) + beg;
  6171. if (beg < 0) /* ${v: -999999} is "" */
  6172. beg = len = 0;
  6173. }
  6174. debug_printf_varexp("from val:'%s'\n", val);
  6175. if (len < 0) {
  6176. /* in bash, len=-n means strlen()-n */
  6177. len = (arith_t)strlen(val) - beg + len;
  6178. if (len < 0) /* bash compat */
  6179. msg_and_die_if_script("%s: substring expression < 0", var);
  6180. }
  6181. if (len <= 0 || !val || beg >= strlen(val)) {
  6182. arith_err:
  6183. val = NULL;
  6184. } else {
  6185. /* Paranoia. What if user entered 9999999999999
  6186. * which fits in arith_t but not int? */
  6187. if (len >= INT_MAX)
  6188. len = INT_MAX;
  6189. val = to_be_freed = xstrndup(val + beg, len);
  6190. }
  6191. debug_printf_varexp("val:'%s'\n", val);
  6192. #else /* not (HUSH_SUBSTR_EXPANSION && FEATURE_SH_MATH) */
  6193. msg_and_die_if_script("malformed ${%s:...}", var);
  6194. val = NULL;
  6195. #endif
  6196. } else { /* one of "-=+?" */
  6197. /* Standard-mandated substitution ops:
  6198. * ${var?word} - indicate error if unset
  6199. * If var is unset, word (or a message indicating it is unset
  6200. * if word is null) is written to standard error
  6201. * and the shell exits with a non-zero exit status.
  6202. * Otherwise, the value of var is substituted.
  6203. * ${var-word} - use default value
  6204. * If var is unset, word is substituted.
  6205. * ${var=word} - assign and use default value
  6206. * If var is unset, word is assigned to var.
  6207. * In all cases, final value of var is substituted.
  6208. * ${var+word} - use alternative value
  6209. * If var is unset, null is substituted.
  6210. * Otherwise, word is substituted.
  6211. *
  6212. * Word is subjected to tilde expansion, parameter expansion,
  6213. * command substitution, and arithmetic expansion.
  6214. * If word is not needed, it is not expanded.
  6215. *
  6216. * Colon forms (${var:-word}, ${var:=word} etc) do the same,
  6217. * but also treat null var as if it is unset.
  6218. *
  6219. * Word-splitting and single quote behavior:
  6220. *
  6221. * $ f() { for i; do echo "|$i|"; done; };
  6222. *
  6223. * $ x=; f ${x:?'x y' z}
  6224. * bash: x: x y z #BUG: does not abort, ${} results in empty expansion
  6225. * $ x=; f "${x:?'x y' z}"
  6226. * bash: x: x y z # dash prints: dash: x: 'x y' z #BUG: does not abort, ${} results in ""
  6227. *
  6228. * $ x=; f ${x:='x y' z}
  6229. * |x|
  6230. * |y|
  6231. * |z|
  6232. * $ x=; f "${x:='x y' z}"
  6233. * |'x y' z|
  6234. *
  6235. * $ x=x; f ${x:+'x y' z}
  6236. * |x y|
  6237. * |z|
  6238. * $ x=x; f "${x:+'x y' z}"
  6239. * |'x y' z|
  6240. *
  6241. * $ x=; f ${x:-'x y' z}
  6242. * |x y|
  6243. * |z|
  6244. * $ x=; f "${x:-'x y' z}"
  6245. * |'x y' z|
  6246. */
  6247. int use_word = (!val || ((exp_save == ':') && !val[0]));
  6248. if (exp_op == '+')
  6249. use_word = !use_word;
  6250. debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
  6251. (exp_save == ':') ? "true" : "false", use_word);
  6252. if (use_word) {
  6253. if (exp_op == '+' || exp_op == '-') {
  6254. /* ${var+word} - use alternative value */
  6255. /* ${var-word} - use default value */
  6256. n = encode_then_append_var_plusminus(output, n, exp_word,
  6257. /*dquoted:*/ (arg0 & 0x80)
  6258. );
  6259. val = NULL;
  6260. } else {
  6261. /* ${var?word} - indicate error if unset */
  6262. /* ${var=word} - assign and use default value */
  6263. to_be_freed = encode_then_expand_vararg(exp_word,
  6264. /*handle_squotes:*/ !(arg0 & 0x80),
  6265. /*unbackslash:*/ 0
  6266. );
  6267. if (to_be_freed)
  6268. exp_word = to_be_freed;
  6269. if (exp_op == '?') {
  6270. /* mimic bash message */
  6271. msg_and_die_if_script("%s: %s",
  6272. var,
  6273. exp_word[0]
  6274. ? exp_word
  6275. : "parameter null or not set"
  6276. /* ash has more specific messages, a-la: */
  6277. /*: (exp_save == ':' ? "parameter null or not set" : "parameter not set")*/
  6278. );
  6279. //TODO: how interactive bash aborts expansion mid-command?
  6280. //It aborts the entire line, returns to prompt:
  6281. // $ f() { for i; do echo "|$i|"; done; }; x=; f "${x:?'x y' z}"; echo YO
  6282. // bash: x: x y z
  6283. // $
  6284. // ("echo YO" is not executed, neither the f function call)
  6285. } else {
  6286. val = exp_word;
  6287. }
  6288. if (exp_op == '=') {
  6289. /* ${var=[word]} or ${var:=[word]} */
  6290. if (isdigit(var[0]) || var[0] == '#') {
  6291. /* mimic bash message */
  6292. msg_and_die_if_script("$%s: cannot assign in this way", var);
  6293. val = NULL;
  6294. } else {
  6295. char *new_var = xasprintf("%s=%s", var, val);
  6296. set_local_var(new_var, /*flag:*/ 0);
  6297. }
  6298. }
  6299. }
  6300. }
  6301. } /* one of "-=+?" */
  6302. *exp_saveptr = exp_save;
  6303. } /* if (exp_op) */
  6304. arg[0] = arg0;
  6305. *pp = p;
  6306. n = append_str_maybe_ifs_split(output, n, first_ch, val);
  6307. free(to_be_freed);
  6308. return n;
  6309. }
  6310. /* Expand all variable references in given string, adding words to list[]
  6311. * at n, n+1,... positions. Return updated n (so that list[n] is next one
  6312. * to be filled). This routine is extremely tricky: has to deal with
  6313. * variables/parameters with whitespace, $* and $@, and constructs like
  6314. * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
  6315. static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
  6316. {
  6317. /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
  6318. * expansion of right-hand side of assignment == 1-element expand.
  6319. */
  6320. char cant_be_null = 0; /* only bit 0x80 matters */
  6321. char *p;
  6322. debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
  6323. !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
  6324. debug_print_list("expand_vars_to_list[0]", output, n);
  6325. while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
  6326. char first_ch;
  6327. #if ENABLE_FEATURE_SH_MATH
  6328. char arith_buf[sizeof(arith_t)*3 + 2];
  6329. #endif
  6330. if (output->ended_in_ifs) {
  6331. o_addchr(output, '\0');
  6332. n = o_save_ptr(output, n);
  6333. output->ended_in_ifs = 0;
  6334. }
  6335. o_addblock(output, arg, p - arg);
  6336. debug_print_list("expand_vars_to_list[1]", output, n);
  6337. arg = ++p;
  6338. p = strchr(p, SPECIAL_VAR_SYMBOL);
  6339. /* Fetch special var name (if it is indeed one of them)
  6340. * and quote bit, force the bit on if singleword expansion -
  6341. * important for not getting v=$@ expand to many words. */
  6342. first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
  6343. /* Is this variable quoted and thus expansion can't be null?
  6344. * "$@" is special. Even if quoted, it can still
  6345. * expand to nothing (not even an empty string),
  6346. * thus it is excluded. */
  6347. if ((first_ch & 0x7f) != '@')
  6348. cant_be_null |= first_ch;
  6349. switch (first_ch & 0x7f) {
  6350. /* Highest bit in first_ch indicates that var is double-quoted */
  6351. case '*':
  6352. case '@': {
  6353. int i;
  6354. if (!G.global_argv[1])
  6355. break;
  6356. i = 1;
  6357. cant_be_null |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
  6358. if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
  6359. while (G.global_argv[i]) {
  6360. n = expand_on_ifs(output, n, G.global_argv[i]);
  6361. debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
  6362. if (G.global_argv[i++][0] && G.global_argv[i]) {
  6363. /* this argv[] is not empty and not last:
  6364. * put terminating NUL, start new word */
  6365. o_addchr(output, '\0');
  6366. debug_print_list("expand_vars_to_list[2]", output, n);
  6367. n = o_save_ptr(output, n);
  6368. debug_print_list("expand_vars_to_list[3]", output, n);
  6369. }
  6370. }
  6371. } else
  6372. /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
  6373. * and in this case should treat it like '$*' - see 'else...' below */
  6374. if (first_ch == (char)('@'|0x80) /* quoted $@ */
  6375. && !(output->o_expflags & EXP_FLAG_SINGLEWORD) /* not v="$@" case */
  6376. ) {
  6377. while (1) {
  6378. o_addQstr(output, G.global_argv[i]);
  6379. if (++i >= G.global_argc)
  6380. break;
  6381. o_addchr(output, '\0');
  6382. debug_print_list("expand_vars_to_list[4]", output, n);
  6383. n = o_save_ptr(output, n);
  6384. }
  6385. } else { /* quoted $* (or v="$@" case): add as one word */
  6386. while (1) {
  6387. o_addQstr(output, G.global_argv[i]);
  6388. if (!G.global_argv[++i])
  6389. break;
  6390. if (G.ifs[0])
  6391. o_addchr(output, G.ifs[0]);
  6392. }
  6393. output->has_quoted_part = 1;
  6394. }
  6395. break;
  6396. }
  6397. case SPECIAL_VAR_SYMBOL: {
  6398. /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
  6399. /* "Empty variable", used to make "" etc to not disappear */
  6400. output->has_quoted_part = 1;
  6401. cant_be_null = 0x80;
  6402. arg++;
  6403. break;
  6404. }
  6405. case SPECIAL_VAR_QUOTED_SVS:
  6406. /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_QUOTED_SVS><SPECIAL_VAR_SYMBOL> */
  6407. /* "^C variable", represents literal ^C char (possible in scripts) */
  6408. o_addchr(output, SPECIAL_VAR_SYMBOL);
  6409. arg++;
  6410. break;
  6411. #if ENABLE_HUSH_TICK
  6412. case '`': {
  6413. /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
  6414. o_string subst_result = NULL_O_STRING;
  6415. *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
  6416. arg++;
  6417. /* Can't just stuff it into output o_string,
  6418. * expanded result may need to be globbed
  6419. * and $IFS-split */
  6420. debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
  6421. G.last_exitcode = process_command_subs(&subst_result, arg);
  6422. G.expand_exitcode = G.last_exitcode;
  6423. debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
  6424. n = append_str_maybe_ifs_split(output, n, first_ch, subst_result.data);
  6425. o_free(&subst_result);
  6426. break;
  6427. }
  6428. #endif
  6429. #if ENABLE_FEATURE_SH_MATH
  6430. case '+': {
  6431. /* <SPECIAL_VAR_SYMBOL>+arith<SPECIAL_VAR_SYMBOL> */
  6432. arith_t res;
  6433. arg++; /* skip '+' */
  6434. *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
  6435. debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
  6436. res = expand_and_evaluate_arith(arg, NULL);
  6437. debug_printf_subst("ARITH RES '"ARITH_FMT"'\n", res);
  6438. sprintf(arith_buf, ARITH_FMT, res);
  6439. if (res < 0
  6440. && first_ch == (char)('+'|0x80)
  6441. /* && (output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS) */
  6442. ) {
  6443. /* Quoted negative ariths, like filename[0"$((-9))"],
  6444. * should not be interpreted as glob ranges.
  6445. * Convert leading '-' to '\-':
  6446. */
  6447. o_grow_by(output, 1);
  6448. output->data[output->length++] = '\\';
  6449. }
  6450. o_addstr(output, arith_buf);
  6451. break;
  6452. }
  6453. #endif
  6454. default:
  6455. /* <SPECIAL_VAR_SYMBOL>varname[ops]<SPECIAL_VAR_SYMBOL> */
  6456. n = expand_one_var(output, n, first_ch, arg, &p);
  6457. break;
  6458. } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
  6459. /* Restore NULL'ed SPECIAL_VAR_SYMBOL.
  6460. * Do the check to avoid writing to a const string. */
  6461. if (*p != SPECIAL_VAR_SYMBOL)
  6462. *p = SPECIAL_VAR_SYMBOL;
  6463. arg = ++p;
  6464. } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
  6465. if (*arg) {
  6466. /* handle trailing string */
  6467. if (output->ended_in_ifs) {
  6468. o_addchr(output, '\0');
  6469. n = o_save_ptr(output, n);
  6470. }
  6471. debug_print_list("expand_vars_to_list[a]", output, n);
  6472. /* this part is literal, and it was already pre-quoted
  6473. * if needed (much earlier), do not use o_addQstr here!
  6474. */
  6475. o_addstr(output, arg);
  6476. debug_print_list("expand_vars_to_list[b]", output, n);
  6477. } else
  6478. if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
  6479. && !(cant_be_null & 0x80) /* and all vars were not quoted */
  6480. && !output->has_quoted_part
  6481. ) {
  6482. n--;
  6483. /* allow to reuse list[n] later without re-growth */
  6484. output->has_empty_slot = 1;
  6485. }
  6486. return n;
  6487. }
  6488. static char **expand_variables(char **argv, unsigned expflags)
  6489. {
  6490. int n;
  6491. char **list;
  6492. o_string output = NULL_O_STRING;
  6493. output.o_expflags = expflags;
  6494. n = 0;
  6495. for (;;) {
  6496. /* go to next list[n] */
  6497. output.ended_in_ifs = 0;
  6498. n = o_save_ptr(&output, n);
  6499. if (!*argv)
  6500. break;
  6501. /* expand argv[i] */
  6502. n = expand_vars_to_list(&output, n, *argv++);
  6503. /* if (!output->has_empty_slot) -- need this?? */
  6504. o_addchr(&output, '\0');
  6505. }
  6506. debug_print_list("expand_variables", &output, n);
  6507. /* output.data (malloced in one block) gets returned in "list" */
  6508. list = o_finalize_list(&output, n);
  6509. debug_print_strings("expand_variables[1]", list);
  6510. return list;
  6511. }
  6512. static char **expand_strvec_to_strvec(char **argv)
  6513. {
  6514. return expand_variables(argv, EXP_FLAG_GLOB | EXP_FLAG_ESC_GLOB_CHARS);
  6515. }
  6516. #if defined(CMD_SINGLEWORD_NOGLOB)
  6517. static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
  6518. {
  6519. return expand_variables(argv, EXP_FLAG_SINGLEWORD);
  6520. }
  6521. #endif
  6522. /* Used for expansion of right hand of assignments,
  6523. * $((...)), heredocs, variable expansion parts.
  6524. *
  6525. * NB: should NOT do globbing!
  6526. * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*"
  6527. */
  6528. static char *expand_string_to_string(const char *str, int EXP_flags, int do_unbackslash)
  6529. {
  6530. #if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
  6531. const int do_unbackslash = 1;
  6532. const int EXP_flags = EXP_FLAG_ESC_GLOB_CHARS;
  6533. #endif
  6534. char *argv[2], **list;
  6535. debug_printf_expand("string_to_string<='%s'\n", str);
  6536. /* This is generally an optimization, but it also
  6537. * handles "", which otherwise trips over !list[0] check below.
  6538. * (is this ever happens that we actually get str="" here?)
  6539. */
  6540. if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
  6541. //TODO: Can use on strings with \ too, just unbackslash() them?
  6542. debug_printf_expand("string_to_string(fast)=>'%s'\n", str);
  6543. return xstrdup(str);
  6544. }
  6545. argv[0] = (char*)str;
  6546. argv[1] = NULL;
  6547. list = expand_variables(argv, EXP_flags | EXP_FLAG_SINGLEWORD);
  6548. if (!list[0]) {
  6549. /* Example where it happens:
  6550. * x=; echo ${x:-"$@"}
  6551. */
  6552. ((char*)list)[0] = '\0';
  6553. } else {
  6554. if (HUSH_DEBUG)
  6555. if (list[1])
  6556. bb_simple_error_msg_and_die("BUG in varexp2");
  6557. /* actually, just move string 2*sizeof(char*) bytes back */
  6558. overlapping_strcpy((char*)list, list[0]);
  6559. if (do_unbackslash)
  6560. unbackslash((char*)list);
  6561. }
  6562. debug_printf_expand("string_to_string=>'%s'\n", (char*)list);
  6563. return (char*)list;
  6564. }
  6565. #if 0
  6566. static char* expand_strvec_to_string(char **argv)
  6567. {
  6568. char **list;
  6569. list = expand_variables(argv, EXP_FLAG_SINGLEWORD);
  6570. /* Convert all NULs to spaces */
  6571. if (list[0]) {
  6572. int n = 1;
  6573. while (list[n]) {
  6574. if (HUSH_DEBUG)
  6575. if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
  6576. bb_error_msg_and_die("BUG in varexp3");
  6577. /* bash uses ' ' regardless of $IFS contents */
  6578. list[n][-1] = ' ';
  6579. n++;
  6580. }
  6581. }
  6582. overlapping_strcpy((char*)list, list[0] ? list[0] : "");
  6583. debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
  6584. return (char*)list;
  6585. }
  6586. #endif
  6587. static char **expand_assignments(char **argv, int count)
  6588. {
  6589. int i;
  6590. char **p;
  6591. G.expanded_assignments = p = NULL;
  6592. /* Expand assignments into one string each */
  6593. for (i = 0; i < count; i++) {
  6594. p = add_string_to_strings(p,
  6595. expand_string_to_string(argv[i],
  6596. EXP_FLAG_ESC_GLOB_CHARS,
  6597. /*unbackslash:*/ 1
  6598. )
  6599. );
  6600. G.expanded_assignments = p;
  6601. }
  6602. G.expanded_assignments = NULL;
  6603. return p;
  6604. }
  6605. static void switch_off_special_sigs(unsigned mask)
  6606. {
  6607. unsigned sig = 0;
  6608. while ((mask >>= 1) != 0) {
  6609. sig++;
  6610. if (!(mask & 1))
  6611. continue;
  6612. #if ENABLE_HUSH_TRAP
  6613. if (G_traps) {
  6614. if (G_traps[sig] && !G_traps[sig][0])
  6615. /* trap is '', has to remain SIG_IGN */
  6616. continue;
  6617. free(G_traps[sig]);
  6618. G_traps[sig] = NULL;
  6619. }
  6620. #endif
  6621. /* We are here only if no trap or trap was not '' */
  6622. install_sighandler(sig, SIG_DFL);
  6623. }
  6624. }
  6625. #if BB_MMU
  6626. /* never called */
  6627. void re_execute_shell(char ***to_free, const char *s,
  6628. char *g_argv0, char **g_argv,
  6629. char **builtin_argv) NORETURN;
  6630. static void reset_traps_to_defaults(void)
  6631. {
  6632. /* This function is always called in a child shell
  6633. * after fork (not vfork, NOMMU doesn't use this function).
  6634. */
  6635. IF_HUSH_TRAP(unsigned sig;)
  6636. unsigned mask;
  6637. /* Child shells are not interactive.
  6638. * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
  6639. * Testcase: (while :; do :; done) + ^Z should background.
  6640. * Same goes for SIGTERM, SIGHUP, SIGINT.
  6641. */
  6642. mask = (G.special_sig_mask & SPECIAL_INTERACTIVE_SIGS) | G_fatal_sig_mask;
  6643. if (!G_traps && !mask)
  6644. return; /* already no traps and no special sigs */
  6645. /* Switch off special sigs */
  6646. switch_off_special_sigs(mask);
  6647. # if ENABLE_HUSH_JOB
  6648. G_fatal_sig_mask = 0;
  6649. # endif
  6650. G.special_sig_mask &= ~SPECIAL_INTERACTIVE_SIGS;
  6651. /* SIGQUIT,SIGCHLD and maybe SPECIAL_JOBSTOP_SIGS
  6652. * remain set in G.special_sig_mask */
  6653. # if ENABLE_HUSH_TRAP
  6654. if (!G_traps)
  6655. return;
  6656. /* Reset all sigs to default except ones with empty traps */
  6657. for (sig = 0; sig < NSIG; sig++) {
  6658. if (!G_traps[sig])
  6659. continue; /* no trap: nothing to do */
  6660. if (!G_traps[sig][0])
  6661. continue; /* empty trap: has to remain SIG_IGN */
  6662. /* sig has non-empty trap, reset it: */
  6663. free(G_traps[sig]);
  6664. G_traps[sig] = NULL;
  6665. /* There is no signal for trap 0 (EXIT) */
  6666. if (sig == 0)
  6667. continue;
  6668. install_sighandler(sig, pick_sighandler(sig));
  6669. }
  6670. # endif
  6671. }
  6672. #else /* !BB_MMU */
  6673. static void re_execute_shell(char ***to_free, const char *s,
  6674. char *g_argv0, char **g_argv,
  6675. char **builtin_argv) NORETURN;
  6676. static void re_execute_shell(char ***to_free, const char *s,
  6677. char *g_argv0, char **g_argv,
  6678. char **builtin_argv)
  6679. {
  6680. # define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
  6681. /* delims + 2 * (number of bytes in printed hex numbers) */
  6682. char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
  6683. char *heredoc_argv[4];
  6684. struct variable *cur;
  6685. # if ENABLE_HUSH_FUNCTIONS
  6686. struct function *funcp;
  6687. # endif
  6688. char **argv, **pp;
  6689. unsigned cnt;
  6690. unsigned long long empty_trap_mask;
  6691. if (!g_argv0) { /* heredoc */
  6692. argv = heredoc_argv;
  6693. argv[0] = (char *) G.argv0_for_re_execing;
  6694. argv[1] = (char *) "-<";
  6695. argv[2] = (char *) s;
  6696. argv[3] = NULL;
  6697. pp = &argv[3]; /* used as pointer to empty environment */
  6698. goto do_exec;
  6699. }
  6700. cnt = 0;
  6701. pp = builtin_argv;
  6702. if (pp) while (*pp++)
  6703. cnt++;
  6704. empty_trap_mask = 0;
  6705. if (G_traps) {
  6706. int sig;
  6707. for (sig = 1; sig < NSIG; sig++) {
  6708. if (G_traps[sig] && !G_traps[sig][0])
  6709. empty_trap_mask |= 1LL << sig;
  6710. }
  6711. }
  6712. sprintf(param_buf, NOMMU_HACK_FMT
  6713. , (unsigned) G.root_pid
  6714. , (unsigned) G.root_ppid
  6715. , (unsigned) G.last_bg_pid
  6716. , (unsigned) G.last_exitcode
  6717. , cnt
  6718. , empty_trap_mask
  6719. IF_HUSH_LOOPS(, G.depth_of_loop)
  6720. );
  6721. # undef NOMMU_HACK_FMT
  6722. /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
  6723. * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
  6724. */
  6725. cnt += 6;
  6726. for (cur = G.top_var; cur; cur = cur->next) {
  6727. if (!cur->flg_export || cur->flg_read_only)
  6728. cnt += 2;
  6729. }
  6730. # if ENABLE_HUSH_FUNCTIONS
  6731. for (funcp = G.top_func; funcp; funcp = funcp->next)
  6732. cnt += 3;
  6733. # endif
  6734. pp = g_argv;
  6735. while (*pp++)
  6736. cnt++;
  6737. *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
  6738. *pp++ = (char *) G.argv0_for_re_execing;
  6739. *pp++ = param_buf;
  6740. for (cur = G.top_var; cur; cur = cur->next) {
  6741. if (strcmp(cur->varstr, hush_version_str) == 0)
  6742. continue;
  6743. if (cur->flg_read_only) {
  6744. *pp++ = (char *) "-R";
  6745. *pp++ = cur->varstr;
  6746. } else if (!cur->flg_export) {
  6747. *pp++ = (char *) "-V";
  6748. *pp++ = cur->varstr;
  6749. }
  6750. }
  6751. # if ENABLE_HUSH_FUNCTIONS
  6752. for (funcp = G.top_func; funcp; funcp = funcp->next) {
  6753. *pp++ = (char *) "-F";
  6754. *pp++ = funcp->name;
  6755. *pp++ = funcp->body_as_string;
  6756. }
  6757. # endif
  6758. /* We can pass activated traps here. Say, -Tnn:trap_string
  6759. *
  6760. * However, POSIX says that subshells reset signals with traps
  6761. * to SIG_DFL.
  6762. * I tested bash-3.2 and it not only does that with true subshells
  6763. * of the form ( list ), but with any forked children shells.
  6764. * I set trap "echo W" WINCH; and then tried:
  6765. *
  6766. * { echo 1; sleep 20; echo 2; } &
  6767. * while true; do echo 1; sleep 20; echo 2; break; done &
  6768. * true | { echo 1; sleep 20; echo 2; } | cat
  6769. *
  6770. * In all these cases sending SIGWINCH to the child shell
  6771. * did not run the trap. If I add trap "echo V" WINCH;
  6772. * _inside_ group (just before echo 1), it works.
  6773. *
  6774. * I conclude it means we don't need to pass active traps here.
  6775. */
  6776. *pp++ = (char *) "-c";
  6777. *pp++ = (char *) s;
  6778. if (builtin_argv) {
  6779. while (*++builtin_argv)
  6780. *pp++ = *builtin_argv;
  6781. *pp++ = (char *) "";
  6782. }
  6783. *pp++ = g_argv0;
  6784. while (*g_argv)
  6785. *pp++ = *g_argv++;
  6786. /* *pp = NULL; - is already there */
  6787. pp = environ;
  6788. do_exec:
  6789. debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
  6790. /* Don't propagate SIG_IGN to the child */
  6791. if (SPECIAL_JOBSTOP_SIGS != 0)
  6792. switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
  6793. execve(bb_busybox_exec_path, argv, pp);
  6794. /* Fallback. Useful for init=/bin/hush usage etc */
  6795. if (argv[0][0] == '/')
  6796. execve(argv[0], argv, pp);
  6797. xfunc_error_retval = 127;
  6798. bb_simple_error_msg_and_die("can't re-execute the shell");
  6799. }
  6800. #endif /* !BB_MMU */
  6801. static int run_and_free_list(struct pipe *pi);
  6802. /* Executing from string: eval, sh -c '...'
  6803. * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
  6804. * end_trigger controls how often we stop parsing
  6805. * NUL: parse all, execute, return
  6806. * ';': parse till ';' or newline, execute, repeat till EOF
  6807. */
  6808. static void parse_and_run_stream(struct in_str *inp, int end_trigger)
  6809. {
  6810. /* Why we need empty flag?
  6811. * An obscure corner case "false; ``; echo $?":
  6812. * empty command in `` should still set $? to 0.
  6813. * But we can't just set $? to 0 at the start,
  6814. * this breaks "false; echo `echo $?`" case.
  6815. */
  6816. bool empty = 1;
  6817. while (1) {
  6818. struct pipe *pipe_list;
  6819. #if ENABLE_HUSH_INTERACTIVE
  6820. if (end_trigger == ';') {
  6821. G.promptmode = 0; /* PS1 */
  6822. debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
  6823. }
  6824. #endif
  6825. pipe_list = parse_stream(NULL, NULL, inp, end_trigger);
  6826. if (!pipe_list || pipe_list == ERR_PTR) { /* EOF/error */
  6827. /* If we are in "big" script
  6828. * (not in `cmd` or something similar)...
  6829. */
  6830. if (pipe_list == ERR_PTR && end_trigger == ';') {
  6831. /* Discard cached input (rest of line) */
  6832. int ch = inp->last_char;
  6833. while (ch != EOF && ch != '\n') {
  6834. //bb_error_msg("Discarded:'%c'", ch);
  6835. ch = i_getch(inp);
  6836. }
  6837. /* Force prompt */
  6838. inp->p = NULL;
  6839. /* This stream isn't empty */
  6840. empty = 0;
  6841. continue;
  6842. }
  6843. if (!pipe_list && empty)
  6844. G.last_exitcode = 0;
  6845. break;
  6846. }
  6847. debug_print_tree(pipe_list, 0);
  6848. debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
  6849. run_and_free_list(pipe_list);
  6850. empty = 0;
  6851. if (G_flag_return_in_progress == 1)
  6852. break;
  6853. }
  6854. }
  6855. static void parse_and_run_string(const char *s)
  6856. {
  6857. struct in_str input;
  6858. //IF_HUSH_LINENO_VAR(unsigned sv = G.parse_lineno;)
  6859. setup_string_in_str(&input, s);
  6860. parse_and_run_stream(&input, '\0');
  6861. //IF_HUSH_LINENO_VAR(G.parse_lineno = sv;)
  6862. }
  6863. static void parse_and_run_file(HFILE *fp)
  6864. {
  6865. struct in_str input;
  6866. IF_HUSH_LINENO_VAR(unsigned sv = G.parse_lineno;)
  6867. IF_HUSH_LINENO_VAR(G.parse_lineno = 1;)
  6868. setup_file_in_str(&input, fp);
  6869. parse_and_run_stream(&input, ';');
  6870. IF_HUSH_LINENO_VAR(G.parse_lineno = sv;)
  6871. }
  6872. #if ENABLE_HUSH_TICK
  6873. static int generate_stream_from_string(const char *s, pid_t *pid_p)
  6874. {
  6875. pid_t pid;
  6876. int channel[2];
  6877. # if !BB_MMU
  6878. char **to_free = NULL;
  6879. # endif
  6880. xpipe(channel);
  6881. pid = BB_MMU ? xfork() : xvfork();
  6882. if (pid == 0) { /* child */
  6883. disable_restore_tty_pgrp_on_exit();
  6884. /* Process substitution is not considered to be usual
  6885. * 'command execution'.
  6886. * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
  6887. */
  6888. bb_signals(0
  6889. + (1 << SIGTSTP)
  6890. + (1 << SIGTTIN)
  6891. + (1 << SIGTTOU)
  6892. , SIG_IGN);
  6893. close(channel[0]); /* NB: close _first_, then move fd! */
  6894. xmove_fd(channel[1], 1);
  6895. # if ENABLE_HUSH_TRAP
  6896. /* Awful hack for `trap` or $(trap).
  6897. *
  6898. * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
  6899. * contains an example where "trap" is executed in a subshell:
  6900. *
  6901. * save_traps=$(trap)
  6902. * ...
  6903. * eval "$save_traps"
  6904. *
  6905. * Standard does not say that "trap" in subshell shall print
  6906. * parent shell's traps. It only says that its output
  6907. * must have suitable form, but then, in the above example
  6908. * (which is not supposed to be normative), it implies that.
  6909. *
  6910. * bash (and probably other shell) does implement it
  6911. * (traps are reset to defaults, but "trap" still shows them),
  6912. * but as a result, "trap" logic is hopelessly messed up:
  6913. *
  6914. * # trap
  6915. * trap -- 'echo Ho' SIGWINCH <--- we have a handler
  6916. * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
  6917. * # true | trap <--- trap is in subshell - no output (ditto)
  6918. * # echo `true | trap` <--- in subshell - output (but traps are reset!)
  6919. * trap -- 'echo Ho' SIGWINCH
  6920. * # echo `(trap)` <--- in subshell in subshell - output
  6921. * trap -- 'echo Ho' SIGWINCH
  6922. * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
  6923. * trap -- 'echo Ho' SIGWINCH
  6924. *
  6925. * The rules when to forget and when to not forget traps
  6926. * get really complex and nonsensical.
  6927. *
  6928. * Our solution: ONLY bare $(trap) or `trap` is special.
  6929. */
  6930. s = skip_whitespace(s);
  6931. if (is_prefixed_with(s, "trap")
  6932. && skip_whitespace(s + 4)[0] == '\0'
  6933. ) {
  6934. static const char *const argv[] = { NULL, NULL };
  6935. builtin_trap((char**)argv);
  6936. fflush_all(); /* important */
  6937. _exit(0);
  6938. }
  6939. # endif
  6940. # if BB_MMU
  6941. /* Prevent it from trying to handle ctrl-z etc */
  6942. IF_HUSH_JOB(G.run_list_level = 1;)
  6943. CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
  6944. reset_traps_to_defaults();
  6945. IF_HUSH_MODE_X(G.x_mode_depth++;)
  6946. //bb_error_msg("%s: ++x_mode_depth=%d", __func__, G.x_mode_depth);
  6947. parse_and_run_string(s);
  6948. _exit(G.last_exitcode);
  6949. # else
  6950. /* We re-execute after vfork on NOMMU. This makes this script safe:
  6951. * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
  6952. * huge=`cat BIG` # was blocking here forever
  6953. * echo OK
  6954. */
  6955. re_execute_shell(&to_free,
  6956. s,
  6957. G.global_argv[0],
  6958. G.global_argv + 1,
  6959. NULL);
  6960. # endif
  6961. }
  6962. /* parent */
  6963. *pid_p = pid;
  6964. # if ENABLE_HUSH_FAST
  6965. G.count_SIGCHLD++;
  6966. //bb_error_msg("[%d] fork in generate_stream_from_string:"
  6967. // " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
  6968. // getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
  6969. # endif
  6970. enable_restore_tty_pgrp_on_exit();
  6971. # if !BB_MMU
  6972. free(to_free);
  6973. # endif
  6974. close(channel[1]);
  6975. return channel[0];
  6976. }
  6977. /* Return code is exit status of the process that is run. */
  6978. static int process_command_subs(o_string *dest, const char *s)
  6979. {
  6980. FILE *fp;
  6981. pid_t pid;
  6982. int status, ch, eol_cnt;
  6983. fp = xfdopen_for_read(generate_stream_from_string(s, &pid));
  6984. /* Now send results of command back into original context */
  6985. eol_cnt = 0;
  6986. while ((ch = getc(fp)) != EOF) {
  6987. if (ch == '\0')
  6988. continue;
  6989. if (ch == '\n') {
  6990. eol_cnt++;
  6991. continue;
  6992. }
  6993. while (eol_cnt) {
  6994. o_addchr(dest, '\n');
  6995. eol_cnt--;
  6996. }
  6997. o_addQchr(dest, ch);
  6998. }
  6999. debug_printf("done reading from `cmd` pipe, closing it\n");
  7000. fclose(fp);
  7001. /* We need to extract exitcode. Test case
  7002. * "true; echo `sleep 1; false` $?"
  7003. * should print 1 */
  7004. safe_waitpid(pid, &status, 0);
  7005. debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
  7006. return WEXITSTATUS(status);
  7007. }
  7008. #endif /* ENABLE_HUSH_TICK */
  7009. static void setup_heredoc(struct redir_struct *redir)
  7010. {
  7011. struct fd_pair pair;
  7012. pid_t pid;
  7013. int len, written;
  7014. /* the _body_ of heredoc (misleading field name) */
  7015. const char *heredoc = redir->rd_filename;
  7016. char *expanded;
  7017. #if !BB_MMU
  7018. char **to_free;
  7019. #endif
  7020. expanded = NULL;
  7021. if (!(redir->rd_dup & HEREDOC_QUOTED)) {
  7022. expanded = encode_then_expand_string(heredoc);
  7023. if (expanded)
  7024. heredoc = expanded;
  7025. }
  7026. len = strlen(heredoc);
  7027. close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
  7028. xpiped_pair(pair);
  7029. xmove_fd(pair.rd, redir->rd_fd);
  7030. /* Try writing without forking. Newer kernels have
  7031. * dynamically growing pipes. Must use non-blocking write! */
  7032. ndelay_on(pair.wr);
  7033. while (1) {
  7034. written = write(pair.wr, heredoc, len);
  7035. if (written <= 0)
  7036. break;
  7037. len -= written;
  7038. if (len == 0) {
  7039. close(pair.wr);
  7040. free(expanded);
  7041. return;
  7042. }
  7043. heredoc += written;
  7044. }
  7045. ndelay_off(pair.wr);
  7046. /* Okay, pipe buffer was not big enough */
  7047. /* Note: we must not create a stray child (bastard? :)
  7048. * for the unsuspecting parent process. Child creates a grandchild
  7049. * and exits before parent execs the process which consumes heredoc
  7050. * (that exec happens after we return from this function) */
  7051. #if !BB_MMU
  7052. to_free = NULL;
  7053. #endif
  7054. pid = xvfork();
  7055. if (pid == 0) {
  7056. /* child */
  7057. disable_restore_tty_pgrp_on_exit();
  7058. pid = BB_MMU ? xfork() : xvfork();
  7059. if (pid != 0)
  7060. _exit(0);
  7061. /* grandchild */
  7062. close(redir->rd_fd); /* read side of the pipe */
  7063. #if BB_MMU
  7064. full_write(pair.wr, heredoc, len); /* may loop or block */
  7065. _exit(0);
  7066. #else
  7067. /* Delegate blocking writes to another process */
  7068. xmove_fd(pair.wr, STDOUT_FILENO);
  7069. re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
  7070. #endif
  7071. }
  7072. /* parent */
  7073. #if ENABLE_HUSH_FAST
  7074. G.count_SIGCHLD++;
  7075. //bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
  7076. #endif
  7077. enable_restore_tty_pgrp_on_exit();
  7078. #if !BB_MMU
  7079. free(to_free);
  7080. #endif
  7081. close(pair.wr);
  7082. free(expanded);
  7083. wait(NULL); /* wait till child has died */
  7084. }
  7085. struct squirrel {
  7086. int orig_fd;
  7087. int moved_to;
  7088. /* moved_to = n: fd was moved to n; restore back to orig_fd after redir */
  7089. /* moved_to = -1: fd was opened by redirect; close orig_fd after redir */
  7090. };
  7091. static struct squirrel *append_squirrel(struct squirrel *sq, int i, int orig, int moved)
  7092. {
  7093. sq = xrealloc(sq, (i + 2) * sizeof(sq[0]));
  7094. sq[i].orig_fd = orig;
  7095. sq[i].moved_to = moved;
  7096. sq[i+1].orig_fd = -1; /* end marker */
  7097. return sq;
  7098. }
  7099. static struct squirrel *add_squirrel(struct squirrel *sq, int fd, int avoid_fd)
  7100. {
  7101. int moved_to;
  7102. int i;
  7103. i = 0;
  7104. if (sq) for (; sq[i].orig_fd >= 0; i++) {
  7105. /* If we collide with an already moved fd... */
  7106. if (fd == sq[i].moved_to) {
  7107. sq[i].moved_to = dup_CLOEXEC(sq[i].moved_to, avoid_fd);
  7108. debug_printf_redir("redirect_fd %d: already busy, moving to %d\n", fd, sq[i].moved_to);
  7109. if (sq[i].moved_to < 0) /* what? */
  7110. xfunc_die();
  7111. return sq;
  7112. }
  7113. if (fd == sq[i].orig_fd) {
  7114. /* Example: echo Hello >/dev/null 1>&2 */
  7115. debug_printf_redir("redirect_fd %d: already moved\n", fd);
  7116. return sq;
  7117. }
  7118. }
  7119. /* If this fd is open, we move and remember it; if it's closed, moved_to = -1 */
  7120. moved_to = dup_CLOEXEC(fd, avoid_fd);
  7121. debug_printf_redir("redirect_fd %d: previous fd is moved to %d (-1 if it was closed)\n", fd, moved_to);
  7122. if (moved_to < 0 && errno != EBADF)
  7123. xfunc_die();
  7124. return append_squirrel(sq, i, fd, moved_to);
  7125. }
  7126. static struct squirrel *add_squirrel_closed(struct squirrel *sq, int fd)
  7127. {
  7128. int i;
  7129. i = 0;
  7130. if (sq) for (; sq[i].orig_fd >= 0; i++) {
  7131. /* If we collide with an already moved fd... */
  7132. if (fd == sq[i].orig_fd) {
  7133. /* Examples:
  7134. * "echo 3>FILE 3>&- 3>FILE"
  7135. * "echo 3>&- 3>FILE"
  7136. * No need for last redirect to insert
  7137. * another "need to close 3" indicator.
  7138. */
  7139. debug_printf_redir("redirect_fd %d: already moved or closed\n", fd);
  7140. return sq;
  7141. }
  7142. }
  7143. debug_printf_redir("redirect_fd %d: previous fd was closed\n", fd);
  7144. return append_squirrel(sq, i, fd, -1);
  7145. }
  7146. /* fd: redirect wants this fd to be used (e.g. 3>file).
  7147. * Move all conflicting internally used fds,
  7148. * and remember them so that we can restore them later.
  7149. */
  7150. static int save_fd_on_redirect(int fd, int avoid_fd, struct squirrel **sqp)
  7151. {
  7152. if (avoid_fd < 9) /* the important case here is that it can be -1 */
  7153. avoid_fd = 9;
  7154. #if ENABLE_HUSH_INTERACTIVE
  7155. if (fd != 0 /* don't trigger for G_interactive_fd == 0 (that's "not interactive" flag) */
  7156. && fd == G_interactive_fd
  7157. ) {
  7158. /* Testcase: "ls -l /proc/$$/fd 255>&-" should work */
  7159. G_interactive_fd = xdup_CLOEXEC_and_close(G_interactive_fd, avoid_fd);
  7160. debug_printf_redir("redirect_fd %d: matches interactive_fd, moving it to %d\n", fd, G_interactive_fd);
  7161. return 1; /* "we closed fd" */
  7162. }
  7163. #endif
  7164. /* Are we called from setup_redirects(squirrel==NULL)
  7165. * in redirect in a [v]forked child?
  7166. */
  7167. if (sqp == NULL) {
  7168. /* No need to move script fds.
  7169. * For NOMMU case, it's actively wrong: we'd change ->fd
  7170. * fields in memory for the parent, but parent's fds
  7171. * aren't moved, it would use wrong fd!
  7172. * Reproducer: "cmd 3>FILE" in script.
  7173. * If we would call move_HFILEs_on_redirect(), child would:
  7174. * fcntl64(3, F_DUPFD_CLOEXEC, 10) = 10
  7175. * close(3) = 0
  7176. * and change ->fd to 10 if fd#3 is a script fd. WRONG.
  7177. */
  7178. //bb_error_msg("sqp == NULL: [v]forked child");
  7179. return 0;
  7180. }
  7181. /* If this one of script's fds? */
  7182. if (move_HFILEs_on_redirect(fd, avoid_fd))
  7183. return 1; /* yes. "we closed fd" (actually moved it) */
  7184. /* Are we called for "exec 3>FILE"? Came through
  7185. * redirect_and_varexp_helper(squirrel=ERR_PTR) -> setup_redirects(ERR_PTR)
  7186. * This case used to fail for this script:
  7187. * exec 3>FILE
  7188. * echo Ok
  7189. * ...100000 more lines...
  7190. * echo Ok
  7191. * as follows:
  7192. * read(3, "exec 3>FILE\necho Ok\necho Ok"..., 1024) = 1024
  7193. * open("FILE", O_WRONLY|O_CREAT|O_TRUNC|O_LARGEFILE, 0666) = 4
  7194. * dup2(4, 3) = 3
  7195. * ^^^^^^^^ oops, we lost fd#3 opened to our script!
  7196. * close(4) = 0
  7197. * write(1, "Ok\n", 3) = 3
  7198. * ... = 3
  7199. * write(1, "Ok\n", 3) = 3
  7200. * read(3, 0x94fbc08, 1024) = -1 EBADF (Bad file descriptor)
  7201. * ^^^^^^^^ oops, wrong fd!!!
  7202. * With this case separate from sqp == NULL and *after* move_HFILEs,
  7203. * it now works:
  7204. */
  7205. if (sqp == ERR_PTR) {
  7206. /* Don't preserve redirected fds: exec is _meant_ to change these */
  7207. //bb_error_msg("sqp == ERR_PTR: exec >FILE");
  7208. return 0;
  7209. }
  7210. /* Check whether it collides with any open fds (e.g. stdio), save fds as needed */
  7211. *sqp = add_squirrel(*sqp, fd, avoid_fd);
  7212. return 0; /* "we did not close fd" */
  7213. }
  7214. static void restore_redirects(struct squirrel *sq)
  7215. {
  7216. if (sq) {
  7217. int i;
  7218. for (i = 0; sq[i].orig_fd >= 0; i++) {
  7219. if (sq[i].moved_to >= 0) {
  7220. /* We simply die on error */
  7221. debug_printf_redir("restoring redirected fd from %d to %d\n", sq[i].moved_to, sq[i].orig_fd);
  7222. xmove_fd(sq[i].moved_to, sq[i].orig_fd);
  7223. } else {
  7224. /* cmd1 9>FILE; cmd2_should_see_fd9_closed */
  7225. debug_printf_redir("restoring redirected fd %d: closing it\n", sq[i].orig_fd);
  7226. close(sq[i].orig_fd);
  7227. }
  7228. }
  7229. free(sq);
  7230. }
  7231. if (G.HFILE_stdin
  7232. && G.HFILE_stdin->fd != STDIN_FILENO
  7233. ) {
  7234. /* Testcase: interactive "read r <FILE; echo $r; read r; echo $r".
  7235. * Redirect moves ->fd to e.g. 10,
  7236. * and it is not restored above (we do not restore script fds
  7237. * after redirects, we just use new, "moved" fds).
  7238. * However for stdin, get_user_input() -> read_line_input(),
  7239. * and read builtin, depend on fd == STDIN_FILENO.
  7240. */
  7241. debug_printf_redir("restoring %d to stdin\n", G.HFILE_stdin->fd);
  7242. xmove_fd(G.HFILE_stdin->fd, STDIN_FILENO);
  7243. G.HFILE_stdin->fd = STDIN_FILENO;
  7244. }
  7245. /* If moved, G_interactive_fd stays on new fd, not restoring it */
  7246. }
  7247. #if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
  7248. static void close_saved_fds_and_FILE_fds(void)
  7249. {
  7250. if (G_interactive_fd)
  7251. close(G_interactive_fd);
  7252. close_all_HFILE_list();
  7253. }
  7254. #endif
  7255. static int internally_opened_fd(int fd, struct squirrel *sq)
  7256. {
  7257. int i;
  7258. #if ENABLE_HUSH_INTERACTIVE
  7259. if (fd == G_interactive_fd)
  7260. return 1;
  7261. #endif
  7262. /* If this one of script's fds? */
  7263. if (fd_in_HFILEs(fd))
  7264. return 1;
  7265. if (sq) for (i = 0; sq[i].orig_fd >= 0; i++) {
  7266. if (fd == sq[i].moved_to)
  7267. return 1;
  7268. }
  7269. return 0;
  7270. }
  7271. /* squirrel != NULL means we squirrel away copies of stdin, stdout,
  7272. * and stderr if they are redirected. */
  7273. static int setup_redirects(struct command *prog, struct squirrel **sqp)
  7274. {
  7275. struct redir_struct *redir;
  7276. for (redir = prog->redirects; redir; redir = redir->next) {
  7277. int newfd;
  7278. int closed;
  7279. if (redir->rd_type == REDIRECT_HEREDOC2) {
  7280. /* "rd_fd<<HERE" case */
  7281. save_fd_on_redirect(redir->rd_fd, /*avoid:*/ 0, sqp);
  7282. /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
  7283. * of the heredoc */
  7284. debug_printf_redir("set heredoc '%s'\n",
  7285. redir->rd_filename);
  7286. setup_heredoc(redir);
  7287. continue;
  7288. }
  7289. if (redir->rd_dup == REDIRFD_TO_FILE) {
  7290. /* "rd_fd<*>file" case (<*> is <,>,>>,<>) */
  7291. char *p;
  7292. int mode;
  7293. if (redir->rd_filename == NULL) {
  7294. /* Examples:
  7295. * "cmd >" (no filename)
  7296. * "cmd > <file" (2nd redirect starts too early)
  7297. */
  7298. syntax_error("invalid redirect");
  7299. continue;
  7300. }
  7301. mode = redir_table[redir->rd_type].mode;
  7302. p = expand_string_to_string(redir->rd_filename,
  7303. EXP_FLAG_ESC_GLOB_CHARS, /*unbackslash:*/ 1);
  7304. newfd = open_or_warn(p, mode);
  7305. free(p);
  7306. if (newfd < 0) {
  7307. /* Error message from open_or_warn can be lost
  7308. * if stderr has been redirected, but bash
  7309. * and ash both lose it as well
  7310. * (though zsh doesn't!)
  7311. */
  7312. return 1;
  7313. }
  7314. if (newfd == redir->rd_fd && sqp) {
  7315. /* open() gave us precisely the fd we wanted.
  7316. * This means that this fd was not busy
  7317. * (not opened to anywhere).
  7318. * Remember to close it on restore:
  7319. */
  7320. *sqp = add_squirrel_closed(*sqp, newfd);
  7321. debug_printf_redir("redir to previously closed fd %d\n", newfd);
  7322. }
  7323. } else {
  7324. /* "rd_fd>&rd_dup" or "rd_fd>&-" case */
  7325. newfd = redir->rd_dup;
  7326. }
  7327. if (newfd == redir->rd_fd)
  7328. continue;
  7329. /* if "N>FILE": move newfd to redir->rd_fd */
  7330. /* if "N>&M": dup newfd to redir->rd_fd */
  7331. /* if "N>&-": close redir->rd_fd (newfd is REDIRFD_CLOSE) */
  7332. closed = save_fd_on_redirect(redir->rd_fd, /*avoid:*/ newfd, sqp);
  7333. if (newfd == REDIRFD_CLOSE) {
  7334. /* "N>&-" means "close me" */
  7335. if (!closed) {
  7336. /* ^^^ optimization: saving may already
  7337. * have closed it. If not... */
  7338. close(redir->rd_fd);
  7339. }
  7340. /* Sometimes we do another close on restore, getting EBADF.
  7341. * Consider "echo 3>FILE 3>&-"
  7342. * first redirect remembers "need to close 3",
  7343. * and second redirect closes 3! Restore code then closes 3 again.
  7344. */
  7345. } else {
  7346. /* if newfd is a script fd or saved fd, simulate EBADF */
  7347. if (internally_opened_fd(newfd, sqp && sqp != ERR_PTR ? *sqp : NULL)) {
  7348. //errno = EBADF;
  7349. //bb_perror_msg_and_die("can't duplicate file descriptor");
  7350. newfd = -1; /* same effect as code above */
  7351. }
  7352. xdup2(newfd, redir->rd_fd);
  7353. if (redir->rd_dup == REDIRFD_TO_FILE)
  7354. /* "rd_fd > FILE" */
  7355. close(newfd);
  7356. /* else: "rd_fd > rd_dup" */
  7357. }
  7358. }
  7359. return 0;
  7360. }
  7361. static char *find_in_path(const char *arg)
  7362. {
  7363. char *ret = NULL;
  7364. const char *PATH = get_local_var_value("PATH");
  7365. if (!PATH)
  7366. return NULL;
  7367. while (1) {
  7368. const char *end = strchrnul(PATH, ':');
  7369. int sz = end - PATH; /* must be int! */
  7370. free(ret);
  7371. if (sz != 0) {
  7372. ret = xasprintf("%.*s/%s", sz, PATH, arg);
  7373. } else {
  7374. /* We have xxx::yyyy in $PATH,
  7375. * it means "use current dir" */
  7376. ret = xstrdup(arg);
  7377. }
  7378. if (access(ret, F_OK) == 0)
  7379. break;
  7380. if (*end == '\0') {
  7381. free(ret);
  7382. return NULL;
  7383. }
  7384. PATH = end + 1;
  7385. }
  7386. return ret;
  7387. }
  7388. static const struct built_in_command *find_builtin_helper(const char *name,
  7389. const struct built_in_command *x,
  7390. const struct built_in_command *end)
  7391. {
  7392. while (x != end) {
  7393. if (strcmp(name, x->b_cmd) != 0) {
  7394. x++;
  7395. continue;
  7396. }
  7397. debug_printf_exec("found builtin '%s'\n", name);
  7398. return x;
  7399. }
  7400. return NULL;
  7401. }
  7402. static const struct built_in_command *find_builtin1(const char *name)
  7403. {
  7404. return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
  7405. }
  7406. static const struct built_in_command *find_builtin(const char *name)
  7407. {
  7408. const struct built_in_command *x = find_builtin1(name);
  7409. if (x)
  7410. return x;
  7411. return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
  7412. }
  7413. #if EDITING_HAS_get_exe_name
  7414. static const char * FAST_FUNC get_builtin_name(int i)
  7415. {
  7416. if (/*i >= 0 && */ i < ARRAY_SIZE(bltins1)) {
  7417. return bltins1[i].b_cmd;
  7418. }
  7419. i -= ARRAY_SIZE(bltins1);
  7420. if (i < ARRAY_SIZE(bltins2)) {
  7421. return bltins2[i].b_cmd;
  7422. }
  7423. return NULL;
  7424. }
  7425. #endif
  7426. static void remove_nested_vars(void)
  7427. {
  7428. struct variable *cur;
  7429. struct variable **cur_pp;
  7430. cur_pp = &G.top_var;
  7431. while ((cur = *cur_pp) != NULL) {
  7432. if (cur->var_nest_level <= G.var_nest_level) {
  7433. cur_pp = &cur->next;
  7434. continue;
  7435. }
  7436. /* Unexport */
  7437. if (cur->flg_export) {
  7438. debug_printf_env("unexporting nested '%s'/%u\n", cur->varstr, cur->var_nest_level);
  7439. bb_unsetenv(cur->varstr);
  7440. }
  7441. /* Remove from global list */
  7442. *cur_pp = cur->next;
  7443. /* Free */
  7444. if (!cur->max_len) {
  7445. debug_printf_env("freeing nested '%s'/%u\n", cur->varstr, cur->var_nest_level);
  7446. free(cur->varstr);
  7447. }
  7448. free(cur);
  7449. }
  7450. }
  7451. static void enter_var_nest_level(void)
  7452. {
  7453. G.var_nest_level++;
  7454. debug_printf_env("var_nest_level++ %u\n", G.var_nest_level);
  7455. /* Try: f() { echo -n .; f; }; f
  7456. * struct variable::var_nest_level is uint16_t,
  7457. * thus limiting recursion to < 2^16.
  7458. * In any case, with 8 Mbyte stack SEGV happens
  7459. * not too long after 2^16 recursions anyway.
  7460. */
  7461. if (G.var_nest_level > 0xff00)
  7462. bb_error_msg_and_die("fatal recursion (depth %u)", G.var_nest_level);
  7463. }
  7464. static void leave_var_nest_level(void)
  7465. {
  7466. G.var_nest_level--;
  7467. debug_printf_env("var_nest_level-- %u\n", G.var_nest_level);
  7468. if (HUSH_DEBUG && (int)G.var_nest_level < 0)
  7469. bb_simple_error_msg_and_die("BUG: nesting underflow");
  7470. remove_nested_vars();
  7471. }
  7472. #if ENABLE_HUSH_FUNCTIONS
  7473. static struct function **find_function_slot(const char *name)
  7474. {
  7475. struct function *funcp;
  7476. struct function **funcpp = &G.top_func;
  7477. while ((funcp = *funcpp) != NULL) {
  7478. if (strcmp(name, funcp->name) == 0) {
  7479. debug_printf_exec("found function '%s'\n", name);
  7480. break;
  7481. }
  7482. funcpp = &funcp->next;
  7483. }
  7484. return funcpp;
  7485. }
  7486. static ALWAYS_INLINE const struct function *find_function(const char *name)
  7487. {
  7488. const struct function *funcp = *find_function_slot(name);
  7489. return funcp;
  7490. }
  7491. /* Note: takes ownership on name ptr */
  7492. static struct function *new_function(char *name)
  7493. {
  7494. struct function **funcpp = find_function_slot(name);
  7495. struct function *funcp = *funcpp;
  7496. if (funcp != NULL) {
  7497. struct command *cmd = funcp->parent_cmd;
  7498. debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
  7499. if (!cmd) {
  7500. debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
  7501. free(funcp->name);
  7502. /* Note: if !funcp->body, do not free body_as_string!
  7503. * This is a special case of "-F name body" function:
  7504. * body_as_string was not malloced! */
  7505. if (funcp->body) {
  7506. free_pipe_list(funcp->body);
  7507. # if !BB_MMU
  7508. free(funcp->body_as_string);
  7509. # endif
  7510. }
  7511. } else {
  7512. debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
  7513. cmd->argv[0] = funcp->name;
  7514. cmd->group = funcp->body;
  7515. # if !BB_MMU
  7516. cmd->group_as_string = funcp->body_as_string;
  7517. # endif
  7518. }
  7519. } else {
  7520. debug_printf_exec("remembering new function '%s'\n", name);
  7521. funcp = *funcpp = xzalloc(sizeof(*funcp));
  7522. /*funcp->next = NULL;*/
  7523. }
  7524. funcp->name = name;
  7525. return funcp;
  7526. }
  7527. # if ENABLE_HUSH_UNSET
  7528. static void unset_func(const char *name)
  7529. {
  7530. struct function **funcpp = find_function_slot(name);
  7531. struct function *funcp = *funcpp;
  7532. if (funcp != NULL) {
  7533. debug_printf_exec("freeing function '%s'\n", funcp->name);
  7534. *funcpp = funcp->next;
  7535. /* funcp is unlinked now, deleting it.
  7536. * Note: if !funcp->body, the function was created by
  7537. * "-F name body", do not free ->body_as_string
  7538. * and ->name as they were not malloced. */
  7539. if (funcp->body) {
  7540. free_pipe_list(funcp->body);
  7541. free(funcp->name);
  7542. # if !BB_MMU
  7543. free(funcp->body_as_string);
  7544. # endif
  7545. }
  7546. free(funcp);
  7547. }
  7548. }
  7549. # endif
  7550. # if BB_MMU
  7551. #define exec_function(to_free, funcp, argv) \
  7552. exec_function(funcp, argv)
  7553. # endif
  7554. static void exec_function(char ***to_free,
  7555. const struct function *funcp,
  7556. char **argv) NORETURN;
  7557. static void exec_function(char ***to_free,
  7558. const struct function *funcp,
  7559. char **argv)
  7560. {
  7561. # if BB_MMU
  7562. int n;
  7563. argv[0] = G.global_argv[0];
  7564. G.global_argv = argv;
  7565. G.global_argc = n = 1 + string_array_len(argv + 1);
  7566. // Example when we are here: "cmd | func"
  7567. // func will run with saved-redirect fds open.
  7568. // $ f() { echo /proc/self/fd/*; }
  7569. // $ true | f
  7570. // /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3
  7571. // stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ DIR fd for glob
  7572. // Same in script:
  7573. // $ . ./SCRIPT
  7574. // /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3 /proc/self/fd/4
  7575. // stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ opened ./SCRIPT DIR fd for glob
  7576. // They are CLOEXEC so external programs won't see them, but
  7577. // for "more correctness" we might want to close those extra fds here:
  7578. //? close_saved_fds_and_FILE_fds();
  7579. /* "we are in a function, ok to use return" */
  7580. G_flag_return_in_progress = -1;
  7581. enter_var_nest_level();
  7582. IF_HUSH_LOCAL(G.func_nest_level++;)
  7583. /* On MMU, funcp->body is always non-NULL */
  7584. n = run_list(funcp->body);
  7585. fflush_all();
  7586. _exit(n);
  7587. # else
  7588. //? close_saved_fds_and_FILE_fds();
  7589. //TODO: check whether "true | func_with_return" works
  7590. re_execute_shell(to_free,
  7591. funcp->body_as_string,
  7592. G.global_argv[0],
  7593. argv + 1,
  7594. NULL);
  7595. # endif
  7596. }
  7597. static int run_function(const struct function *funcp, char **argv)
  7598. {
  7599. int rc;
  7600. save_arg_t sv;
  7601. smallint sv_flg;
  7602. save_and_replace_G_args(&sv, argv);
  7603. /* "We are in function, ok to use return" */
  7604. sv_flg = G_flag_return_in_progress;
  7605. G_flag_return_in_progress = -1;
  7606. /* Make "local" variables properly shadow previous ones */
  7607. IF_HUSH_LOCAL(enter_var_nest_level();)
  7608. IF_HUSH_LOCAL(G.func_nest_level++;)
  7609. /* On MMU, funcp->body is always non-NULL */
  7610. # if !BB_MMU
  7611. if (!funcp->body) {
  7612. /* Function defined by -F */
  7613. parse_and_run_string(funcp->body_as_string);
  7614. rc = G.last_exitcode;
  7615. } else
  7616. # endif
  7617. {
  7618. rc = run_list(funcp->body);
  7619. }
  7620. IF_HUSH_LOCAL(G.func_nest_level--;)
  7621. IF_HUSH_LOCAL(leave_var_nest_level();)
  7622. G_flag_return_in_progress = sv_flg;
  7623. # if ENABLE_HUSH_TRAP
  7624. debug_printf_exec("G.return_exitcode=-1\n");
  7625. G.return_exitcode = -1; /* invalidate stashed return value */
  7626. # endif
  7627. restore_G_args(&sv, argv);
  7628. return rc;
  7629. }
  7630. #endif /* ENABLE_HUSH_FUNCTIONS */
  7631. #if BB_MMU
  7632. #define exec_builtin(to_free, x, argv) \
  7633. exec_builtin(x, argv)
  7634. #else
  7635. #define exec_builtin(to_free, x, argv) \
  7636. exec_builtin(to_free, argv)
  7637. #endif
  7638. static void exec_builtin(char ***to_free,
  7639. const struct built_in_command *x,
  7640. char **argv) NORETURN;
  7641. static void exec_builtin(char ***to_free,
  7642. const struct built_in_command *x,
  7643. char **argv)
  7644. {
  7645. #if BB_MMU
  7646. int rcode;
  7647. fflush_all();
  7648. //? close_saved_fds_and_FILE_fds();
  7649. rcode = x->b_function(argv);
  7650. fflush_all();
  7651. _exit(rcode);
  7652. #else
  7653. fflush_all();
  7654. /* On NOMMU, we must never block!
  7655. * Example: { sleep 99 | read line; } & echo Ok
  7656. */
  7657. re_execute_shell(to_free,
  7658. argv[0],
  7659. G.global_argv[0],
  7660. G.global_argv + 1,
  7661. argv);
  7662. #endif
  7663. }
  7664. static void execvp_or_die(char **argv) NORETURN;
  7665. static void execvp_or_die(char **argv)
  7666. {
  7667. int e;
  7668. debug_printf_exec("execing '%s'\n", argv[0]);
  7669. /* Don't propagate SIG_IGN to the child */
  7670. if (SPECIAL_JOBSTOP_SIGS != 0)
  7671. switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
  7672. execvp(argv[0], argv);
  7673. e = 2;
  7674. if (errno == EACCES) e = 126;
  7675. if (errno == ENOENT) e = 127;
  7676. bb_perror_msg("can't execute '%s'", argv[0]);
  7677. _exit(e);
  7678. }
  7679. #if ENABLE_HUSH_MODE_X
  7680. static void x_mode_print_optionally_squoted(const char *str)
  7681. {
  7682. unsigned len;
  7683. const char *cp;
  7684. cp = str;
  7685. /* the set of chars which-cause-string-to-be-squoted mimics bash */
  7686. /* test a char with: bash -c 'set -x; echo "CH"' */
  7687. if (str[strcspn(str, "\\\"'`$(){}[]<>;#&|~*?!^"
  7688. " " "\001\002\003\004\005\006\007"
  7689. "\010\011\012\013\014\015\016\017"
  7690. "\020\021\022\023\024\025\026\027"
  7691. "\030\031\032\033\034\035\036\037"
  7692. )
  7693. ] == '\0'
  7694. ) {
  7695. /* string has no special chars */
  7696. x_mode_addstr(str);
  7697. return;
  7698. }
  7699. cp = str;
  7700. for (;;) {
  7701. /* print '....' up to EOL or first squote */
  7702. len = (int)(strchrnul(cp, '\'') - cp);
  7703. if (len != 0) {
  7704. x_mode_addchr('\'');
  7705. x_mode_addblock(cp, len);
  7706. x_mode_addchr('\'');
  7707. cp += len;
  7708. }
  7709. if (*cp == '\0')
  7710. break;
  7711. /* string contains squote(s), print them as \' */
  7712. x_mode_addchr('\\');
  7713. x_mode_addchr('\'');
  7714. cp++;
  7715. }
  7716. }
  7717. static void dump_cmd_in_x_mode(char **argv)
  7718. {
  7719. if (G_x_mode && argv) {
  7720. unsigned n;
  7721. /* "+[+++...][ cmd...]\n\0" */
  7722. x_mode_prefix();
  7723. n = 0;
  7724. while (argv[n]) {
  7725. x_mode_addchr(' ');
  7726. if (argv[n][0] == '\0') {
  7727. x_mode_addchr('\'');
  7728. x_mode_addchr('\'');
  7729. } else {
  7730. x_mode_print_optionally_squoted(argv[n]);
  7731. }
  7732. n++;
  7733. }
  7734. x_mode_flush();
  7735. }
  7736. }
  7737. #else
  7738. # define dump_cmd_in_x_mode(argv) ((void)0)
  7739. #endif
  7740. #if ENABLE_HUSH_COMMAND
  7741. static void if_command_vV_print_and_exit(char opt_vV, char *cmd, const char *explanation)
  7742. {
  7743. char *to_free;
  7744. if (!opt_vV)
  7745. return;
  7746. to_free = NULL;
  7747. if (!explanation) {
  7748. char *path = getenv("PATH");
  7749. explanation = to_free = find_executable(cmd, &path); /* path == NULL is ok */
  7750. if (!explanation)
  7751. _exit(1); /* PROG was not found */
  7752. if (opt_vV != 'V')
  7753. cmd = to_free; /* -v PROG prints "/path/to/PROG" */
  7754. }
  7755. printf((opt_vV == 'V') ? "%s is %s\n" : "%s\n", cmd, explanation);
  7756. free(to_free);
  7757. fflush_all();
  7758. _exit(0);
  7759. }
  7760. #else
  7761. # define if_command_vV_print_and_exit(a,b,c) ((void)0)
  7762. #endif
  7763. #if BB_MMU
  7764. #define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
  7765. pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
  7766. #define pseudo_exec(nommu_save, command, argv_expanded) \
  7767. pseudo_exec(command, argv_expanded)
  7768. #endif
  7769. /* Called after [v]fork() in run_pipe, or from builtin_exec.
  7770. * Never returns.
  7771. * Don't exit() here. If you don't exec, use _exit instead.
  7772. * The at_exit handlers apparently confuse the calling process,
  7773. * in particular stdin handling. Not sure why? -- because of vfork! (vda)
  7774. */
  7775. static void pseudo_exec_argv(nommu_save_t *nommu_save,
  7776. char **argv, int assignment_cnt,
  7777. char **argv_expanded) NORETURN;
  7778. static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
  7779. char **argv, int assignment_cnt,
  7780. char **argv_expanded)
  7781. {
  7782. const struct built_in_command *x;
  7783. struct variable **sv_shadowed;
  7784. char **new_env;
  7785. IF_HUSH_COMMAND(char opt_vV = 0;)
  7786. IF_HUSH_FUNCTIONS(const struct function *funcp;)
  7787. new_env = expand_assignments(argv, assignment_cnt);
  7788. dump_cmd_in_x_mode(new_env);
  7789. if (!argv[assignment_cnt]) {
  7790. /* Case when we are here: ... | var=val | ...
  7791. * (note that we do not exit early, i.e., do not optimize out
  7792. * expand_assignments(): think about ... | var=`sleep 1` | ...
  7793. */
  7794. free_strings(new_env);
  7795. _exit(EXIT_SUCCESS);
  7796. }
  7797. sv_shadowed = G.shadowed_vars_pp;
  7798. #if BB_MMU
  7799. G.shadowed_vars_pp = NULL; /* "don't save, free them instead" */
  7800. #else
  7801. G.shadowed_vars_pp = &nommu_save->old_vars;
  7802. G.var_nest_level++;
  7803. #endif
  7804. set_vars_and_save_old(new_env);
  7805. G.shadowed_vars_pp = sv_shadowed;
  7806. if (argv_expanded) {
  7807. argv = argv_expanded;
  7808. } else {
  7809. argv = expand_strvec_to_strvec(argv + assignment_cnt);
  7810. #if !BB_MMU
  7811. nommu_save->argv = argv;
  7812. #endif
  7813. }
  7814. dump_cmd_in_x_mode(argv);
  7815. #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
  7816. if (strchr(argv[0], '/') != NULL)
  7817. goto skip;
  7818. #endif
  7819. #if ENABLE_HUSH_FUNCTIONS
  7820. /* Check if the command matches any functions (this goes before bltins) */
  7821. funcp = find_function(argv[0]);
  7822. if (funcp)
  7823. exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
  7824. #endif
  7825. #if ENABLE_HUSH_COMMAND
  7826. /* "command BAR": run BAR without looking it up among functions
  7827. * "command -v BAR": print "BAR" or "/path/to/BAR"; or exit 1
  7828. * "command -V BAR": print "BAR is {a function,a shell builtin,/path/to/BAR}"
  7829. */
  7830. while (strcmp(argv[0], "command") == 0 && argv[1]) {
  7831. char *p;
  7832. argv++;
  7833. p = *argv;
  7834. if (p[0] != '-' || !p[1])
  7835. continue; /* bash allows "command command command [-OPT] BAR" */
  7836. for (;;) {
  7837. p++;
  7838. switch (*p) {
  7839. case '\0':
  7840. argv++;
  7841. p = *argv;
  7842. if (p[0] != '-' || !p[1])
  7843. goto after_opts;
  7844. continue; /* next arg is also -opts, process it too */
  7845. case 'v':
  7846. case 'V':
  7847. opt_vV = *p;
  7848. continue;
  7849. default:
  7850. bb_error_msg_and_die("%s: %s: invalid option", "command", argv[0]);
  7851. }
  7852. }
  7853. }
  7854. after_opts:
  7855. # if ENABLE_HUSH_FUNCTIONS
  7856. if (opt_vV && find_function(argv[0]))
  7857. if_command_vV_print_and_exit(opt_vV, argv[0], "a function");
  7858. # endif
  7859. #endif
  7860. /* Check if the command matches any of the builtins.
  7861. * Depending on context, this might be redundant. But it's
  7862. * easier to waste a few CPU cycles than it is to figure out
  7863. * if this is one of those cases.
  7864. */
  7865. /* Why "BB_MMU ? :" difference in logic? -
  7866. * On NOMMU, it is more expensive to re-execute shell
  7867. * just in order to run echo or test builtin.
  7868. * It's better to skip it here and run corresponding
  7869. * non-builtin later. */
  7870. x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
  7871. if (x) {
  7872. if_command_vV_print_and_exit(opt_vV, argv[0], "a shell builtin");
  7873. exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
  7874. }
  7875. #if ENABLE_FEATURE_SH_STANDALONE
  7876. /* Check if the command matches any busybox applets */
  7877. {
  7878. int a = find_applet_by_name(argv[0]);
  7879. if (a >= 0) {
  7880. if_command_vV_print_and_exit(opt_vV, argv[0], "an applet");
  7881. # if BB_MMU /* see above why on NOMMU it is not allowed */
  7882. if (APPLET_IS_NOEXEC(a)) {
  7883. /* Do not leak open fds from opened script files etc.
  7884. * Testcase: interactive "ls -l /proc/self/fd"
  7885. * should not show tty fd open.
  7886. */
  7887. close_saved_fds_and_FILE_fds();
  7888. //FIXME: should also close saved redir fds
  7889. //This casuses test failures in
  7890. //redir_children_should_not_see_saved_fd_2.tests
  7891. //redir_children_should_not_see_saved_fd_3.tests
  7892. //if you replace "busybox find" with just "find" in them
  7893. /* Without this, "rm -i FILE" can't be ^C'ed: */
  7894. switch_off_special_sigs(G.special_sig_mask);
  7895. debug_printf_exec("running applet '%s'\n", argv[0]);
  7896. run_noexec_applet_and_exit(a, argv[0], argv);
  7897. }
  7898. # endif
  7899. /* Re-exec ourselves */
  7900. debug_printf_exec("re-execing applet '%s'\n", argv[0]);
  7901. /* Don't propagate SIG_IGN to the child */
  7902. if (SPECIAL_JOBSTOP_SIGS != 0)
  7903. switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
  7904. execv(bb_busybox_exec_path, argv);
  7905. /* If they called chroot or otherwise made the binary no longer
  7906. * executable, fall through */
  7907. }
  7908. }
  7909. #endif
  7910. #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
  7911. skip:
  7912. #endif
  7913. if_command_vV_print_and_exit(opt_vV, argv[0], NULL);
  7914. execvp_or_die(argv);
  7915. }
  7916. /* Called after [v]fork() in run_pipe
  7917. */
  7918. static void pseudo_exec(nommu_save_t *nommu_save,
  7919. struct command *command,
  7920. char **argv_expanded) NORETURN;
  7921. static void pseudo_exec(nommu_save_t *nommu_save,
  7922. struct command *command,
  7923. char **argv_expanded)
  7924. {
  7925. #if ENABLE_HUSH_FUNCTIONS
  7926. if (command->cmd_type == CMD_FUNCDEF) {
  7927. /* Ignore funcdefs in pipes:
  7928. * true | f() { cmd }
  7929. */
  7930. _exit(0);
  7931. }
  7932. #endif
  7933. if (command->argv) {
  7934. pseudo_exec_argv(nommu_save, command->argv,
  7935. command->assignment_cnt, argv_expanded);
  7936. }
  7937. if (command->group) {
  7938. /* Cases when we are here:
  7939. * ( list )
  7940. * { list } &
  7941. * ... | ( list ) | ...
  7942. * ... | { list } | ...
  7943. */
  7944. #if BB_MMU
  7945. int rcode;
  7946. debug_printf_exec("pseudo_exec: run_list\n");
  7947. reset_traps_to_defaults();
  7948. rcode = run_list(command->group);
  7949. /* OK to leak memory by not calling free_pipe_list,
  7950. * since this process is about to exit */
  7951. _exit(rcode);
  7952. #else
  7953. re_execute_shell(&nommu_save->argv_from_re_execing,
  7954. command->group_as_string,
  7955. G.global_argv[0],
  7956. G.global_argv + 1,
  7957. NULL);
  7958. #endif
  7959. }
  7960. /* Case when we are here: ... | >file */
  7961. debug_printf_exec("pseudo_exec'ed null command\n");
  7962. _exit(EXIT_SUCCESS);
  7963. }
  7964. #if ENABLE_HUSH_JOB
  7965. static const char *get_cmdtext(struct pipe *pi)
  7966. {
  7967. char **argv;
  7968. char *p;
  7969. int len;
  7970. /* This is subtle. ->cmdtext is created only on first backgrounding.
  7971. * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
  7972. * On subsequent bg argv is trashed, but we won't use it */
  7973. if (pi->cmdtext)
  7974. return pi->cmdtext;
  7975. argv = pi->cmds[0].argv;
  7976. if (!argv) {
  7977. pi->cmdtext = xzalloc(1);
  7978. return pi->cmdtext;
  7979. }
  7980. len = 0;
  7981. do {
  7982. len += strlen(*argv) + 1;
  7983. } while (*++argv);
  7984. p = xmalloc(len);
  7985. pi->cmdtext = p;
  7986. argv = pi->cmds[0].argv;
  7987. do {
  7988. p = stpcpy(p, *argv);
  7989. *p++ = ' ';
  7990. } while (*++argv);
  7991. p[-1] = '\0';
  7992. return pi->cmdtext;
  7993. }
  7994. static void remove_job_from_table(struct pipe *pi)
  7995. {
  7996. struct pipe *prev_pipe;
  7997. if (pi == G.job_list) {
  7998. G.job_list = pi->next;
  7999. } else {
  8000. prev_pipe = G.job_list;
  8001. while (prev_pipe->next != pi)
  8002. prev_pipe = prev_pipe->next;
  8003. prev_pipe->next = pi->next;
  8004. }
  8005. G.last_jobid = 0;
  8006. if (G.job_list)
  8007. G.last_jobid = G.job_list->jobid;
  8008. }
  8009. static void delete_finished_job(struct pipe *pi)
  8010. {
  8011. remove_job_from_table(pi);
  8012. free_pipe(pi);
  8013. }
  8014. static void clean_up_last_dead_job(void)
  8015. {
  8016. if (G.job_list && !G.job_list->alive_cmds)
  8017. delete_finished_job(G.job_list);
  8018. }
  8019. static void insert_job_into_table(struct pipe *pi)
  8020. {
  8021. struct pipe *job, **jobp;
  8022. int i;
  8023. clean_up_last_dead_job();
  8024. /* Find the end of the list, and find next job ID to use */
  8025. i = 0;
  8026. jobp = &G.job_list;
  8027. while ((job = *jobp) != NULL) {
  8028. if (job->jobid > i)
  8029. i = job->jobid;
  8030. jobp = &job->next;
  8031. }
  8032. pi->jobid = i + 1;
  8033. /* Create a new job struct at the end */
  8034. job = *jobp = xmemdup(pi, sizeof(*pi));
  8035. job->next = NULL;
  8036. job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
  8037. /* Cannot copy entire pi->cmds[] vector! This causes double frees */
  8038. for (i = 0; i < pi->num_cmds; i++) {
  8039. job->cmds[i].pid = pi->cmds[i].pid;
  8040. /* all other fields are not used and stay zero */
  8041. }
  8042. job->cmdtext = xstrdup(get_cmdtext(pi));
  8043. if (G_interactive_fd)
  8044. printf("[%u] %u %s\n", job->jobid, (unsigned)job->cmds[0].pid, job->cmdtext);
  8045. G.last_jobid = job->jobid;
  8046. }
  8047. #endif /* JOB */
  8048. static int job_exited_or_stopped(struct pipe *pi)
  8049. {
  8050. int rcode, i;
  8051. if (pi->alive_cmds != pi->stopped_cmds)
  8052. return -1;
  8053. /* All processes in fg pipe have exited or stopped */
  8054. rcode = 0;
  8055. i = pi->num_cmds;
  8056. while (--i >= 0) {
  8057. rcode = pi->cmds[i].cmd_exitcode;
  8058. /* usually last process gives overall exitstatus,
  8059. * but with "set -o pipefail", last *failed* process does */
  8060. if (G.o_opt[OPT_O_PIPEFAIL] == 0 || rcode != 0)
  8061. break;
  8062. }
  8063. IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
  8064. return rcode;
  8065. }
  8066. static int process_wait_result(struct pipe *fg_pipe, pid_t childpid, int status)
  8067. {
  8068. #if ENABLE_HUSH_JOB
  8069. struct pipe *pi;
  8070. #endif
  8071. int i, dead;
  8072. dead = WIFEXITED(status) || WIFSIGNALED(status);
  8073. #if DEBUG_JOBS
  8074. if (WIFSTOPPED(status))
  8075. debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
  8076. childpid, WSTOPSIG(status), WEXITSTATUS(status));
  8077. if (WIFSIGNALED(status))
  8078. debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
  8079. childpid, WTERMSIG(status), WEXITSTATUS(status));
  8080. if (WIFEXITED(status))
  8081. debug_printf_jobs("pid %d exited, exitcode %d\n",
  8082. childpid, WEXITSTATUS(status));
  8083. #endif
  8084. /* Were we asked to wait for a fg pipe? */
  8085. if (fg_pipe) {
  8086. i = fg_pipe->num_cmds;
  8087. while (--i >= 0) {
  8088. int rcode;
  8089. debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
  8090. if (fg_pipe->cmds[i].pid != childpid)
  8091. continue;
  8092. if (dead) {
  8093. int ex;
  8094. fg_pipe->cmds[i].pid = 0;
  8095. fg_pipe->alive_cmds--;
  8096. ex = WEXITSTATUS(status);
  8097. /* bash prints killer signal's name for *last*
  8098. * process in pipe (prints just newline for SIGINT/SIGPIPE).
  8099. * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
  8100. */
  8101. if (WIFSIGNALED(status)) {
  8102. int sig = WTERMSIG(status);
  8103. if (i == fg_pipe->num_cmds-1)
  8104. /* TODO: use strsignal() instead for bash compat? but that's bloat... */
  8105. puts(sig == SIGINT || sig == SIGPIPE ? "" : get_signame(sig));
  8106. /* TODO: if (WCOREDUMP(status)) + " (core dumped)"; */
  8107. /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
  8108. * Maybe we need to use sig | 128? */
  8109. ex = sig + 128;
  8110. }
  8111. fg_pipe->cmds[i].cmd_exitcode = ex;
  8112. } else {
  8113. fg_pipe->stopped_cmds++;
  8114. }
  8115. debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
  8116. fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
  8117. rcode = job_exited_or_stopped(fg_pipe);
  8118. if (rcode >= 0) {
  8119. /* Note: *non-interactive* bash does not continue if all processes in fg pipe
  8120. * are stopped. Testcase: "cat | cat" in a script (not on command line!)
  8121. * and "killall -STOP cat" */
  8122. if (G_interactive_fd) {
  8123. #if ENABLE_HUSH_JOB
  8124. if (fg_pipe->alive_cmds != 0)
  8125. insert_job_into_table(fg_pipe);
  8126. #endif
  8127. return rcode;
  8128. }
  8129. if (fg_pipe->alive_cmds == 0)
  8130. return rcode;
  8131. }
  8132. /* There are still running processes in the fg_pipe */
  8133. return -1;
  8134. }
  8135. /* It wasn't in fg_pipe, look for process in bg pipes */
  8136. }
  8137. #if ENABLE_HUSH_JOB
  8138. /* We were asked to wait for bg or orphaned children */
  8139. /* No need to remember exitcode in this case */
  8140. for (pi = G.job_list; pi; pi = pi->next) {
  8141. for (i = 0; i < pi->num_cmds; i++) {
  8142. if (pi->cmds[i].pid == childpid)
  8143. goto found_pi_and_prognum;
  8144. }
  8145. }
  8146. /* Happens when shell is used as init process (init=/bin/sh) */
  8147. debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
  8148. return -1; /* this wasn't a process from fg_pipe */
  8149. found_pi_and_prognum:
  8150. if (dead) {
  8151. /* child exited */
  8152. int rcode = WEXITSTATUS(status);
  8153. if (WIFSIGNALED(status))
  8154. rcode = 128 + WTERMSIG(status);
  8155. pi->cmds[i].cmd_exitcode = rcode;
  8156. if (G.last_bg_pid == pi->cmds[i].pid)
  8157. G.last_bg_pid_exitcode = rcode;
  8158. pi->cmds[i].pid = 0;
  8159. pi->alive_cmds--;
  8160. if (!pi->alive_cmds) {
  8161. # if ENABLE_HUSH_BASH_COMPAT
  8162. G.dead_job_exitcode = job_exited_or_stopped(pi);
  8163. # endif
  8164. if (G_interactive_fd) {
  8165. printf(JOB_STATUS_FORMAT, pi->jobid,
  8166. "Done", pi->cmdtext);
  8167. delete_finished_job(pi);
  8168. } else {
  8169. /*
  8170. * bash deletes finished jobs from job table only in interactive mode,
  8171. * after "jobs" cmd, or if pid of a new process matches one of the old ones
  8172. * (see cleanup_dead_jobs(), delete_old_job(), J_NOTIFIED in bash source).
  8173. * Testcase script: "(exit 3) & sleep 1; wait %1; echo $?" prints 3 in bash.
  8174. * We only retain one "dead" job, if it's the single job on the list.
  8175. * This covers most of real-world scenarios where this is useful.
  8176. */
  8177. if (pi != G.job_list)
  8178. delete_finished_job(pi);
  8179. }
  8180. }
  8181. } else {
  8182. /* child stopped */
  8183. pi->stopped_cmds++;
  8184. }
  8185. #endif
  8186. return -1; /* this wasn't a process from fg_pipe */
  8187. }
  8188. /* Check to see if any processes have exited -- if they have,
  8189. * figure out why and see if a job has completed.
  8190. *
  8191. * If non-NULL fg_pipe: wait for its completion or stop.
  8192. * Return its exitcode or zero if stopped.
  8193. *
  8194. * Alternatively (fg_pipe == NULL, waitfor_pid != 0):
  8195. * waitpid(WNOHANG), if waitfor_pid exits or stops, return exitcode+1,
  8196. * else return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
  8197. * or 0 if no children changed status.
  8198. *
  8199. * Alternatively (fg_pipe == NULL, waitfor_pid == 0),
  8200. * return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
  8201. * or 0 if no children changed status.
  8202. */
  8203. static int checkjobs(struct pipe *fg_pipe, pid_t waitfor_pid)
  8204. {
  8205. int attributes;
  8206. int status;
  8207. int rcode = 0;
  8208. debug_printf_jobs("checkjobs %p\n", fg_pipe);
  8209. attributes = WUNTRACED;
  8210. if (fg_pipe == NULL)
  8211. attributes |= WNOHANG;
  8212. errno = 0;
  8213. #if ENABLE_HUSH_FAST
  8214. if (G.handled_SIGCHLD == G.count_SIGCHLD) {
  8215. //bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
  8216. //getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
  8217. /* There was neither fork nor SIGCHLD since last waitpid */
  8218. /* Avoid doing waitpid syscall if possible */
  8219. if (!G.we_have_children) {
  8220. errno = ECHILD;
  8221. return -1;
  8222. }
  8223. if (fg_pipe == NULL) { /* is WNOHANG set? */
  8224. /* We have children, but they did not exit
  8225. * or stop yet (we saw no SIGCHLD) */
  8226. return 0;
  8227. }
  8228. /* else: !WNOHANG, waitpid will block, can't short-circuit */
  8229. }
  8230. #endif
  8231. /* Do we do this right?
  8232. * bash-3.00# sleep 20 | false
  8233. * <ctrl-Z pressed>
  8234. * [3]+ Stopped sleep 20 | false
  8235. * bash-3.00# echo $?
  8236. * 1 <========== bg pipe is not fully done, but exitcode is already known!
  8237. * [hush 1.14.0: yes we do it right]
  8238. */
  8239. while (1) {
  8240. pid_t childpid;
  8241. #if ENABLE_HUSH_FAST
  8242. int i;
  8243. i = G.count_SIGCHLD;
  8244. #endif
  8245. childpid = waitpid(-1, &status, attributes);
  8246. if (childpid <= 0) {
  8247. if (childpid && errno != ECHILD)
  8248. bb_simple_perror_msg("waitpid");
  8249. #if ENABLE_HUSH_FAST
  8250. else { /* Until next SIGCHLD, waitpid's are useless */
  8251. G.we_have_children = (childpid == 0);
  8252. G.handled_SIGCHLD = i;
  8253. //bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
  8254. }
  8255. #endif
  8256. /* ECHILD (no children), or 0 (no change in children status) */
  8257. rcode = childpid;
  8258. break;
  8259. }
  8260. rcode = process_wait_result(fg_pipe, childpid, status);
  8261. if (rcode >= 0) {
  8262. /* fg_pipe exited or stopped */
  8263. break;
  8264. }
  8265. if (childpid == waitfor_pid) { /* "wait PID" */
  8266. debug_printf_exec("childpid==waitfor_pid:%d status:0x%08x\n", childpid, status);
  8267. rcode = WEXITSTATUS(status);
  8268. if (WIFSIGNALED(status))
  8269. rcode = 128 + WTERMSIG(status);
  8270. if (WIFSTOPPED(status))
  8271. /* bash: "cmd & wait $!" and cmd stops: $? = 128 + stopsig */
  8272. rcode = 128 + WSTOPSIG(status);
  8273. rcode++;
  8274. break; /* "wait PID" called us, give it exitcode+1 */
  8275. }
  8276. #if ENABLE_HUSH_BASH_COMPAT
  8277. if (-1 == waitfor_pid /* "wait -n" (wait for any one job) */
  8278. && G.dead_job_exitcode >= 0 /* some job did finish */
  8279. ) {
  8280. debug_printf_exec("waitfor_pid:-1\n");
  8281. rcode = G.dead_job_exitcode + 1;
  8282. break;
  8283. }
  8284. #endif
  8285. /* This wasn't one of our processes, or */
  8286. /* fg_pipe still has running processes, do waitpid again */
  8287. } /* while (waitpid succeeds)... */
  8288. return rcode;
  8289. }
  8290. #if ENABLE_HUSH_JOB
  8291. static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
  8292. {
  8293. pid_t p;
  8294. int rcode = checkjobs(fg_pipe, 0 /*(no pid to wait for)*/);
  8295. if (G_saved_tty_pgrp) {
  8296. /* Job finished, move the shell to the foreground */
  8297. p = getpgrp(); /* our process group id */
  8298. debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
  8299. tcsetpgrp(G_interactive_fd, p);
  8300. }
  8301. return rcode;
  8302. }
  8303. #endif
  8304. /* Start all the jobs, but don't wait for anything to finish.
  8305. * See checkjobs().
  8306. *
  8307. * Return code is normally -1, when the caller has to wait for children
  8308. * to finish to determine the exit status of the pipe. If the pipe
  8309. * is a simple builtin command, however, the action is done by the
  8310. * time run_pipe returns, and the exit code is provided as the
  8311. * return value.
  8312. *
  8313. * Returns -1 only if started some children. IOW: we have to
  8314. * mask out retvals of builtins etc with 0xff!
  8315. *
  8316. * The only case when we do not need to [v]fork is when the pipe
  8317. * is single, non-backgrounded, non-subshell command. Examples:
  8318. * cmd ; ... { list } ; ...
  8319. * cmd && ... { list } && ...
  8320. * cmd || ... { list } || ...
  8321. * If it is, then we can run cmd as a builtin, NOFORK,
  8322. * or (if SH_STANDALONE) an applet, and we can run the { list }
  8323. * with run_list. If it isn't one of these, we fork and exec cmd.
  8324. *
  8325. * Cases when we must fork:
  8326. * non-single: cmd | cmd
  8327. * backgrounded: cmd & { list } &
  8328. * subshell: ( list ) [&]
  8329. */
  8330. #if !ENABLE_HUSH_MODE_X
  8331. #define redirect_and_varexp_helper(command, sqp, argv_expanded) \
  8332. redirect_and_varexp_helper(command, sqp)
  8333. #endif
  8334. static int redirect_and_varexp_helper(
  8335. struct command *command,
  8336. struct squirrel **sqp,
  8337. char **argv_expanded)
  8338. {
  8339. /* Assignments occur before redirects. Try:
  8340. * a=`sleep 1` sleep 2 3>/qwe/rty
  8341. */
  8342. char **new_env = expand_assignments(command->argv, command->assignment_cnt);
  8343. dump_cmd_in_x_mode(new_env);
  8344. dump_cmd_in_x_mode(argv_expanded);
  8345. /* this takes ownership of new_env[i] elements, and frees new_env: */
  8346. set_vars_and_save_old(new_env);
  8347. return setup_redirects(command, sqp);
  8348. }
  8349. static NOINLINE int run_pipe(struct pipe *pi)
  8350. {
  8351. static const char *const null_ptr = NULL;
  8352. int cmd_no;
  8353. int next_infd;
  8354. struct command *command;
  8355. char **argv_expanded;
  8356. char **argv;
  8357. struct squirrel *squirrel = NULL;
  8358. int rcode;
  8359. debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
  8360. debug_enter();
  8361. /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
  8362. * Result should be 3 lines: q w e, qwe, q w e
  8363. */
  8364. if (G.ifs_whitespace != G.ifs)
  8365. free(G.ifs_whitespace);
  8366. G.ifs = get_local_var_value("IFS");
  8367. if (G.ifs) {
  8368. char *p;
  8369. G.ifs_whitespace = (char*)G.ifs;
  8370. p = skip_whitespace(G.ifs);
  8371. if (*p) {
  8372. /* Not all $IFS is whitespace */
  8373. char *d;
  8374. int len = p - G.ifs;
  8375. p = skip_non_whitespace(p);
  8376. G.ifs_whitespace = xmalloc(len + strlen(p) + 1); /* can overestimate */
  8377. d = mempcpy(G.ifs_whitespace, G.ifs, len);
  8378. while (*p) {
  8379. if (isspace(*p))
  8380. *d++ = *p;
  8381. p++;
  8382. }
  8383. *d = '\0';
  8384. }
  8385. } else {
  8386. G.ifs = defifs;
  8387. G.ifs_whitespace = (char*)G.ifs;
  8388. }
  8389. IF_HUSH_JOB(pi->pgrp = -1;)
  8390. pi->stopped_cmds = 0;
  8391. command = &pi->cmds[0];
  8392. argv_expanded = NULL;
  8393. if (pi->num_cmds != 1
  8394. || pi->followup == PIPE_BG
  8395. || command->cmd_type == CMD_SUBSHELL
  8396. ) {
  8397. goto must_fork;
  8398. }
  8399. pi->alive_cmds = 1;
  8400. debug_printf_exec(": group:%p argv:'%s'\n",
  8401. command->group, command->argv ? command->argv[0] : "NONE");
  8402. if (command->group) {
  8403. #if ENABLE_HUSH_FUNCTIONS
  8404. if (command->cmd_type == CMD_FUNCDEF) {
  8405. /* "executing" func () { list } */
  8406. struct function *funcp;
  8407. funcp = new_function(command->argv[0]);
  8408. /* funcp->name is already set to argv[0] */
  8409. funcp->body = command->group;
  8410. # if !BB_MMU
  8411. funcp->body_as_string = command->group_as_string;
  8412. command->group_as_string = NULL;
  8413. # endif
  8414. command->group = NULL;
  8415. command->argv[0] = NULL;
  8416. debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
  8417. funcp->parent_cmd = command;
  8418. command->child_func = funcp;
  8419. debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
  8420. debug_leave();
  8421. return EXIT_SUCCESS;
  8422. }
  8423. #endif
  8424. /* { list } */
  8425. debug_printf_exec("non-subshell group\n");
  8426. rcode = 1; /* exitcode if redir failed */
  8427. if (setup_redirects(command, &squirrel) == 0) {
  8428. debug_printf_exec(": run_list\n");
  8429. //FIXME: we need to pass squirrel down into run_list()
  8430. //for SH_STANDALONE case, or else this construct:
  8431. // { find /proc/self/fd; true; } >FILE; cmd2
  8432. //has no way of closing saved fd#1 for "find",
  8433. //and in SH_STANDALONE mode, "find" is not execed,
  8434. //therefore CLOEXEC on saved fd does not help.
  8435. rcode = run_list(command->group) & 0xff;
  8436. }
  8437. restore_redirects(squirrel);
  8438. IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
  8439. debug_leave();
  8440. debug_printf_exec("run_pipe: return %d\n", rcode);
  8441. return rcode;
  8442. }
  8443. argv = command->argv ? command->argv : (char **) &null_ptr;
  8444. {
  8445. const struct built_in_command *x;
  8446. IF_HUSH_FUNCTIONS(const struct function *funcp;)
  8447. IF_NOT_HUSH_FUNCTIONS(enum { funcp = 0 };)
  8448. struct variable **sv_shadowed;
  8449. struct variable *old_vars;
  8450. #if ENABLE_HUSH_LINENO_VAR
  8451. G.execute_lineno = command->lineno;
  8452. #endif
  8453. if (argv[command->assignment_cnt] == NULL) {
  8454. /* Assignments, but no command.
  8455. * Ensure redirects take effect (that is, create files).
  8456. * Try "a=t >file"
  8457. */
  8458. unsigned i;
  8459. G.expand_exitcode = 0;
  8460. only_assignments:
  8461. rcode = setup_redirects(command, &squirrel);
  8462. restore_redirects(squirrel);
  8463. /* Set shell variables */
  8464. i = 0;
  8465. while (i < command->assignment_cnt) {
  8466. char *p = expand_string_to_string(argv[i],
  8467. EXP_FLAG_ESC_GLOB_CHARS,
  8468. /*unbackslash:*/ 1
  8469. );
  8470. #if ENABLE_HUSH_MODE_X
  8471. if (G_x_mode) {
  8472. char *eq;
  8473. if (i == 0)
  8474. x_mode_prefix();
  8475. x_mode_addchr(' ');
  8476. eq = strchrnul(p, '=');
  8477. if (*eq) eq++;
  8478. x_mode_addblock(p, (eq - p));
  8479. x_mode_print_optionally_squoted(eq);
  8480. x_mode_flush();
  8481. }
  8482. #endif
  8483. debug_printf_env("set shell var:'%s'->'%s'\n", *argv, p);
  8484. if (set_local_var(p, /*flag:*/ 0)) {
  8485. /* assignment to readonly var / putenv error? */
  8486. rcode = 1;
  8487. }
  8488. i++;
  8489. }
  8490. /* Redirect error sets $? to 1. Otherwise,
  8491. * if evaluating assignment value set $?, retain it.
  8492. * Else, clear $?:
  8493. * false; q=`exit 2`; echo $? - should print 2
  8494. * false; x=1; echo $? - should print 0
  8495. * Because of the 2nd case, we can't just use G.last_exitcode.
  8496. */
  8497. if (rcode == 0)
  8498. rcode = G.expand_exitcode;
  8499. IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
  8500. debug_leave();
  8501. debug_printf_exec("run_pipe: return %d\n", rcode);
  8502. return rcode;
  8503. }
  8504. /* Expand the rest into (possibly) many strings each */
  8505. #if defined(CMD_SINGLEWORD_NOGLOB)
  8506. if (command->cmd_type == CMD_SINGLEWORD_NOGLOB)
  8507. argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
  8508. else
  8509. #endif
  8510. argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
  8511. /* If someone gives us an empty string: `cmd with empty output` */
  8512. if (!argv_expanded[0]) {
  8513. free(argv_expanded);
  8514. /* `false` still has to set exitcode 1 */
  8515. G.expand_exitcode = G.last_exitcode;
  8516. goto only_assignments;
  8517. }
  8518. old_vars = NULL;
  8519. sv_shadowed = G.shadowed_vars_pp;
  8520. /* Check if argv[0] matches any functions (this goes before bltins) */
  8521. IF_HUSH_FUNCTIONS(funcp = find_function(argv_expanded[0]);)
  8522. IF_HUSH_FUNCTIONS(x = NULL;)
  8523. IF_HUSH_FUNCTIONS(if (!funcp))
  8524. x = find_builtin(argv_expanded[0]);
  8525. if (x || funcp) {
  8526. if (x && x->b_function == builtin_exec && argv_expanded[1] == NULL) {
  8527. debug_printf("exec with redirects only\n");
  8528. /*
  8529. * Variable assignments are executed, but then "forgotten":
  8530. * a=`sleep 1;echo A` exec 3>&-; echo $a
  8531. * sleeps, but prints nothing.
  8532. */
  8533. enter_var_nest_level();
  8534. G.shadowed_vars_pp = &old_vars;
  8535. rcode = redirect_and_varexp_helper(command,
  8536. /*squirrel:*/ ERR_PTR,
  8537. argv_expanded
  8538. );
  8539. G.shadowed_vars_pp = sv_shadowed;
  8540. /* rcode=1 can be if redir file can't be opened */
  8541. goto clean_up_and_ret1;
  8542. }
  8543. /* Bump var nesting, or this will leak exported $a:
  8544. * a=b true; env | grep ^a=
  8545. */
  8546. enter_var_nest_level();
  8547. /* Collect all variables "shadowed" by helper
  8548. * (IOW: old vars overridden by "var1=val1 var2=val2 cmd..." syntax)
  8549. * into old_vars list:
  8550. */
  8551. G.shadowed_vars_pp = &old_vars;
  8552. rcode = redirect_and_varexp_helper(command, &squirrel, argv_expanded);
  8553. if (rcode == 0) {
  8554. if (!funcp) {
  8555. /* Do not collect *to old_vars list* vars shadowed
  8556. * by e.g. "local VAR" builtin (collect them
  8557. * in the previously nested list instead):
  8558. * don't want them to be restored immediately
  8559. * after "local" completes.
  8560. */
  8561. G.shadowed_vars_pp = sv_shadowed;
  8562. debug_printf_exec(": builtin '%s' '%s'...\n",
  8563. x->b_cmd, argv_expanded[1]);
  8564. fflush_all();
  8565. rcode = x->b_function(argv_expanded) & 0xff;
  8566. fflush_all();
  8567. }
  8568. #if ENABLE_HUSH_FUNCTIONS
  8569. else {
  8570. debug_printf_exec(": function '%s' '%s'...\n",
  8571. funcp->name, argv_expanded[1]);
  8572. rcode = run_function(funcp, argv_expanded) & 0xff;
  8573. /*
  8574. * But do collect *to old_vars list* vars shadowed
  8575. * within function execution. To that end, restore
  8576. * this pointer _after_ function run:
  8577. */
  8578. G.shadowed_vars_pp = sv_shadowed;
  8579. }
  8580. #endif
  8581. }
  8582. } else
  8583. if (ENABLE_FEATURE_SH_NOFORK && NUM_APPLETS > 1) {
  8584. int n = find_applet_by_name(argv_expanded[0]);
  8585. if (n < 0 || !APPLET_IS_NOFORK(n))
  8586. goto must_fork;
  8587. enter_var_nest_level();
  8588. /* Collect all variables "shadowed" by helper into old_vars list */
  8589. G.shadowed_vars_pp = &old_vars;
  8590. rcode = redirect_and_varexp_helper(command, &squirrel, argv_expanded);
  8591. G.shadowed_vars_pp = sv_shadowed;
  8592. if (rcode == 0) {
  8593. debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
  8594. argv_expanded[0], argv_expanded[1]);
  8595. /*
  8596. * Note: signals (^C) can't interrupt here.
  8597. * We remember them and they will be acted upon
  8598. * after applet returns.
  8599. * This makes applets which can run for a long time
  8600. * and/or wait for user input ineligible for NOFORK:
  8601. * for example, "yes" or "rm" (rm -i waits for input).
  8602. */
  8603. rcode = run_nofork_applet(n, argv_expanded);
  8604. }
  8605. } else
  8606. goto must_fork;
  8607. restore_redirects(squirrel);
  8608. clean_up_and_ret1:
  8609. leave_var_nest_level();
  8610. add_vars(old_vars);
  8611. /*
  8612. * Try "usleep 99999999" + ^C + "echo $?"
  8613. * with FEATURE_SH_NOFORK=y.
  8614. */
  8615. if (!funcp) {
  8616. /* It was builtin or nofork.
  8617. * if this would be a real fork/execed program,
  8618. * it should have died if a fatal sig was received.
  8619. * But OTOH, there was no separate process,
  8620. * the sig was sent to _shell_, not to non-existing
  8621. * child.
  8622. * Let's just handle ^C only, this one is obvious:
  8623. * we aren't ok with exitcode 0 when ^C was pressed
  8624. * during builtin/nofork.
  8625. */
  8626. if (sigismember(&G.pending_set, SIGINT))
  8627. rcode = 128 + SIGINT;
  8628. }
  8629. free(argv_expanded);
  8630. IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
  8631. debug_leave();
  8632. debug_printf_exec("run_pipe return %d\n", rcode);
  8633. return rcode;
  8634. }
  8635. must_fork:
  8636. /* NB: argv_expanded may already be created, and that
  8637. * might include `cmd` runs! Do not rerun it! We *must*
  8638. * use argv_expanded if it's non-NULL */
  8639. /* Going to fork a child per each pipe member */
  8640. pi->alive_cmds = 0;
  8641. next_infd = 0;
  8642. cmd_no = 0;
  8643. while (cmd_no < pi->num_cmds) {
  8644. struct fd_pair pipefds;
  8645. #if !BB_MMU
  8646. int sv_var_nest_level = G.var_nest_level;
  8647. volatile nommu_save_t nommu_save;
  8648. nommu_save.old_vars = NULL;
  8649. nommu_save.argv = NULL;
  8650. nommu_save.argv_from_re_execing = NULL;
  8651. #endif
  8652. command = &pi->cmds[cmd_no];
  8653. cmd_no++;
  8654. if (command->argv) {
  8655. debug_printf_exec(": pipe member '%s' '%s'...\n",
  8656. command->argv[0], command->argv[1]);
  8657. } else {
  8658. debug_printf_exec(": pipe member with no argv\n");
  8659. }
  8660. /* pipes are inserted between pairs of commands */
  8661. pipefds.rd = 0;
  8662. pipefds.wr = 1;
  8663. if (cmd_no < pi->num_cmds)
  8664. xpiped_pair(pipefds);
  8665. #if ENABLE_HUSH_LINENO_VAR
  8666. G.execute_lineno = command->lineno;
  8667. #endif
  8668. command->pid = BB_MMU ? fork() : vfork();
  8669. if (!command->pid) { /* child */
  8670. #if ENABLE_HUSH_JOB
  8671. disable_restore_tty_pgrp_on_exit();
  8672. CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
  8673. /* Every child adds itself to new process group
  8674. * with pgid == pid_of_first_child_in_pipe */
  8675. if (G.run_list_level == 1 && G_interactive_fd) {
  8676. pid_t pgrp;
  8677. pgrp = pi->pgrp;
  8678. if (pgrp < 0) /* true for 1st process only */
  8679. pgrp = getpid();
  8680. if (setpgid(0, pgrp) == 0
  8681. && pi->followup != PIPE_BG
  8682. && G_saved_tty_pgrp /* we have ctty */
  8683. ) {
  8684. /* We do it in *every* child, not just first,
  8685. * to avoid races */
  8686. tcsetpgrp(G_interactive_fd, pgrp);
  8687. }
  8688. }
  8689. #endif
  8690. if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
  8691. /* 1st cmd in backgrounded pipe
  8692. * should have its stdin /dev/null'ed */
  8693. close(0);
  8694. if (open(bb_dev_null, O_RDONLY))
  8695. xopen("/", O_RDONLY);
  8696. } else {
  8697. xmove_fd(next_infd, 0);
  8698. }
  8699. xmove_fd(pipefds.wr, 1);
  8700. if (pipefds.rd > 1)
  8701. close(pipefds.rd);
  8702. /* Like bash, explicit redirects override pipes,
  8703. * and the pipe fd (fd#1) is available for dup'ing:
  8704. * "cmd1 2>&1 | cmd2": fd#1 is duped to fd#2, thus stderr
  8705. * of cmd1 goes into pipe.
  8706. */
  8707. if (setup_redirects(command, NULL)) {
  8708. /* Happens when redir file can't be opened:
  8709. * $ hush -c 'echo FOO >&2 | echo BAR 3>/qwe/rty; echo BAZ'
  8710. * FOO
  8711. * hush: can't open '/qwe/rty': No such file or directory
  8712. * BAZ
  8713. * (echo BAR is not executed, it hits _exit(1) below)
  8714. */
  8715. _exit(1);
  8716. }
  8717. /* Stores to nommu_save list of env vars putenv'ed
  8718. * (NOMMU, on MMU we don't need that) */
  8719. /* cast away volatility... */
  8720. pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
  8721. /* pseudo_exec() does not return */
  8722. }
  8723. /* parent or error */
  8724. #if ENABLE_HUSH_FAST
  8725. G.count_SIGCHLD++;
  8726. //bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
  8727. #endif
  8728. enable_restore_tty_pgrp_on_exit();
  8729. #if !BB_MMU
  8730. /* Clean up after vforked child */
  8731. free(nommu_save.argv);
  8732. free(nommu_save.argv_from_re_execing);
  8733. G.var_nest_level = sv_var_nest_level;
  8734. remove_nested_vars();
  8735. add_vars(nommu_save.old_vars);
  8736. #endif
  8737. free(argv_expanded);
  8738. argv_expanded = NULL;
  8739. if (command->pid < 0) { /* [v]fork failed */
  8740. /* Clearly indicate, was it fork or vfork */
  8741. bb_simple_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
  8742. } else {
  8743. pi->alive_cmds++;
  8744. #if ENABLE_HUSH_JOB
  8745. /* Second and next children need to know pid of first one */
  8746. if (pi->pgrp < 0)
  8747. pi->pgrp = command->pid;
  8748. #endif
  8749. }
  8750. if (cmd_no > 1)
  8751. close(next_infd);
  8752. if (cmd_no < pi->num_cmds)
  8753. close(pipefds.wr);
  8754. /* Pass read (output) pipe end to next iteration */
  8755. next_infd = pipefds.rd;
  8756. }
  8757. if (!pi->alive_cmds) {
  8758. debug_leave();
  8759. debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
  8760. return 1;
  8761. }
  8762. debug_leave();
  8763. debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
  8764. return -1;
  8765. }
  8766. /* NB: called by pseudo_exec, and therefore must not modify any
  8767. * global data until exec/_exit (we can be a child after vfork!) */
  8768. static int run_list(struct pipe *pi)
  8769. {
  8770. #if ENABLE_HUSH_CASE
  8771. char *case_word = NULL;
  8772. #endif
  8773. #if ENABLE_HUSH_LOOPS
  8774. struct pipe *loop_top = NULL;
  8775. char **for_lcur = NULL;
  8776. char **for_list = NULL;
  8777. #endif
  8778. smallint last_followup;
  8779. smalluint rcode;
  8780. #if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
  8781. smalluint cond_code = 0;
  8782. #else
  8783. enum { cond_code = 0 };
  8784. #endif
  8785. #if HAS_KEYWORDS
  8786. smallint rword; /* RES_foo */
  8787. smallint last_rword; /* ditto */
  8788. #endif
  8789. debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
  8790. debug_enter();
  8791. #if ENABLE_HUSH_LOOPS
  8792. /* Check syntax for "for" */
  8793. {
  8794. struct pipe *cpipe;
  8795. for (cpipe = pi; cpipe; cpipe = cpipe->next) {
  8796. if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
  8797. continue;
  8798. /* current word is FOR or IN (BOLD in comments below) */
  8799. if (cpipe->next == NULL) {
  8800. syntax_error("malformed for");
  8801. debug_leave();
  8802. debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
  8803. return 1;
  8804. }
  8805. /* "FOR v; do ..." and "for v IN a b; do..." are ok */
  8806. if (cpipe->next->res_word == RES_DO)
  8807. continue;
  8808. /* next word is not "do". It must be "in" then ("FOR v in ...") */
  8809. if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
  8810. || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
  8811. ) {
  8812. syntax_error("malformed for");
  8813. debug_leave();
  8814. debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
  8815. return 1;
  8816. }
  8817. }
  8818. }
  8819. #endif
  8820. /* Past this point, all code paths should jump to ret: label
  8821. * in order to return, no direct "return" statements please.
  8822. * This helps to ensure that no memory is leaked. */
  8823. #if ENABLE_HUSH_JOB
  8824. G.run_list_level++;
  8825. #endif
  8826. #if HAS_KEYWORDS
  8827. rword = RES_NONE;
  8828. last_rword = RES_XXXX;
  8829. #endif
  8830. last_followup = PIPE_SEQ;
  8831. rcode = G.last_exitcode;
  8832. /* Go through list of pipes, (maybe) executing them. */
  8833. for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
  8834. int r;
  8835. int sv_errexit_depth;
  8836. if (G.flag_SIGINT)
  8837. break;
  8838. if (G_flag_return_in_progress == 1)
  8839. break;
  8840. IF_HAS_KEYWORDS(rword = pi->res_word;)
  8841. debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
  8842. rword, cond_code, last_rword);
  8843. sv_errexit_depth = G.errexit_depth;
  8844. if (
  8845. #if ENABLE_HUSH_IF
  8846. rword == RES_IF || rword == RES_ELIF ||
  8847. #endif
  8848. pi->followup != PIPE_SEQ
  8849. ) {
  8850. G.errexit_depth++;
  8851. }
  8852. #if ENABLE_HUSH_LOOPS
  8853. if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
  8854. && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
  8855. ) {
  8856. /* start of a loop: remember where loop starts */
  8857. loop_top = pi;
  8858. G.depth_of_loop++;
  8859. }
  8860. #endif
  8861. /* Still in the same "if...", "then..." or "do..." branch? */
  8862. if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
  8863. if ((rcode == 0 && last_followup == PIPE_OR)
  8864. || (rcode != 0 && last_followup == PIPE_AND)
  8865. ) {
  8866. /* It is "<true> || CMD" or "<false> && CMD"
  8867. * and we should not execute CMD */
  8868. debug_printf_exec("skipped cmd because of || or &&\n");
  8869. last_followup = pi->followup;
  8870. goto dont_check_jobs_but_continue;
  8871. }
  8872. }
  8873. last_followup = pi->followup;
  8874. IF_HAS_KEYWORDS(last_rword = rword;)
  8875. #if ENABLE_HUSH_IF
  8876. if (cond_code) {
  8877. if (rword == RES_THEN) {
  8878. /* if false; then ... fi has exitcode 0! */
  8879. G.last_exitcode = rcode = EXIT_SUCCESS;
  8880. /* "if <false> THEN cmd": skip cmd */
  8881. continue;
  8882. }
  8883. } else {
  8884. if (rword == RES_ELSE || rword == RES_ELIF) {
  8885. /* "if <true> then ... ELSE/ELIF cmd":
  8886. * skip cmd and all following ones */
  8887. break;
  8888. }
  8889. }
  8890. #endif
  8891. #if ENABLE_HUSH_LOOPS
  8892. if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
  8893. if (!for_lcur) {
  8894. /* first loop through for */
  8895. static const char encoded_dollar_at[] ALIGN1 = {
  8896. SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
  8897. }; /* encoded representation of "$@" */
  8898. static const char *const encoded_dollar_at_argv[] = {
  8899. encoded_dollar_at, NULL
  8900. }; /* argv list with one element: "$@" */
  8901. char **vals;
  8902. G.last_exitcode = rcode = EXIT_SUCCESS;
  8903. vals = (char**)encoded_dollar_at_argv;
  8904. if (pi->next->res_word == RES_IN) {
  8905. /* if no variable values after "in" we skip "for" */
  8906. if (!pi->next->cmds[0].argv) {
  8907. debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
  8908. break;
  8909. }
  8910. vals = pi->next->cmds[0].argv;
  8911. } /* else: "for var; do..." -> assume "$@" list */
  8912. /* create list of variable values */
  8913. debug_print_strings("for_list made from", vals);
  8914. for_list = expand_strvec_to_strvec(vals);
  8915. for_lcur = for_list;
  8916. debug_print_strings("for_list", for_list);
  8917. }
  8918. if (!*for_lcur) {
  8919. /* "for" loop is over, clean up */
  8920. free(for_list);
  8921. for_list = NULL;
  8922. for_lcur = NULL;
  8923. break;
  8924. }
  8925. /* Insert next value from for_lcur */
  8926. /* note: *for_lcur already has quotes removed, $var expanded, etc */
  8927. set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*flag:*/ 0);
  8928. continue;
  8929. }
  8930. if (rword == RES_IN) {
  8931. continue; /* "for v IN list;..." - "in" has no cmds anyway */
  8932. }
  8933. if (rword == RES_DONE) {
  8934. continue; /* "done" has no cmds too */
  8935. }
  8936. #endif
  8937. #if ENABLE_HUSH_CASE
  8938. if (rword == RES_CASE) {
  8939. debug_printf_exec("CASE cond_code:%d\n", cond_code);
  8940. case_word = expand_string_to_string(pi->cmds->argv[0],
  8941. EXP_FLAG_ESC_GLOB_CHARS, /*unbackslash:*/ 1);
  8942. debug_printf_exec("CASE word1:'%s'\n", case_word);
  8943. //unbackslash(case_word);
  8944. //debug_printf_exec("CASE word2:'%s'\n", case_word);
  8945. continue;
  8946. }
  8947. if (rword == RES_MATCH) {
  8948. char **argv;
  8949. debug_printf_exec("MATCH cond_code:%d\n", cond_code);
  8950. if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
  8951. break;
  8952. /* all prev words didn't match, does this one match? */
  8953. argv = pi->cmds->argv;
  8954. while (*argv) {
  8955. char *pattern;
  8956. debug_printf_exec("expand_string_to_string('%s')\n", *argv);
  8957. pattern = expand_string_to_string(*argv,
  8958. EXP_FLAG_ESC_GLOB_CHARS,
  8959. /*unbackslash:*/ 0
  8960. );
  8961. /* TODO: which FNM_xxx flags to use? */
  8962. cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
  8963. debug_printf_exec("fnmatch(pattern:'%s',str:'%s'):%d\n",
  8964. pattern, case_word, cond_code);
  8965. free(pattern);
  8966. if (cond_code == 0) {
  8967. /* match! we will execute this branch */
  8968. free(case_word);
  8969. case_word = NULL; /* make future "word)" stop */
  8970. break;
  8971. }
  8972. argv++;
  8973. }
  8974. continue;
  8975. }
  8976. if (rword == RES_CASE_BODY) { /* inside of a case branch */
  8977. debug_printf_exec("CASE_BODY cond_code:%d\n", cond_code);
  8978. if (cond_code != 0)
  8979. continue; /* not matched yet, skip this pipe */
  8980. }
  8981. if (rword == RES_ESAC) {
  8982. debug_printf_exec("ESAC cond_code:%d\n", cond_code);
  8983. if (case_word) {
  8984. /* "case" did not match anything: still set $? (to 0) */
  8985. G.last_exitcode = rcode = EXIT_SUCCESS;
  8986. }
  8987. }
  8988. #endif
  8989. /* Just pressing <enter> in shell should check for jobs.
  8990. * OTOH, in non-interactive shell this is useless
  8991. * and only leads to extra job checks */
  8992. if (pi->num_cmds == 0) {
  8993. if (G_interactive_fd)
  8994. goto check_jobs_and_continue;
  8995. continue;
  8996. }
  8997. /* After analyzing all keywords and conditions, we decided
  8998. * to execute this pipe. NB: have to do checkjobs(NULL)
  8999. * after run_pipe to collect any background children,
  9000. * even if list execution is to be stopped. */
  9001. debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
  9002. #if ENABLE_HUSH_LOOPS
  9003. G.flag_break_continue = 0;
  9004. #endif
  9005. rcode = r = run_pipe(pi); /* NB: rcode is a smalluint, r is int */
  9006. if (r != -1) {
  9007. /* We ran a builtin, function, or group.
  9008. * rcode is already known
  9009. * and we don't need to wait for anything. */
  9010. debug_printf_exec(": builtin/func exitcode %d\n", rcode);
  9011. G.last_exitcode = rcode;
  9012. check_and_run_traps();
  9013. #if ENABLE_HUSH_TRAP && ENABLE_HUSH_FUNCTIONS
  9014. rcode = G.last_exitcode; /* "return" in trap can change it, read back */
  9015. #endif
  9016. #if ENABLE_HUSH_LOOPS
  9017. /* Was it "break" or "continue"? */
  9018. if (G.flag_break_continue) {
  9019. smallint fbc = G.flag_break_continue;
  9020. /* We might fall into outer *loop*,
  9021. * don't want to break it too */
  9022. if (loop_top) {
  9023. G.depth_break_continue--;
  9024. if (G.depth_break_continue == 0)
  9025. G.flag_break_continue = 0;
  9026. /* else: e.g. "continue 2" should *break* once, *then* continue */
  9027. } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
  9028. if (G.depth_break_continue != 0 || fbc == BC_BREAK) {
  9029. checkjobs(NULL, 0 /*(no pid to wait for)*/);
  9030. break;
  9031. }
  9032. /* "continue": simulate end of loop */
  9033. rword = RES_DONE;
  9034. continue;
  9035. }
  9036. #endif
  9037. if (G_flag_return_in_progress == 1) {
  9038. checkjobs(NULL, 0 /*(no pid to wait for)*/);
  9039. break;
  9040. }
  9041. } else if (pi->followup == PIPE_BG) {
  9042. /* What does bash do with attempts to background builtins? */
  9043. /* even bash 3.2 doesn't do that well with nested bg:
  9044. * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
  9045. * I'm NOT treating inner &'s as jobs */
  9046. #if ENABLE_HUSH_JOB
  9047. if (G.run_list_level == 1)
  9048. insert_job_into_table(pi);
  9049. #endif
  9050. /* Last command's pid goes to $! */
  9051. G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
  9052. G.last_bg_pid_exitcode = 0;
  9053. debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
  9054. /* Check pi->pi_inverted? "! sleep 1 & echo $?": bash says 1. dash and ash say 0 */
  9055. rcode = EXIT_SUCCESS;
  9056. goto check_traps;
  9057. } else {
  9058. #if ENABLE_HUSH_JOB
  9059. if (G.run_list_level == 1 && G_interactive_fd) {
  9060. /* Waits for completion, then fg's main shell */
  9061. rcode = checkjobs_and_fg_shell(pi);
  9062. debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
  9063. goto check_traps;
  9064. }
  9065. #endif
  9066. /* This one just waits for completion */
  9067. rcode = checkjobs(pi, 0 /*(no pid to wait for)*/);
  9068. debug_printf_exec(": checkjobs exitcode %d\n", rcode);
  9069. check_traps:
  9070. G.last_exitcode = rcode;
  9071. check_and_run_traps();
  9072. #if ENABLE_HUSH_TRAP && ENABLE_HUSH_FUNCTIONS
  9073. rcode = G.last_exitcode; /* "return" in trap can change it, read back */
  9074. #endif
  9075. }
  9076. /* Handle "set -e" */
  9077. if (rcode != 0 && G.o_opt[OPT_O_ERREXIT]) {
  9078. debug_printf_exec("ERREXIT:1 errexit_depth:%d\n", G.errexit_depth);
  9079. if (G.errexit_depth == 0)
  9080. hush_exit(rcode);
  9081. }
  9082. G.errexit_depth = sv_errexit_depth;
  9083. /* Analyze how result affects subsequent commands */
  9084. #if ENABLE_HUSH_IF
  9085. if (rword == RES_IF || rword == RES_ELIF)
  9086. cond_code = rcode;
  9087. #endif
  9088. check_jobs_and_continue:
  9089. checkjobs(NULL, 0 /*(no pid to wait for)*/);
  9090. dont_check_jobs_but_continue: ;
  9091. #if ENABLE_HUSH_LOOPS
  9092. /* Beware of "while false; true; do ..."! */
  9093. if (pi->next
  9094. && (pi->next->res_word == RES_DO || pi->next->res_word == RES_DONE)
  9095. /* check for RES_DONE is needed for "while ...; do \n done" case */
  9096. ) {
  9097. if (rword == RES_WHILE) {
  9098. if (rcode) {
  9099. /* "while false; do...done" - exitcode 0 */
  9100. G.last_exitcode = rcode = EXIT_SUCCESS;
  9101. debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
  9102. break;
  9103. }
  9104. }
  9105. if (rword == RES_UNTIL) {
  9106. if (!rcode) {
  9107. debug_printf_exec(": until expr is true: breaking\n");
  9108. break;
  9109. }
  9110. }
  9111. }
  9112. #endif
  9113. } /* for (pi) */
  9114. #if ENABLE_HUSH_JOB
  9115. G.run_list_level--;
  9116. #endif
  9117. #if ENABLE_HUSH_LOOPS
  9118. if (loop_top)
  9119. G.depth_of_loop--;
  9120. free(for_list);
  9121. #endif
  9122. #if ENABLE_HUSH_CASE
  9123. free(case_word);
  9124. #endif
  9125. debug_leave();
  9126. debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
  9127. return rcode;
  9128. }
  9129. /* Select which version we will use */
  9130. static int run_and_free_list(struct pipe *pi)
  9131. {
  9132. int rcode = 0;
  9133. debug_printf_exec("run_and_free_list entered\n");
  9134. if (!G.o_opt[OPT_O_NOEXEC]) {
  9135. debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
  9136. rcode = run_list(pi);
  9137. }
  9138. /* free_pipe_list has the side effect of clearing memory.
  9139. * In the long run that function can be merged with run_list,
  9140. * but doing that now would hobble the debugging effort. */
  9141. free_pipe_list(pi);
  9142. debug_printf_exec("run_and_free_list return %d\n", rcode);
  9143. return rcode;
  9144. }
  9145. static void install_sighandlers(unsigned mask)
  9146. {
  9147. sighandler_t old_handler;
  9148. unsigned sig = 0;
  9149. while ((mask >>= 1) != 0) {
  9150. sig++;
  9151. if (!(mask & 1))
  9152. continue;
  9153. old_handler = install_sighandler(sig, pick_sighandler(sig));
  9154. /* POSIX allows shell to re-enable SIGCHLD
  9155. * even if it was SIG_IGN on entry.
  9156. * Therefore we skip IGN check for it:
  9157. */
  9158. if (sig == SIGCHLD)
  9159. continue;
  9160. /* Interactive bash re-enables SIGHUP which is SIG_IGNed on entry.
  9161. * Try:
  9162. * trap '' hup; bash; echo RET # type "kill -hup $$", see SIGHUP having effect
  9163. * trap '' hup; bash -c 'kill -hup $$; echo ALIVE' # here SIGHUP is SIG_IGNed
  9164. */
  9165. if (sig == SIGHUP && G_interactive_fd)
  9166. continue;
  9167. /* Unless one of the above signals, is it SIG_IGN? */
  9168. if (old_handler == SIG_IGN) {
  9169. /* oops... restore back to IGN, and record this fact */
  9170. install_sighandler(sig, old_handler);
  9171. #if ENABLE_HUSH_TRAP
  9172. if (!G_traps)
  9173. G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
  9174. free(G_traps[sig]);
  9175. G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
  9176. #endif
  9177. }
  9178. }
  9179. }
  9180. /* Called a few times only (or even once if "sh -c") */
  9181. static void install_special_sighandlers(void)
  9182. {
  9183. unsigned mask;
  9184. /* Which signals are shell-special? */
  9185. mask = (1 << SIGQUIT) | (1 << SIGCHLD);
  9186. if (G_interactive_fd) {
  9187. mask |= SPECIAL_INTERACTIVE_SIGS;
  9188. if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
  9189. mask |= SPECIAL_JOBSTOP_SIGS;
  9190. }
  9191. /* Careful, do not re-install handlers we already installed */
  9192. if (G.special_sig_mask != mask) {
  9193. unsigned diff = mask & ~G.special_sig_mask;
  9194. G.special_sig_mask = mask;
  9195. install_sighandlers(diff);
  9196. }
  9197. }
  9198. #if ENABLE_HUSH_JOB
  9199. /* helper */
  9200. /* Set handlers to restore tty pgrp and exit */
  9201. static void install_fatal_sighandlers(void)
  9202. {
  9203. unsigned mask;
  9204. /* We will restore tty pgrp on these signals */
  9205. mask = 0
  9206. /*+ (1 << SIGILL ) * HUSH_DEBUG*/
  9207. /*+ (1 << SIGFPE ) * HUSH_DEBUG*/
  9208. + (1 << SIGBUS ) * HUSH_DEBUG
  9209. + (1 << SIGSEGV) * HUSH_DEBUG
  9210. /*+ (1 << SIGTRAP) * HUSH_DEBUG*/
  9211. + (1 << SIGABRT)
  9212. /* bash 3.2 seems to handle these just like 'fatal' ones */
  9213. + (1 << SIGPIPE)
  9214. + (1 << SIGALRM)
  9215. /* if we are interactive, SIGHUP, SIGTERM and SIGINT are special sigs.
  9216. * if we aren't interactive... but in this case
  9217. * we never want to restore pgrp on exit, and this fn is not called
  9218. */
  9219. /*+ (1 << SIGHUP )*/
  9220. /*+ (1 << SIGTERM)*/
  9221. /*+ (1 << SIGINT )*/
  9222. ;
  9223. G_fatal_sig_mask = mask;
  9224. install_sighandlers(mask);
  9225. }
  9226. #endif
  9227. static int set_mode(int state, char mode, const char *o_opt)
  9228. {
  9229. int idx;
  9230. switch (mode) {
  9231. case 'n':
  9232. G.o_opt[OPT_O_NOEXEC] = state;
  9233. break;
  9234. case 'x':
  9235. IF_HUSH_MODE_X(G_x_mode = state;)
  9236. IF_HUSH_MODE_X(if (G.x_mode_fd <= 0) G.x_mode_fd = dup_CLOEXEC(2, 10);)
  9237. break;
  9238. case 'e':
  9239. G.o_opt[OPT_O_ERREXIT] = state;
  9240. break;
  9241. case 'o':
  9242. if (!o_opt) {
  9243. /* "set -o" or "set +o" without parameter.
  9244. * in bash, set -o produces this output:
  9245. * pipefail off
  9246. * and set +o:
  9247. * set +o pipefail
  9248. * We always use the second form.
  9249. */
  9250. const char *p = o_opt_strings;
  9251. idx = 0;
  9252. while (*p) {
  9253. printf("set %co %s\n", (G.o_opt[idx] ? '-' : '+'), p);
  9254. idx++;
  9255. p += strlen(p) + 1;
  9256. }
  9257. break;
  9258. }
  9259. idx = index_in_strings(o_opt_strings, o_opt);
  9260. if (idx >= 0) {
  9261. G.o_opt[idx] = state;
  9262. break;
  9263. }
  9264. /* fall through to error */
  9265. default:
  9266. return EXIT_FAILURE;
  9267. }
  9268. return EXIT_SUCCESS;
  9269. }
  9270. int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  9271. int hush_main(int argc, char **argv)
  9272. {
  9273. enum {
  9274. OPT_login = (1 << 0),
  9275. };
  9276. unsigned flags;
  9277. unsigned builtin_argc;
  9278. char **e;
  9279. struct variable *cur_var;
  9280. struct variable *shell_ver;
  9281. INIT_G();
  9282. if (EXIT_SUCCESS != 0) /* if EXIT_SUCCESS == 0, it is already done */
  9283. G.last_exitcode = EXIT_SUCCESS;
  9284. #if ENABLE_HUSH_TRAP
  9285. # if ENABLE_HUSH_FUNCTIONS
  9286. G.return_exitcode = -1;
  9287. # endif
  9288. G.pre_trap_exitcode = -1;
  9289. #endif
  9290. #if ENABLE_HUSH_FAST
  9291. G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
  9292. #endif
  9293. #if !BB_MMU
  9294. G.argv0_for_re_execing = argv[0];
  9295. #endif
  9296. /* Deal with HUSH_VERSION */
  9297. debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
  9298. unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
  9299. shell_ver = xzalloc(sizeof(*shell_ver));
  9300. shell_ver->flg_export = 1;
  9301. shell_ver->flg_read_only = 1;
  9302. /* Code which handles ${var<op>...} needs writable values for all variables,
  9303. * therefore we xstrdup: */
  9304. shell_ver->varstr = xstrdup(hush_version_str);
  9305. /* Create shell local variables from the values
  9306. * currently living in the environment */
  9307. G.top_var = shell_ver;
  9308. cur_var = G.top_var;
  9309. e = environ;
  9310. if (e) while (*e) {
  9311. char *value = strchr(*e, '=');
  9312. if (value) { /* paranoia */
  9313. cur_var->next = xzalloc(sizeof(*cur_var));
  9314. cur_var = cur_var->next;
  9315. cur_var->varstr = *e;
  9316. cur_var->max_len = strlen(*e);
  9317. cur_var->flg_export = 1;
  9318. }
  9319. e++;
  9320. }
  9321. /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
  9322. debug_printf_env("putenv '%s'\n", shell_ver->varstr);
  9323. putenv(shell_ver->varstr);
  9324. /* Export PWD */
  9325. set_pwd_var(SETFLAG_EXPORT);
  9326. #if BASH_HOSTNAME_VAR
  9327. /* Set (but not export) HOSTNAME unless already set */
  9328. if (!get_local_var_value("HOSTNAME")) {
  9329. struct utsname uts;
  9330. uname(&uts);
  9331. set_local_var_from_halves("HOSTNAME", uts.nodename);
  9332. }
  9333. #endif
  9334. /* IFS is not inherited from the parent environment */
  9335. set_local_var_from_halves("IFS", defifs);
  9336. if (!get_local_var_value("PATH"))
  9337. set_local_var_from_halves("PATH", bb_default_root_path);
  9338. /* PS1/PS2 are set later, if we determine that we are interactive */
  9339. /* bash also exports SHLVL and _,
  9340. * and sets (but doesn't export) the following variables:
  9341. * BASH=/bin/bash
  9342. * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
  9343. * BASH_VERSION='3.2.0(1)-release'
  9344. * HOSTTYPE=i386
  9345. * MACHTYPE=i386-pc-linux-gnu
  9346. * OSTYPE=linux-gnu
  9347. * PPID=<NNNNN> - we also do it elsewhere
  9348. * EUID=<NNNNN>
  9349. * UID=<NNNNN>
  9350. * GROUPS=()
  9351. * LINES=<NNN>
  9352. * COLUMNS=<NNN>
  9353. * BASH_ARGC=()
  9354. * BASH_ARGV=()
  9355. * BASH_LINENO=()
  9356. * BASH_SOURCE=()
  9357. * DIRSTACK=()
  9358. * PIPESTATUS=([0]="0")
  9359. * HISTFILE=/<xxx>/.bash_history
  9360. * HISTFILESIZE=500
  9361. * HISTSIZE=500
  9362. * MAILCHECK=60
  9363. * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
  9364. * SHELL=/bin/bash
  9365. * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
  9366. * TERM=dumb
  9367. * OPTERR=1
  9368. * OPTIND=1
  9369. * PS4='+ '
  9370. */
  9371. /* Initialize some more globals to non-zero values */
  9372. die_func = restore_ttypgrp_and__exit;
  9373. /* Shell is non-interactive at first. We need to call
  9374. * install_special_sighandlers() if we are going to execute "sh <script>",
  9375. * "sh -c <cmds>" or login shell's /etc/profile and friends.
  9376. * If we later decide that we are interactive, we run install_special_sighandlers()
  9377. * in order to intercept (more) signals.
  9378. */
  9379. /* Parse options */
  9380. /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
  9381. flags = (argv[0] && argv[0][0] == '-') ? OPT_login : 0;
  9382. builtin_argc = 0;
  9383. #if NUM_SCRIPTS > 0
  9384. if (argc < 0) {
  9385. optarg = get_script_content(-argc - 1);
  9386. optind = 0;
  9387. argc = string_array_len(argv);
  9388. goto run_script;
  9389. }
  9390. #endif
  9391. while (1) {
  9392. int opt = getopt(argc, argv, "+c:exinsl"
  9393. #if !BB_MMU
  9394. "<:$:R:V:"
  9395. # if ENABLE_HUSH_FUNCTIONS
  9396. "F:"
  9397. # endif
  9398. #endif
  9399. );
  9400. if (opt <= 0)
  9401. break;
  9402. switch (opt) {
  9403. case 'c':
  9404. /* Possibilities:
  9405. * sh ... -c 'script'
  9406. * sh ... -c 'script' ARG0 [ARG1...]
  9407. * On NOMMU, if builtin_argc != 0,
  9408. * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
  9409. * "" needs to be replaced with NULL
  9410. * and BARGV vector fed to builtin function.
  9411. * Note: the form without ARG0 never happens:
  9412. * sh ... -c 'builtin' BARGV... ""
  9413. */
  9414. #if NUM_SCRIPTS > 0
  9415. run_script:
  9416. #endif
  9417. if (!G.root_pid) {
  9418. G.root_pid = getpid();
  9419. G.root_ppid = getppid();
  9420. }
  9421. G.global_argv = argv + optind;
  9422. G.global_argc = argc - optind;
  9423. if (builtin_argc) {
  9424. /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
  9425. const struct built_in_command *x;
  9426. install_special_sighandlers();
  9427. x = find_builtin(optarg);
  9428. if (x) { /* paranoia */
  9429. G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
  9430. G.global_argv += builtin_argc;
  9431. G.global_argv[-1] = NULL; /* replace "" */
  9432. fflush_all();
  9433. G.last_exitcode = x->b_function(argv + optind - 1);
  9434. }
  9435. goto final_return;
  9436. }
  9437. G.opt_c = 1;
  9438. if (!G.global_argv[0]) {
  9439. /* -c 'script' (no params): prevent empty $0 */
  9440. G.global_argv--; /* points to argv[i] of 'script' */
  9441. G.global_argv[0] = argv[0];
  9442. G.global_argc++;
  9443. } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
  9444. install_special_sighandlers();
  9445. parse_and_run_string(optarg);
  9446. goto final_return;
  9447. case 'i':
  9448. /* Well, we cannot just declare interactiveness,
  9449. * we have to have some stuff (ctty, etc) */
  9450. /* G_interactive_fd++; */
  9451. break;
  9452. case 's':
  9453. G.opt_s = 1;
  9454. break;
  9455. case 'l':
  9456. flags |= OPT_login;
  9457. break;
  9458. #if !BB_MMU
  9459. case '<': /* "big heredoc" support */
  9460. full_write1_str(optarg);
  9461. _exit(0);
  9462. case '$': {
  9463. unsigned long long empty_trap_mask;
  9464. G.root_pid = bb_strtou(optarg, &optarg, 16);
  9465. optarg++;
  9466. G.root_ppid = bb_strtou(optarg, &optarg, 16);
  9467. optarg++;
  9468. G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
  9469. optarg++;
  9470. G.last_exitcode = bb_strtou(optarg, &optarg, 16);
  9471. optarg++;
  9472. builtin_argc = bb_strtou(optarg, &optarg, 16);
  9473. optarg++;
  9474. empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
  9475. if (empty_trap_mask != 0) {
  9476. IF_HUSH_TRAP(int sig;)
  9477. install_special_sighandlers();
  9478. # if ENABLE_HUSH_TRAP
  9479. G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
  9480. for (sig = 1; sig < NSIG; sig++) {
  9481. if (empty_trap_mask & (1LL << sig)) {
  9482. G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
  9483. install_sighandler(sig, SIG_IGN);
  9484. }
  9485. }
  9486. # endif
  9487. }
  9488. # if ENABLE_HUSH_LOOPS
  9489. optarg++;
  9490. G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
  9491. # endif
  9492. # if ENABLE_HUSH_FUNCTIONS
  9493. /* nommu uses re-exec trick for "... | func | ...",
  9494. * should allow "return".
  9495. * This accidentally allows returns in subshells.
  9496. */
  9497. G_flag_return_in_progress = -1;
  9498. # endif
  9499. break;
  9500. }
  9501. case 'R':
  9502. case 'V':
  9503. set_local_var(xstrdup(optarg), opt == 'R' ? SETFLAG_MAKE_RO : 0);
  9504. break;
  9505. # if ENABLE_HUSH_FUNCTIONS
  9506. case 'F': {
  9507. struct function *funcp = new_function(optarg);
  9508. /* funcp->name is already set to optarg */
  9509. /* funcp->body is set to NULL. It's a special case. */
  9510. funcp->body_as_string = argv[optind];
  9511. optind++;
  9512. break;
  9513. }
  9514. # endif
  9515. #endif
  9516. case 'n':
  9517. case 'x':
  9518. case 'e':
  9519. if (set_mode(1, opt, NULL) == 0) /* no error */
  9520. break;
  9521. default:
  9522. #ifndef BB_VER
  9523. fprintf(stderr, "Usage: sh [FILE]...\n"
  9524. " or: sh -c command [args]...\n\n");
  9525. exit(EXIT_FAILURE);
  9526. #else
  9527. bb_show_usage();
  9528. #endif
  9529. }
  9530. } /* option parsing loop */
  9531. /* Skip options. Try "hush -l": $1 should not be "-l"! */
  9532. G.global_argc = argc - (optind - 1);
  9533. G.global_argv = argv + (optind - 1);
  9534. G.global_argv[0] = argv[0];
  9535. if (!G.root_pid) {
  9536. G.root_pid = getpid();
  9537. G.root_ppid = getppid();
  9538. }
  9539. /* If we are login shell... */
  9540. if (flags & OPT_login) {
  9541. HFILE *input;
  9542. debug_printf("sourcing /etc/profile\n");
  9543. input = hfopen("/etc/profile");
  9544. if (input != NULL) {
  9545. install_special_sighandlers();
  9546. parse_and_run_file(input);
  9547. hfclose(input);
  9548. }
  9549. /* bash: after sourcing /etc/profile,
  9550. * tries to source (in the given order):
  9551. * ~/.bash_profile, ~/.bash_login, ~/.profile,
  9552. * stopping on first found. --noprofile turns this off.
  9553. * bash also sources ~/.bash_logout on exit.
  9554. * If called as sh, skips .bash_XXX files.
  9555. */
  9556. }
  9557. /* -s is: hush -s ARGV1 ARGV2 (no SCRIPT) */
  9558. if (!G.opt_s && G.global_argv[1]) {
  9559. HFILE *input;
  9560. /*
  9561. * "bash <script>" (which is never interactive (unless -i?))
  9562. * sources $BASH_ENV here (without scanning $PATH).
  9563. * If called as sh, does the same but with $ENV.
  9564. * Also NB, per POSIX, $ENV should undergo parameter expansion.
  9565. */
  9566. G.global_argc--;
  9567. G.global_argv++;
  9568. debug_printf("running script '%s'\n", G.global_argv[0]);
  9569. xfunc_error_retval = 127; /* for "hush /does/not/exist" case */
  9570. input = hfopen(G.global_argv[0]);
  9571. if (!input) {
  9572. bb_simple_perror_msg_and_die(G.global_argv[0]);
  9573. }
  9574. xfunc_error_retval = 1;
  9575. install_special_sighandlers();
  9576. parse_and_run_file(input);
  9577. #if ENABLE_FEATURE_CLEAN_UP
  9578. hfclose(input);
  9579. #endif
  9580. goto final_return;
  9581. }
  9582. /* "implicit" -s: bare interactive hush shows 's' in $- */
  9583. G.opt_s = 1;
  9584. /* Up to here, shell was non-interactive. Now it may become one.
  9585. * NB: don't forget to (re)run install_special_sighandlers() as needed.
  9586. */
  9587. /* A shell is interactive if the '-i' flag was given,
  9588. * or if all of the following conditions are met:
  9589. * no -c command
  9590. * no arguments remaining or the -s flag given
  9591. * standard input is a terminal
  9592. * standard output is a terminal
  9593. * Refer to Posix.2, the description of the 'sh' utility.
  9594. */
  9595. #if ENABLE_HUSH_JOB
  9596. if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
  9597. G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
  9598. debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
  9599. if (G_saved_tty_pgrp < 0)
  9600. G_saved_tty_pgrp = 0;
  9601. /* try to dup stdin to high fd#, >= 255 */
  9602. G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, 254);
  9603. if (G_interactive_fd < 0) {
  9604. /* try to dup to any fd */
  9605. G_interactive_fd = dup(STDIN_FILENO);
  9606. if (G_interactive_fd < 0) {
  9607. /* give up */
  9608. G_interactive_fd = 0;
  9609. G_saved_tty_pgrp = 0;
  9610. }
  9611. }
  9612. }
  9613. debug_printf("interactive_fd:%d\n", G_interactive_fd);
  9614. if (G_interactive_fd) {
  9615. close_on_exec_on(G_interactive_fd);
  9616. if (G_saved_tty_pgrp) {
  9617. /* If we were run as 'hush &', sleep until we are
  9618. * in the foreground (tty pgrp == our pgrp).
  9619. * If we get started under a job aware app (like bash),
  9620. * make sure we are now in charge so we don't fight over
  9621. * who gets the foreground */
  9622. while (1) {
  9623. pid_t shell_pgrp = getpgrp();
  9624. G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
  9625. if (G_saved_tty_pgrp == shell_pgrp)
  9626. break;
  9627. /* send TTIN to ourself (should stop us) */
  9628. kill(- shell_pgrp, SIGTTIN);
  9629. }
  9630. }
  9631. /* Install more signal handlers */
  9632. install_special_sighandlers();
  9633. if (G_saved_tty_pgrp) {
  9634. /* Set other signals to restore saved_tty_pgrp */
  9635. install_fatal_sighandlers();
  9636. /* Put ourselves in our own process group
  9637. * (bash, too, does this only if ctty is available) */
  9638. bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
  9639. /* Grab control of the terminal */
  9640. tcsetpgrp(G_interactive_fd, getpid());
  9641. }
  9642. enable_restore_tty_pgrp_on_exit();
  9643. # if ENABLE_FEATURE_EDITING
  9644. G.line_input_state = new_line_input_t(FOR_SHELL);
  9645. # if EDITING_HAS_get_exe_name
  9646. G.line_input_state->get_exe_name = get_builtin_name;
  9647. # endif
  9648. # endif
  9649. # if ENABLE_HUSH_SAVEHISTORY && MAX_HISTORY > 0
  9650. {
  9651. const char *hp = get_local_var_value("HISTFILE");
  9652. if (!hp) {
  9653. hp = get_local_var_value("HOME");
  9654. if (hp)
  9655. hp = concat_path_file(hp, ".hush_history");
  9656. } else {
  9657. hp = xstrdup(hp);
  9658. }
  9659. if (hp) {
  9660. G.line_input_state->hist_file = hp;
  9661. //set_local_var(xasprintf("HISTFILE=%s", ...));
  9662. }
  9663. # if ENABLE_FEATURE_SH_HISTFILESIZE
  9664. hp = get_local_var_value("HISTFILESIZE");
  9665. G.line_input_state->max_history = size_from_HISTFILESIZE(hp);
  9666. # endif
  9667. }
  9668. # endif
  9669. } else {
  9670. install_special_sighandlers();
  9671. }
  9672. #elif ENABLE_HUSH_INTERACTIVE
  9673. /* No job control compiled in, only prompt/line editing */
  9674. if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
  9675. G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, 254);
  9676. if (G_interactive_fd < 0) {
  9677. /* try to dup to any fd */
  9678. G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, -1);
  9679. if (G_interactive_fd < 0)
  9680. /* give up */
  9681. G_interactive_fd = 0;
  9682. }
  9683. }
  9684. if (G_interactive_fd) {
  9685. close_on_exec_on(G_interactive_fd);
  9686. }
  9687. install_special_sighandlers();
  9688. #else
  9689. /* We have interactiveness code disabled */
  9690. install_special_sighandlers();
  9691. #endif
  9692. /* bash:
  9693. * if interactive but not a login shell, sources ~/.bashrc
  9694. * (--norc turns this off, --rcfile <file> overrides)
  9695. */
  9696. if (G_interactive_fd) {
  9697. #if ENABLE_HUSH_INTERACTIVE && ENABLE_FEATURE_EDITING_FANCY_PROMPT
  9698. /* Set (but not export) PS1/2 unless already set */
  9699. if (!get_local_var_value("PS1"))
  9700. set_local_var_from_halves("PS1", "\\w \\$ ");
  9701. if (!get_local_var_value("PS2"))
  9702. set_local_var_from_halves("PS2", "> ");
  9703. #endif
  9704. if (!ENABLE_FEATURE_SH_EXTRA_QUIET) {
  9705. /* note: ash and hush share this string */
  9706. printf("\n\n%s %s\n"
  9707. IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
  9708. "\n",
  9709. bb_banner,
  9710. "hush - the humble shell"
  9711. );
  9712. }
  9713. }
  9714. parse_and_run_file(hfopen(NULL)); /* stdin */
  9715. final_return:
  9716. hush_exit(G.last_exitcode);
  9717. }
  9718. /*
  9719. * Built-ins
  9720. */
  9721. static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
  9722. {
  9723. return 0;
  9724. }
  9725. #if ENABLE_HUSH_TEST || ENABLE_HUSH_ECHO || ENABLE_HUSH_PRINTF || ENABLE_HUSH_KILL
  9726. static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
  9727. {
  9728. int argc = string_array_len(argv);
  9729. return applet_main_func(argc, argv);
  9730. }
  9731. #endif
  9732. #if ENABLE_HUSH_TEST || BASH_TEST2
  9733. static int FAST_FUNC builtin_test(char **argv)
  9734. {
  9735. return run_applet_main(argv, test_main);
  9736. }
  9737. #endif
  9738. #if ENABLE_HUSH_ECHO
  9739. static int FAST_FUNC builtin_echo(char **argv)
  9740. {
  9741. return run_applet_main(argv, echo_main);
  9742. }
  9743. #endif
  9744. #if ENABLE_HUSH_PRINTF
  9745. static int FAST_FUNC builtin_printf(char **argv)
  9746. {
  9747. return run_applet_main(argv, printf_main);
  9748. }
  9749. #endif
  9750. #if ENABLE_HUSH_HELP
  9751. static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
  9752. {
  9753. const struct built_in_command *x;
  9754. printf(
  9755. "Built-in commands:\n"
  9756. "------------------\n");
  9757. for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
  9758. if (x->b_descr)
  9759. printf("%-10s%s\n", x->b_cmd, x->b_descr);
  9760. }
  9761. return EXIT_SUCCESS;
  9762. }
  9763. #endif
  9764. #if MAX_HISTORY && ENABLE_FEATURE_EDITING
  9765. static int FAST_FUNC builtin_history(char **argv UNUSED_PARAM)
  9766. {
  9767. if (G.line_input_state)
  9768. show_history(G.line_input_state);
  9769. return EXIT_SUCCESS;
  9770. }
  9771. #endif
  9772. static char **skip_dash_dash(char **argv)
  9773. {
  9774. argv++;
  9775. if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
  9776. argv++;
  9777. return argv;
  9778. }
  9779. static int FAST_FUNC builtin_cd(char **argv)
  9780. {
  9781. const char *newdir;
  9782. argv = skip_dash_dash(argv);
  9783. newdir = argv[0];
  9784. if (newdir == NULL) {
  9785. /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
  9786. * bash says "bash: cd: HOME not set" and does nothing
  9787. * (exitcode 1)
  9788. */
  9789. const char *home = get_local_var_value("HOME");
  9790. newdir = home ? home : "/";
  9791. }
  9792. if (chdir(newdir)) {
  9793. /* Mimic bash message exactly */
  9794. bb_perror_msg("cd: %s", newdir);
  9795. return EXIT_FAILURE;
  9796. }
  9797. /* Read current dir (get_cwd(1) is inside) and set PWD.
  9798. * Note: do not enforce exporting. If PWD was unset or unexported,
  9799. * set it again, but do not export. bash does the same.
  9800. */
  9801. set_pwd_var(/*flag:*/ 0);
  9802. return EXIT_SUCCESS;
  9803. }
  9804. static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
  9805. {
  9806. puts(get_cwd(0));
  9807. return EXIT_SUCCESS;
  9808. }
  9809. static int FAST_FUNC builtin_eval(char **argv)
  9810. {
  9811. argv = skip_dash_dash(argv);
  9812. if (!argv[0])
  9813. return EXIT_SUCCESS;
  9814. IF_HUSH_MODE_X(G.x_mode_depth++;)
  9815. //bb_error_msg("%s: ++x_mode_depth=%d", __func__, G.x_mode_depth);
  9816. if (!argv[1]) {
  9817. /* bash:
  9818. * eval "echo Hi; done" ("done" is syntax error):
  9819. * "echo Hi" will not execute too.
  9820. */
  9821. parse_and_run_string(argv[0]);
  9822. } else {
  9823. /* "The eval utility shall construct a command by
  9824. * concatenating arguments together, separating
  9825. * each with a <space> character."
  9826. */
  9827. char *str, *p;
  9828. unsigned len = 0;
  9829. char **pp = argv;
  9830. do
  9831. len += strlen(*pp) + 1;
  9832. while (*++pp);
  9833. str = p = xmalloc(len);
  9834. pp = argv;
  9835. for (;;) {
  9836. p = stpcpy(p, *pp);
  9837. pp++;
  9838. if (!*pp)
  9839. break;
  9840. *p++ = ' ';
  9841. }
  9842. parse_and_run_string(str);
  9843. free(str);
  9844. }
  9845. IF_HUSH_MODE_X(G.x_mode_depth--;)
  9846. //bb_error_msg("%s: --x_mode_depth=%d", __func__, G.x_mode_depth);
  9847. return G.last_exitcode;
  9848. }
  9849. static int FAST_FUNC builtin_exec(char **argv)
  9850. {
  9851. argv = skip_dash_dash(argv);
  9852. if (argv[0] == NULL)
  9853. return EXIT_SUCCESS; /* bash does this */
  9854. /* Careful: we can end up here after [v]fork. Do not restore
  9855. * tty pgrp then, only top-level shell process does that */
  9856. if (G_saved_tty_pgrp && getpid() == G.root_pid)
  9857. tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
  9858. /* Saved-redirect fds, script fds and G_interactive_fd are still
  9859. * open here. However, they are all CLOEXEC, and execv below
  9860. * closes them. Try interactive "exec ls -l /proc/self/fd",
  9861. * it should show no extra open fds in the "ls" process.
  9862. * If we'd try to run builtins/NOEXECs, this would need improving.
  9863. */
  9864. //close_saved_fds_and_FILE_fds();
  9865. /* TODO: if exec fails, bash does NOT exit! We do.
  9866. * We'll need to undo trap cleanup (it's inside execvp_or_die)
  9867. * and tcsetpgrp, and this is inherently racy.
  9868. */
  9869. execvp_or_die(argv);
  9870. }
  9871. static int FAST_FUNC builtin_exit(char **argv)
  9872. {
  9873. debug_printf_exec("%s()\n", __func__);
  9874. /* interactive bash:
  9875. * # trap "echo EEE" EXIT
  9876. * # exit
  9877. * exit
  9878. * There are stopped jobs.
  9879. * (if there are _stopped_ jobs, running ones don't count)
  9880. * # exit
  9881. * exit
  9882. * EEE (then bash exits)
  9883. *
  9884. * TODO: we can use G.exiting = -1 as indicator "last cmd was exit"
  9885. */
  9886. /* note: EXIT trap is run by hush_exit */
  9887. argv = skip_dash_dash(argv);
  9888. if (argv[0] == NULL) {
  9889. #if ENABLE_HUSH_TRAP
  9890. if (G.pre_trap_exitcode >= 0) /* "exit" in trap uses $? from before the trap */
  9891. hush_exit(G.pre_trap_exitcode);
  9892. #endif
  9893. hush_exit(G.last_exitcode);
  9894. }
  9895. /* mimic bash: exit 123abc == exit 255 + error msg */
  9896. xfunc_error_retval = 255;
  9897. /* bash: exit -2 == exit 254, no error msg */
  9898. hush_exit(xatoi(argv[0]) & 0xff);
  9899. }
  9900. #if ENABLE_HUSH_TYPE
  9901. /* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
  9902. static int FAST_FUNC builtin_type(char **argv)
  9903. {
  9904. int ret = EXIT_SUCCESS;
  9905. while (*++argv) {
  9906. const char *type;
  9907. char *path = NULL;
  9908. if (0) {} /* make conditional compile easier below */
  9909. /*else if (find_alias(*argv))
  9910. type = "an alias";*/
  9911. # if ENABLE_HUSH_FUNCTIONS
  9912. else if (find_function(*argv))
  9913. type = "a function";
  9914. # endif
  9915. else if (find_builtin(*argv))
  9916. type = "a shell builtin";
  9917. else if ((path = find_in_path(*argv)) != NULL)
  9918. type = path;
  9919. else {
  9920. bb_error_msg("type: %s: not found", *argv);
  9921. ret = EXIT_FAILURE;
  9922. continue;
  9923. }
  9924. printf("%s is %s\n", *argv, type);
  9925. free(path);
  9926. }
  9927. return ret;
  9928. }
  9929. #endif
  9930. #if ENABLE_HUSH_READ
  9931. /* Interruptibility of read builtin in bash
  9932. * (tested on bash-4.2.8 by sending signals (not by ^C)):
  9933. *
  9934. * Empty trap makes read ignore corresponding signal, for any signal.
  9935. *
  9936. * SIGINT:
  9937. * - terminates non-interactive shell;
  9938. * - interrupts read in interactive shell;
  9939. * if it has non-empty trap:
  9940. * - executes trap and returns to command prompt in interactive shell;
  9941. * - executes trap and returns to read in non-interactive shell;
  9942. * SIGTERM:
  9943. * - is ignored (does not interrupt) read in interactive shell;
  9944. * - terminates non-interactive shell;
  9945. * if it has non-empty trap:
  9946. * - executes trap and returns to read;
  9947. * SIGHUP:
  9948. * - terminates shell (regardless of interactivity);
  9949. * if it has non-empty trap:
  9950. * - executes trap and returns to read;
  9951. * SIGCHLD from children:
  9952. * - does not interrupt read regardless of interactivity:
  9953. * try: sleep 1 & read x; echo $x
  9954. */
  9955. static int FAST_FUNC builtin_read(char **argv)
  9956. {
  9957. const char *r;
  9958. struct builtin_read_params params;
  9959. memset(&params, 0, sizeof(params));
  9960. /* "!": do not abort on errors.
  9961. * Option string must start with "sr" to match BUILTIN_READ_xxx
  9962. */
  9963. params.read_flags = getopt32(argv,
  9964. # if BASH_READ_D
  9965. "!srn:p:t:u:d:", &params.opt_n, &params.opt_p, &params.opt_t, &params.opt_u, &params.opt_d
  9966. # else
  9967. "!srn:p:t:u:", &params.opt_n, &params.opt_p, &params.opt_t, &params.opt_u
  9968. # endif
  9969. );
  9970. if ((uint32_t)params.read_flags == (uint32_t)-1)
  9971. return EXIT_FAILURE;
  9972. argv += optind;
  9973. params.argv = argv;
  9974. params.setvar = set_local_var_from_halves;
  9975. params.ifs = get_local_var_value("IFS"); /* can be NULL */
  9976. again:
  9977. r = shell_builtin_read(&params);
  9978. if ((uintptr_t)r == 1 && errno == EINTR) {
  9979. unsigned sig = check_and_run_traps();
  9980. if (sig != SIGINT)
  9981. goto again;
  9982. }
  9983. if ((uintptr_t)r > 1) {
  9984. bb_simple_error_msg(r);
  9985. r = (char*)(uintptr_t)1;
  9986. }
  9987. return (uintptr_t)r;
  9988. }
  9989. #endif
  9990. #if ENABLE_HUSH_UMASK
  9991. static int FAST_FUNC builtin_umask(char **argv)
  9992. {
  9993. int rc;
  9994. mode_t mask;
  9995. rc = 1;
  9996. mask = umask(0);
  9997. argv = skip_dash_dash(argv);
  9998. if (argv[0]) {
  9999. mode_t old_mask = mask;
  10000. /* numeric umasks are taken as-is */
  10001. /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
  10002. if (!isdigit(argv[0][0]))
  10003. mask ^= 0777;
  10004. mask = bb_parse_mode(argv[0], mask);
  10005. if (!isdigit(argv[0][0]))
  10006. mask ^= 0777;
  10007. if ((unsigned)mask > 0777) {
  10008. mask = old_mask;
  10009. /* bash messages:
  10010. * bash: umask: 'q': invalid symbolic mode operator
  10011. * bash: umask: 999: octal number out of range
  10012. */
  10013. bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
  10014. rc = 0;
  10015. }
  10016. } else {
  10017. /* Mimic bash */
  10018. printf("%04o\n", (unsigned) mask);
  10019. /* fall through and restore mask which we set to 0 */
  10020. }
  10021. umask(mask);
  10022. return !rc; /* rc != 0 - success */
  10023. }
  10024. #endif
  10025. #if ENABLE_HUSH_EXPORT || ENABLE_HUSH_TRAP
  10026. static void print_escaped(const char *s)
  10027. {
  10028. if (*s == '\'')
  10029. goto squote;
  10030. do {
  10031. const char *p = strchrnul(s, '\'');
  10032. /* print 'xxxx', possibly just '' */
  10033. printf("'%.*s'", (int)(p - s), s);
  10034. if (*p == '\0')
  10035. break;
  10036. s = p;
  10037. squote:
  10038. /* s points to '; print "'''...'''" */
  10039. putchar('"');
  10040. do putchar('\''); while (*++s == '\'');
  10041. putchar('"');
  10042. } while (*s);
  10043. }
  10044. #endif
  10045. #if ENABLE_HUSH_EXPORT || ENABLE_HUSH_LOCAL || ENABLE_HUSH_READONLY
  10046. static int helper_export_local(char **argv, unsigned flags)
  10047. {
  10048. do {
  10049. char *name = *argv;
  10050. const char *name_end = endofname(name);
  10051. if (*name_end == '\0') {
  10052. struct variable *var, **vpp;
  10053. vpp = get_ptr_to_local_var(name, name_end - name);
  10054. var = vpp ? *vpp : NULL;
  10055. if (flags & SETFLAG_UNEXPORT) {
  10056. /* export -n NAME (without =VALUE) */
  10057. if (var) {
  10058. var->flg_export = 0;
  10059. debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
  10060. unsetenv(name);
  10061. } /* else: export -n NOT_EXISTING_VAR: no-op */
  10062. continue;
  10063. }
  10064. if (flags & SETFLAG_EXPORT) {
  10065. /* export NAME (without =VALUE) */
  10066. if (var) {
  10067. var->flg_export = 1;
  10068. debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
  10069. putenv(var->varstr);
  10070. continue;
  10071. }
  10072. }
  10073. if (flags & SETFLAG_MAKE_RO) {
  10074. /* readonly NAME (without =VALUE) */
  10075. if (var) {
  10076. var->flg_read_only = 1;
  10077. continue;
  10078. }
  10079. }
  10080. # if ENABLE_HUSH_LOCAL
  10081. /* Is this "local" bltin? */
  10082. if (!(flags & (SETFLAG_EXPORT|SETFLAG_UNEXPORT|SETFLAG_MAKE_RO))) {
  10083. unsigned lvl = flags >> SETFLAG_VARLVL_SHIFT;
  10084. if (var && var->var_nest_level == lvl) {
  10085. /* "local x=abc; ...; local x" - ignore second local decl */
  10086. continue;
  10087. }
  10088. }
  10089. # endif
  10090. /* Exporting non-existing variable.
  10091. * bash does not put it in environment,
  10092. * but remembers that it is exported,
  10093. * and does put it in env when it is set later.
  10094. * We just set it to "" and export.
  10095. */
  10096. /* Or, it's "local NAME" (without =VALUE).
  10097. * bash sets the value to "".
  10098. */
  10099. /* Or, it's "readonly NAME" (without =VALUE).
  10100. * bash remembers NAME and disallows its creation
  10101. * in the future.
  10102. */
  10103. name = xasprintf("%s=", name);
  10104. } else {
  10105. if (*name_end != '=') {
  10106. bb_error_msg("'%s': bad variable name", name);
  10107. /* do not parse following argv[]s: */
  10108. return 1;
  10109. }
  10110. /* (Un)exporting/making local NAME=VALUE */
  10111. name = xstrdup(name);
  10112. /* Testcase: export PS1='\w \$ ' */
  10113. unbackslash(name);
  10114. }
  10115. debug_printf_env("%s: set_local_var('%s')\n", __func__, name);
  10116. if (set_local_var(name, flags))
  10117. return EXIT_FAILURE;
  10118. } while (*++argv);
  10119. return EXIT_SUCCESS;
  10120. }
  10121. #endif
  10122. #if ENABLE_HUSH_EXPORT
  10123. static int FAST_FUNC builtin_export(char **argv)
  10124. {
  10125. unsigned opt_unexport;
  10126. # if ENABLE_HUSH_EXPORT_N
  10127. /* "!": do not abort on errors */
  10128. opt_unexport = getopt32(argv, "!n");
  10129. if (opt_unexport == (uint32_t)-1)
  10130. return EXIT_FAILURE;
  10131. argv += optind;
  10132. # else
  10133. opt_unexport = 0;
  10134. argv++;
  10135. # endif
  10136. if (argv[0] == NULL) {
  10137. char **e = environ;
  10138. if (e) {
  10139. while (*e) {
  10140. # if 0
  10141. puts(*e++);
  10142. # else
  10143. /* ash emits: export VAR='VAL'
  10144. * bash: declare -x VAR="VAL"
  10145. * we follow ash example */
  10146. const char *s = *e++;
  10147. const char *p = strchr(s, '=');
  10148. if (!p) /* wtf? take next variable */
  10149. continue;
  10150. /* export var= */
  10151. printf("export %.*s", (int)(p - s) + 1, s);
  10152. print_escaped(p + 1);
  10153. putchar('\n');
  10154. # endif
  10155. }
  10156. /*fflush_all(); - done after each builtin anyway */
  10157. }
  10158. return EXIT_SUCCESS;
  10159. }
  10160. return helper_export_local(argv, opt_unexport ? SETFLAG_UNEXPORT : SETFLAG_EXPORT);
  10161. }
  10162. #endif
  10163. #if ENABLE_HUSH_LOCAL
  10164. static int FAST_FUNC builtin_local(char **argv)
  10165. {
  10166. if (G.func_nest_level == 0) {
  10167. bb_error_msg("%s: not in a function", argv[0]);
  10168. return EXIT_FAILURE; /* bash compat */
  10169. }
  10170. argv++;
  10171. /* Since all builtins run in a nested variable level,
  10172. * need to use level - 1 here. Or else the variable will be removed at once
  10173. * after builtin returns.
  10174. */
  10175. return helper_export_local(argv, (G.var_nest_level - 1) << SETFLAG_VARLVL_SHIFT);
  10176. }
  10177. #endif
  10178. #if ENABLE_HUSH_READONLY
  10179. static int FAST_FUNC builtin_readonly(char **argv)
  10180. {
  10181. argv++;
  10182. if (*argv == NULL) {
  10183. /* bash: readonly [-p]: list all readonly VARs
  10184. * (-p has no effect in bash)
  10185. */
  10186. struct variable *e;
  10187. for (e = G.top_var; e; e = e->next) {
  10188. if (e->flg_read_only) {
  10189. //TODO: quote value: readonly VAR='VAL'
  10190. printf("readonly %s\n", e->varstr);
  10191. }
  10192. }
  10193. return EXIT_SUCCESS;
  10194. }
  10195. return helper_export_local(argv, SETFLAG_MAKE_RO);
  10196. }
  10197. #endif
  10198. #if ENABLE_HUSH_UNSET
  10199. /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
  10200. static int FAST_FUNC builtin_unset(char **argv)
  10201. {
  10202. int ret;
  10203. unsigned opts;
  10204. /* "!": do not abort on errors */
  10205. /* "+": stop at 1st non-option */
  10206. opts = getopt32(argv, "!+vf");
  10207. if (opts == (unsigned)-1)
  10208. return EXIT_FAILURE;
  10209. if (opts == 3) {
  10210. bb_simple_error_msg("unset: -v and -f are exclusive");
  10211. return EXIT_FAILURE;
  10212. }
  10213. argv += optind;
  10214. ret = EXIT_SUCCESS;
  10215. while (*argv) {
  10216. if (!(opts & 2)) { /* not -f */
  10217. if (unset_local_var(*argv)) {
  10218. /* unset <nonexistent_var> doesn't fail.
  10219. * Error is when one tries to unset RO var.
  10220. * Message was printed by unset_local_var. */
  10221. ret = EXIT_FAILURE;
  10222. }
  10223. }
  10224. # if ENABLE_HUSH_FUNCTIONS
  10225. else {
  10226. unset_func(*argv);
  10227. }
  10228. # endif
  10229. argv++;
  10230. }
  10231. return ret;
  10232. }
  10233. #endif
  10234. #if ENABLE_HUSH_SET
  10235. /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
  10236. * built-in 'set' handler
  10237. * SUSv3 says:
  10238. * set [-abCefhmnuvx] [-o option] [argument...]
  10239. * set [+abCefhmnuvx] [+o option] [argument...]
  10240. * set -- [argument...]
  10241. * set -o
  10242. * set +o
  10243. * Implementations shall support the options in both their hyphen and
  10244. * plus-sign forms. These options can also be specified as options to sh.
  10245. * Examples:
  10246. * Write out all variables and their values: set
  10247. * Set $1, $2, and $3 and set "$#" to 3: set c a b
  10248. * Turn on the -x and -v options: set -xv
  10249. * Unset all positional parameters: set --
  10250. * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
  10251. * Set the positional parameters to the expansion of x, even if x expands
  10252. * with a leading '-' or '+': set -- $x
  10253. *
  10254. * So far, we only support "set -- [argument...]" and some of the short names.
  10255. */
  10256. static int FAST_FUNC builtin_set(char **argv)
  10257. {
  10258. int n;
  10259. char **pp, **g_argv;
  10260. char *arg = *++argv;
  10261. if (arg == NULL) {
  10262. struct variable *e;
  10263. for (e = G.top_var; e; e = e->next)
  10264. puts(e->varstr);
  10265. return EXIT_SUCCESS;
  10266. }
  10267. do {
  10268. if (strcmp(arg, "--") == 0) {
  10269. ++argv;
  10270. goto set_argv;
  10271. }
  10272. if (arg[0] != '+' && arg[0] != '-')
  10273. break;
  10274. for (n = 1; arg[n]; ++n) {
  10275. if (set_mode((arg[0] == '-'), arg[n], argv[1])) {
  10276. bb_error_msg("%s: %s: invalid option", "set", arg);
  10277. return EXIT_FAILURE;
  10278. }
  10279. if (arg[n] == 'o' && argv[1])
  10280. argv++;
  10281. }
  10282. } while ((arg = *++argv) != NULL);
  10283. /* Now argv[0] is 1st argument */
  10284. if (arg == NULL)
  10285. return EXIT_SUCCESS;
  10286. set_argv:
  10287. /* NB: G.global_argv[0] ($0) is never freed/changed */
  10288. g_argv = G.global_argv;
  10289. if (G.global_args_malloced) {
  10290. pp = g_argv;
  10291. while (*++pp)
  10292. free(*pp);
  10293. g_argv[1] = NULL;
  10294. } else {
  10295. G.global_args_malloced = 1;
  10296. pp = xzalloc(sizeof(pp[0]) * 2);
  10297. pp[0] = g_argv[0]; /* retain $0 */
  10298. g_argv = pp;
  10299. }
  10300. /* This realloc's G.global_argv */
  10301. G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
  10302. G.global_argc = 1 + string_array_len(pp + 1);
  10303. return EXIT_SUCCESS;
  10304. }
  10305. #endif
  10306. static int FAST_FUNC builtin_shift(char **argv)
  10307. {
  10308. int n = 1;
  10309. argv = skip_dash_dash(argv);
  10310. if (argv[0]) {
  10311. n = bb_strtou(argv[0], NULL, 10);
  10312. if (errno || n < 0) {
  10313. /* shared string with ash.c */
  10314. bb_error_msg("Illegal number: %s", argv[0]);
  10315. /*
  10316. * ash aborts in this case.
  10317. * bash prints error message and set $? to 1.
  10318. * Interestingly, for "shift 99999" bash does not
  10319. * print error message, but does set $? to 1
  10320. * (and does no shifting at all).
  10321. */
  10322. }
  10323. }
  10324. if (n >= 0 && n < G.global_argc) {
  10325. if (G_global_args_malloced) {
  10326. int m = 1;
  10327. while (m <= n)
  10328. free(G.global_argv[m++]);
  10329. }
  10330. G.global_argc -= n;
  10331. memmove(&G.global_argv[1], &G.global_argv[n+1],
  10332. G.global_argc * sizeof(G.global_argv[0]));
  10333. return EXIT_SUCCESS;
  10334. }
  10335. return EXIT_FAILURE;
  10336. }
  10337. #if ENABLE_HUSH_GETOPTS
  10338. static int FAST_FUNC builtin_getopts(char **argv)
  10339. {
  10340. /* http://pubs.opengroup.org/onlinepubs/9699919799/utilities/getopts.html
  10341. TODO:
  10342. If a required argument is not found, and getopts is not silent,
  10343. a question mark (?) is placed in VAR, OPTARG is unset, and a
  10344. diagnostic message is printed. If getopts is silent, then a
  10345. colon (:) is placed in VAR and OPTARG is set to the option
  10346. character found.
  10347. Test that VAR is a valid variable name?
  10348. "Whenever the shell is invoked, OPTIND shall be initialized to 1"
  10349. */
  10350. char cbuf[2];
  10351. const char *cp, *optstring, *var;
  10352. int c, n, exitcode, my_opterr;
  10353. unsigned count;
  10354. optstring = *++argv;
  10355. if (!optstring || !(var = *++argv)) {
  10356. bb_simple_error_msg("usage: getopts OPTSTRING VAR [ARGS]");
  10357. return EXIT_FAILURE;
  10358. }
  10359. if (argv[1])
  10360. argv[0] = G.global_argv[0]; /* for error messages in getopt() */
  10361. else
  10362. argv = G.global_argv;
  10363. cbuf[1] = '\0';
  10364. my_opterr = 0;
  10365. if (optstring[0] != ':') {
  10366. cp = get_local_var_value("OPTERR");
  10367. /* 0 if "OPTERR=0", 1 otherwise */
  10368. my_opterr = (!cp || NOT_LONE_CHAR(cp, '0'));
  10369. }
  10370. /* getopts stops on first non-option. Add "+" to force that */
  10371. /*if (optstring[0] != '+')*/ {
  10372. char *s = alloca(strlen(optstring) + 2);
  10373. sprintf(s, "+%s", optstring);
  10374. optstring = s;
  10375. }
  10376. /* Naively, now we should just
  10377. * cp = get_local_var_value("OPTIND");
  10378. * optind = cp ? atoi(cp) : 0;
  10379. * optarg = NULL;
  10380. * opterr = my_opterr;
  10381. * c = getopt(string_array_len(argv), argv, optstring);
  10382. * and be done? Not so fast...
  10383. * Unlike normal getopt() usage in C programs, here
  10384. * each successive call will (usually) have the same argv[] CONTENTS,
  10385. * but not the ADDRESSES. Worse yet, it's possible that between
  10386. * invocations of "getopts", there will be calls to shell builtins
  10387. * which use getopt() internally. Example:
  10388. * while getopts "abc" RES -a -bc -abc de; do
  10389. * unset -ff func
  10390. * done
  10391. * This would not work correctly: getopt() call inside "unset"
  10392. * modifies internal libc state which is tracking position in
  10393. * multi-option strings ("-abc"). At best, it can skip options
  10394. * or return the same option infinitely. With glibc implementation
  10395. * of getopt(), it would use outright invalid pointers and return
  10396. * garbage even _without_ "unset" mangling internal state.
  10397. *
  10398. * We resort to resetting getopt() state and calling it N times,
  10399. * until we get Nth result (or failure).
  10400. * (N == G.getopt_count is reset to 0 whenever OPTIND is [un]set).
  10401. */
  10402. GETOPT_RESET();
  10403. count = 0;
  10404. n = string_array_len(argv);
  10405. do {
  10406. optarg = NULL;
  10407. opterr = (count < G.getopt_count) ? 0 : my_opterr;
  10408. c = getopt(n, argv, optstring);
  10409. if (c < 0)
  10410. break;
  10411. count++;
  10412. } while (count <= G.getopt_count);
  10413. /* Set OPTIND. Prevent resetting of the magic counter! */
  10414. set_local_var_from_halves("OPTIND", utoa(optind));
  10415. G.getopt_count = count; /* "next time, give me N+1'th result" */
  10416. GETOPT_RESET(); /* just in case */
  10417. /* Set OPTARG */
  10418. /* Always set or unset, never left as-is, even on exit/error:
  10419. * "If no option was found, or if the option that was found
  10420. * does not have an option-argument, OPTARG shall be unset."
  10421. */
  10422. cp = optarg;
  10423. if (c == '?') {
  10424. /* If ":optstring" and unknown option is seen,
  10425. * it is stored to OPTARG.
  10426. */
  10427. if (optstring[1] == ':') {
  10428. cbuf[0] = optopt;
  10429. cp = cbuf;
  10430. }
  10431. }
  10432. if (cp)
  10433. set_local_var_from_halves("OPTARG", cp);
  10434. else
  10435. unset_local_var("OPTARG");
  10436. /* Convert -1 to "?" */
  10437. exitcode = EXIT_SUCCESS;
  10438. if (c < 0) { /* -1: end of options */
  10439. exitcode = EXIT_FAILURE;
  10440. c = '?';
  10441. }
  10442. /* Set VAR */
  10443. cbuf[0] = c;
  10444. set_local_var_from_halves(var, cbuf);
  10445. return exitcode;
  10446. }
  10447. #endif
  10448. static int FAST_FUNC builtin_source(char **argv)
  10449. {
  10450. char *arg_path, *filename;
  10451. HFILE *input;
  10452. save_arg_t sv;
  10453. char *args_need_save;
  10454. #if ENABLE_HUSH_FUNCTIONS
  10455. smallint sv_flg;
  10456. #endif
  10457. argv = skip_dash_dash(argv);
  10458. filename = argv[0];
  10459. if (!filename) {
  10460. /* bash says: "bash: .: filename argument required" */
  10461. return 2; /* bash compat */
  10462. }
  10463. arg_path = NULL;
  10464. if (!strchr(filename, '/')) {
  10465. arg_path = find_in_path(filename);
  10466. if (arg_path)
  10467. filename = arg_path;
  10468. else if (!ENABLE_HUSH_BASH_SOURCE_CURDIR) {
  10469. errno = ENOENT;
  10470. bb_simple_perror_msg(filename);
  10471. return EXIT_FAILURE;
  10472. }
  10473. }
  10474. input = hfopen(filename);
  10475. free(arg_path);
  10476. if (!input) {
  10477. bb_perror_msg("%s", filename);
  10478. /* POSIX: non-interactive shell should abort here,
  10479. * not merely fail. So far no one complained :)
  10480. */
  10481. return EXIT_FAILURE;
  10482. }
  10483. #if ENABLE_HUSH_FUNCTIONS
  10484. sv_flg = G_flag_return_in_progress;
  10485. /* "we are inside sourced file, ok to use return" */
  10486. G_flag_return_in_progress = -1;
  10487. #endif
  10488. args_need_save = argv[1]; /* used as a boolean variable */
  10489. if (args_need_save)
  10490. save_and_replace_G_args(&sv, argv);
  10491. /* "false; . ./empty_line; echo Zero:$?" should print 0 */
  10492. G.last_exitcode = 0;
  10493. parse_and_run_file(input);
  10494. hfclose(input);
  10495. if (args_need_save) /* can't use argv[1] instead: "shift" can mangle it */
  10496. restore_G_args(&sv, argv);
  10497. #if ENABLE_HUSH_FUNCTIONS
  10498. G_flag_return_in_progress = sv_flg;
  10499. #endif
  10500. return G.last_exitcode;
  10501. }
  10502. #if ENABLE_HUSH_TRAP
  10503. static int FAST_FUNC builtin_trap(char **argv)
  10504. {
  10505. int sig;
  10506. char *new_cmd;
  10507. if (!G_traps)
  10508. G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
  10509. argv++;
  10510. if (!*argv) {
  10511. int i;
  10512. /* No args: print all trapped */
  10513. for (i = 0; i < NSIG; ++i) {
  10514. if (G_traps[i]) {
  10515. printf("trap -- ");
  10516. print_escaped(G_traps[i]);
  10517. /* note: bash adds "SIG", but only if invoked
  10518. * as "bash". If called as "sh", or if set -o posix,
  10519. * then it prints short signal names.
  10520. * We are printing short names: */
  10521. printf(" %s\n", get_signame(i));
  10522. }
  10523. }
  10524. /*fflush_all(); - done after each builtin anyway */
  10525. return EXIT_SUCCESS;
  10526. }
  10527. new_cmd = NULL;
  10528. /* If first arg is a number: reset all specified signals */
  10529. sig = bb_strtou(*argv, NULL, 10);
  10530. if (errno == 0) {
  10531. int ret;
  10532. process_sig_list:
  10533. ret = EXIT_SUCCESS;
  10534. while (*argv) {
  10535. sighandler_t handler;
  10536. sig = get_signum(*argv++);
  10537. if (sig < 0) {
  10538. ret = EXIT_FAILURE;
  10539. /* Mimic bash message exactly */
  10540. bb_error_msg("trap: %s: invalid signal specification", argv[-1]);
  10541. continue;
  10542. }
  10543. free(G_traps[sig]);
  10544. G_traps[sig] = xstrdup(new_cmd);
  10545. debug_printf("trap: setting SIG%s (%i) to '%s'\n",
  10546. get_signame(sig), sig, G_traps[sig]);
  10547. /* There is no signal for 0 (EXIT) */
  10548. if (sig == 0)
  10549. continue;
  10550. if (new_cmd)
  10551. handler = (new_cmd[0] ? record_pending_signo : SIG_IGN);
  10552. else
  10553. /* We are removing trap handler */
  10554. handler = pick_sighandler(sig);
  10555. install_sighandler(sig, handler);
  10556. }
  10557. return ret;
  10558. }
  10559. if (!argv[1]) { /* no second arg */
  10560. bb_simple_error_msg("trap: invalid arguments");
  10561. return EXIT_FAILURE;
  10562. }
  10563. /* First arg is "-": reset all specified to default */
  10564. /* First arg is "--": skip it, the rest is "handler SIGs..." */
  10565. /* Everything else: set arg as signal handler
  10566. * (includes "" case, which ignores signal) */
  10567. if (argv[0][0] == '-') {
  10568. if (argv[0][1] == '\0') { /* "-" */
  10569. /* new_cmd remains NULL: "reset these sigs" */
  10570. goto reset_traps;
  10571. }
  10572. if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
  10573. argv++;
  10574. }
  10575. /* else: "-something", no special meaning */
  10576. }
  10577. new_cmd = *argv;
  10578. reset_traps:
  10579. argv++;
  10580. goto process_sig_list;
  10581. }
  10582. #endif
  10583. #if ENABLE_HUSH_JOB
  10584. static struct pipe *parse_jobspec(const char *str)
  10585. {
  10586. struct pipe *pi;
  10587. unsigned jobnum;
  10588. if (sscanf(str, "%%%u", &jobnum) != 1) {
  10589. if (str[0] != '%'
  10590. || (str[1] != '%' && str[1] != '+' && str[1] != '\0')
  10591. ) {
  10592. bb_error_msg("bad argument '%s'", str);
  10593. return NULL;
  10594. }
  10595. /* It is "%%", "%+" or "%" - current job */
  10596. jobnum = G.last_jobid;
  10597. if (jobnum == 0) {
  10598. bb_simple_error_msg("no current job");
  10599. return NULL;
  10600. }
  10601. }
  10602. for (pi = G.job_list; pi; pi = pi->next) {
  10603. if (pi->jobid == jobnum) {
  10604. return pi;
  10605. }
  10606. }
  10607. bb_error_msg("%u: no such job", jobnum);
  10608. return NULL;
  10609. }
  10610. static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
  10611. {
  10612. struct pipe *job;
  10613. const char *status_string;
  10614. checkjobs(NULL, 0 /*(no pid to wait for)*/);
  10615. for (job = G.job_list; job; job = job->next) {
  10616. if (job->alive_cmds == job->stopped_cmds)
  10617. status_string = "Stopped";
  10618. else
  10619. status_string = "Running";
  10620. printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
  10621. }
  10622. clean_up_last_dead_job();
  10623. return EXIT_SUCCESS;
  10624. }
  10625. /* built-in 'fg' and 'bg' handler */
  10626. static int FAST_FUNC builtin_fg_bg(char **argv)
  10627. {
  10628. int i;
  10629. struct pipe *pi;
  10630. if (!G_interactive_fd)
  10631. return EXIT_FAILURE;
  10632. /* If they gave us no args, assume they want the last backgrounded task */
  10633. if (!argv[1]) {
  10634. for (pi = G.job_list; pi; pi = pi->next) {
  10635. if (pi->jobid == G.last_jobid) {
  10636. goto found;
  10637. }
  10638. }
  10639. bb_error_msg("%s: no current job", argv[0]);
  10640. return EXIT_FAILURE;
  10641. }
  10642. pi = parse_jobspec(argv[1]);
  10643. if (!pi)
  10644. return EXIT_FAILURE;
  10645. found:
  10646. /* TODO: bash prints a string representation
  10647. * of job being foregrounded (like "sleep 1 | cat") */
  10648. if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
  10649. /* Put the job into the foreground. */
  10650. tcsetpgrp(G_interactive_fd, pi->pgrp);
  10651. }
  10652. /* Restart the processes in the job */
  10653. debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
  10654. for (i = 0; i < pi->num_cmds; i++) {
  10655. debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
  10656. }
  10657. pi->stopped_cmds = 0;
  10658. i = kill(- pi->pgrp, SIGCONT);
  10659. if (i < 0) {
  10660. if (errno == ESRCH) {
  10661. delete_finished_job(pi);
  10662. return EXIT_SUCCESS;
  10663. }
  10664. bb_simple_perror_msg("kill (SIGCONT)");
  10665. }
  10666. if (argv[0][0] == 'f') {
  10667. remove_job_from_table(pi); /* FG job shouldn't be in job table */
  10668. return checkjobs_and_fg_shell(pi);
  10669. }
  10670. return EXIT_SUCCESS;
  10671. }
  10672. #endif
  10673. #if ENABLE_HUSH_KILL
  10674. static int FAST_FUNC builtin_kill(char **argv)
  10675. {
  10676. int ret = 0;
  10677. # if ENABLE_HUSH_JOB
  10678. if (argv[1] && strcmp(argv[1], "-l") != 0) {
  10679. int i = 1;
  10680. do {
  10681. struct pipe *pi;
  10682. char *dst;
  10683. int j, n;
  10684. if (argv[i][0] != '%')
  10685. continue;
  10686. /*
  10687. * "kill %N" - job kill
  10688. * Converting to pgrp / pid kill
  10689. */
  10690. pi = parse_jobspec(argv[i]);
  10691. if (!pi) {
  10692. /* Eat bad jobspec */
  10693. j = i;
  10694. do {
  10695. j++;
  10696. argv[j - 1] = argv[j];
  10697. } while (argv[j]);
  10698. ret = 1;
  10699. i--;
  10700. continue;
  10701. }
  10702. /*
  10703. * In jobs started under job control, we signal
  10704. * entire process group by kill -PGRP_ID.
  10705. * This happens, f.e., in interactive shell.
  10706. *
  10707. * Otherwise, we signal each child via
  10708. * kill PID1 PID2 PID3.
  10709. * Testcases:
  10710. * sh -c 'sleep 1|sleep 1 & kill %1'
  10711. * sh -c 'true|sleep 2 & sleep 1; kill %1'
  10712. * sh -c 'true|sleep 1 & sleep 2; kill %1'
  10713. */
  10714. n = G_interactive_fd ? 1 : pi->num_cmds;
  10715. dst = alloca(n * sizeof(int)*4);
  10716. argv[i] = dst;
  10717. if (G_interactive_fd)
  10718. dst += sprintf(dst, " -%u", (int)pi->pgrp);
  10719. else for (j = 0; j < n; j++) {
  10720. struct command *cmd = &pi->cmds[j];
  10721. /* Skip exited members of the job */
  10722. if (cmd->pid == 0)
  10723. continue;
  10724. /*
  10725. * kill_main has matching code to expect
  10726. * leading space. Needed to not confuse
  10727. * negative pids with "kill -SIGNAL_NO" syntax
  10728. */
  10729. dst += sprintf(dst, " %u", (int)cmd->pid);
  10730. }
  10731. *dst = '\0';
  10732. } while (argv[++i]);
  10733. }
  10734. # endif
  10735. if (argv[1] || ret == 0) {
  10736. ret = run_applet_main(argv, kill_main);
  10737. }
  10738. /* else: ret = 1, "kill %bad_jobspec" case */
  10739. return ret;
  10740. }
  10741. #endif
  10742. #if ENABLE_HUSH_WAIT
  10743. /* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
  10744. # if !ENABLE_HUSH_JOB
  10745. # define wait_for_child_or_signal(pipe,pid) wait_for_child_or_signal(pid)
  10746. # endif
  10747. static int wait_for_child_or_signal(struct pipe *waitfor_pipe, pid_t waitfor_pid)
  10748. {
  10749. int ret = 0;
  10750. for (;;) {
  10751. int sig;
  10752. sigset_t oldset;
  10753. if (!sigisemptyset(&G.pending_set))
  10754. goto check_sig;
  10755. /* waitpid is not interruptible by SA_RESTARTed
  10756. * signals which we use. Thus, this ugly dance:
  10757. */
  10758. /* Make sure possible SIGCHLD is stored in kernel's
  10759. * pending signal mask before we call waitpid.
  10760. * Or else we may race with SIGCHLD, lose it,
  10761. * and get stuck in sigsuspend...
  10762. */
  10763. sigfillset(&oldset); /* block all signals, remember old set */
  10764. sigprocmask2(SIG_SETMASK, &oldset);
  10765. if (!sigisemptyset(&G.pending_set)) {
  10766. /* Crap! we raced with some signal! */
  10767. goto restore;
  10768. }
  10769. /*errno = 0; - checkjobs does this */
  10770. /* Can't pass waitfor_pipe into checkjobs(): it won't be interruptible */
  10771. ret = checkjobs(NULL, waitfor_pid); /* waitpid(WNOHANG) inside */
  10772. debug_printf_exec("checkjobs:%d\n", ret);
  10773. # if ENABLE_HUSH_JOB
  10774. if (waitfor_pipe) {
  10775. int rcode = job_exited_or_stopped(waitfor_pipe);
  10776. debug_printf_exec("job_exited_or_stopped:%d\n", rcode);
  10777. if (rcode >= 0) {
  10778. ret = rcode;
  10779. sigprocmask(SIG_SETMASK, &oldset, NULL);
  10780. break;
  10781. }
  10782. }
  10783. # endif
  10784. /* if ECHILD, there are no children (ret is -1 or 0) */
  10785. /* if ret == 0, no children changed state */
  10786. /* if ret != 0, it's exitcode+1 of exited waitfor_pid child */
  10787. if (errno == ECHILD || ret) {
  10788. ret--;
  10789. if (ret < 0) /* if ECHILD, may need to fix "ret" */
  10790. ret = 0;
  10791. # if ENABLE_HUSH_BASH_COMPAT
  10792. if (waitfor_pid == -1 && errno == ECHILD) {
  10793. /* exitcode of "wait -n" with no children is 127, not 0 */
  10794. ret = 127;
  10795. }
  10796. # endif
  10797. sigprocmask(SIG_SETMASK, &oldset, NULL);
  10798. break;
  10799. }
  10800. /* Wait for SIGCHLD or any other signal */
  10801. /* It is vitally important for sigsuspend that SIGCHLD has non-DFL handler! */
  10802. /* Note: sigsuspend invokes signal handler */
  10803. sigsuspend(&oldset);
  10804. /* ^^^ add "sigdelset(&oldset, SIGCHLD)" before sigsuspend
  10805. * to make sure SIGCHLD is not masked off?
  10806. * It was reported that this:
  10807. * fn() { : | return; }
  10808. * shopt -s lastpipe
  10809. * fn
  10810. * exec hush SCRIPT
  10811. * under bash 4.4.23 runs SCRIPT with SIGCHLD masked,
  10812. * making "wait" commands in SCRIPT block forever.
  10813. */
  10814. restore:
  10815. sigprocmask(SIG_SETMASK, &oldset, NULL);
  10816. check_sig:
  10817. /* So, did we get a signal? */
  10818. sig = check_and_run_traps();
  10819. if (sig /*&& sig != SIGCHLD - always true */) {
  10820. /* Do this for any (non-ignored) signal, not only for ^C */
  10821. ret = 128 + sig;
  10822. break;
  10823. }
  10824. /* SIGCHLD, or no signal, or ignored one, such as SIGQUIT. Repeat */
  10825. }
  10826. return ret;
  10827. }
  10828. static int FAST_FUNC builtin_wait(char **argv)
  10829. {
  10830. int ret;
  10831. int status;
  10832. argv = skip_dash_dash(argv);
  10833. # if ENABLE_HUSH_BASH_COMPAT
  10834. if (argv[0] && strcmp(argv[0], "-n") == 0) {
  10835. /* wait -n */
  10836. /* (bash accepts "wait -n PID" too and ignores PID) */
  10837. G.dead_job_exitcode = -1;
  10838. return wait_for_child_or_signal(NULL, -1 /*no job, wait for one job*/);
  10839. }
  10840. # endif
  10841. if (argv[0] == NULL) {
  10842. /* Don't care about wait results */
  10843. /* Note 1: must wait until there are no more children */
  10844. /* Note 2: must be interruptible */
  10845. /* Examples:
  10846. * $ sleep 3 & sleep 6 & wait
  10847. * [1] 30934 sleep 3
  10848. * [2] 30935 sleep 6
  10849. * [1] Done sleep 3
  10850. * [2] Done sleep 6
  10851. * $ sleep 3 & sleep 6 & wait
  10852. * [1] 30936 sleep 3
  10853. * [2] 30937 sleep 6
  10854. * [1] Done sleep 3
  10855. * ^C <-- after ~4 sec from keyboard
  10856. * $
  10857. */
  10858. return wait_for_child_or_signal(NULL, 0 /*no job and no pid to wait for*/);
  10859. }
  10860. do {
  10861. pid_t pid = bb_strtou(*argv, NULL, 10);
  10862. if (errno || pid <= 0) {
  10863. # if ENABLE_HUSH_JOB
  10864. if (argv[0][0] == '%') {
  10865. struct pipe *wait_pipe;
  10866. ret = 127; /* bash compat for bad jobspecs */
  10867. wait_pipe = parse_jobspec(*argv);
  10868. if (wait_pipe) {
  10869. ret = job_exited_or_stopped(wait_pipe);
  10870. if (ret < 0) {
  10871. ret = wait_for_child_or_signal(wait_pipe, 0);
  10872. } else {
  10873. /* waiting on "last dead job" removes it */
  10874. clean_up_last_dead_job();
  10875. }
  10876. }
  10877. /* else: parse_jobspec() already emitted error msg */
  10878. continue;
  10879. }
  10880. # endif
  10881. /* mimic bash message */
  10882. bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
  10883. ret = EXIT_FAILURE;
  10884. continue; /* bash checks all argv[] */
  10885. }
  10886. /* Do we have such child? */
  10887. ret = waitpid(pid, &status, WNOHANG);
  10888. if (ret < 0) {
  10889. /* No */
  10890. ret = 127;
  10891. if (errno == ECHILD) {
  10892. if (pid == G.last_bg_pid) {
  10893. /* "wait $!" but last bg task has already exited. Try:
  10894. * (sleep 1; exit 3) & sleep 2; echo $?; wait $!; echo $?
  10895. * In bash it prints exitcode 0, then 3.
  10896. * In dash, it is 127.
  10897. */
  10898. ret = G.last_bg_pid_exitcode;
  10899. } else {
  10900. /* Example: "wait 1". mimic bash message */
  10901. bb_error_msg("wait: pid %u is not a child of this shell", (unsigned)pid);
  10902. }
  10903. } else {
  10904. /* ??? */
  10905. bb_perror_msg("wait %s", *argv);
  10906. }
  10907. continue; /* bash checks all argv[] */
  10908. }
  10909. if (ret == 0) {
  10910. /* Yes, and it still runs */
  10911. ret = wait_for_child_or_signal(NULL, pid);
  10912. } else {
  10913. /* Yes, and it just exited */
  10914. process_wait_result(NULL, pid, status);
  10915. ret = WEXITSTATUS(status);
  10916. if (WIFSIGNALED(status))
  10917. ret = 128 + WTERMSIG(status);
  10918. }
  10919. } while (*++argv);
  10920. return ret;
  10921. }
  10922. #endif
  10923. #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
  10924. static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
  10925. {
  10926. if (argv[1]) {
  10927. def = bb_strtou(argv[1], NULL, 10);
  10928. if (errno || def < def_min || argv[2]) {
  10929. bb_error_msg("%s: bad arguments", argv[0]);
  10930. def = UINT_MAX;
  10931. }
  10932. }
  10933. return def;
  10934. }
  10935. #endif
  10936. #if ENABLE_HUSH_LOOPS
  10937. static int FAST_FUNC builtin_break(char **argv)
  10938. {
  10939. unsigned depth;
  10940. if (G.depth_of_loop == 0) {
  10941. bb_error_msg("%s: only meaningful in a loop", argv[0]);
  10942. /* if we came from builtin_continue(), need to undo "= 1" */
  10943. G.flag_break_continue = 0;
  10944. return EXIT_SUCCESS; /* bash compat */
  10945. }
  10946. G.flag_break_continue++; /* BC_BREAK = 1, or BC_CONTINUE = 2 */
  10947. G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
  10948. if (depth == UINT_MAX)
  10949. G.flag_break_continue = BC_BREAK;
  10950. if (G.depth_of_loop < depth)
  10951. G.depth_break_continue = G.depth_of_loop;
  10952. return EXIT_SUCCESS;
  10953. }
  10954. static int FAST_FUNC builtin_continue(char **argv)
  10955. {
  10956. G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
  10957. return builtin_break(argv);
  10958. }
  10959. #endif
  10960. #if ENABLE_HUSH_FUNCTIONS
  10961. static int FAST_FUNC builtin_return(char **argv)
  10962. {
  10963. int rc;
  10964. if (G_flag_return_in_progress != -1) {
  10965. bb_error_msg("%s: not in a function or sourced script", argv[0]);
  10966. return EXIT_FAILURE; /* bash compat */
  10967. }
  10968. G_flag_return_in_progress = 1;
  10969. /* bash:
  10970. * out of range: wraps around at 256, does not error out
  10971. * non-numeric param:
  10972. * f() { false; return qwe; }; f; echo $?
  10973. * bash: return: qwe: numeric argument required <== we do this
  10974. * 255 <== we also do this
  10975. */
  10976. rc = parse_numeric_argv1(argv, G.last_exitcode, 0);
  10977. # if ENABLE_HUSH_TRAP
  10978. if (argv[1]) { /* "return ARG" inside a running trap sets $? */
  10979. debug_printf_exec("G.return_exitcode=%d\n", rc);
  10980. G.return_exitcode = rc;
  10981. }
  10982. # endif
  10983. return rc;
  10984. }
  10985. #endif
  10986. #if ENABLE_HUSH_TIMES
  10987. static int FAST_FUNC builtin_times(char **argv UNUSED_PARAM)
  10988. {
  10989. static const uint8_t times_tbl[] ALIGN1 = {
  10990. ' ', offsetof(struct tms, tms_utime),
  10991. '\n', offsetof(struct tms, tms_stime),
  10992. ' ', offsetof(struct tms, tms_cutime),
  10993. '\n', offsetof(struct tms, tms_cstime),
  10994. 0
  10995. };
  10996. const uint8_t *p;
  10997. unsigned clk_tck;
  10998. struct tms buf;
  10999. clk_tck = bb_clk_tck();
  11000. times(&buf);
  11001. p = times_tbl;
  11002. do {
  11003. unsigned sec, frac;
  11004. unsigned long t;
  11005. t = *(clock_t *)(((char *) &buf) + p[1]);
  11006. sec = t / clk_tck;
  11007. frac = t % clk_tck;
  11008. printf("%um%u.%03us%c",
  11009. sec / 60, sec % 60,
  11010. (frac * 1000) / clk_tck,
  11011. p[0]);
  11012. p += 2;
  11013. } while (*p);
  11014. return EXIT_SUCCESS;
  11015. }
  11016. #endif
  11017. #if ENABLE_HUSH_MEMLEAK
  11018. static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
  11019. {
  11020. void *p;
  11021. unsigned long l;
  11022. # ifdef M_TRIM_THRESHOLD
  11023. /* Optional. Reduces probability of false positives */
  11024. malloc_trim(0);
  11025. # endif
  11026. /* Crude attempt to find where "free memory" starts,
  11027. * sans fragmentation. */
  11028. p = malloc(240);
  11029. l = (unsigned long)p;
  11030. free(p);
  11031. p = malloc(3400);
  11032. if (l < (unsigned long)p) l = (unsigned long)p;
  11033. free(p);
  11034. # if 0 /* debug */
  11035. {
  11036. struct mallinfo mi = mallinfo();
  11037. printf("top alloc:0x%lx malloced:%d+%d=%d\n", l,
  11038. mi.arena, mi.hblkhd, mi.arena + mi.hblkhd);
  11039. }
  11040. # endif
  11041. if (!G.memleak_value)
  11042. G.memleak_value = l;
  11043. l -= G.memleak_value;
  11044. if ((long)l < 0)
  11045. l = 0;
  11046. l /= 1024;
  11047. if (l > 127)
  11048. l = 127;
  11049. /* Exitcode is "how many kilobytes we leaked since 1st call" */
  11050. return l;
  11051. }
  11052. #endif