hush.c 329 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997
  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. * let EXPR [EXPR...]
  67. * Each EXPR is an arithmetic expression (ARITHMETIC EVALUATION)
  68. * If the last arg evaluates to 0, let returns 1; 0 otherwise.
  69. * NB: let `echo 'a=a + 1'` - error (IOW: multi-word expansion is used)
  70. * ((EXPR))
  71. * The EXPR is evaluated according to ARITHMETIC EVALUATION.
  72. * This is exactly equivalent to let "EXPR".
  73. * $[EXPR]: synonym for $((EXPR))
  74. * indirect expansion: ${!VAR}
  75. * substring op on @: ${@:n:m}
  76. *
  77. * Won't do:
  78. * Some builtins mandated by standards:
  79. * newgrp [GRP]: not a builtin in bash but a suid binary
  80. * which spawns a new shell with new group ID
  81. *
  82. * Status of [[ support:
  83. * [[ args ]] are CMD_SINGLEWORD_NOGLOB:
  84. * v='a b'; [[ $v = 'a b' ]]; echo 0:$?
  85. * [[ /bin/n* ]]; echo 0:$?
  86. * = is glob match operator, not equality operator: STR = GLOB
  87. * == same as =
  88. * =~ is regex match operator: STR =~ REGEX
  89. * TODO:
  90. * quoting needs to be considered (-f is an operator, "-f" and ""-f are not; etc)
  91. * in word = GLOB, quoting should be significant on char-by-char basis: a*cd"*"
  92. */
  93. //config:config HUSH
  94. //config: bool "hush (68 kb)"
  95. //config: default y
  96. //config: select SHELL_HUSH
  97. //config: help
  98. //config: hush is a small shell. It handles the normal flow control
  99. //config: constructs such as if/then/elif/else/fi, for/in/do/done, while loops,
  100. //config: case/esac. Redirections, here documents, $((arithmetic))
  101. //config: and functions are supported.
  102. //config:
  103. //config: It will compile and work on no-mmu systems.
  104. //config:
  105. //config: It does not handle select, aliases, tilde expansion,
  106. //config: &>file and >&file redirection of stdout+stderr.
  107. //config:
  108. // This option is visible (has a description) to make it possible to select
  109. // a "scripted" applet (such as NOLOGIN) but avoid selecting any shells:
  110. //config:config SHELL_HUSH
  111. //config: bool "Internal shell for embedded script support"
  112. //config: default n
  113. //config:
  114. //config:# hush options
  115. //config:# It's only needed to get "nice" menuconfig indenting.
  116. //config:if SHELL_HUSH || HUSH || SH_IS_HUSH || BASH_IS_HUSH
  117. //config:
  118. //config:config HUSH_BASH_COMPAT
  119. //config: bool "bash-compatible extensions"
  120. //config: default y
  121. //config: depends on SHELL_HUSH
  122. //config:
  123. //config:config HUSH_BRACE_EXPANSION
  124. //config: bool "Brace expansion"
  125. //config: default y
  126. //config: depends on HUSH_BASH_COMPAT
  127. //config: help
  128. //config: Enable {abc,def} extension.
  129. //config:
  130. //config:config HUSH_LINENO_VAR
  131. //config: bool "$LINENO variable"
  132. //config: default y
  133. //config: depends on HUSH_BASH_COMPAT
  134. //config:
  135. //config:config HUSH_BASH_SOURCE_CURDIR
  136. //config: bool "'source' and '.' builtins search current directory after $PATH"
  137. //config: default n # do not encourage non-standard behavior
  138. //config: depends on HUSH_BASH_COMPAT
  139. //config: help
  140. //config: This is not compliant with standards. Avoid if possible.
  141. //config:
  142. //config:config HUSH_INTERACTIVE
  143. //config: bool "Interactive mode"
  144. //config: default y
  145. //config: depends on SHELL_HUSH
  146. //config: help
  147. //config: Enable interactive mode (prompt and command editing).
  148. //config: Without this, hush simply reads and executes commands
  149. //config: from stdin just like a shell script from a file.
  150. //config: No prompt, no PS1/PS2 magic shell variables.
  151. //config:
  152. //config:config HUSH_SAVEHISTORY
  153. //config: bool "Save command history to .hush_history"
  154. //config: default y
  155. //config: depends on HUSH_INTERACTIVE && FEATURE_EDITING_SAVEHISTORY
  156. //config:
  157. //config:config HUSH_JOB
  158. //config: bool "Job control"
  159. //config: default y
  160. //config: depends on HUSH_INTERACTIVE
  161. //config: help
  162. //config: Enable job control: Ctrl-Z backgrounds, Ctrl-C interrupts current
  163. //config: command (not entire shell), fg/bg builtins work. Without this option,
  164. //config: "cmd &" still works by simply spawning a process and immediately
  165. //config: prompting for next command (or executing next command in a script),
  166. //config: but no separate process group is formed.
  167. //config:
  168. //config:config HUSH_TICK
  169. //config: bool "Support command substitution"
  170. //config: default y
  171. //config: depends on SHELL_HUSH
  172. //config: help
  173. //config: Enable `command` and $(command).
  174. //config:
  175. //config:config HUSH_IF
  176. //config: bool "Support if/then/elif/else/fi"
  177. //config: default y
  178. //config: depends on SHELL_HUSH
  179. //config:
  180. //config:config HUSH_LOOPS
  181. //config: bool "Support for, while and until loops"
  182. //config: default y
  183. //config: depends on SHELL_HUSH
  184. //config:
  185. //config:config HUSH_CASE
  186. //config: bool "Support case ... esac statement"
  187. //config: default y
  188. //config: depends on SHELL_HUSH
  189. //config: help
  190. //config: Enable case ... esac statement. +400 bytes.
  191. //config:
  192. //config:config HUSH_FUNCTIONS
  193. //config: bool "Support funcname() { commands; } syntax"
  194. //config: default y
  195. //config: depends on SHELL_HUSH
  196. //config: help
  197. //config: Enable support for shell functions. +800 bytes.
  198. //config:
  199. //config:config HUSH_LOCAL
  200. //config: bool "local builtin"
  201. //config: default y
  202. //config: depends on HUSH_FUNCTIONS
  203. //config: help
  204. //config: Enable support for local variables in functions.
  205. //config:
  206. //config:config HUSH_RANDOM_SUPPORT
  207. //config: bool "Pseudorandom generator and $RANDOM variable"
  208. //config: default y
  209. //config: depends on SHELL_HUSH
  210. //config: help
  211. //config: Enable pseudorandom generator and dynamic variable "$RANDOM".
  212. //config: Each read of "$RANDOM" will generate a new pseudorandom value.
  213. //config:
  214. //config:config HUSH_MODE_X
  215. //config: bool "Support 'hush -x' option and 'set -x' command"
  216. //config: default y
  217. //config: depends on SHELL_HUSH
  218. //config: help
  219. //config: This instructs hush to print commands before execution.
  220. //config: Adds ~300 bytes.
  221. //config:
  222. //config:config HUSH_ECHO
  223. //config: bool "echo builtin"
  224. //config: default y
  225. //config: depends on SHELL_HUSH
  226. //config:
  227. //config:config HUSH_PRINTF
  228. //config: bool "printf builtin"
  229. //config: default y
  230. //config: depends on SHELL_HUSH
  231. //config:
  232. //config:config HUSH_TEST
  233. //config: bool "test builtin"
  234. //config: default y
  235. //config: depends on SHELL_HUSH
  236. //config:
  237. //config:config HUSH_HELP
  238. //config: bool "help builtin"
  239. //config: default y
  240. //config: depends on SHELL_HUSH
  241. //config:
  242. //config:config HUSH_EXPORT
  243. //config: bool "export builtin"
  244. //config: default y
  245. //config: depends on SHELL_HUSH
  246. //config:
  247. //config:config HUSH_EXPORT_N
  248. //config: bool "Support 'export -n' option"
  249. //config: default y
  250. //config: depends on HUSH_EXPORT
  251. //config: help
  252. //config: export -n unexports variables. It is a bash extension.
  253. //config:
  254. //config:config HUSH_READONLY
  255. //config: bool "readonly builtin"
  256. //config: default y
  257. //config: depends on SHELL_HUSH
  258. //config: help
  259. //config: Enable support for read-only variables.
  260. //config:
  261. //config:config HUSH_KILL
  262. //config: bool "kill builtin (supports kill %jobspec)"
  263. //config: default y
  264. //config: depends on SHELL_HUSH
  265. //config:
  266. //config:config HUSH_WAIT
  267. //config: bool "wait builtin"
  268. //config: default y
  269. //config: depends on SHELL_HUSH
  270. //config:
  271. //config:config HUSH_COMMAND
  272. //config: bool "command builtin"
  273. //config: default y
  274. //config: depends on SHELL_HUSH
  275. //config:
  276. //config:config HUSH_TRAP
  277. //config: bool "trap builtin"
  278. //config: default y
  279. //config: depends on SHELL_HUSH
  280. //config:
  281. //config:config HUSH_TYPE
  282. //config: bool "type builtin"
  283. //config: default y
  284. //config: depends on SHELL_HUSH
  285. //config:
  286. //config:config HUSH_TIMES
  287. //config: bool "times builtin"
  288. //config: default y
  289. //config: depends on SHELL_HUSH
  290. //config:
  291. //config:config HUSH_READ
  292. //config: bool "read builtin"
  293. //config: default y
  294. //config: depends on SHELL_HUSH
  295. //config:
  296. //config:config HUSH_SET
  297. //config: bool "set builtin"
  298. //config: default y
  299. //config: depends on SHELL_HUSH
  300. //config:
  301. //config:config HUSH_UNSET
  302. //config: bool "unset builtin"
  303. //config: default y
  304. //config: depends on SHELL_HUSH
  305. //config:
  306. //config:config HUSH_ULIMIT
  307. //config: bool "ulimit builtin"
  308. //config: default y
  309. //config: depends on SHELL_HUSH
  310. //config:
  311. //config:config HUSH_UMASK
  312. //config: bool "umask builtin"
  313. //config: default y
  314. //config: depends on SHELL_HUSH
  315. //config:
  316. //config:config HUSH_GETOPTS
  317. //config: bool "getopts builtin"
  318. //config: default y
  319. //config: depends on SHELL_HUSH
  320. //config:
  321. //config:config HUSH_MEMLEAK
  322. //config: bool "memleak builtin (debugging)"
  323. //config: default n
  324. //config: depends on SHELL_HUSH
  325. //config:
  326. //config:endif # hush options
  327. //applet:IF_HUSH(APPLET(hush, BB_DIR_BIN, BB_SUID_DROP))
  328. // APPLET_ODDNAME:name main location suid_type help
  329. //applet:IF_SH_IS_HUSH( APPLET_ODDNAME(sh, hush, BB_DIR_BIN, BB_SUID_DROP, hush))
  330. //applet:IF_BASH_IS_HUSH(APPLET_ODDNAME(bash, hush, BB_DIR_BIN, BB_SUID_DROP, hush))
  331. //kbuild:lib-$(CONFIG_SHELL_HUSH) += hush.o match.o shell_common.o
  332. //kbuild:lib-$(CONFIG_HUSH_RANDOM_SUPPORT) += random.o
  333. /* -i (interactive) is also accepted,
  334. * but does nothing, therefore not shown in help.
  335. * NOMMU-specific options are not meant to be used by users,
  336. * therefore we don't show them either.
  337. */
  338. //usage:#define hush_trivial_usage
  339. //usage: "[-enxl] [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS] / -s [ARGS]]"
  340. //usage:#define hush_full_usage "\n\n"
  341. //usage: "Unix shell interpreter"
  342. #if !(defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) \
  343. || defined(__APPLE__) \
  344. )
  345. # include <malloc.h> /* for malloc_trim */
  346. #endif
  347. #include <glob.h>
  348. /* #include <dmalloc.h> */
  349. #if ENABLE_HUSH_CASE
  350. # include <fnmatch.h>
  351. #endif
  352. #include <sys/times.h>
  353. #include <sys/utsname.h> /* for setting $HOSTNAME */
  354. #include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
  355. #include "unicode.h"
  356. #include "shell_common.h"
  357. #include "math.h"
  358. #include "match.h"
  359. #if ENABLE_HUSH_RANDOM_SUPPORT
  360. # include "random.h"
  361. #else
  362. # define CLEAR_RANDOM_T(rnd) ((void)0)
  363. #endif
  364. #ifndef O_CLOEXEC
  365. # define O_CLOEXEC 0
  366. #endif
  367. #ifndef F_DUPFD_CLOEXEC
  368. # define F_DUPFD_CLOEXEC F_DUPFD
  369. #endif
  370. #if ENABLE_FEATURE_SH_EMBEDDED_SCRIPTS && !(ENABLE_ASH || ENABLE_SH_IS_ASH || ENABLE_BASH_IS_ASH)
  371. # include "embedded_scripts.h"
  372. #else
  373. # define NUM_SCRIPTS 0
  374. #endif
  375. /* So far, all bash compat is controlled by one config option */
  376. /* Separate defines document which part of code implements what */
  377. #define BASH_PATTERN_SUBST ENABLE_HUSH_BASH_COMPAT
  378. #define BASH_SUBSTR ENABLE_HUSH_BASH_COMPAT
  379. #define BASH_SOURCE ENABLE_HUSH_BASH_COMPAT
  380. #define BASH_HOSTNAME_VAR ENABLE_HUSH_BASH_COMPAT
  381. #define BASH_EPOCH_VARS ENABLE_HUSH_BASH_COMPAT
  382. #define BASH_TEST2 (ENABLE_HUSH_BASH_COMPAT && ENABLE_HUSH_TEST)
  383. #define BASH_READ_D ENABLE_HUSH_BASH_COMPAT
  384. /* Build knobs */
  385. #define LEAK_HUNTING 0
  386. #define BUILD_AS_NOMMU 0
  387. /* Enable/disable sanity checks. Ok to enable in production,
  388. * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
  389. * Keeping 1 for now even in released versions.
  390. */
  391. #define HUSH_DEBUG 1
  392. /* Slightly bigger (+200 bytes), but faster hush.
  393. * So far it only enables a trick with counting SIGCHLDs and forks,
  394. * which allows us to do fewer waitpid's.
  395. * (we can detect a case where neither forks were done nor SIGCHLDs happened
  396. * and therefore waitpid will return the same result as last time)
  397. */
  398. #define ENABLE_HUSH_FAST 0
  399. /* TODO: implement simplified code for users which do not need ${var%...} ops
  400. * So far ${var%...} ops are always enabled:
  401. */
  402. #define ENABLE_HUSH_DOLLAR_OPS 1
  403. #if BUILD_AS_NOMMU
  404. # undef BB_MMU
  405. # undef USE_FOR_NOMMU
  406. # undef USE_FOR_MMU
  407. # define BB_MMU 0
  408. # define USE_FOR_NOMMU(...) __VA_ARGS__
  409. # define USE_FOR_MMU(...)
  410. #endif
  411. #include "NUM_APPLETS.h"
  412. #if NUM_APPLETS == 1
  413. /* STANDALONE does not make sense, and won't compile */
  414. # undef CONFIG_FEATURE_SH_STANDALONE
  415. # undef ENABLE_FEATURE_SH_STANDALONE
  416. # undef IF_FEATURE_SH_STANDALONE
  417. # undef IF_NOT_FEATURE_SH_STANDALONE
  418. # define ENABLE_FEATURE_SH_STANDALONE 0
  419. # define IF_FEATURE_SH_STANDALONE(...)
  420. # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
  421. #endif
  422. #if !ENABLE_HUSH_INTERACTIVE
  423. # undef ENABLE_FEATURE_EDITING
  424. # define ENABLE_FEATURE_EDITING 0
  425. # undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
  426. # define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
  427. # undef ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
  428. # define ENABLE_FEATURE_EDITING_SAVE_ON_EXIT 0
  429. #endif
  430. /* Do we support ANY keywords? */
  431. #if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
  432. # define HAS_KEYWORDS 1
  433. # define IF_HAS_KEYWORDS(...) __VA_ARGS__
  434. # define IF_HAS_NO_KEYWORDS(...)
  435. #else
  436. # define HAS_KEYWORDS 0
  437. # define IF_HAS_KEYWORDS(...)
  438. # define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
  439. #endif
  440. /* If you comment out one of these below, it will be #defined later
  441. * to perform debug printfs to stderr: */
  442. #define debug_printf(...) do {} while (0)
  443. /* Finer-grained debug switches */
  444. #define debug_printf_parse(...) do {} while (0)
  445. #define debug_printf_heredoc(...) do {} while (0)
  446. #define debug_print_tree(a, b) do {} while (0)
  447. #define debug_printf_exec(...) do {} while (0)
  448. #define debug_printf_env(...) do {} while (0)
  449. #define debug_printf_jobs(...) do {} while (0)
  450. #define debug_printf_expand(...) do {} while (0)
  451. #define debug_printf_varexp(...) do {} while (0)
  452. #define debug_printf_glob(...) do {} while (0)
  453. #define debug_printf_redir(...) do {} while (0)
  454. #define debug_printf_list(...) do {} while (0)
  455. #define debug_printf_subst(...) do {} while (0)
  456. #define debug_printf_prompt(...) do {} while (0)
  457. #define debug_printf_clean(...) do {} while (0)
  458. #define ERR_PTR ((void*)(long)1)
  459. #define JOB_STATUS_FORMAT "[%u] %-22s %.40s\n"
  460. #define _SPECIAL_VARS_STR "_*@$!?#-"
  461. #define SPECIAL_VARS_STR ("_*@$!?#-" + 1)
  462. #define NUMERIC_SPECVARS_STR ("_*@$!?#-" + 3)
  463. #if BASH_PATTERN_SUBST
  464. /* Support / and // replace ops */
  465. /* Note that // is stored as \ in "encoded" string representation */
  466. # define VAR_ENCODED_SUBST_OPS "\\/%#:-=+?"
  467. # define VAR_SUBST_OPS ("\\/%#:-=+?" + 1)
  468. # define MINUS_PLUS_EQUAL_QUESTION ("\\/%#:-=+?" + 5)
  469. #else
  470. # define VAR_ENCODED_SUBST_OPS "%#:-=+?"
  471. # define VAR_SUBST_OPS "%#:-=+?"
  472. # define MINUS_PLUS_EQUAL_QUESTION ("%#:-=+?" + 3)
  473. #endif
  474. #define SPECIAL_VAR_SYMBOL_STR "\3"
  475. #define SPECIAL_VAR_SYMBOL 3
  476. /* The "variable" with name "\1" emits string "\3". Testcase: "echo ^C" */
  477. #define SPECIAL_VAR_QUOTED_SVS 1
  478. struct variable;
  479. static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
  480. /* This supports saving pointers malloced in vfork child,
  481. * to be freed in the parent.
  482. */
  483. #if !BB_MMU
  484. typedef struct nommu_save_t {
  485. struct variable *old_vars;
  486. char **argv;
  487. char **argv_from_re_execing;
  488. } nommu_save_t;
  489. #endif
  490. enum {
  491. RES_NONE = 0,
  492. #if ENABLE_HUSH_IF
  493. RES_IF ,
  494. RES_THEN ,
  495. RES_ELIF ,
  496. RES_ELSE ,
  497. RES_FI ,
  498. #endif
  499. #if ENABLE_HUSH_LOOPS
  500. RES_FOR ,
  501. RES_WHILE ,
  502. RES_UNTIL ,
  503. RES_DO ,
  504. RES_DONE ,
  505. #endif
  506. #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
  507. RES_IN ,
  508. #endif
  509. #if ENABLE_HUSH_CASE
  510. RES_CASE ,
  511. /* three pseudo-keywords support contrived "case" syntax: */
  512. RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
  513. RES_MATCH , /* "word)" */
  514. RES_CASE_BODY, /* "this command is inside CASE" */
  515. RES_ESAC ,
  516. #endif
  517. RES_XXXX ,
  518. RES_SNTX
  519. };
  520. typedef struct o_string {
  521. char *data;
  522. int length; /* position where data is appended */
  523. int maxlen;
  524. int o_expflags;
  525. /* At least some part of the string was inside '' or "",
  526. * possibly empty one: word"", wo''rd etc. */
  527. smallint has_quoted_part;
  528. smallint has_empty_slot;
  529. smallint ended_in_ifs;
  530. } o_string;
  531. enum {
  532. EXP_FLAG_SINGLEWORD = 0x80, /* must be 0x80 */
  533. EXP_FLAG_GLOB = 0x2,
  534. /* Protect newly added chars against globbing
  535. * by prepending \ to *, ?, [, \ */
  536. EXP_FLAG_ESC_GLOB_CHARS = 0x1,
  537. };
  538. /* Used for initialization: o_string foo = NULL_O_STRING; */
  539. #define NULL_O_STRING { NULL }
  540. #ifndef debug_printf_parse
  541. static const char *const assignment_flag[] = {
  542. "MAYBE_ASSIGNMENT",
  543. "DEFINITELY_ASSIGNMENT",
  544. "NOT_ASSIGNMENT",
  545. "WORD_IS_KEYWORD",
  546. };
  547. #endif
  548. /* We almost can use standard FILE api, but we need an ability to move
  549. * its fd when redirects coincide with it. No api exists for that
  550. * (RFE for it at https://sourceware.org/bugzilla/show_bug.cgi?id=21902).
  551. * HFILE is our internal alternative. Only supports reading.
  552. * Since we now can, we incorporate linked list of all opened HFILEs
  553. * into the struct (used to be a separate mini-list).
  554. */
  555. typedef struct HFILE {
  556. char *cur;
  557. char *end;
  558. struct HFILE *next_hfile;
  559. int fd;
  560. char buf[1024];
  561. } HFILE;
  562. typedef struct in_str {
  563. const char *p;
  564. int peek_buf[2];
  565. int last_char;
  566. HFILE *file;
  567. } in_str;
  568. /* The descrip member of this structure is only used to make
  569. * debugging output pretty */
  570. static const struct {
  571. int32_t mode;
  572. signed char default_fd;
  573. char descrip[3];
  574. } redir_table[] ALIGN4 = {
  575. { O_RDONLY, 0, "<" },
  576. { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
  577. { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
  578. { O_CREAT|O_RDWR, 1, "<>" },
  579. { O_RDONLY, 0, "<<" },
  580. /* Should not be needed. Bogus default_fd helps in debugging */
  581. /* { O_RDONLY, 77, "<<" }, */
  582. };
  583. struct redir_struct {
  584. struct redir_struct *next;
  585. char *rd_filename; /* filename */
  586. int rd_fd; /* fd to redirect */
  587. /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
  588. int rd_dup;
  589. smallint rd_type; /* (enum redir_type) */
  590. /* note: for heredocs, rd_filename contains heredoc delimiter,
  591. * and subsequently heredoc itself; and rd_dup is a bitmask:
  592. * bit 0: do we need to trim leading tabs?
  593. * bit 1: is heredoc quoted (<<'delim' syntax) ?
  594. */
  595. };
  596. typedef enum redir_type {
  597. REDIRECT_INPUT = 0,
  598. REDIRECT_OVERWRITE = 1,
  599. REDIRECT_APPEND = 2,
  600. REDIRECT_IO = 3,
  601. REDIRECT_HEREDOC = 4,
  602. REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
  603. REDIRFD_CLOSE = -3,
  604. REDIRFD_SYNTAX_ERR = -2,
  605. REDIRFD_TO_FILE = -1,
  606. /* otherwise, rd_fd is redirected to rd_dup */
  607. HEREDOC_SKIPTABS = 1,
  608. HEREDOC_QUOTED = 2,
  609. } redir_type;
  610. struct command {
  611. pid_t pid; /* 0 if exited */
  612. unsigned assignment_cnt; /* how many argv[i] are assignments? */
  613. #if ENABLE_HUSH_LINENO_VAR
  614. unsigned lineno;
  615. #endif
  616. smallint cmd_type; /* CMD_xxx */
  617. #define CMD_NORMAL 0
  618. #define CMD_SUBSHELL 1
  619. #if BASH_TEST2
  620. /* used for "[[ EXPR ]]" */
  621. # define CMD_TEST2_SINGLEWORD_NOGLOB 2
  622. #endif
  623. #if BASH_TEST2 || ENABLE_HUSH_LOCAL || ENABLE_HUSH_EXPORT || ENABLE_HUSH_READONLY
  624. /* used to prevent word splitting and globbing in "export v=t*" */
  625. # define CMD_SINGLEWORD_NOGLOB 3
  626. #endif
  627. #if ENABLE_HUSH_FUNCTIONS
  628. # define CMD_FUNCDEF 4
  629. #endif
  630. smalluint cmd_exitcode;
  631. /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
  632. struct pipe *group;
  633. #if !BB_MMU
  634. char *group_as_string;
  635. #endif
  636. #if ENABLE_HUSH_FUNCTIONS
  637. struct function *child_func;
  638. /* This field is used to prevent a bug here:
  639. * while...do f1() {a;}; f1; f1() {b;}; f1; done
  640. * When we execute "f1() {a;}" cmd, we create new function and clear
  641. * cmd->group, cmd->group_as_string, cmd->argv[0].
  642. * When we execute "f1() {b;}", we notice that f1 exists,
  643. * and that its "parent cmd" struct is still "alive",
  644. * we put those fields back into cmd->xxx
  645. * (struct function has ->parent_cmd ptr to facilitate that).
  646. * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
  647. * Without this trick, loop would execute a;b;b;b;...
  648. * instead of correct sequence a;b;a;b;...
  649. * When command is freed, it severs the link
  650. * (sets ->child_func->parent_cmd to NULL).
  651. */
  652. #endif
  653. char **argv; /* command name and arguments */
  654. /* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
  655. * and on execution these are substituted with their values.
  656. * Substitution can make _several_ words out of one argv[n]!
  657. * Example: argv[0]=='.^C*^C.' here: echo .$*.
  658. * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
  659. */
  660. struct redir_struct *redirects; /* I/O redirections */
  661. };
  662. /* Is there anything in this command at all? */
  663. #define IS_NULL_CMD(cmd) \
  664. (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
  665. struct pipe {
  666. struct pipe *next;
  667. int num_cmds; /* total number of commands in pipe */
  668. int alive_cmds; /* number of commands running (not exited) */
  669. int stopped_cmds; /* number of commands alive, but stopped */
  670. #if ENABLE_HUSH_JOB
  671. unsigned jobid; /* job number */
  672. pid_t pgrp; /* process group ID for the job */
  673. char *cmdtext; /* name of job */
  674. #endif
  675. struct command *cmds; /* array of commands in pipe */
  676. smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
  677. IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
  678. IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
  679. };
  680. typedef enum pipe_style {
  681. PIPE_SEQ = 0,
  682. PIPE_AND = 1,
  683. PIPE_OR = 2,
  684. PIPE_BG = 3,
  685. } pipe_style;
  686. /* Is there anything in this pipe at all? */
  687. #define IS_NULL_PIPE(pi) \
  688. ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
  689. /* This holds pointers to the various results of parsing */
  690. struct parse_context {
  691. /* linked list of pipes */
  692. struct pipe *list_head;
  693. /* last pipe (being constructed right now) */
  694. struct pipe *pipe;
  695. /* last command in pipe (being constructed right now) */
  696. struct command *command;
  697. /* last redirect in command->redirects list */
  698. struct redir_struct *pending_redirect;
  699. o_string word;
  700. #if !BB_MMU
  701. o_string as_string;
  702. #endif
  703. smallint is_assignment; /* 0:maybe, 1:yes, 2:no, 3:keyword */
  704. #if HAS_KEYWORDS
  705. smallint ctx_res_w;
  706. smallint ctx_inverted; /* "! cmd | cmd" */
  707. #if ENABLE_HUSH_CASE
  708. smallint ctx_dsemicolon; /* ";;" seen */
  709. #endif
  710. /* bitmask of FLAG_xxx, for figuring out valid reserved words */
  711. int old_flag;
  712. /* group we are enclosed in:
  713. * example: "if pipe1; pipe2; then pipe3; fi"
  714. * when we see "if" or "then", we malloc and copy current context,
  715. * and make ->stack point to it. then we parse pipeN.
  716. * when closing "then" / fi" / whatever is found,
  717. * we move list_head into ->stack->command->group,
  718. * copy ->stack into current context, and delete ->stack.
  719. * (parsing of { list } and ( list ) doesn't use this method)
  720. */
  721. struct parse_context *stack;
  722. #endif
  723. };
  724. enum {
  725. MAYBE_ASSIGNMENT = 0,
  726. DEFINITELY_ASSIGNMENT = 1,
  727. NOT_ASSIGNMENT = 2,
  728. /* Not an assignment, but next word may be: "if v=xyz cmd;" */
  729. WORD_IS_KEYWORD = 3,
  730. };
  731. /* On program start, environ points to initial environment.
  732. * putenv adds new pointers into it, unsetenv removes them.
  733. * Neither of these (de)allocates the strings.
  734. * setenv allocates new strings in malloc space and does putenv,
  735. * and thus setenv is unusable (leaky) for shell's purposes */
  736. #define setenv(...) setenv_is_leaky_dont_use()
  737. struct variable {
  738. struct variable *next;
  739. char *varstr; /* points to "name=" portion */
  740. int max_len; /* if > 0, name is part of initial env; else name is malloced */
  741. uint16_t var_nest_level;
  742. smallint flg_export; /* putenv should be done on this var */
  743. smallint flg_read_only;
  744. };
  745. enum {
  746. BC_BREAK = 1,
  747. BC_CONTINUE = 2,
  748. };
  749. #if ENABLE_HUSH_FUNCTIONS
  750. struct function {
  751. struct function *next;
  752. char *name;
  753. struct command *parent_cmd;
  754. struct pipe *body;
  755. # if !BB_MMU
  756. char *body_as_string;
  757. # endif
  758. };
  759. #endif
  760. /* set -/+o OPT support. (TODO: make it optional)
  761. * bash supports the following opts:
  762. * allexport off
  763. * braceexpand on
  764. * emacs on
  765. * errexit off
  766. * errtrace off
  767. * functrace off
  768. * hashall on
  769. * histexpand off
  770. * history on
  771. * ignoreeof off
  772. * interactive-comments on
  773. * keyword off
  774. * monitor on
  775. * noclobber off
  776. * noexec off
  777. * noglob off
  778. * nolog off
  779. * notify off
  780. * nounset off
  781. * onecmd off
  782. * physical off
  783. * pipefail off
  784. * posix off
  785. * privileged off
  786. * verbose off
  787. * vi off
  788. * xtrace off
  789. */
  790. static const char o_opt_strings[] ALIGN1 =
  791. "pipefail\0"
  792. "noexec\0"
  793. "errexit\0"
  794. #if ENABLE_HUSH_MODE_X
  795. "xtrace\0"
  796. #endif
  797. ;
  798. enum {
  799. OPT_O_PIPEFAIL,
  800. OPT_O_NOEXEC,
  801. OPT_O_ERREXIT,
  802. #if ENABLE_HUSH_MODE_X
  803. OPT_O_XTRACE,
  804. #endif
  805. NUM_OPT_O
  806. };
  807. /* "Globals" within this file */
  808. /* Sorted roughly by size (smaller offsets == smaller code) */
  809. struct globals {
  810. /* interactive_fd != 0 means we are an interactive shell.
  811. * If we are, then saved_tty_pgrp can also be != 0, meaning
  812. * that controlling tty is available. With saved_tty_pgrp == 0,
  813. * job control still works, but terminal signals
  814. * (^C, ^Z, ^Y, ^\) won't work at all, and background
  815. * process groups can only be created with "cmd &".
  816. * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
  817. * to give tty to the foreground process group,
  818. * and will take it back when the group is stopped (^Z)
  819. * or killed (^C).
  820. */
  821. #if ENABLE_HUSH_INTERACTIVE
  822. /* 'interactive_fd' is a fd# open to ctty, if we have one
  823. * _AND_ if we decided to act interactively */
  824. int interactive_fd;
  825. IF_NOT_FEATURE_EDITING_FANCY_PROMPT(char *PS1;)
  826. # define G_interactive_fd (G.interactive_fd)
  827. #else
  828. # define G_interactive_fd 0
  829. #endif
  830. #if ENABLE_FEATURE_EDITING
  831. line_input_t *line_input_state;
  832. #endif
  833. pid_t root_pid;
  834. pid_t root_ppid;
  835. pid_t last_bg_pid;
  836. #if ENABLE_HUSH_RANDOM_SUPPORT
  837. random_t random_gen;
  838. #endif
  839. #if ENABLE_HUSH_JOB
  840. int run_list_level;
  841. unsigned last_jobid;
  842. pid_t saved_tty_pgrp;
  843. struct pipe *job_list;
  844. # define G_saved_tty_pgrp (G.saved_tty_pgrp)
  845. #else
  846. # define G_saved_tty_pgrp 0
  847. #endif
  848. /* How deeply are we in context where "set -e" is ignored */
  849. int errexit_depth;
  850. /* "set -e" rules (do we follow them correctly?):
  851. * Exit if pipe, list, or compound command exits with a non-zero status.
  852. * Shell does not exit if failed command is part of condition in
  853. * if/while, part of && or || list except the last command, any command
  854. * in a pipe but the last, or if the command's return value is being
  855. * inverted with !. If a compound command other than a subshell returns a
  856. * non-zero status because a command failed while -e was being ignored, the
  857. * shell does not exit. A trap on ERR, if set, is executed before the shell
  858. * exits [ERR is a bashism].
  859. *
  860. * If a compound command or function executes in a context where -e is
  861. * ignored, none of the commands executed within are affected by the -e
  862. * setting. If a compound command or function sets -e while executing in a
  863. * context where -e is ignored, that setting does not have any effect until
  864. * the compound command or the command containing the function call completes.
  865. */
  866. char o_opt[NUM_OPT_O];
  867. #if ENABLE_HUSH_MODE_X
  868. # define G_x_mode (G.o_opt[OPT_O_XTRACE])
  869. #else
  870. # define G_x_mode 0
  871. #endif
  872. char opt_s;
  873. char opt_c;
  874. #if ENABLE_HUSH_INTERACTIVE
  875. smallint promptmode; /* 0: PS1, 1: PS2 */
  876. #endif
  877. smallint flag_SIGINT;
  878. #if ENABLE_HUSH_LOOPS
  879. smallint flag_break_continue;
  880. #endif
  881. #if ENABLE_HUSH_FUNCTIONS
  882. /* 0: outside of a function (or sourced file)
  883. * -1: inside of a function, ok to use return builtin
  884. * 1: return is invoked, skip all till end of func
  885. */
  886. smallint flag_return_in_progress;
  887. # define G_flag_return_in_progress (G.flag_return_in_progress)
  888. #else
  889. # define G_flag_return_in_progress 0
  890. #endif
  891. smallint exiting; /* used to prevent EXIT trap recursion */
  892. /* These support $? */
  893. smalluint last_exitcode;
  894. smalluint expand_exitcode;
  895. smalluint last_bg_pid_exitcode;
  896. #if ENABLE_HUSH_SET
  897. /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
  898. smalluint global_args_malloced;
  899. # define G_global_args_malloced (G.global_args_malloced)
  900. #else
  901. # define G_global_args_malloced 0
  902. #endif
  903. #if ENABLE_HUSH_BASH_COMPAT
  904. int dead_job_exitcode; /* for "wait -n" */
  905. #endif
  906. /* how many non-NULL argv's we have. NB: $# + 1 */
  907. int global_argc;
  908. char **global_argv;
  909. #if !BB_MMU
  910. char *argv0_for_re_execing;
  911. #endif
  912. #if ENABLE_HUSH_LOOPS
  913. unsigned depth_break_continue;
  914. unsigned depth_of_loop;
  915. #endif
  916. #if ENABLE_HUSH_GETOPTS
  917. unsigned getopt_count;
  918. #endif
  919. const char *ifs;
  920. char *ifs_whitespace; /* = G.ifs or malloced */
  921. const char *cwd;
  922. struct variable *top_var;
  923. char **expanded_assignments;
  924. struct variable **shadowed_vars_pp;
  925. unsigned var_nest_level;
  926. #if ENABLE_HUSH_FUNCTIONS
  927. # if ENABLE_HUSH_LOCAL
  928. unsigned func_nest_level; /* solely to prevent "local v" in non-functions */
  929. # endif
  930. struct function *top_func;
  931. #endif
  932. /* Signal and trap handling */
  933. #if ENABLE_HUSH_FAST
  934. unsigned count_SIGCHLD;
  935. unsigned handled_SIGCHLD;
  936. smallint we_have_children;
  937. #endif
  938. #if ENABLE_HUSH_LINENO_VAR
  939. unsigned parse_lineno;
  940. unsigned execute_lineno;
  941. #endif
  942. HFILE *HFILE_list;
  943. HFILE *HFILE_stdin;
  944. /* Which signals have non-DFL handler (even with no traps set)?
  945. * Set at the start to:
  946. * (SIGQUIT + maybe SPECIAL_INTERACTIVE_SIGS + maybe SPECIAL_JOBSTOP_SIGS)
  947. * SPECIAL_INTERACTIVE_SIGS are cleared after fork.
  948. * The rest is cleared right before execv syscalls.
  949. * Other than these two times, never modified.
  950. */
  951. unsigned special_sig_mask;
  952. #if ENABLE_HUSH_JOB
  953. unsigned fatal_sig_mask;
  954. # define G_fatal_sig_mask (G.fatal_sig_mask)
  955. #else
  956. # define G_fatal_sig_mask 0
  957. #endif
  958. #if ENABLE_HUSH_TRAP
  959. int pre_trap_exitcode;
  960. # if ENABLE_HUSH_FUNCTIONS
  961. int return_exitcode;
  962. # endif
  963. char **traps; /* char *traps[NSIG] */
  964. # define G_traps G.traps
  965. #else
  966. # define G_traps ((char**)NULL)
  967. #endif
  968. sigset_t pending_set;
  969. #if ENABLE_HUSH_MEMLEAK
  970. unsigned long memleak_value;
  971. #endif
  972. #if ENABLE_HUSH_MODE_X
  973. unsigned x_mode_depth;
  974. /* "set -x" output should not be redirectable with subsequent 2>FILE.
  975. * We dup fd#2 to x_mode_fd when "set -x" is executed, and use it
  976. * for all subsequent output.
  977. */
  978. int x_mode_fd;
  979. o_string x_mode_buf;
  980. #endif
  981. #if HUSH_DEBUG >= 2
  982. int debug_indent;
  983. #endif
  984. struct sigaction sa;
  985. char optstring_buf[sizeof("eixcs")];
  986. #if BASH_EPOCH_VARS
  987. char epoch_buf[sizeof("%llu.nnnnnn") + sizeof(long long)*3];
  988. #endif
  989. #if ENABLE_FEATURE_EDITING
  990. char user_input_buf[CONFIG_FEATURE_EDITING_MAX_LEN];
  991. #endif
  992. };
  993. #define G (*ptr_to_globals)
  994. /* Not #defining name to G.name - this quickly gets unwieldy
  995. * (too many defines). Also, I actually prefer to see when a variable
  996. * is global, thus "G." prefix is a useful hint */
  997. #define INIT_G() do { \
  998. SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
  999. /* memset(&G.sa, 0, sizeof(G.sa)); */ \
  1000. sigfillset(&G.sa.sa_mask); \
  1001. G.sa.sa_flags = SA_RESTART; \
  1002. } while (0)
  1003. /* Function prototypes for builtins */
  1004. static int builtin_cd(char **argv) FAST_FUNC;
  1005. #if ENABLE_HUSH_ECHO
  1006. static int builtin_echo(char **argv) FAST_FUNC;
  1007. #endif
  1008. static int builtin_eval(char **argv) FAST_FUNC;
  1009. static int builtin_exec(char **argv) FAST_FUNC;
  1010. static int builtin_exit(char **argv) FAST_FUNC;
  1011. #if ENABLE_HUSH_EXPORT
  1012. static int builtin_export(char **argv) FAST_FUNC;
  1013. #endif
  1014. #if ENABLE_HUSH_READONLY
  1015. static int builtin_readonly(char **argv) FAST_FUNC;
  1016. #endif
  1017. #if ENABLE_HUSH_JOB
  1018. static int builtin_fg_bg(char **argv) FAST_FUNC;
  1019. static int builtin_jobs(char **argv) FAST_FUNC;
  1020. #endif
  1021. #if ENABLE_HUSH_GETOPTS
  1022. static int builtin_getopts(char **argv) FAST_FUNC;
  1023. #endif
  1024. #if ENABLE_HUSH_HELP
  1025. static int builtin_help(char **argv) FAST_FUNC;
  1026. #endif
  1027. #if MAX_HISTORY && ENABLE_FEATURE_EDITING
  1028. static int builtin_history(char **argv) FAST_FUNC;
  1029. #endif
  1030. #if ENABLE_HUSH_LOCAL
  1031. static int builtin_local(char **argv) FAST_FUNC;
  1032. #endif
  1033. #if ENABLE_HUSH_MEMLEAK
  1034. static int builtin_memleak(char **argv) FAST_FUNC;
  1035. #endif
  1036. #if ENABLE_HUSH_PRINTF
  1037. static int builtin_printf(char **argv) FAST_FUNC;
  1038. #endif
  1039. static int builtin_pwd(char **argv) FAST_FUNC;
  1040. #if ENABLE_HUSH_READ
  1041. static int builtin_read(char **argv) FAST_FUNC;
  1042. #endif
  1043. #if ENABLE_HUSH_SET
  1044. static int builtin_set(char **argv) FAST_FUNC;
  1045. #endif
  1046. static int builtin_shift(char **argv) FAST_FUNC;
  1047. static int builtin_source(char **argv) FAST_FUNC;
  1048. #if ENABLE_HUSH_TEST || BASH_TEST2
  1049. static int builtin_test(char **argv) FAST_FUNC;
  1050. #endif
  1051. #if ENABLE_HUSH_TRAP
  1052. static int builtin_trap(char **argv) FAST_FUNC;
  1053. #endif
  1054. #if ENABLE_HUSH_TYPE
  1055. static int builtin_type(char **argv) FAST_FUNC;
  1056. #endif
  1057. #if ENABLE_HUSH_TIMES
  1058. static int builtin_times(char **argv) FAST_FUNC;
  1059. #endif
  1060. static int builtin_true(char **argv) FAST_FUNC;
  1061. #if ENABLE_HUSH_UMASK
  1062. static int builtin_umask(char **argv) FAST_FUNC;
  1063. #endif
  1064. #if ENABLE_HUSH_UNSET
  1065. static int builtin_unset(char **argv) FAST_FUNC;
  1066. #endif
  1067. #if ENABLE_HUSH_KILL
  1068. static int builtin_kill(char **argv) FAST_FUNC;
  1069. #endif
  1070. #if ENABLE_HUSH_WAIT
  1071. static int builtin_wait(char **argv) FAST_FUNC;
  1072. #endif
  1073. #if ENABLE_HUSH_LOOPS
  1074. static int builtin_break(char **argv) FAST_FUNC;
  1075. static int builtin_continue(char **argv) FAST_FUNC;
  1076. #endif
  1077. #if ENABLE_HUSH_FUNCTIONS
  1078. static int builtin_return(char **argv) FAST_FUNC;
  1079. #endif
  1080. /* Table of built-in functions. They can be forked or not, depending on
  1081. * context: within pipes, they fork. As simple commands, they do not.
  1082. * When used in non-forking context, they can change global variables
  1083. * in the parent shell process. If forked, of course they cannot.
  1084. * For example, 'unset foo | whatever' will parse and run, but foo will
  1085. * still be set at the end. */
  1086. struct built_in_command {
  1087. const char *b_cmd;
  1088. int (*b_function)(char **argv) FAST_FUNC;
  1089. #if ENABLE_HUSH_HELP
  1090. const char *b_descr;
  1091. # define BLTIN(cmd, func, help) { cmd, func, help }
  1092. #else
  1093. # define BLTIN(cmd, func, help) { cmd, func }
  1094. #endif
  1095. };
  1096. static const struct built_in_command bltins1[] ALIGN_PTR = {
  1097. BLTIN("." , builtin_source , "Run commands in file"),
  1098. BLTIN(":" , builtin_true , NULL),
  1099. #if ENABLE_HUSH_JOB
  1100. BLTIN("bg" , builtin_fg_bg , "Resume job in background"),
  1101. #endif
  1102. #if ENABLE_HUSH_LOOPS
  1103. BLTIN("break" , builtin_break , "Exit loop"),
  1104. #endif
  1105. BLTIN("cd" , builtin_cd , "Change directory"),
  1106. #if ENABLE_HUSH_LOOPS
  1107. BLTIN("continue" , builtin_continue, "Start new loop iteration"),
  1108. #endif
  1109. BLTIN("eval" , builtin_eval , "Construct and run shell command"),
  1110. BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
  1111. BLTIN("exit" , builtin_exit , NULL),
  1112. #if ENABLE_HUSH_EXPORT
  1113. BLTIN("export" , builtin_export , "Set environment variables"),
  1114. #endif
  1115. #if ENABLE_HUSH_JOB
  1116. BLTIN("fg" , builtin_fg_bg , "Bring job to foreground"),
  1117. #endif
  1118. #if ENABLE_HUSH_GETOPTS
  1119. BLTIN("getopts" , builtin_getopts , NULL),
  1120. #endif
  1121. #if ENABLE_HUSH_HELP
  1122. BLTIN("help" , builtin_help , NULL),
  1123. #endif
  1124. #if MAX_HISTORY && ENABLE_FEATURE_EDITING
  1125. BLTIN("history" , builtin_history , "Show history"),
  1126. #endif
  1127. #if ENABLE_HUSH_JOB
  1128. BLTIN("jobs" , builtin_jobs , "List jobs"),
  1129. #endif
  1130. #if ENABLE_HUSH_KILL
  1131. BLTIN("kill" , builtin_kill , "Send signals to processes"),
  1132. #endif
  1133. #if ENABLE_HUSH_LOCAL
  1134. BLTIN("local" , builtin_local , "Set local variables"),
  1135. #endif
  1136. #if ENABLE_HUSH_MEMLEAK
  1137. BLTIN("memleak" , builtin_memleak , NULL),
  1138. #endif
  1139. #if ENABLE_HUSH_READ
  1140. BLTIN("read" , builtin_read , "Input into variable"),
  1141. #endif
  1142. #if ENABLE_HUSH_READONLY
  1143. BLTIN("readonly" , builtin_readonly, "Make variables read-only"),
  1144. #endif
  1145. #if ENABLE_HUSH_FUNCTIONS
  1146. BLTIN("return" , builtin_return , "Return from function"),
  1147. #endif
  1148. #if ENABLE_HUSH_SET
  1149. BLTIN("set" , builtin_set , "Set positional parameters"),
  1150. #endif
  1151. BLTIN("shift" , builtin_shift , "Shift positional parameters"),
  1152. #if BASH_SOURCE
  1153. BLTIN("source" , builtin_source , NULL),
  1154. #endif
  1155. #if ENABLE_HUSH_TIMES
  1156. BLTIN("times" , builtin_times , NULL),
  1157. #endif
  1158. #if ENABLE_HUSH_TRAP
  1159. BLTIN("trap" , builtin_trap , "Trap signals"),
  1160. #endif
  1161. BLTIN("true" , builtin_true , NULL),
  1162. #if ENABLE_HUSH_TYPE
  1163. BLTIN("type" , builtin_type , "Show command type"),
  1164. #endif
  1165. #if ENABLE_HUSH_ULIMIT
  1166. BLTIN("ulimit" , shell_builtin_ulimit, "Control resource limits"),
  1167. #endif
  1168. #if ENABLE_HUSH_UMASK
  1169. BLTIN("umask" , builtin_umask , "Set file creation mask"),
  1170. #endif
  1171. #if ENABLE_HUSH_UNSET
  1172. BLTIN("unset" , builtin_unset , "Unset variables"),
  1173. #endif
  1174. #if ENABLE_HUSH_WAIT
  1175. BLTIN("wait" , builtin_wait , "Wait for process to finish"),
  1176. #endif
  1177. };
  1178. /* These builtins won't be used if we are on NOMMU and need to re-exec
  1179. * (it's cheaper to run an external program in this case):
  1180. */
  1181. static const struct built_in_command bltins2[] ALIGN_PTR = {
  1182. #if ENABLE_HUSH_TEST
  1183. BLTIN("[" , builtin_test , NULL),
  1184. #endif
  1185. #if BASH_TEST2
  1186. BLTIN("[[" , builtin_test , NULL),
  1187. #endif
  1188. #if ENABLE_HUSH_ECHO
  1189. BLTIN("echo" , builtin_echo , NULL),
  1190. #endif
  1191. #if ENABLE_HUSH_PRINTF
  1192. BLTIN("printf" , builtin_printf , NULL),
  1193. #endif
  1194. BLTIN("pwd" , builtin_pwd , NULL),
  1195. #if ENABLE_HUSH_TEST
  1196. BLTIN("test" , builtin_test , NULL),
  1197. #endif
  1198. };
  1199. /* Debug printouts.
  1200. */
  1201. #if HUSH_DEBUG >= 2
  1202. /* prevent disasters with G.debug_indent < 0 */
  1203. # define indent() fdprintf(2, "%*s", (G.debug_indent * 2) & 0xff, "")
  1204. # define debug_enter() (G.debug_indent++)
  1205. # define debug_leave() (G.debug_indent--)
  1206. #else
  1207. # define indent() ((void)0)
  1208. # define debug_enter() ((void)0)
  1209. # define debug_leave() ((void)0)
  1210. #endif
  1211. #ifndef debug_printf
  1212. # define debug_printf(...) (indent(), fdprintf(2, __VA_ARGS__))
  1213. #endif
  1214. #ifndef debug_printf_parse
  1215. # define debug_printf_parse(...) (indent(), fdprintf(2, __VA_ARGS__))
  1216. #endif
  1217. #ifndef debug_printf_heredoc
  1218. # define debug_printf_heredoc(...) (indent(), fdprintf(2, __VA_ARGS__))
  1219. #endif
  1220. #ifndef debug_printf_exec
  1221. #define debug_printf_exec(...) (indent(), fdprintf(2, __VA_ARGS__))
  1222. #endif
  1223. #ifndef debug_printf_env
  1224. # define debug_printf_env(...) (indent(), fdprintf(2, __VA_ARGS__))
  1225. #endif
  1226. #ifndef debug_printf_jobs
  1227. # define debug_printf_jobs(...) (indent(), fdprintf(2, __VA_ARGS__))
  1228. # define DEBUG_JOBS 1
  1229. #else
  1230. # define DEBUG_JOBS 0
  1231. #endif
  1232. #ifndef debug_printf_expand
  1233. # define debug_printf_expand(...) (indent(), fdprintf(2, __VA_ARGS__))
  1234. # define DEBUG_EXPAND 1
  1235. #else
  1236. # define DEBUG_EXPAND 0
  1237. #endif
  1238. #ifndef debug_printf_varexp
  1239. # define debug_printf_varexp(...) (indent(), fdprintf(2, __VA_ARGS__))
  1240. #endif
  1241. #ifndef debug_printf_glob
  1242. # define debug_printf_glob(...) (indent(), fdprintf(2, __VA_ARGS__))
  1243. # define DEBUG_GLOB 1
  1244. #else
  1245. # define DEBUG_GLOB 0
  1246. #endif
  1247. #ifndef debug_printf_redir
  1248. # define debug_printf_redir(...) (indent(), fdprintf(2, __VA_ARGS__))
  1249. #endif
  1250. #ifndef debug_printf_list
  1251. # define debug_printf_list(...) (indent(), fdprintf(2, __VA_ARGS__))
  1252. #endif
  1253. #ifndef debug_printf_subst
  1254. # define debug_printf_subst(...) (indent(), fdprintf(2, __VA_ARGS__))
  1255. #endif
  1256. #ifndef debug_printf_prompt
  1257. # define debug_printf_prompt(...) (indent(), fdprintf(2, __VA_ARGS__))
  1258. #endif
  1259. #ifndef debug_printf_clean
  1260. # define debug_printf_clean(...) (indent(), fdprintf(2, __VA_ARGS__))
  1261. # define DEBUG_CLEAN 1
  1262. #else
  1263. # define DEBUG_CLEAN 0
  1264. #endif
  1265. #if DEBUG_EXPAND
  1266. static void debug_print_strings(const char *prefix, char **vv)
  1267. {
  1268. indent();
  1269. fdprintf(2, "%s:\n", prefix);
  1270. while (*vv)
  1271. fdprintf(2, " '%s'\n", *vv++);
  1272. }
  1273. #else
  1274. # define debug_print_strings(prefix, vv) ((void)0)
  1275. #endif
  1276. /* Leak hunting. Use hush_leaktool.sh for post-processing.
  1277. */
  1278. #if LEAK_HUNTING
  1279. static void *xxmalloc(int lineno, size_t size)
  1280. {
  1281. void *ptr = xmalloc((size + 0xff) & ~0xff);
  1282. fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
  1283. return ptr;
  1284. }
  1285. static void *xxrealloc(int lineno, void *ptr, size_t size)
  1286. {
  1287. ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
  1288. fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
  1289. return ptr;
  1290. }
  1291. static char *xxstrdup(int lineno, const char *str)
  1292. {
  1293. char *ptr = xstrdup(str);
  1294. fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
  1295. return ptr;
  1296. }
  1297. static void xxfree(void *ptr)
  1298. {
  1299. fdprintf(2, "free %p\n", ptr);
  1300. free(ptr);
  1301. }
  1302. # define xmalloc(s) xxmalloc(__LINE__, s)
  1303. # define xrealloc(p, s) xxrealloc(__LINE__, p, s)
  1304. # define xstrdup(s) xxstrdup(__LINE__, s)
  1305. # define free(p) xxfree(p)
  1306. #endif
  1307. /* Syntax and runtime errors. They always abort scripts.
  1308. * In interactive use they usually discard unparsed and/or unexecuted commands
  1309. * and return to the prompt.
  1310. * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
  1311. */
  1312. #if HUSH_DEBUG < 2
  1313. # define msg_and_die_if_script(lineno, ...) msg_and_die_if_script(__VA_ARGS__)
  1314. # define syntax_error(lineno, msg) syntax_error(msg)
  1315. # define syntax_error_at(lineno, msg) syntax_error_at(msg)
  1316. # define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
  1317. # define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
  1318. # define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
  1319. #endif
  1320. static void die_if_script(void)
  1321. {
  1322. if (!G_interactive_fd) {
  1323. if (G.last_exitcode) /* sometines it's 2, not 1 (bash compat) */
  1324. xfunc_error_retval = G.last_exitcode;
  1325. xfunc_die();
  1326. }
  1327. }
  1328. static void msg_and_die_if_script(unsigned lineno, const char *fmt, ...)
  1329. {
  1330. va_list p;
  1331. #if HUSH_DEBUG >= 2
  1332. bb_error_msg("hush.c:%u", lineno);
  1333. #endif
  1334. va_start(p, fmt);
  1335. bb_verror_msg(fmt, p, NULL);
  1336. va_end(p);
  1337. die_if_script();
  1338. }
  1339. static void syntax_error(unsigned lineno UNUSED_PARAM, const char *msg)
  1340. {
  1341. if (msg)
  1342. bb_error_msg("syntax error: %s", msg);
  1343. else
  1344. bb_simple_error_msg("syntax error");
  1345. die_if_script();
  1346. }
  1347. static void syntax_error_at(unsigned lineno UNUSED_PARAM, const char *msg)
  1348. {
  1349. bb_error_msg("syntax error at '%s'", msg);
  1350. die_if_script();
  1351. }
  1352. static void syntax_error_unterm_str(unsigned lineno UNUSED_PARAM, const char *s)
  1353. {
  1354. bb_error_msg("syntax error: unterminated %s", s);
  1355. //? source4.tests fails: in bash, echo ${^} in script does not terminate the script
  1356. // die_if_script();
  1357. }
  1358. static void syntax_error_unterm_ch(unsigned lineno, char ch)
  1359. {
  1360. char msg[2] = { ch, '\0' };
  1361. syntax_error_unterm_str(lineno, msg);
  1362. }
  1363. static void syntax_error_unexpected_ch(unsigned lineno UNUSED_PARAM, int ch)
  1364. {
  1365. char msg[2];
  1366. msg[0] = ch;
  1367. msg[1] = '\0';
  1368. #if HUSH_DEBUG >= 2
  1369. bb_error_msg("hush.c:%u", lineno);
  1370. #endif
  1371. bb_error_msg("syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
  1372. die_if_script();
  1373. }
  1374. #if HUSH_DEBUG < 2
  1375. # undef msg_and_die_if_script
  1376. # undef syntax_error
  1377. # undef syntax_error_at
  1378. # undef syntax_error_unterm_ch
  1379. # undef syntax_error_unterm_str
  1380. # undef syntax_error_unexpected_ch
  1381. #else
  1382. # define msg_and_die_if_script(...) msg_and_die_if_script(__LINE__, __VA_ARGS__)
  1383. # define syntax_error(msg) syntax_error(__LINE__, msg)
  1384. # define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
  1385. # define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
  1386. # define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
  1387. # define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
  1388. #endif
  1389. /* Utility functions
  1390. */
  1391. /* Replace each \x with x in place, return ptr past NUL. */
  1392. static char *unbackslash(char *src)
  1393. {
  1394. char *dst = src = strchrnul(src, '\\');
  1395. while (1) {
  1396. if (*src == '\\') {
  1397. src++;
  1398. if (*src != '\0') {
  1399. /* \x -> x */
  1400. *dst++ = *src++;
  1401. continue;
  1402. }
  1403. /* else: "\<nul>". Do not delete this backslash.
  1404. * Testcase: eval 'echo ok\'
  1405. */
  1406. *dst++ = '\\';
  1407. /* fallthrough */
  1408. }
  1409. if ((*dst++ = *src++) == '\0')
  1410. break;
  1411. }
  1412. return dst;
  1413. }
  1414. static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
  1415. {
  1416. int i;
  1417. unsigned count1;
  1418. unsigned count2;
  1419. char **v;
  1420. v = strings;
  1421. count1 = 0;
  1422. if (v) {
  1423. while (*v) {
  1424. count1++;
  1425. v++;
  1426. }
  1427. }
  1428. count2 = 0;
  1429. v = add;
  1430. while (*v) {
  1431. count2++;
  1432. v++;
  1433. }
  1434. v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
  1435. v[count1 + count2] = NULL;
  1436. i = count2;
  1437. while (--i >= 0)
  1438. v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
  1439. return v;
  1440. }
  1441. #if LEAK_HUNTING
  1442. static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
  1443. {
  1444. char **ptr = add_strings_to_strings(strings, add, need_to_dup);
  1445. fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
  1446. return ptr;
  1447. }
  1448. #define add_strings_to_strings(strings, add, need_to_dup) \
  1449. xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
  1450. #endif
  1451. /* Note: takes ownership of "add" ptr (it is not strdup'ed) */
  1452. static char **add_string_to_strings(char **strings, char *add)
  1453. {
  1454. char *v[2];
  1455. v[0] = add;
  1456. v[1] = NULL;
  1457. return add_strings_to_strings(strings, v, /*dup:*/ 0);
  1458. }
  1459. #if LEAK_HUNTING
  1460. static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
  1461. {
  1462. char **ptr = add_string_to_strings(strings, add);
  1463. fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
  1464. return ptr;
  1465. }
  1466. #define add_string_to_strings(strings, add) \
  1467. xx_add_string_to_strings(__LINE__, strings, add)
  1468. #endif
  1469. static void free_strings(char **strings)
  1470. {
  1471. char **v;
  1472. if (!strings)
  1473. return;
  1474. v = strings;
  1475. while (*v) {
  1476. free(*v);
  1477. v++;
  1478. }
  1479. free(strings);
  1480. }
  1481. static int dup_CLOEXEC(int fd, int avoid_fd)
  1482. {
  1483. int newfd;
  1484. repeat:
  1485. newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
  1486. if (newfd >= 0) {
  1487. if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
  1488. fcntl(newfd, F_SETFD, FD_CLOEXEC);
  1489. } else { /* newfd < 0 */
  1490. if (errno == EBUSY)
  1491. goto repeat;
  1492. if (errno == EINTR)
  1493. goto repeat;
  1494. }
  1495. return newfd;
  1496. }
  1497. static int xdup_CLOEXEC_and_close(int fd, int avoid_fd)
  1498. {
  1499. int newfd;
  1500. repeat:
  1501. newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
  1502. if (newfd < 0) {
  1503. if (errno == EBUSY)
  1504. goto repeat;
  1505. if (errno == EINTR)
  1506. goto repeat;
  1507. /* fd was not open? */
  1508. if (errno == EBADF)
  1509. return fd;
  1510. xfunc_die();
  1511. }
  1512. if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
  1513. fcntl(newfd, F_SETFD, FD_CLOEXEC);
  1514. close(fd);
  1515. return newfd;
  1516. }
  1517. /* Manipulating HFILEs */
  1518. static HFILE *hfopen(const char *name)
  1519. {
  1520. HFILE *fp;
  1521. int fd;
  1522. fd = STDIN_FILENO;
  1523. if (name) {
  1524. fd = open(name, O_RDONLY | O_CLOEXEC);
  1525. if (fd < 0)
  1526. return NULL;
  1527. if (O_CLOEXEC == 0) /* ancient libc */
  1528. close_on_exec_on(fd);
  1529. }
  1530. fp = xmalloc(sizeof(*fp));
  1531. if (name == NULL)
  1532. G.HFILE_stdin = fp;
  1533. fp->fd = fd;
  1534. fp->cur = fp->end = fp->buf;
  1535. fp->next_hfile = G.HFILE_list;
  1536. G.HFILE_list = fp;
  1537. return fp;
  1538. }
  1539. static void hfclose(HFILE *fp)
  1540. {
  1541. HFILE **pp = &G.HFILE_list;
  1542. while (*pp) {
  1543. HFILE *cur = *pp;
  1544. if (cur == fp) {
  1545. *pp = cur->next_hfile;
  1546. break;
  1547. }
  1548. pp = &cur->next_hfile;
  1549. }
  1550. if (fp->fd >= 0)
  1551. close(fp->fd);
  1552. free(fp);
  1553. }
  1554. static int refill_HFILE_and_getc(HFILE *fp)
  1555. {
  1556. int n;
  1557. if (fp->fd < 0) {
  1558. /* Already saw EOF */
  1559. return EOF;
  1560. }
  1561. #if ENABLE_HUSH_INTERACTIVE && !ENABLE_FEATURE_EDITING
  1562. /* If user presses ^C, read() restarts after SIGINT (we use SA_RESTART).
  1563. * IOW: ^C will not immediately stop line input.
  1564. * But poll() is different: it does NOT restart after signals.
  1565. */
  1566. if (fp == G.HFILE_stdin) {
  1567. struct pollfd pfd[1];
  1568. pfd[0].fd = fp->fd;
  1569. pfd[0].events = POLLIN;
  1570. n = poll(pfd, 1, -1);
  1571. if (n < 0
  1572. /*&& errno == EINTR - assumed true */
  1573. && sigismember(&G.pending_set, SIGINT)
  1574. ) {
  1575. return '\0';
  1576. }
  1577. }
  1578. #else
  1579. /* if FEATURE_EDITING=y, we do not use this routine for interactive input */
  1580. #endif
  1581. /* Try to buffer more input */
  1582. n = safe_read(fp->fd, fp->buf, sizeof(fp->buf));
  1583. if (n < 0) {
  1584. bb_simple_perror_msg("read error");
  1585. n = 0;
  1586. }
  1587. fp->cur = fp->buf;
  1588. fp->end = fp->buf + n;
  1589. if (n == 0) {
  1590. /* EOF/error */
  1591. close(fp->fd);
  1592. fp->fd = -1;
  1593. return EOF;
  1594. }
  1595. return (unsigned char)(*fp->cur++);
  1596. }
  1597. /* Inlined for common case of non-empty buffer.
  1598. */
  1599. static ALWAYS_INLINE int hfgetc(HFILE *fp)
  1600. {
  1601. if (fp->cur < fp->end)
  1602. return (unsigned char)(*fp->cur++);
  1603. /* Buffer empty */
  1604. return refill_HFILE_and_getc(fp);
  1605. }
  1606. static int move_HFILEs_on_redirect(int fd, int avoid_fd)
  1607. {
  1608. HFILE *fl = G.HFILE_list;
  1609. while (fl) {
  1610. if (fd == fl->fd) {
  1611. /* We use it only on script files, they are all CLOEXEC */
  1612. fl->fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
  1613. debug_printf_redir("redirect_fd %d: matches a script fd, moving it to %d\n", fd, fl->fd);
  1614. return 1; /* "found and moved" */
  1615. }
  1616. fl = fl->next_hfile;
  1617. }
  1618. #if ENABLE_HUSH_MODE_X
  1619. if (G.x_mode_fd > 0 && fd == G.x_mode_fd) {
  1620. G.x_mode_fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
  1621. return 1; /* "found and moved" */
  1622. }
  1623. #endif
  1624. return 0; /* "not in the list" */
  1625. }
  1626. #if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
  1627. static void close_all_HFILE_list(void)
  1628. {
  1629. HFILE *fl = G.HFILE_list;
  1630. while (fl) {
  1631. /* hfclose would also free HFILE object.
  1632. * It is disastrous if we share memory with a vforked parent.
  1633. * I'm not sure we never come here after vfork.
  1634. * Therefore just close fd, nothing more.
  1635. *
  1636. * ">" instead of ">=": we don't close fd#0,
  1637. * interactive shell uses hfopen(NULL) as stdin input
  1638. * which has fl->fd == 0, but fd#0 gets redirected in pipes.
  1639. * If we'd close it here, then e.g. interactive "set | sort"
  1640. * with NOFORKed sort, would have sort's input fd closed.
  1641. */
  1642. if (fl->fd > 0)
  1643. /*hfclose(fl); - unsafe */
  1644. close(fl->fd);
  1645. fl = fl->next_hfile;
  1646. }
  1647. }
  1648. #endif
  1649. static int fd_in_HFILEs(int fd)
  1650. {
  1651. HFILE *fl = G.HFILE_list;
  1652. while (fl) {
  1653. if (fl->fd == fd)
  1654. return 1;
  1655. fl = fl->next_hfile;
  1656. }
  1657. return 0;
  1658. }
  1659. /* Helpers for setting new $n and restoring them back
  1660. */
  1661. typedef struct save_arg_t {
  1662. char *sv_argv0;
  1663. char **sv_g_argv;
  1664. int sv_g_argc;
  1665. IF_HUSH_SET(smallint sv_g_malloced;)
  1666. } save_arg_t;
  1667. static void save_and_replace_G_args(save_arg_t *sv, char **argv)
  1668. {
  1669. sv->sv_argv0 = argv[0];
  1670. sv->sv_g_argv = G.global_argv;
  1671. sv->sv_g_argc = G.global_argc;
  1672. IF_HUSH_SET(sv->sv_g_malloced = G.global_args_malloced;)
  1673. argv[0] = G.global_argv[0]; /* retain $0 */
  1674. G.global_argv = argv;
  1675. IF_HUSH_SET(G.global_args_malloced = 0;)
  1676. G.global_argc = 1 + string_array_len(argv + 1);
  1677. }
  1678. static void restore_G_args(save_arg_t *sv, char **argv)
  1679. {
  1680. #if ENABLE_HUSH_SET
  1681. if (G.global_args_malloced) {
  1682. /* someone ran "set -- arg1 arg2 ...", undo */
  1683. char **pp = G.global_argv;
  1684. while (*++pp) /* note: does not free $0 */
  1685. free(*pp);
  1686. free(G.global_argv);
  1687. }
  1688. #endif
  1689. argv[0] = sv->sv_argv0;
  1690. G.global_argv = sv->sv_g_argv;
  1691. G.global_argc = sv->sv_g_argc;
  1692. IF_HUSH_SET(G.global_args_malloced = sv->sv_g_malloced;)
  1693. }
  1694. /* Basic theory of signal handling in shell
  1695. * ========================================
  1696. * This does not describe what hush does, rather, it is current understanding
  1697. * what it _should_ do. If it doesn't, it's a bug.
  1698. * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
  1699. *
  1700. * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
  1701. * is finished or backgrounded. It is the same in interactive and
  1702. * non-interactive shells, and is the same regardless of whether
  1703. * a user trap handler is installed or a shell special one is in effect.
  1704. * ^C or ^Z from keyboard seems to execute "at once" because it usually
  1705. * backgrounds (i.e. stops) or kills all members of currently running
  1706. * pipe.
  1707. *
  1708. * Wait builtin is interruptible by signals for which user trap is set
  1709. * or by SIGINT in interactive shell.
  1710. *
  1711. * Trap handlers will execute even within trap handlers. (right?)
  1712. *
  1713. * User trap handlers are forgotten when subshell ("(cmd)") is entered,
  1714. * except for handlers set to '' (empty string).
  1715. *
  1716. * If job control is off, backgrounded commands ("cmd &")
  1717. * have SIGINT, SIGQUIT set to SIG_IGN.
  1718. *
  1719. * Commands which are run in command substitution ("`cmd`")
  1720. * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
  1721. *
  1722. * Ordinary commands have signals set to SIG_IGN/DFL as inherited
  1723. * by the shell from its parent.
  1724. *
  1725. * Signals which differ from SIG_DFL action
  1726. * (note: child (i.e., [v]forked) shell is not an interactive shell):
  1727. *
  1728. * SIGQUIT: ignore
  1729. * SIGTERM (interactive): ignore
  1730. * SIGHUP (interactive):
  1731. * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
  1732. * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
  1733. * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
  1734. * that all pipe members are stopped. Try this in bash:
  1735. * while :; do :; done - ^Z does not background it
  1736. * (while :; do :; done) - ^Z backgrounds it
  1737. * SIGINT (interactive): wait for last pipe, ignore the rest
  1738. * of the command line, show prompt. NB: ^C does not send SIGINT
  1739. * to interactive shell while shell is waiting for a pipe,
  1740. * since shell is bg'ed (is not in foreground process group).
  1741. * Example 1: this waits 5 sec, but does not execute ls:
  1742. * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
  1743. * Example 2: this does not wait and does not execute ls:
  1744. * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
  1745. * Example 3: this does not wait 5 sec, but executes ls:
  1746. * "sleep 5; ls -l" + press ^C
  1747. * Example 4: this does not wait and does not execute ls:
  1748. * "sleep 5 & wait; ls -l" + press ^C
  1749. *
  1750. * (What happens to signals which are IGN on shell start?)
  1751. * (What happens with signal mask on shell start?)
  1752. *
  1753. * Old implementation
  1754. * ==================
  1755. * We use in-kernel pending signal mask to determine which signals were sent.
  1756. * We block all signals which we don't want to take action immediately,
  1757. * i.e. we block all signals which need to have special handling as described
  1758. * above, and all signals which have traps set.
  1759. * After each pipe execution, we extract any pending signals via sigtimedwait()
  1760. * and act on them.
  1761. *
  1762. * unsigned special_sig_mask: a mask of such "special" signals
  1763. * sigset_t blocked_set: current blocked signal set
  1764. *
  1765. * "trap - SIGxxx":
  1766. * clear bit in blocked_set unless it is also in special_sig_mask
  1767. * "trap 'cmd' SIGxxx":
  1768. * set bit in blocked_set (even if 'cmd' is '')
  1769. * after [v]fork, if we plan to be a shell:
  1770. * unblock signals with special interactive handling
  1771. * (child shell is not interactive),
  1772. * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
  1773. * after [v]fork, if we plan to exec:
  1774. * POSIX says fork clears pending signal mask in child - no need to clear it.
  1775. * Restore blocked signal set to one inherited by shell just prior to exec.
  1776. *
  1777. * Note: as a result, we do not use signal handlers much. The only uses
  1778. * are to count SIGCHLDs
  1779. * and to restore tty pgrp on signal-induced exit.
  1780. *
  1781. * Note 2 (compat):
  1782. * Standard says "When a subshell is entered, traps that are not being ignored
  1783. * are set to the default actions". bash interprets it so that traps which
  1784. * are set to '' (ignore) are NOT reset to defaults. We do the same.
  1785. *
  1786. * Problem: the above approach makes it unwieldy to catch signals while
  1787. * we are in read builtin, or while we read commands from stdin:
  1788. * masked signals are not visible!
  1789. *
  1790. * New implementation
  1791. * ==================
  1792. * We record each signal we are interested in by installing signal handler
  1793. * for them - a bit like emulating kernel pending signal mask in userspace.
  1794. * We are interested in: signals which need to have special handling
  1795. * as described above, and all signals which have traps set.
  1796. * Signals are recorded in pending_set.
  1797. * After each pipe execution, we extract any pending signals
  1798. * and act on them.
  1799. *
  1800. * unsigned special_sig_mask: a mask of shell-special signals.
  1801. * unsigned fatal_sig_mask: a mask of signals on which we restore tty pgrp.
  1802. * char *traps[sig] if trap for sig is set (even if it's '').
  1803. * sigset_t pending_set: set of sigs we received.
  1804. *
  1805. * "trap - SIGxxx":
  1806. * if sig is in special_sig_mask, set handler back to:
  1807. * record_pending_signo, or to IGN if it's a tty stop signal
  1808. * if sig is in fatal_sig_mask, set handler back to sigexit.
  1809. * else: set handler back to SIG_DFL
  1810. * "trap 'cmd' SIGxxx":
  1811. * set handler to record_pending_signo.
  1812. * "trap '' SIGxxx":
  1813. * set handler to SIG_IGN.
  1814. * after [v]fork, if we plan to be a shell:
  1815. * set signals with special interactive handling to SIG_DFL
  1816. * (because child shell is not interactive),
  1817. * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
  1818. * after [v]fork, if we plan to exec:
  1819. * POSIX says fork clears pending signal mask in child - no need to clear it.
  1820. *
  1821. * To make wait builtin interruptible, we handle SIGCHLD as special signal,
  1822. * otherwise (if we leave it SIG_DFL) sigsuspend in wait builtin will not wake up on it.
  1823. *
  1824. * Note (compat):
  1825. * Standard says "When a subshell is entered, traps that are not being ignored
  1826. * are set to the default actions". bash interprets it so that traps which
  1827. * are set to '' (ignore) are NOT reset to defaults. We do the same.
  1828. */
  1829. enum {
  1830. SPECIAL_INTERACTIVE_SIGS = 0
  1831. | (1 << SIGTERM)
  1832. | (1 << SIGINT)
  1833. | (1 << SIGHUP)
  1834. ,
  1835. SPECIAL_JOBSTOP_SIGS = 0
  1836. #if ENABLE_HUSH_JOB
  1837. | (1 << SIGTTIN)
  1838. | (1 << SIGTTOU)
  1839. | (1 << SIGTSTP)
  1840. #endif
  1841. ,
  1842. };
  1843. static void record_pending_signo(int sig)
  1844. {
  1845. sigaddset(&G.pending_set, sig);
  1846. #if ENABLE_HUSH_FAST
  1847. if (sig == SIGCHLD) {
  1848. G.count_SIGCHLD++;
  1849. //bb_error_msg("[%d] SIGCHLD_handler: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
  1850. }
  1851. #endif
  1852. }
  1853. static sighandler_t install_sighandler(int sig, sighandler_t handler)
  1854. {
  1855. struct sigaction old_sa;
  1856. /* We could use signal() to install handlers... almost:
  1857. * except that we need to mask ALL signals while handlers run.
  1858. * I saw signal nesting in strace, race window isn't small.
  1859. * SA_RESTART is also needed, but in Linux, signal()
  1860. * sets SA_RESTART too.
  1861. */
  1862. /* memset(&G.sa, 0, sizeof(G.sa)); - already done */
  1863. /* sigfillset(&G.sa.sa_mask); - already done */
  1864. /* G.sa.sa_flags = SA_RESTART; - already done */
  1865. G.sa.sa_handler = handler;
  1866. sigaction(sig, &G.sa, &old_sa);
  1867. return old_sa.sa_handler;
  1868. }
  1869. static void hush_exit(int exitcode) NORETURN;
  1870. static void restore_ttypgrp_and__exit(void) NORETURN;
  1871. static void restore_ttypgrp_and__exit(void)
  1872. {
  1873. /* xfunc has failed! die die die */
  1874. /* no EXIT traps, this is an escape hatch! */
  1875. G.exiting = 1;
  1876. hush_exit(xfunc_error_retval);
  1877. }
  1878. #if ENABLE_HUSH_JOB
  1879. /* Needed only on some libc:
  1880. * It was observed that on exit(), fgetc'ed buffered data
  1881. * gets "unwound" via lseek(fd, -NUM, SEEK_CUR).
  1882. * With the net effect that even after fork(), not vfork(),
  1883. * exit() in NOEXECed applet in "sh SCRIPT":
  1884. * noexec_applet_here
  1885. * echo END_OF_SCRIPT
  1886. * lseeks fd in input FILE object from EOF to "e" in "echo END_OF_SCRIPT".
  1887. * This makes "echo END_OF_SCRIPT" executed twice.
  1888. * Similar problems can be seen with msg_and_die_if_script() -> xfunc_die()
  1889. * and in `cmd` handling.
  1890. * If set as die_func(), this makes xfunc_die() exit via _exit(), not exit():
  1891. */
  1892. static void fflush_and__exit(void) NORETURN;
  1893. static void fflush_and__exit(void)
  1894. {
  1895. fflush_all();
  1896. _exit(xfunc_error_retval);
  1897. }
  1898. /* After [v]fork, in child: do not restore tty pgrp on xfunc death */
  1899. # define disable_restore_tty_pgrp_on_exit() (die_func = fflush_and__exit)
  1900. /* After [v]fork, in parent: restore tty pgrp on xfunc death */
  1901. # define enable_restore_tty_pgrp_on_exit() (die_func = restore_ttypgrp_and__exit)
  1902. /* Restores tty foreground process group, and exits.
  1903. * May be called as signal handler for fatal signal
  1904. * (will resend signal to itself, producing correct exit state)
  1905. * or called directly with -EXITCODE.
  1906. * We also call it if xfunc is exiting.
  1907. */
  1908. static void sigexit(int sig) NORETURN;
  1909. static void sigexit(int sig)
  1910. {
  1911. /* Careful: we can end up here after [v]fork. Do not restore
  1912. * tty pgrp then, only top-level shell process does that */
  1913. if (G_saved_tty_pgrp && getpid() == G.root_pid) {
  1914. /* Disable all signals: job control, SIGPIPE, etc.
  1915. * Mostly paranoid measure, to prevent infinite SIGTTOU.
  1916. */
  1917. sigprocmask_allsigs(SIG_BLOCK);
  1918. tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
  1919. }
  1920. /* Not a signal, just exit */
  1921. if (sig <= 0)
  1922. _exit(- sig);
  1923. kill_myself_with_sig(sig); /* does not return */
  1924. }
  1925. #else
  1926. # define disable_restore_tty_pgrp_on_exit() ((void)0)
  1927. # define enable_restore_tty_pgrp_on_exit() ((void)0)
  1928. #endif
  1929. static sighandler_t pick_sighandler(unsigned sig)
  1930. {
  1931. sighandler_t handler = SIG_DFL;
  1932. if (sig < sizeof(unsigned)*8) {
  1933. unsigned sigmask = (1 << sig);
  1934. #if ENABLE_HUSH_JOB
  1935. /* is sig fatal? */
  1936. if (G_fatal_sig_mask & sigmask)
  1937. handler = sigexit;
  1938. else
  1939. #endif
  1940. /* sig has special handling? */
  1941. if (G.special_sig_mask & sigmask) {
  1942. handler = record_pending_signo;
  1943. /* TTIN/TTOU/TSTP can't be set to record_pending_signo
  1944. * in order to ignore them: they will be raised
  1945. * in an endless loop when we try to do some
  1946. * terminal ioctls! We do have to _ignore_ these.
  1947. */
  1948. if (SPECIAL_JOBSTOP_SIGS & sigmask)
  1949. handler = SIG_IGN;
  1950. }
  1951. }
  1952. return handler;
  1953. }
  1954. /* Restores tty foreground process group, and exits. */
  1955. static void hush_exit(int exitcode)
  1956. {
  1957. #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
  1958. save_history(G.line_input_state); /* may be NULL */
  1959. #endif
  1960. fflush_all();
  1961. if (G.exiting <= 0 && G_traps && G_traps[0] && G_traps[0][0]) {
  1962. char *argv[3];
  1963. /* argv[0] is unused */
  1964. argv[1] = xstrdup(G_traps[0]); /* copy, since EXIT trap handler may modify G_traps[0] */
  1965. argv[2] = NULL;
  1966. G.exiting = 1; /* prevent EXIT trap recursion */
  1967. /* Note: G_traps[0] is not cleared!
  1968. * "trap" will still show it, if executed
  1969. * in the handler */
  1970. builtin_eval(argv);
  1971. }
  1972. #if ENABLE_FEATURE_CLEAN_UP
  1973. {
  1974. struct variable *cur_var;
  1975. if (G.cwd != bb_msg_unknown)
  1976. free((char*)G.cwd);
  1977. cur_var = G.top_var;
  1978. while (cur_var) {
  1979. struct variable *tmp = cur_var;
  1980. if (!cur_var->max_len)
  1981. free(cur_var->varstr);
  1982. cur_var = cur_var->next;
  1983. free(tmp);
  1984. }
  1985. }
  1986. #endif
  1987. fflush_all();
  1988. #if ENABLE_HUSH_JOB
  1989. sigexit(- (exitcode & 0xff));
  1990. #else
  1991. _exit(exitcode);
  1992. #endif
  1993. }
  1994. //TODO: return a mask of ALL handled sigs?
  1995. static int check_and_run_traps(void)
  1996. {
  1997. int last_sig = 0;
  1998. while (1) {
  1999. int sig;
  2000. if (sigisemptyset(&G.pending_set))
  2001. break;
  2002. sig = 0;
  2003. do {
  2004. sig++;
  2005. if (sigismember(&G.pending_set, sig)) {
  2006. sigdelset(&G.pending_set, sig);
  2007. goto got_sig;
  2008. }
  2009. } while (sig < NSIG);
  2010. break;
  2011. got_sig:
  2012. #if ENABLE_HUSH_TRAP
  2013. if (G_traps && G_traps[sig]) {
  2014. debug_printf_exec("%s: sig:%d handler:'%s'\n", __func__, sig, G.traps[sig]);
  2015. if (G_traps[sig][0]) {
  2016. /* We have user-defined handler */
  2017. smalluint save_rcode;
  2018. int save_pre;
  2019. char *argv[3];
  2020. /* argv[0] is unused */
  2021. argv[1] = xstrdup(G_traps[sig]);
  2022. /* why strdup? trap can modify itself: trap 'trap "echo oops" INT' INT */
  2023. argv[2] = NULL;
  2024. save_pre = G.pre_trap_exitcode;
  2025. G.pre_trap_exitcode = save_rcode = G.last_exitcode;
  2026. builtin_eval(argv);
  2027. free(argv[1]);
  2028. G.pre_trap_exitcode = save_pre;
  2029. G.last_exitcode = save_rcode;
  2030. # if ENABLE_HUSH_FUNCTIONS
  2031. if (G.return_exitcode >= 0) {
  2032. debug_printf_exec("trap exitcode:%d\n", G.return_exitcode);
  2033. G.last_exitcode = G.return_exitcode;
  2034. }
  2035. # endif
  2036. last_sig = sig;
  2037. } /* else: "" trap, ignoring signal */
  2038. continue;
  2039. }
  2040. #endif
  2041. /* not a trap: special action */
  2042. switch (sig) {
  2043. case SIGINT:
  2044. debug_printf_exec("%s: sig:%d default SIGINT handler\n", __func__, sig);
  2045. G.flag_SIGINT = 1;
  2046. last_sig = sig;
  2047. break;
  2048. #if ENABLE_HUSH_JOB
  2049. case SIGHUP: {
  2050. //TODO: why are we doing this? ash and dash don't do this,
  2051. //they have no handler for SIGHUP at all,
  2052. //they rely on kernel to send SIGHUP+SIGCONT to orphaned process groups
  2053. struct pipe *job;
  2054. debug_printf_exec("%s: sig:%d default SIGHUP handler\n", __func__, sig);
  2055. /* bash is observed to signal whole process groups,
  2056. * not individual processes */
  2057. for (job = G.job_list; job; job = job->next) {
  2058. if (job->pgrp <= 0)
  2059. continue;
  2060. debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
  2061. if (kill(- job->pgrp, SIGHUP) == 0)
  2062. kill(- job->pgrp, SIGCONT);
  2063. }
  2064. sigexit(SIGHUP);
  2065. }
  2066. #endif
  2067. #if ENABLE_HUSH_FAST
  2068. case SIGCHLD:
  2069. debug_printf_exec("%s: sig:%d default SIGCHLD handler\n", __func__, sig);
  2070. G.count_SIGCHLD++;
  2071. //bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
  2072. /* Note:
  2073. * We don't do 'last_sig = sig' here -> NOT returning this sig.
  2074. * This simplifies wait builtin a bit.
  2075. */
  2076. break;
  2077. #endif
  2078. default: /* ignored: */
  2079. debug_printf_exec("%s: sig:%d default handling is to ignore\n", __func__, sig);
  2080. /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
  2081. /* Note:
  2082. * We don't do 'last_sig = sig' here -> NOT returning this sig.
  2083. * Example: wait is not interrupted by TERM
  2084. * in interactive shell, because TERM is ignored.
  2085. */
  2086. break;
  2087. }
  2088. }
  2089. return last_sig;
  2090. }
  2091. static const char *get_cwd(int force)
  2092. {
  2093. if (force || G.cwd == NULL) {
  2094. /* xrealloc_getcwd_or_warn(arg) calls free(arg),
  2095. * we must not try to free(bb_msg_unknown) */
  2096. if (G.cwd == bb_msg_unknown)
  2097. G.cwd = NULL;
  2098. G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
  2099. if (!G.cwd)
  2100. G.cwd = bb_msg_unknown;
  2101. }
  2102. return G.cwd;
  2103. }
  2104. /*
  2105. * Shell and environment variable support
  2106. */
  2107. static struct variable **get_ptr_to_local_var(const char *name, unsigned len)
  2108. {
  2109. struct variable **pp;
  2110. struct variable *cur;
  2111. pp = &G.top_var;
  2112. while ((cur = *pp) != NULL) {
  2113. if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
  2114. return pp;
  2115. pp = &cur->next;
  2116. }
  2117. return NULL;
  2118. }
  2119. static const char* FAST_FUNC get_local_var_value(const char *name)
  2120. {
  2121. struct variable **vpp;
  2122. unsigned len = strlen(name);
  2123. if (G.expanded_assignments) {
  2124. char **cpp = G.expanded_assignments;
  2125. while (*cpp) {
  2126. char *cp = *cpp;
  2127. if (strncmp(cp, name, len) == 0 && cp[len] == '=')
  2128. return cp + len + 1;
  2129. cpp++;
  2130. }
  2131. }
  2132. vpp = get_ptr_to_local_var(name, len);
  2133. if (vpp)
  2134. return (*vpp)->varstr + len + 1;
  2135. if (strcmp(name, "PPID") == 0)
  2136. return utoa(G.root_ppid);
  2137. // bash compat: UID? EUID?
  2138. #if ENABLE_HUSH_RANDOM_SUPPORT
  2139. if (strcmp(name, "RANDOM") == 0)
  2140. return utoa(next_random(&G.random_gen));
  2141. #endif
  2142. #if ENABLE_HUSH_LINENO_VAR
  2143. if (strcmp(name, "LINENO") == 0)
  2144. return utoa(G.execute_lineno);
  2145. #endif
  2146. #if BASH_EPOCH_VARS
  2147. {
  2148. const char *fmt = NULL;
  2149. if (strcmp(name, "EPOCHSECONDS") == 0)
  2150. fmt = "%llu";
  2151. else if (strcmp(name, "EPOCHREALTIME") == 0)
  2152. fmt = "%llu.%06u";
  2153. if (fmt) {
  2154. struct timeval tv;
  2155. xgettimeofday(&tv);
  2156. sprintf(G.epoch_buf, fmt, (unsigned long long)tv.tv_sec,
  2157. (unsigned)tv.tv_usec);
  2158. return G.epoch_buf;
  2159. }
  2160. }
  2161. #endif
  2162. return NULL;
  2163. }
  2164. #if ENABLE_HUSH_GETOPTS
  2165. static void handle_changed_special_names(const char *name, unsigned name_len)
  2166. {
  2167. if (name_len == 6) {
  2168. if (strncmp(name, "OPTIND", 6) == 0) {
  2169. G.getopt_count = 0;
  2170. return;
  2171. }
  2172. }
  2173. }
  2174. #else
  2175. /* Do not even bother evaluating arguments */
  2176. # define handle_changed_special_names(...) ((void)0)
  2177. #endif
  2178. /* str holds "NAME=VAL" and is expected to be malloced.
  2179. * We take ownership of it.
  2180. */
  2181. #define SETFLAG_EXPORT (1 << 0)
  2182. #define SETFLAG_UNEXPORT (1 << 1)
  2183. #define SETFLAG_MAKE_RO (1 << 2)
  2184. #define SETFLAG_VARLVL_SHIFT 3
  2185. static int set_local_var(char *str, unsigned flags)
  2186. {
  2187. struct variable **cur_pp;
  2188. struct variable *cur;
  2189. char *free_me = NULL;
  2190. char *eq_sign;
  2191. int name_len;
  2192. int retval;
  2193. unsigned local_lvl = (flags >> SETFLAG_VARLVL_SHIFT);
  2194. eq_sign = strchr(str, '=');
  2195. if (HUSH_DEBUG && !eq_sign)
  2196. bb_simple_error_msg_and_die("BUG in setvar");
  2197. name_len = eq_sign - str + 1; /* including '=' */
  2198. cur_pp = &G.top_var;
  2199. while ((cur = *cur_pp) != NULL) {
  2200. if (strncmp(cur->varstr, str, name_len) != 0) {
  2201. cur_pp = &cur->next;
  2202. continue;
  2203. }
  2204. /* We found an existing var with this name */
  2205. if (cur->flg_read_only) {
  2206. bb_error_msg("%s: readonly variable", str);
  2207. free(str);
  2208. //NOTE: in bash, assignment in "export READONLY_VAR=Z" fails, and sets $?=1,
  2209. //but export per se succeeds (does put the var in env). We don't mimic that.
  2210. return -1;
  2211. }
  2212. if (flags & SETFLAG_UNEXPORT) { // && cur->flg_export ?
  2213. debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
  2214. *eq_sign = '\0';
  2215. unsetenv(str);
  2216. *eq_sign = '=';
  2217. }
  2218. if (cur->var_nest_level < local_lvl) {
  2219. /* bash 3.2.33(1) and exported vars:
  2220. * # export z=z
  2221. * # f() { local z=a; env | grep ^z; }
  2222. * # f
  2223. * z=a
  2224. * # env | grep ^z
  2225. * z=z
  2226. */
  2227. if (cur->flg_export)
  2228. flags |= SETFLAG_EXPORT;
  2229. /* New variable is local ("local VAR=VAL" or
  2230. * "VAR=VAL cmd")
  2231. * and existing one is global, or local
  2232. * on a lower level that new one.
  2233. * Remove it from global variable list:
  2234. */
  2235. *cur_pp = cur->next;
  2236. if (G.shadowed_vars_pp) {
  2237. /* Save in "shadowed" list */
  2238. debug_printf_env("shadowing %s'%s'/%u by '%s'/%u\n",
  2239. cur->flg_export ? "exported " : "",
  2240. cur->varstr, cur->var_nest_level, str, local_lvl
  2241. );
  2242. cur->next = *G.shadowed_vars_pp;
  2243. *G.shadowed_vars_pp = cur;
  2244. } else {
  2245. /* Came from pseudo_exec_argv(), no need to save: delete it */
  2246. debug_printf_env("shadow-deleting %s'%s'/%u by '%s'/%u\n",
  2247. cur->flg_export ? "exported " : "",
  2248. cur->varstr, cur->var_nest_level, str, local_lvl
  2249. );
  2250. if (cur->max_len == 0) /* allocated "VAR=VAL"? */
  2251. free_me = cur->varstr; /* then free it later */
  2252. free(cur);
  2253. }
  2254. break;
  2255. }
  2256. if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
  2257. debug_printf_env("assignement '%s' does not change anything\n", str);
  2258. free_and_exp:
  2259. free(str);
  2260. goto exp;
  2261. }
  2262. /* Replace the value in the found "struct variable" */
  2263. if (cur->max_len != 0) {
  2264. if (cur->max_len >= strnlen(str, cur->max_len + 1)) {
  2265. /* This one is from startup env, reuse space */
  2266. debug_printf_env("reusing startup env for '%s'\n", str);
  2267. strcpy(cur->varstr, str);
  2268. goto free_and_exp;
  2269. }
  2270. /* Can't reuse */
  2271. cur->max_len = 0;
  2272. goto set_str_and_exp;
  2273. }
  2274. /* max_len == 0 signifies "malloced" var, which we can
  2275. * (and have to) free. But we can't free(cur->varstr) here:
  2276. * if cur->flg_export is 1, it is in the environment.
  2277. * We should either unsetenv+free, or wait until putenv,
  2278. * then putenv(new)+free(old).
  2279. */
  2280. free_me = cur->varstr;
  2281. goto set_str_and_exp;
  2282. }
  2283. /* Not found or shadowed - create new variable struct */
  2284. debug_printf_env("%s: alloc new var '%s'/%u\n", __func__, str, local_lvl);
  2285. cur = xzalloc(sizeof(*cur));
  2286. cur->var_nest_level = local_lvl;
  2287. cur->next = *cur_pp;
  2288. *cur_pp = cur;
  2289. set_str_and_exp:
  2290. cur->varstr = str;
  2291. exp:
  2292. #if !BB_MMU || ENABLE_HUSH_READONLY
  2293. if (flags & SETFLAG_MAKE_RO) {
  2294. cur->flg_read_only = 1;
  2295. }
  2296. #endif
  2297. if (flags & SETFLAG_EXPORT)
  2298. cur->flg_export = 1;
  2299. retval = 0;
  2300. if (cur->flg_export) {
  2301. if (flags & SETFLAG_UNEXPORT) {
  2302. cur->flg_export = 0;
  2303. /* unsetenv was already done */
  2304. } else {
  2305. debug_printf_env("%s: putenv '%s'/%u\n", __func__, cur->varstr, cur->var_nest_level);
  2306. retval = putenv(cur->varstr);
  2307. /* fall through to "free(free_me)" -
  2308. * only now we can free old exported malloced string
  2309. */
  2310. }
  2311. }
  2312. free(free_me);
  2313. handle_changed_special_names(cur->varstr, name_len - 1);
  2314. return retval;
  2315. }
  2316. static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
  2317. {
  2318. char *var = xasprintf("%s=%s", name, val);
  2319. set_local_var(var, /*flag:*/ 0);
  2320. }
  2321. /* Used at startup and after each cd */
  2322. static void set_pwd_var(unsigned flag)
  2323. {
  2324. set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)), flag);
  2325. }
  2326. #if ENABLE_HUSH_UNSET || ENABLE_HUSH_GETOPTS
  2327. static int unset_local_var_len(const char *name, int name_len)
  2328. {
  2329. struct variable *cur;
  2330. struct variable **cur_pp;
  2331. cur_pp = &G.top_var;
  2332. while ((cur = *cur_pp) != NULL) {
  2333. if (strncmp(cur->varstr, name, name_len) == 0
  2334. && cur->varstr[name_len] == '='
  2335. ) {
  2336. if (cur->flg_read_only) {
  2337. bb_error_msg("%s: readonly variable", name);
  2338. return EXIT_FAILURE;
  2339. }
  2340. *cur_pp = cur->next;
  2341. debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
  2342. bb_unsetenv(cur->varstr);
  2343. if (!cur->max_len)
  2344. free(cur->varstr);
  2345. free(cur);
  2346. break;
  2347. }
  2348. cur_pp = &cur->next;
  2349. }
  2350. /* Handle "unset LINENO" et al even if did not find the variable to unset */
  2351. handle_changed_special_names(name, name_len);
  2352. return EXIT_SUCCESS;
  2353. }
  2354. static int unset_local_var(const char *name)
  2355. {
  2356. return unset_local_var_len(name, strlen(name));
  2357. }
  2358. #endif
  2359. /*
  2360. * Helpers for "var1=val1 var2=val2 cmd" feature
  2361. */
  2362. static void add_vars(struct variable *var)
  2363. {
  2364. struct variable *next;
  2365. while (var) {
  2366. next = var->next;
  2367. var->next = G.top_var;
  2368. G.top_var = var;
  2369. if (var->flg_export) {
  2370. debug_printf_env("%s: restoring exported '%s'/%u\n", __func__, var->varstr, var->var_nest_level);
  2371. putenv(var->varstr);
  2372. } else {
  2373. debug_printf_env("%s: restoring variable '%s'/%u\n", __func__, var->varstr, var->var_nest_level);
  2374. }
  2375. var = next;
  2376. }
  2377. }
  2378. /* We put strings[i] into variable table and possibly putenv them.
  2379. * If variable is read only, we can free the strings[i]
  2380. * which attempts to overwrite it.
  2381. * The strings[] vector itself is freed.
  2382. */
  2383. static void set_vars_and_save_old(char **strings)
  2384. {
  2385. char **s;
  2386. if (!strings)
  2387. return;
  2388. s = strings;
  2389. while (*s) {
  2390. struct variable *var_p;
  2391. struct variable **var_pp;
  2392. char *eq;
  2393. eq = strchr(*s, '=');
  2394. if (HUSH_DEBUG && !eq)
  2395. bb_simple_error_msg_and_die("BUG in varexp4");
  2396. var_pp = get_ptr_to_local_var(*s, eq - *s);
  2397. if (var_pp) {
  2398. var_p = *var_pp;
  2399. if (var_p->flg_read_only) {
  2400. char **p;
  2401. bb_error_msg("%s: readonly variable", *s);
  2402. /*
  2403. * "VAR=V BLTIN" unsets VARs after BLTIN completes.
  2404. * If VAR is readonly, leaving it in the list
  2405. * after asssignment error (msg above)
  2406. * causes doubled error message later, on unset.
  2407. */
  2408. debug_printf_env("removing/freeing '%s' element\n", *s);
  2409. free(*s);
  2410. p = s;
  2411. do { *p = p[1]; p++; } while (*p);
  2412. goto next;
  2413. }
  2414. /* below, set_local_var() with nest level will
  2415. * "shadow" (remove) this variable from
  2416. * global linked list.
  2417. */
  2418. }
  2419. debug_printf_env("%s: env override '%s'/%u\n", __func__, *s, G.var_nest_level);
  2420. set_local_var(*s, (G.var_nest_level << SETFLAG_VARLVL_SHIFT) | SETFLAG_EXPORT);
  2421. s++;
  2422. next: ;
  2423. }
  2424. free(strings);
  2425. }
  2426. /*
  2427. * Unicode helper
  2428. */
  2429. static void reinit_unicode_for_hush(void)
  2430. {
  2431. /* Unicode support should be activated even if LANG is set
  2432. * _during_ shell execution, not only if it was set when
  2433. * shell was started. Therefore, re-check LANG every time:
  2434. */
  2435. if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
  2436. || ENABLE_UNICODE_USING_LOCALE
  2437. ) {
  2438. const char *s = get_local_var_value("LC_ALL");
  2439. if (!s) s = get_local_var_value("LC_CTYPE");
  2440. if (!s) s = get_local_var_value("LANG");
  2441. reinit_unicode(s);
  2442. }
  2443. }
  2444. /*
  2445. * in_str support (strings, and "strings" read from files).
  2446. */
  2447. #if ENABLE_HUSH_INTERACTIVE
  2448. /* To test correct lineedit/interactive behavior, type from command line:
  2449. * echo $P\
  2450. * \
  2451. * AT\
  2452. * H\
  2453. * \
  2454. * It exercises a lot of corner cases.
  2455. */
  2456. static const char *setup_prompt_string(void)
  2457. {
  2458. const char *prompt_str;
  2459. debug_printf_prompt("%s promptmode:%d\n", __func__, G.promptmode);
  2460. # if ENABLE_FEATURE_EDITING_FANCY_PROMPT
  2461. prompt_str = get_local_var_value(G.promptmode == 0 ? "PS1" : "PS2");
  2462. if (!prompt_str)
  2463. prompt_str = "";
  2464. # else
  2465. prompt_str = "> "; /* if PS2, else... */
  2466. if (G.promptmode == 0) { /* PS1 */
  2467. /* No fancy prompts supported, (re)generate "CURDIR $ " by hand */
  2468. free(G.PS1);
  2469. /* bash uses $PWD value, even if it is set by user.
  2470. * It uses current dir only if PWD is unset.
  2471. * We always use current dir. */
  2472. prompt_str = G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
  2473. }
  2474. # endif
  2475. debug_printf("prompt_str '%s'\n", prompt_str);
  2476. return prompt_str;
  2477. }
  2478. static int get_user_input(struct in_str *i)
  2479. {
  2480. # if ENABLE_FEATURE_EDITING
  2481. /* In EDITING case, this function reads next input line,
  2482. * saves it in i->p, then returns 1st char of it.
  2483. */
  2484. int r;
  2485. const char *prompt_str;
  2486. prompt_str = setup_prompt_string();
  2487. for (;;) {
  2488. reinit_unicode_for_hush();
  2489. G.flag_SIGINT = 0;
  2490. /* buglet: SIGINT will not make new prompt to appear _at once_,
  2491. * only after <Enter>. (^C works immediately) */
  2492. r = read_line_input(G.line_input_state, prompt_str,
  2493. G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1
  2494. );
  2495. /* read_line_input intercepts ^C, "convert" it to SIGINT */
  2496. if (r == 0) {
  2497. raise(SIGINT);
  2498. }
  2499. check_and_run_traps();
  2500. if (r != 0 && !G.flag_SIGINT)
  2501. break;
  2502. /* ^C or SIGINT: repeat */
  2503. /* bash prints ^C even on real SIGINT (non-kbd generated) */
  2504. write(STDOUT_FILENO, "^C\n", 3);
  2505. G.last_exitcode = 128 | SIGINT;
  2506. }
  2507. if (r < 0) {
  2508. /* EOF/error detected */
  2509. i->p = NULL;
  2510. i->peek_buf[0] = r = EOF;
  2511. return r;
  2512. }
  2513. i->p = G.user_input_buf;
  2514. return (unsigned char)*i->p++;
  2515. # else
  2516. /* In !EDITING case, this function gets called for every char.
  2517. * Buffering happens deeper in the call chain, in hfgetc(i->file).
  2518. */
  2519. int r;
  2520. for (;;) {
  2521. G.flag_SIGINT = 0;
  2522. if (i->last_char == '\0' || i->last_char == '\n') {
  2523. const char *prompt_str = setup_prompt_string();
  2524. /* Why check_and_run_traps here? Try this interactively:
  2525. * $ trap 'echo INT' INT; (sleep 2; kill -INT $$) &
  2526. * $ <[enter], repeatedly...>
  2527. * Without check_and_run_traps, handler never runs.
  2528. */
  2529. check_and_run_traps();
  2530. fputs(prompt_str, stdout);
  2531. fflush_all();
  2532. }
  2533. r = hfgetc(i->file);
  2534. /* In !ENABLE_FEATURE_EDITING we don't use read_line_input,
  2535. * no ^C masking happens during fgetc, no special code for ^C:
  2536. * it generates SIGINT as usual.
  2537. */
  2538. check_and_run_traps();
  2539. if (r != '\0' && !G.flag_SIGINT)
  2540. break;
  2541. if (G.flag_SIGINT) {
  2542. /* ^C or SIGINT: repeat */
  2543. /* bash prints ^C even on real SIGINT (non-kbd generated) */
  2544. /* kernel prints "^C" itself, just print newline: */
  2545. write(STDOUT_FILENO, "\n", 1);
  2546. G.last_exitcode = 128 | SIGINT;
  2547. }
  2548. }
  2549. return r;
  2550. # endif
  2551. }
  2552. /* This is the magic location that prints prompts
  2553. * and gets data back from the user */
  2554. static int fgetc_interactive(struct in_str *i)
  2555. {
  2556. int ch;
  2557. /* If it's interactive stdin, get new line. */
  2558. if (G_interactive_fd && i->file == G.HFILE_stdin) {
  2559. /* Returns first char (or EOF), the rest is in i->p[] */
  2560. ch = get_user_input(i);
  2561. G.promptmode = 1; /* PS2 */
  2562. debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
  2563. } else {
  2564. /* Not stdin: script file, sourced file, etc */
  2565. do ch = hfgetc(i->file); while (ch == '\0');
  2566. }
  2567. return ch;
  2568. }
  2569. #else /* !INTERACTIVE */
  2570. static ALWAYS_INLINE int fgetc_interactive(struct in_str *i)
  2571. {
  2572. int ch;
  2573. do ch = hfgetc(i->file); while (ch == '\0');
  2574. return ch;
  2575. }
  2576. #endif /* !INTERACTIVE */
  2577. static int i_getch(struct in_str *i)
  2578. {
  2579. int ch;
  2580. if (!i->file) {
  2581. /* string-based in_str */
  2582. ch = (unsigned char)*i->p;
  2583. if (ch != '\0') {
  2584. i->p++;
  2585. i->last_char = ch;
  2586. return ch;
  2587. }
  2588. return EOF;
  2589. }
  2590. /* FILE-based in_str */
  2591. #if ENABLE_FEATURE_EDITING
  2592. /* This can be stdin, check line editing char[] buffer */
  2593. if (i->p && *i->p != '\0') {
  2594. ch = (unsigned char)*i->p++;
  2595. goto out;
  2596. }
  2597. #endif
  2598. /* peek_buf[] is an int array, not char. Can contain EOF. */
  2599. ch = i->peek_buf[0];
  2600. if (ch != 0) {
  2601. int ch2 = i->peek_buf[1];
  2602. i->peek_buf[0] = ch2;
  2603. if (ch2 == 0) /* very likely, avoid redundant write */
  2604. goto out;
  2605. i->peek_buf[1] = 0;
  2606. goto out;
  2607. }
  2608. ch = fgetc_interactive(i);
  2609. out:
  2610. debug_printf("file_get: got '%c' %d\n", ch, ch);
  2611. i->last_char = ch;
  2612. #if ENABLE_HUSH_LINENO_VAR
  2613. if (ch == '\n') {
  2614. G.parse_lineno++;
  2615. debug_printf_parse("G.parse_lineno++ = %u\n", G.parse_lineno);
  2616. }
  2617. #endif
  2618. return ch;
  2619. }
  2620. static int i_peek(struct in_str *i)
  2621. {
  2622. int ch;
  2623. if (!i->file) {
  2624. /* string-based in_str */
  2625. /* Doesn't report EOF on NUL. None of the callers care. */
  2626. return (unsigned char)*i->p;
  2627. }
  2628. /* FILE-based in_str */
  2629. #if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
  2630. /* This can be stdin, check line editing char[] buffer */
  2631. if (i->p && *i->p != '\0')
  2632. return (unsigned char)*i->p;
  2633. #endif
  2634. /* peek_buf[] is an int array, not char. Can contain EOF. */
  2635. ch = i->peek_buf[0];
  2636. if (ch != 0)
  2637. return ch;
  2638. /* Need to get a new char */
  2639. ch = fgetc_interactive(i);
  2640. debug_printf("file_peek: got '%c' %d\n", ch, ch);
  2641. /* Save it by either rolling back line editing buffer, or in i->peek_buf[0] */
  2642. #if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
  2643. if (i->p) {
  2644. i->p -= 1;
  2645. return ch;
  2646. }
  2647. #endif
  2648. i->peek_buf[0] = ch;
  2649. /*i->peek_buf[1] = 0; - already is */
  2650. return ch;
  2651. }
  2652. /* Only ever called if i_peek() was called, and did not return EOF.
  2653. * IOW: we know the previous peek saw an ordinary char, not EOF, not NUL,
  2654. * not end-of-line. Therefore we never need to read a new editing line here.
  2655. */
  2656. static int i_peek2(struct in_str *i)
  2657. {
  2658. int ch;
  2659. /* There are two cases when i->p[] buffer exists.
  2660. * (1) it's a string in_str.
  2661. * (2) It's a file, and we have a saved line editing buffer.
  2662. * In both cases, we know that i->p[0] exists and not NUL, and
  2663. * the peek2 result is in i->p[1].
  2664. */
  2665. if (i->p)
  2666. return (unsigned char)i->p[1];
  2667. /* Now we know it is a file-based in_str. */
  2668. /* peek_buf[] is an int array, not char. Can contain EOF. */
  2669. /* Is there 2nd char? */
  2670. ch = i->peek_buf[1];
  2671. if (ch == 0) {
  2672. /* We did not read it yet, get it now */
  2673. do ch = hfgetc(i->file); while (ch == '\0');
  2674. i->peek_buf[1] = ch;
  2675. }
  2676. debug_printf("file_peek2: got '%c' %d\n", ch, ch);
  2677. return ch;
  2678. }
  2679. static int i_getch_and_eat_bkslash_nl(struct in_str *input)
  2680. {
  2681. for (;;) {
  2682. int ch, ch2;
  2683. ch = i_getch(input);
  2684. if (ch != '\\')
  2685. return ch;
  2686. ch2 = i_peek(input);
  2687. if (ch2 != '\n')
  2688. return ch;
  2689. /* backslash+newline, skip it */
  2690. i_getch(input);
  2691. }
  2692. }
  2693. /* Note: this function _eats_ \<newline> pairs, safe to use plain
  2694. * i_getch() after it instead of i_getch_and_eat_bkslash_nl().
  2695. */
  2696. static int i_peek_and_eat_bkslash_nl(struct in_str *input)
  2697. {
  2698. for (;;) {
  2699. int ch, ch2;
  2700. ch = i_peek(input);
  2701. if (ch != '\\')
  2702. return ch;
  2703. ch2 = i_peek2(input);
  2704. if (ch2 != '\n')
  2705. return ch;
  2706. /* backslash+newline, skip it */
  2707. i_getch(input);
  2708. i_getch(input);
  2709. }
  2710. }
  2711. static void setup_file_in_str(struct in_str *i, HFILE *fp)
  2712. {
  2713. memset(i, 0, sizeof(*i));
  2714. i->file = fp;
  2715. /* i->p = NULL; */
  2716. }
  2717. static void setup_string_in_str(struct in_str *i, const char *s)
  2718. {
  2719. memset(i, 0, sizeof(*i));
  2720. /*i->file = NULL */;
  2721. i->p = s;
  2722. }
  2723. /*
  2724. * o_string support
  2725. */
  2726. #define B_CHUNK (32 * sizeof(char*))
  2727. static void o_reset_to_empty_unquoted(o_string *o)
  2728. {
  2729. o->length = 0;
  2730. o->has_quoted_part = 0;
  2731. if (o->data)
  2732. o->data[0] = '\0';
  2733. }
  2734. static void o_free_and_set_NULL(o_string *o)
  2735. {
  2736. free(o->data);
  2737. memset(o, 0, sizeof(*o));
  2738. }
  2739. static ALWAYS_INLINE void o_free(o_string *o)
  2740. {
  2741. free(o->data);
  2742. }
  2743. static void o_grow_by(o_string *o, int len)
  2744. {
  2745. if (o->length + len > o->maxlen) {
  2746. o->maxlen += (2 * len) | (B_CHUNK-1);
  2747. o->data = xrealloc(o->data, 1 + o->maxlen);
  2748. }
  2749. }
  2750. static void o_addchr(o_string *o, int ch)
  2751. {
  2752. debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
  2753. if (o->length < o->maxlen) {
  2754. /* likely. avoid o_grow_by() call */
  2755. add:
  2756. o->data[o->length] = ch;
  2757. o->length++;
  2758. o->data[o->length] = '\0';
  2759. return;
  2760. }
  2761. o_grow_by(o, 1);
  2762. goto add;
  2763. }
  2764. #if 0
  2765. /* Valid only if we know o_string is not empty */
  2766. static void o_delchr(o_string *o)
  2767. {
  2768. o->length--;
  2769. o->data[o->length] = '\0';
  2770. }
  2771. #endif
  2772. static void o_addblock(o_string *o, const char *str, int len)
  2773. {
  2774. o_grow_by(o, len);
  2775. ((char*)mempcpy(&o->data[o->length], str, len))[0] = '\0';
  2776. o->length += len;
  2777. }
  2778. static void o_addstr(o_string *o, const char *str)
  2779. {
  2780. o_addblock(o, str, strlen(str));
  2781. }
  2782. static void o_addstr_with_NUL(o_string *o, const char *str)
  2783. {
  2784. o_addblock(o, str, strlen(str) + 1);
  2785. }
  2786. #if !BB_MMU
  2787. static void nommu_addchr(o_string *o, int ch)
  2788. {
  2789. if (o)
  2790. o_addchr(o, ch);
  2791. }
  2792. #else
  2793. # define nommu_addchr(o, str) ((void)0)
  2794. #endif
  2795. #if ENABLE_HUSH_MODE_X
  2796. static void x_mode_addchr(int ch)
  2797. {
  2798. o_addchr(&G.x_mode_buf, ch);
  2799. }
  2800. static void x_mode_addstr(const char *str)
  2801. {
  2802. o_addstr(&G.x_mode_buf, str);
  2803. }
  2804. static void x_mode_addblock(const char *str, int len)
  2805. {
  2806. o_addblock(&G.x_mode_buf, str, len);
  2807. }
  2808. static void x_mode_prefix(void)
  2809. {
  2810. int n = G.x_mode_depth;
  2811. do x_mode_addchr('+'); while (--n >= 0);
  2812. }
  2813. static void x_mode_flush(void)
  2814. {
  2815. int len = G.x_mode_buf.length;
  2816. if (len <= 0)
  2817. return;
  2818. if (G.x_mode_fd > 0) {
  2819. G.x_mode_buf.data[len] = '\n';
  2820. full_write(G.x_mode_fd, G.x_mode_buf.data, len + 1);
  2821. }
  2822. G.x_mode_buf.length = 0;
  2823. }
  2824. #endif
  2825. /*
  2826. * HUSH_BRACE_EXPANSION code needs corresponding quoting on variable expansion side.
  2827. * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
  2828. * Apparently, on unquoted $v bash still does globbing
  2829. * ("v='*.txt'; echo $v" prints all .txt files),
  2830. * but NOT brace expansion! Thus, there should be TWO independent
  2831. * quoting mechanisms on $v expansion side: one protects
  2832. * $v from brace expansion, and other additionally protects "$v" against globbing.
  2833. * We have only second one.
  2834. */
  2835. #if ENABLE_HUSH_BRACE_EXPANSION
  2836. # define MAYBE_BRACES "{}"
  2837. #else
  2838. # define MAYBE_BRACES ""
  2839. #endif
  2840. /* My analysis of quoting semantics tells me that state information
  2841. * is associated with a destination, not a source.
  2842. */
  2843. static void o_addqchr(o_string *o, int ch)
  2844. {
  2845. int sz = 1;
  2846. /* '-' is included because of this case:
  2847. * >filename0 >filename1 >filename9; v='-'; echo filename[0"$v"9]
  2848. */
  2849. char *found = strchr("*?[-\\" MAYBE_BRACES, ch);
  2850. if (found)
  2851. sz++;
  2852. o_grow_by(o, sz);
  2853. if (found) {
  2854. o->data[o->length] = '\\';
  2855. o->length++;
  2856. }
  2857. o->data[o->length] = ch;
  2858. o->length++;
  2859. o->data[o->length] = '\0';
  2860. }
  2861. static void o_addQchr(o_string *o, int ch)
  2862. {
  2863. int sz = 1;
  2864. if ((o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)
  2865. && strchr("*?[-\\" MAYBE_BRACES, ch)
  2866. ) {
  2867. sz++;
  2868. o->data[o->length] = '\\';
  2869. o->length++;
  2870. }
  2871. o_grow_by(o, sz);
  2872. o->data[o->length] = ch;
  2873. o->length++;
  2874. o->data[o->length] = '\0';
  2875. }
  2876. static void o_addqblock(o_string *o, const char *str, int len)
  2877. {
  2878. while (len) {
  2879. char ch;
  2880. int sz;
  2881. int ordinary_cnt = strcspn(str, "*?[-\\" MAYBE_BRACES);
  2882. if (ordinary_cnt > len) /* paranoia */
  2883. ordinary_cnt = len;
  2884. o_addblock(o, str, ordinary_cnt);
  2885. if (ordinary_cnt == len)
  2886. return; /* NUL is already added by o_addblock */
  2887. str += ordinary_cnt;
  2888. len -= ordinary_cnt + 1; /* we are processing + 1 char below */
  2889. ch = *str++;
  2890. sz = 1;
  2891. if (ch) { /* it is necessarily one of "*?[-\\" MAYBE_BRACES */
  2892. sz++;
  2893. o->data[o->length] = '\\';
  2894. o->length++;
  2895. }
  2896. o_grow_by(o, sz);
  2897. o->data[o->length] = ch;
  2898. o->length++;
  2899. }
  2900. o->data[o->length] = '\0';
  2901. }
  2902. static void o_addQblock(o_string *o, const char *str, int len)
  2903. {
  2904. if (!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)) {
  2905. o_addblock(o, str, len);
  2906. return;
  2907. }
  2908. o_addqblock(o, str, len);
  2909. }
  2910. static void o_addQstr(o_string *o, const char *str)
  2911. {
  2912. o_addQblock(o, str, strlen(str));
  2913. }
  2914. /* A special kind of o_string for $VAR and `cmd` expansion.
  2915. * It contains char* list[] at the beginning, which is grown in 16 element
  2916. * increments. Actual string data starts at the next multiple of 16 * (char*).
  2917. * list[i] contains an INDEX (int!) into this string data.
  2918. * It means that if list[] needs to grow, data needs to be moved higher up
  2919. * but list[i]'s need not be modified.
  2920. * NB: remembering how many list[i]'s you have there is crucial.
  2921. * o_finalize_list() operation post-processes this structure - calculates
  2922. * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
  2923. */
  2924. #if DEBUG_EXPAND || DEBUG_GLOB
  2925. static void debug_print_list(const char *prefix, o_string *o, int n)
  2926. {
  2927. char **list = (char**)o->data;
  2928. int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
  2929. int i = 0;
  2930. indent();
  2931. fdprintf(2, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d glob:%d quoted:%d escape:%d\n",
  2932. prefix, list, n, string_start, o->length, o->maxlen,
  2933. !!(o->o_expflags & EXP_FLAG_GLOB),
  2934. o->has_quoted_part,
  2935. !!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
  2936. while (i < n) {
  2937. indent();
  2938. fdprintf(2, " list[%d]=%d '%s' %p\n", i, (int)(uintptr_t)list[i],
  2939. o->data + (int)(uintptr_t)list[i] + string_start,
  2940. o->data + (int)(uintptr_t)list[i] + string_start);
  2941. i++;
  2942. }
  2943. if (n) {
  2944. const char *p = o->data + (int)(uintptr_t)list[n - 1] + string_start;
  2945. indent();
  2946. fdprintf(2, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
  2947. }
  2948. }
  2949. #else
  2950. # define debug_print_list(prefix, o, n) ((void)0)
  2951. #endif
  2952. /* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
  2953. * in list[n] so that it points past last stored byte so far.
  2954. * It returns n+1. */
  2955. static int o_save_ptr_helper(o_string *o, int n)
  2956. {
  2957. char **list = (char**)o->data;
  2958. int string_start;
  2959. int string_len;
  2960. if (!o->has_empty_slot) {
  2961. string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
  2962. string_len = o->length - string_start;
  2963. if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
  2964. debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
  2965. /* list[n] points to string_start, make space for 16 more pointers */
  2966. o->maxlen += 0x10 * sizeof(list[0]);
  2967. o->data = xrealloc(o->data, o->maxlen + 1);
  2968. list = (char**)o->data;
  2969. memmove(list + n + 0x10, list + n, string_len);
  2970. /*
  2971. * expand_on_ifs() has a "previous argv[] ends in IFS?"
  2972. * check. (grep for -prev-ifs-check-).
  2973. * Ensure that argv[-1][last] is not garbage
  2974. * but zero bytes, to save index check there.
  2975. */
  2976. list[n + 0x10 - 1] = 0;
  2977. o->length += 0x10 * sizeof(list[0]);
  2978. } else {
  2979. debug_printf_list("list[%d]=%d string_start=%d\n",
  2980. n, string_len, string_start);
  2981. }
  2982. } else {
  2983. /* We have empty slot at list[n], reuse without growth */
  2984. string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
  2985. string_len = o->length - string_start;
  2986. debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
  2987. n, string_len, string_start);
  2988. o->has_empty_slot = 0;
  2989. }
  2990. o->has_quoted_part = 0;
  2991. list[n] = (char*)(uintptr_t)string_len;
  2992. return n + 1;
  2993. }
  2994. /* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
  2995. static int o_get_last_ptr(o_string *o, int n)
  2996. {
  2997. char **list = (char**)o->data;
  2998. int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
  2999. return ((int)(uintptr_t)list[n-1]) + string_start;
  3000. }
  3001. /*
  3002. * Globbing routines.
  3003. *
  3004. * Most words in commands need to be globbed, even ones which are
  3005. * (single or double) quoted. This stems from the possiblity of
  3006. * constructs like "abc"* and 'abc'* - these should be globbed.
  3007. * Having a different code path for fully-quoted strings ("abc",
  3008. * 'abc') would only help performance-wise, but we still need
  3009. * code for partially-quoted strings.
  3010. *
  3011. * Unfortunately, if we want to match bash and ash behavior in all cases,
  3012. * the logic can't be "shell-syntax argument is first transformed
  3013. * to a string, then globbed, and if globbing does not match anything,
  3014. * it is used verbatim". Here are two examples where it fails:
  3015. *
  3016. * echo 'b\*'?
  3017. *
  3018. * The globbing can't be avoided (because of '?' at the end).
  3019. * The glob pattern is: b\\\*? - IOW, both \ and * are literals
  3020. * and are glob-escaped. If this does not match, bash/ash print b\*?
  3021. * - IOW: they "unbackslash" the glob pattern.
  3022. * Now, look at this:
  3023. *
  3024. * v='\\\*'; echo b$v?
  3025. *
  3026. * The glob pattern is the same here: b\\\*? - the unquoted $v expansion
  3027. * should be used as glob pattern with no changes. However, if glob
  3028. * does not match, bash/ash print b\\\*? - NOT THE SAME as first example!
  3029. *
  3030. * ash implements this by having an encoded representation of the word
  3031. * to glob, which IS NOT THE SAME as the glob pattern - it has more data.
  3032. * Glob pattern is derived from it. If glob fails, the decision what result
  3033. * should be is made using that encoded representation. Not glob pattern.
  3034. */
  3035. #if ENABLE_HUSH_BRACE_EXPANSION
  3036. /* There in a GNU extension, GLOB_BRACE, but it is not usable:
  3037. * first, it processes even {a} (no commas), second,
  3038. * I didn't manage to make it return strings when they don't match
  3039. * existing files. Need to re-implement it.
  3040. */
  3041. /* Helper */
  3042. static int glob_needed(const char *s)
  3043. {
  3044. while (*s) {
  3045. if (*s == '\\') {
  3046. if (!s[1])
  3047. return 0;
  3048. s += 2;
  3049. continue;
  3050. }
  3051. if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
  3052. return 1;
  3053. s++;
  3054. }
  3055. return 0;
  3056. }
  3057. /* Return pointer to next closing brace or to comma */
  3058. static const char *next_brace_sub(const char *cp)
  3059. {
  3060. unsigned depth = 0;
  3061. cp++;
  3062. while (*cp != '\0') {
  3063. if (*cp == '\\') {
  3064. if (*++cp == '\0')
  3065. break;
  3066. cp++;
  3067. continue;
  3068. }
  3069. if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
  3070. break;
  3071. if (*cp++ == '{')
  3072. depth++;
  3073. }
  3074. return *cp != '\0' ? cp : NULL;
  3075. }
  3076. /* Recursive brace globber. Note: may garble pattern[]. */
  3077. static int glob_brace(char *pattern, o_string *o, int n)
  3078. {
  3079. char *new_pattern_buf;
  3080. const char *begin;
  3081. const char *next;
  3082. const char *rest;
  3083. const char *p;
  3084. size_t rest_len;
  3085. debug_printf_glob("glob_brace('%s')\n", pattern);
  3086. begin = pattern;
  3087. while (1) {
  3088. if (*begin == '\0')
  3089. goto simple_glob;
  3090. if (*begin == '{') {
  3091. /* Find the first sub-pattern and at the same time
  3092. * find the rest after the closing brace */
  3093. next = next_brace_sub(begin);
  3094. if (next == NULL) {
  3095. /* An illegal expression */
  3096. goto simple_glob;
  3097. }
  3098. if (*next == '}') {
  3099. /* "{abc}" with no commas - illegal
  3100. * brace expr, disregard and skip it */
  3101. begin = next + 1;
  3102. continue;
  3103. }
  3104. break;
  3105. }
  3106. if (*begin == '\\' && begin[1] != '\0')
  3107. begin++;
  3108. begin++;
  3109. }
  3110. debug_printf_glob("begin:%s\n", begin);
  3111. debug_printf_glob("next:%s\n", next);
  3112. /* Now find the end of the whole brace expression */
  3113. rest = next;
  3114. while (*rest != '}') {
  3115. rest = next_brace_sub(rest);
  3116. if (rest == NULL) {
  3117. /* An illegal expression */
  3118. goto simple_glob;
  3119. }
  3120. debug_printf_glob("rest:%s\n", rest);
  3121. }
  3122. rest_len = strlen(++rest) + 1;
  3123. /* We are sure the brace expression is well-formed */
  3124. /* Allocate working buffer large enough for our work */
  3125. new_pattern_buf = xmalloc(strlen(pattern));
  3126. /* We have a brace expression. BEGIN points to the opening {,
  3127. * NEXT points past the terminator of the first element, and REST
  3128. * points past the final }. We will accumulate result names from
  3129. * recursive runs for each brace alternative in the buffer using
  3130. * GLOB_APPEND. */
  3131. p = begin + 1;
  3132. while (1) {
  3133. /* Construct the new glob expression */
  3134. memcpy(
  3135. mempcpy(
  3136. mempcpy(new_pattern_buf,
  3137. /* We know the prefix for all sub-patterns */
  3138. pattern, begin - pattern),
  3139. p, next - p),
  3140. rest, rest_len);
  3141. /* Note: glob_brace() may garble new_pattern_buf[].
  3142. * That's why we re-copy prefix every time (1st memcpy above).
  3143. */
  3144. n = glob_brace(new_pattern_buf, o, n);
  3145. if (*next == '}') {
  3146. /* We saw the last entry */
  3147. break;
  3148. }
  3149. p = next + 1;
  3150. next = next_brace_sub(next);
  3151. }
  3152. free(new_pattern_buf);
  3153. return n;
  3154. simple_glob:
  3155. {
  3156. int gr;
  3157. glob_t globdata;
  3158. memset(&globdata, 0, sizeof(globdata));
  3159. gr = glob(pattern, 0, NULL, &globdata);
  3160. debug_printf_glob("glob('%s'):%d\n", pattern, gr);
  3161. if (gr != 0) {
  3162. if (gr == GLOB_NOMATCH) {
  3163. globfree(&globdata);
  3164. /* NB: garbles parameter */
  3165. unbackslash(pattern);
  3166. o_addstr_with_NUL(o, pattern);
  3167. debug_printf_glob("glob pattern '%s' is literal\n", pattern);
  3168. return o_save_ptr_helper(o, n);
  3169. }
  3170. if (gr == GLOB_NOSPACE)
  3171. bb_die_memory_exhausted();
  3172. /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
  3173. * but we didn't specify it. Paranoia again. */
  3174. bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
  3175. }
  3176. if (globdata.gl_pathv && globdata.gl_pathv[0]) {
  3177. char **argv = globdata.gl_pathv;
  3178. while (1) {
  3179. o_addstr_with_NUL(o, *argv);
  3180. n = o_save_ptr_helper(o, n);
  3181. argv++;
  3182. if (!*argv)
  3183. break;
  3184. }
  3185. }
  3186. globfree(&globdata);
  3187. }
  3188. return n;
  3189. }
  3190. /* Performs globbing on last list[],
  3191. * saving each result as a new list[].
  3192. */
  3193. static int perform_glob(o_string *o, int n)
  3194. {
  3195. char *pattern, *copy;
  3196. debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
  3197. if (!o->data)
  3198. return o_save_ptr_helper(o, n);
  3199. pattern = o->data + o_get_last_ptr(o, n);
  3200. debug_printf_glob("glob pattern '%s'\n", pattern);
  3201. if (!glob_needed(pattern)) {
  3202. /* unbackslash last string in o in place, fix length */
  3203. o->length = unbackslash(pattern) - o->data;
  3204. debug_printf_glob("glob pattern '%s' is literal\n", pattern);
  3205. return o_save_ptr_helper(o, n);
  3206. }
  3207. copy = xstrdup(pattern);
  3208. /* "forget" pattern in o */
  3209. o->length = pattern - o->data;
  3210. n = glob_brace(copy, o, n);
  3211. free(copy);
  3212. if (DEBUG_GLOB)
  3213. debug_print_list("perform_glob returning", o, n);
  3214. return n;
  3215. }
  3216. #else /* !HUSH_BRACE_EXPANSION */
  3217. /* Helper */
  3218. static int glob_needed(const char *s)
  3219. {
  3220. while (*s) {
  3221. if (*s == '\\') {
  3222. if (!s[1])
  3223. return 0;
  3224. s += 2;
  3225. continue;
  3226. }
  3227. if (*s == '*' || *s == '[' || *s == '?')
  3228. return 1;
  3229. s++;
  3230. }
  3231. return 0;
  3232. }
  3233. /* Performs globbing on last list[],
  3234. * saving each result as a new list[].
  3235. */
  3236. static int perform_glob(o_string *o, int n)
  3237. {
  3238. glob_t globdata;
  3239. int gr;
  3240. char *pattern;
  3241. debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
  3242. if (!o->data)
  3243. return o_save_ptr_helper(o, n);
  3244. pattern = o->data + o_get_last_ptr(o, n);
  3245. debug_printf_glob("glob pattern '%s'\n", pattern);
  3246. if (!glob_needed(pattern)) {
  3247. literal:
  3248. /* unbackslash last string in o in place, fix length */
  3249. o->length = unbackslash(pattern) - o->data;
  3250. debug_printf_glob("glob pattern '%s' is literal\n", pattern);
  3251. return o_save_ptr_helper(o, n);
  3252. }
  3253. memset(&globdata, 0, sizeof(globdata));
  3254. /* Can't use GLOB_NOCHECK: it does not unescape the string.
  3255. * If we glob "*.\*" and don't find anything, we need
  3256. * to fall back to using literal "*.*", but GLOB_NOCHECK
  3257. * will return "*.\*"!
  3258. */
  3259. gr = glob(pattern, 0, NULL, &globdata);
  3260. debug_printf_glob("glob('%s'):%d\n", pattern, gr);
  3261. if (gr != 0) {
  3262. if (gr == GLOB_NOMATCH) {
  3263. globfree(&globdata);
  3264. goto literal;
  3265. }
  3266. if (gr == GLOB_NOSPACE)
  3267. bb_die_memory_exhausted();
  3268. /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
  3269. * but we didn't specify it. Paranoia again. */
  3270. bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
  3271. }
  3272. if (globdata.gl_pathv && globdata.gl_pathv[0]) {
  3273. char **argv = globdata.gl_pathv;
  3274. /* "forget" pattern in o */
  3275. o->length = pattern - o->data;
  3276. while (1) {
  3277. o_addstr_with_NUL(o, *argv);
  3278. n = o_save_ptr_helper(o, n);
  3279. argv++;
  3280. if (!*argv)
  3281. break;
  3282. }
  3283. }
  3284. globfree(&globdata);
  3285. if (DEBUG_GLOB)
  3286. debug_print_list("perform_glob returning", o, n);
  3287. return n;
  3288. }
  3289. #endif /* !HUSH_BRACE_EXPANSION */
  3290. /* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered.
  3291. * Otherwise, just finish current list[] and start new */
  3292. static int o_save_ptr(o_string *o, int n)
  3293. {
  3294. if (o->o_expflags & EXP_FLAG_GLOB) {
  3295. /* If o->has_empty_slot, list[n] was already globbed
  3296. * (if it was requested back then when it was filled)
  3297. * so don't do that again! */
  3298. if (!o->has_empty_slot)
  3299. return perform_glob(o, n); /* o_save_ptr_helper is inside */
  3300. }
  3301. return o_save_ptr_helper(o, n);
  3302. }
  3303. /* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
  3304. static char **o_finalize_list(o_string *o, int n)
  3305. {
  3306. char **list;
  3307. int string_start;
  3308. if (DEBUG_EXPAND)
  3309. debug_print_list("finalized", o, n);
  3310. debug_printf_expand("finalized n:%d\n", n);
  3311. list = (char**)o->data;
  3312. string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
  3313. list[--n] = NULL;
  3314. while (n) {
  3315. n--;
  3316. list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
  3317. }
  3318. return list;
  3319. }
  3320. static void free_pipe_list(struct pipe *pi);
  3321. /* Returns pi->next - next pipe in the list */
  3322. static struct pipe *free_pipe(struct pipe *pi)
  3323. {
  3324. struct pipe *next;
  3325. int i;
  3326. debug_printf_clean("free_pipe (pid %d)\n", getpid());
  3327. for (i = 0; i < pi->num_cmds; i++) {
  3328. struct command *command;
  3329. struct redir_struct *r, *rnext;
  3330. command = &pi->cmds[i];
  3331. debug_printf_clean(" command %d:\n", i);
  3332. if (command->argv) {
  3333. if (DEBUG_CLEAN) {
  3334. int a;
  3335. char **p;
  3336. for (a = 0, p = command->argv; *p; a++, p++) {
  3337. debug_printf_clean(" argv[%d] = %s\n", a, *p);
  3338. }
  3339. }
  3340. free_strings(command->argv);
  3341. //command->argv = NULL;
  3342. }
  3343. /* not "else if": on syntax error, we may have both! */
  3344. if (command->group) {
  3345. debug_printf_clean(" begin group (cmd_type:%d)\n",
  3346. command->cmd_type);
  3347. free_pipe_list(command->group);
  3348. debug_printf_clean(" end group\n");
  3349. //command->group = NULL;
  3350. }
  3351. /* else is crucial here.
  3352. * If group != NULL, child_func is meaningless */
  3353. #if ENABLE_HUSH_FUNCTIONS
  3354. else if (command->child_func) {
  3355. debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
  3356. command->child_func->parent_cmd = NULL;
  3357. }
  3358. #endif
  3359. #if !BB_MMU
  3360. free(command->group_as_string);
  3361. //command->group_as_string = NULL;
  3362. #endif
  3363. for (r = command->redirects; r; r = rnext) {
  3364. debug_printf_clean(" redirect %d%s",
  3365. r->rd_fd, redir_table[r->rd_type].descrip);
  3366. /* guard against the case >$FOO, where foo is unset or blank */
  3367. if (r->rd_filename) {
  3368. debug_printf_clean(" fname:'%s'\n", r->rd_filename);
  3369. free(r->rd_filename);
  3370. //r->rd_filename = NULL;
  3371. }
  3372. debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
  3373. rnext = r->next;
  3374. free(r);
  3375. }
  3376. //command->redirects = NULL;
  3377. }
  3378. free(pi->cmds); /* children are an array, they get freed all at once */
  3379. //pi->cmds = NULL;
  3380. #if ENABLE_HUSH_JOB
  3381. free(pi->cmdtext);
  3382. //pi->cmdtext = NULL;
  3383. #endif
  3384. next = pi->next;
  3385. free(pi);
  3386. return next;
  3387. }
  3388. static void free_pipe_list(struct pipe *pi)
  3389. {
  3390. while (pi) {
  3391. #if HAS_KEYWORDS
  3392. debug_printf_clean("pipe reserved word %d\n", pi->res_word);
  3393. #endif
  3394. debug_printf_clean("pipe followup code %d\n", pi->followup);
  3395. pi = free_pipe(pi);
  3396. }
  3397. }
  3398. /*** Parsing routines ***/
  3399. #ifndef debug_print_tree
  3400. static void debug_print_tree(struct pipe *pi, int lvl)
  3401. {
  3402. static const char *const PIPE[] = {
  3403. [PIPE_SEQ] = "SEQ",
  3404. [PIPE_AND] = "AND",
  3405. [PIPE_OR ] = "OR" ,
  3406. [PIPE_BG ] = "BG" ,
  3407. };
  3408. static const char *RES[] = {
  3409. [RES_NONE ] = "NONE" ,
  3410. # if ENABLE_HUSH_IF
  3411. [RES_IF ] = "IF" ,
  3412. [RES_THEN ] = "THEN" ,
  3413. [RES_ELIF ] = "ELIF" ,
  3414. [RES_ELSE ] = "ELSE" ,
  3415. [RES_FI ] = "FI" ,
  3416. # endif
  3417. # if ENABLE_HUSH_LOOPS
  3418. [RES_FOR ] = "FOR" ,
  3419. [RES_WHILE] = "WHILE",
  3420. [RES_UNTIL] = "UNTIL",
  3421. [RES_DO ] = "DO" ,
  3422. [RES_DONE ] = "DONE" ,
  3423. # endif
  3424. # if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
  3425. [RES_IN ] = "IN" ,
  3426. # endif
  3427. # if ENABLE_HUSH_CASE
  3428. [RES_CASE ] = "CASE" ,
  3429. [RES_CASE_IN ] = "CASE_IN" ,
  3430. [RES_MATCH] = "MATCH",
  3431. [RES_CASE_BODY] = "CASE_BODY",
  3432. [RES_ESAC ] = "ESAC" ,
  3433. # endif
  3434. [RES_XXXX ] = "XXXX" ,
  3435. [RES_SNTX ] = "SNTX" ,
  3436. };
  3437. static const char *const CMDTYPE[] = {
  3438. "{}",
  3439. "()",
  3440. "[noglob]",
  3441. # if ENABLE_HUSH_FUNCTIONS
  3442. "func()",
  3443. # endif
  3444. };
  3445. int pin, prn;
  3446. pin = 0;
  3447. while (pi) {
  3448. fdprintf(2, "%*spipe %d %sres_word=%s followup=%d %s\n",
  3449. lvl*2, "",
  3450. pin,
  3451. (IF_HAS_KEYWORDS(pi->pi_inverted ? "! " :) ""),
  3452. RES[pi->res_word],
  3453. pi->followup, PIPE[pi->followup]
  3454. );
  3455. prn = 0;
  3456. while (prn < pi->num_cmds) {
  3457. struct command *command = &pi->cmds[prn];
  3458. char **argv = command->argv;
  3459. fdprintf(2, "%*s cmd %d assignment_cnt:%d",
  3460. lvl*2, "", prn,
  3461. command->assignment_cnt);
  3462. # if ENABLE_HUSH_LINENO_VAR
  3463. fdprintf(2, " LINENO:%u", command->lineno);
  3464. # endif
  3465. if (command->group) {
  3466. fdprintf(2, " group %s: (argv=%p)%s%s\n",
  3467. CMDTYPE[command->cmd_type],
  3468. argv
  3469. # if !BB_MMU
  3470. , " group_as_string:", command->group_as_string
  3471. # else
  3472. , "", ""
  3473. # endif
  3474. );
  3475. debug_print_tree(command->group, lvl+1);
  3476. prn++;
  3477. continue;
  3478. }
  3479. if (argv) while (*argv) {
  3480. fdprintf(2, " '%s'", *argv);
  3481. argv++;
  3482. }
  3483. if (command->redirects)
  3484. fdprintf(2, " {redir}");
  3485. fdprintf(2, "\n");
  3486. prn++;
  3487. }
  3488. pi = pi->next;
  3489. pin++;
  3490. }
  3491. }
  3492. #endif /* debug_print_tree */
  3493. static struct pipe *new_pipe(void)
  3494. {
  3495. struct pipe *pi;
  3496. pi = xzalloc(sizeof(struct pipe));
  3497. /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
  3498. return pi;
  3499. }
  3500. /* Command (member of a pipe) is complete, or we start a new pipe
  3501. * if ctx->command is NULL.
  3502. * No errors possible here.
  3503. */
  3504. static int done_command(struct parse_context *ctx)
  3505. {
  3506. /* The command is really already in the pipe structure, so
  3507. * advance the pipe counter and make a new, null command. */
  3508. struct pipe *pi = ctx->pipe;
  3509. struct command *command = ctx->command;
  3510. #if 0 /* Instead we emit error message at run time */
  3511. if (ctx->pending_redirect) {
  3512. /* For example, "cmd >" (no filename to redirect to) */
  3513. syntax_error("invalid redirect");
  3514. ctx->pending_redirect = NULL;
  3515. }
  3516. #endif
  3517. if (command) {
  3518. if (IS_NULL_CMD(command)) {
  3519. debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
  3520. goto clear_and_ret;
  3521. }
  3522. pi->num_cmds++;
  3523. debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
  3524. //debug_print_tree(ctx->list_head, 20);
  3525. } else {
  3526. debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
  3527. }
  3528. /* Only real trickiness here is that the uncommitted
  3529. * command structure is not counted in pi->num_cmds. */
  3530. pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
  3531. ctx->command = command = &pi->cmds[pi->num_cmds];
  3532. clear_and_ret:
  3533. memset(command, 0, sizeof(*command));
  3534. #if ENABLE_HUSH_LINENO_VAR
  3535. command->lineno = G.parse_lineno;
  3536. debug_printf_parse("command->lineno = G.parse_lineno (%u)\n", G.parse_lineno);
  3537. #endif
  3538. return pi->num_cmds; /* used only for 0/nonzero check */
  3539. }
  3540. static void done_pipe(struct parse_context *ctx, pipe_style type)
  3541. {
  3542. int not_null;
  3543. debug_printf_parse("done_pipe entered, followup %d\n", type);
  3544. /* Close previous command */
  3545. not_null = done_command(ctx);
  3546. #if HAS_KEYWORDS
  3547. ctx->pipe->pi_inverted = ctx->ctx_inverted;
  3548. ctx->ctx_inverted = 0;
  3549. ctx->pipe->res_word = ctx->ctx_res_w;
  3550. #endif
  3551. if (type == PIPE_BG && ctx->list_head != ctx->pipe) {
  3552. /* Necessary since && and || have precedence over &:
  3553. * "cmd1 && cmd2 &" must spawn both cmds, not only cmd2,
  3554. * in a backgrounded subshell.
  3555. */
  3556. struct pipe *pi;
  3557. struct command *command;
  3558. /* Is this actually this construct, all pipes end with && or ||? */
  3559. pi = ctx->list_head;
  3560. while (pi != ctx->pipe) {
  3561. if (pi->followup != PIPE_AND && pi->followup != PIPE_OR)
  3562. goto no_conv;
  3563. pi = pi->next;
  3564. }
  3565. debug_printf_parse("BG with more than one pipe, converting to { p1 &&...pN; } &\n");
  3566. pi->followup = PIPE_SEQ; /* close pN _not_ with "&"! */
  3567. pi = xzalloc(sizeof(*pi));
  3568. pi->followup = PIPE_BG;
  3569. pi->num_cmds = 1;
  3570. pi->cmds = xzalloc(sizeof(pi->cmds[0]));
  3571. command = &pi->cmds[0];
  3572. if (CMD_NORMAL != 0) /* "if xzalloc didn't do that already" */
  3573. command->cmd_type = CMD_NORMAL;
  3574. command->group = ctx->list_head;
  3575. #if !BB_MMU
  3576. command->group_as_string = xstrndup(
  3577. ctx->as_string.data,
  3578. ctx->as_string.length - 1 /* do not copy last char, "&" */
  3579. );
  3580. #endif
  3581. /* Replace all pipes in ctx with one newly created */
  3582. ctx->list_head = ctx->pipe = pi;
  3583. } else {
  3584. no_conv:
  3585. ctx->pipe->followup = type;
  3586. }
  3587. /* Without this check, even just <enter> on command line generates
  3588. * tree of three NOPs (!). Which is harmless but annoying.
  3589. * IOW: it is safe to do it unconditionally. */
  3590. if (not_null
  3591. #if ENABLE_HUSH_IF
  3592. || ctx->ctx_res_w == RES_FI
  3593. #endif
  3594. #if ENABLE_HUSH_LOOPS
  3595. || ctx->ctx_res_w == RES_DONE
  3596. || ctx->ctx_res_w == RES_FOR
  3597. || ctx->ctx_res_w == RES_IN
  3598. #endif
  3599. #if ENABLE_HUSH_CASE
  3600. || ctx->ctx_res_w == RES_ESAC
  3601. #endif
  3602. ) {
  3603. struct pipe *new_p;
  3604. debug_printf_parse("done_pipe: adding new pipe: "
  3605. "not_null:%d ctx->ctx_res_w:%d\n",
  3606. not_null, ctx->ctx_res_w);
  3607. new_p = new_pipe();
  3608. ctx->pipe->next = new_p;
  3609. ctx->pipe = new_p;
  3610. /* RES_THEN, RES_DO etc are "sticky" -
  3611. * they remain set for pipes inside if/while.
  3612. * This is used to control execution.
  3613. * RES_FOR and RES_IN are NOT sticky (needed to support
  3614. * cases where variable or value happens to match a keyword):
  3615. */
  3616. #if ENABLE_HUSH_LOOPS
  3617. if (ctx->ctx_res_w == RES_FOR
  3618. || ctx->ctx_res_w == RES_IN)
  3619. ctx->ctx_res_w = RES_NONE;
  3620. #endif
  3621. #if ENABLE_HUSH_CASE
  3622. if (ctx->ctx_res_w == RES_MATCH)
  3623. ctx->ctx_res_w = RES_CASE_BODY;
  3624. if (ctx->ctx_res_w == RES_CASE)
  3625. ctx->ctx_res_w = RES_CASE_IN;
  3626. #endif
  3627. ctx->command = NULL; /* trick done_command below */
  3628. /* Create the memory for command, roughly:
  3629. * ctx->pipe->cmds = new struct command;
  3630. * ctx->command = &ctx->pipe->cmds[0];
  3631. */
  3632. done_command(ctx);
  3633. //debug_print_tree(ctx->list_head, 10);
  3634. }
  3635. debug_printf_parse("done_pipe return\n");
  3636. }
  3637. static void initialize_context(struct parse_context *ctx)
  3638. {
  3639. memset(ctx, 0, sizeof(*ctx));
  3640. if (MAYBE_ASSIGNMENT != 0)
  3641. ctx->is_assignment = MAYBE_ASSIGNMENT;
  3642. ctx->pipe = ctx->list_head = new_pipe();
  3643. /* Create the memory for command, roughly:
  3644. * ctx->pipe->cmds = new struct command;
  3645. * ctx->command = &ctx->pipe->cmds[0];
  3646. */
  3647. done_command(ctx);
  3648. }
  3649. /* If a reserved word is found and processed, parse context is modified
  3650. * and 1 is returned.
  3651. */
  3652. #if HAS_KEYWORDS
  3653. struct reserved_combo {
  3654. char literal[6];
  3655. unsigned char res;
  3656. unsigned char assignment_flag;
  3657. uint32_t flag;
  3658. };
  3659. enum {
  3660. FLAG_END = (1 << RES_NONE ),
  3661. # if ENABLE_HUSH_IF
  3662. FLAG_IF = (1 << RES_IF ),
  3663. FLAG_THEN = (1 << RES_THEN ),
  3664. FLAG_ELIF = (1 << RES_ELIF ),
  3665. FLAG_ELSE = (1 << RES_ELSE ),
  3666. FLAG_FI = (1 << RES_FI ),
  3667. # endif
  3668. # if ENABLE_HUSH_LOOPS
  3669. FLAG_FOR = (1 << RES_FOR ),
  3670. FLAG_WHILE = (1 << RES_WHILE),
  3671. FLAG_UNTIL = (1 << RES_UNTIL),
  3672. FLAG_DO = (1 << RES_DO ),
  3673. FLAG_DONE = (1 << RES_DONE ),
  3674. FLAG_IN = (1 << RES_IN ),
  3675. # endif
  3676. # if ENABLE_HUSH_CASE
  3677. FLAG_MATCH = (1 << RES_MATCH),
  3678. FLAG_ESAC = (1 << RES_ESAC ),
  3679. # endif
  3680. FLAG_START = (1 << RES_XXXX ),
  3681. };
  3682. static const struct reserved_combo* match_reserved_word(o_string *word)
  3683. {
  3684. /* Mostly a list of accepted follow-up reserved words.
  3685. * FLAG_END means we are done with the sequence, and are ready
  3686. * to turn the compound list into a command.
  3687. * FLAG_START means the word must start a new compound list.
  3688. */
  3689. static const struct reserved_combo reserved_list[] ALIGN4 = {
  3690. # if ENABLE_HUSH_IF
  3691. { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
  3692. { "if", RES_IF, MAYBE_ASSIGNMENT, FLAG_THEN | FLAG_START },
  3693. { "then", RES_THEN, MAYBE_ASSIGNMENT, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
  3694. { "elif", RES_ELIF, MAYBE_ASSIGNMENT, FLAG_THEN },
  3695. { "else", RES_ELSE, MAYBE_ASSIGNMENT, FLAG_FI },
  3696. { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
  3697. # endif
  3698. # if ENABLE_HUSH_LOOPS
  3699. { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
  3700. { "while", RES_WHILE, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
  3701. { "until", RES_UNTIL, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
  3702. { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
  3703. { "do", RES_DO, MAYBE_ASSIGNMENT, FLAG_DONE },
  3704. { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
  3705. # endif
  3706. # if ENABLE_HUSH_CASE
  3707. { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
  3708. { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
  3709. # endif
  3710. };
  3711. const struct reserved_combo *r;
  3712. for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
  3713. if (strcmp(word->data, r->literal) == 0)
  3714. return r;
  3715. }
  3716. return NULL;
  3717. }
  3718. /* Return NULL: not a keyword, else: keyword
  3719. */
  3720. static const struct reserved_combo* reserved_word(struct parse_context *ctx)
  3721. {
  3722. # if ENABLE_HUSH_CASE
  3723. static const struct reserved_combo reserved_match = {
  3724. "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
  3725. };
  3726. # endif
  3727. const struct reserved_combo *r;
  3728. if (ctx->word.has_quoted_part)
  3729. return 0;
  3730. r = match_reserved_word(&ctx->word);
  3731. if (!r)
  3732. return r; /* NULL */
  3733. debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
  3734. # if ENABLE_HUSH_CASE
  3735. if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
  3736. /* "case word IN ..." - IN part starts first MATCH part */
  3737. r = &reserved_match;
  3738. } else
  3739. # endif
  3740. if (r->flag == 0) { /* '!' */
  3741. if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
  3742. syntax_error("! ! command");
  3743. ctx->ctx_res_w = RES_SNTX;
  3744. }
  3745. ctx->ctx_inverted = 1;
  3746. return r;
  3747. }
  3748. if (r->flag & FLAG_START) {
  3749. struct parse_context *old;
  3750. old = xmemdup(ctx, sizeof(*ctx));
  3751. debug_printf_parse("push stack %p\n", old);
  3752. initialize_context(ctx);
  3753. ctx->stack = old;
  3754. } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
  3755. syntax_error_at(ctx->word.data);
  3756. ctx->ctx_res_w = RES_SNTX;
  3757. return r;
  3758. } else {
  3759. /* "{...} fi" is ok. "{...} if" is not
  3760. * Example:
  3761. * if { echo foo; } then { echo bar; } fi */
  3762. if (ctx->command->group)
  3763. done_pipe(ctx, PIPE_SEQ);
  3764. }
  3765. ctx->ctx_res_w = r->res;
  3766. ctx->old_flag = r->flag;
  3767. ctx->is_assignment = r->assignment_flag;
  3768. debug_printf_parse("ctx->is_assignment='%s'\n", assignment_flag[ctx->is_assignment]);
  3769. if (ctx->old_flag & FLAG_END) {
  3770. struct parse_context *old;
  3771. done_pipe(ctx, PIPE_SEQ);
  3772. debug_printf_parse("pop stack %p\n", ctx->stack);
  3773. old = ctx->stack;
  3774. old->command->group = ctx->list_head;
  3775. old->command->cmd_type = CMD_NORMAL;
  3776. # if !BB_MMU
  3777. /* At this point, the compound command's string is in
  3778. * ctx->as_string... except for the leading keyword!
  3779. * Consider this example: "echo a | if true; then echo a; fi"
  3780. * ctx->as_string will contain "true; then echo a; fi",
  3781. * with "if " remaining in old->as_string!
  3782. */
  3783. {
  3784. char *str;
  3785. int len = old->as_string.length;
  3786. /* Concatenate halves */
  3787. o_addstr(&old->as_string, ctx->as_string.data);
  3788. o_free(&ctx->as_string);
  3789. /* Find where leading keyword starts in first half */
  3790. str = old->as_string.data + len;
  3791. if (str > old->as_string.data)
  3792. str--; /* skip whitespace after keyword */
  3793. while (str > old->as_string.data && isalpha(str[-1]))
  3794. str--;
  3795. /* Ugh, we're done with this horrid hack */
  3796. old->command->group_as_string = xstrdup(str);
  3797. debug_printf_parse("pop, remembering as:'%s'\n",
  3798. old->command->group_as_string);
  3799. }
  3800. # endif
  3801. *ctx = *old; /* physical copy */
  3802. free(old);
  3803. }
  3804. return r;
  3805. }
  3806. #endif /* HAS_KEYWORDS */
  3807. /* Word is complete, look at it and update parsing context.
  3808. * Normal return is 0. Syntax errors return 1.
  3809. * Note: on return, word is reset, but not o_free'd!
  3810. */
  3811. static int done_word(struct parse_context *ctx)
  3812. {
  3813. struct command *command = ctx->command;
  3814. debug_printf_parse("done_word entered: '%s' %p\n", ctx->word.data, command);
  3815. if (ctx->word.length == 0 && !ctx->word.has_quoted_part) {
  3816. debug_printf_parse("done_word return 0: true null, ignored\n");
  3817. return 0;
  3818. }
  3819. if (ctx->pending_redirect) {
  3820. /* We do not glob in e.g. >*.tmp case. bash seems to glob here
  3821. * only if run as "bash", not "sh" */
  3822. /* http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
  3823. * "2.7 Redirection
  3824. * If the redirection operator is "<<" or "<<-", the word
  3825. * that follows the redirection operator shall be
  3826. * subjected to quote removal; it is unspecified whether
  3827. * any of the other expansions occur. For the other
  3828. * redirection operators, the word that follows the
  3829. * redirection operator shall be subjected to tilde
  3830. * expansion, parameter expansion, command substitution,
  3831. * arithmetic expansion, and quote removal.
  3832. * Pathname expansion shall not be performed
  3833. * on the word by a non-interactive shell; an interactive
  3834. * shell may perform it, but shall do so only when
  3835. * the expansion would result in one word."
  3836. */
  3837. //bash does not do parameter/command substitution or arithmetic expansion
  3838. //for _heredoc_ redirection word: these constructs look for exact eof marker
  3839. // as written:
  3840. // <<EOF$t
  3841. // <<EOF$((1))
  3842. // <<EOF`true` [this case also makes heredoc "quoted", a-la <<"EOF". Probably bash-4.3.43 bug]
  3843. ctx->pending_redirect->rd_filename = xstrdup(ctx->word.data);
  3844. /* Cater for >\file case:
  3845. * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
  3846. * Same with heredocs:
  3847. * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
  3848. */
  3849. if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
  3850. unbackslash(ctx->pending_redirect->rd_filename);
  3851. /* Is it <<"HEREDOC"? */
  3852. if (ctx->word.has_quoted_part) {
  3853. ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
  3854. }
  3855. }
  3856. debug_printf_parse("word stored in rd_filename: '%s'\n", ctx->word.data);
  3857. ctx->pending_redirect = NULL;
  3858. } else {
  3859. #if HAS_KEYWORDS
  3860. # if ENABLE_HUSH_CASE
  3861. if (ctx->ctx_dsemicolon
  3862. && strcmp(ctx->word.data, "esac") != 0 /* not "... pattern) cmd;; esac" */
  3863. ) {
  3864. /* already done when ctx_dsemicolon was set to 1: */
  3865. /* ctx->ctx_res_w = RES_MATCH; */
  3866. ctx->ctx_dsemicolon = 0;
  3867. } else
  3868. # endif
  3869. # if defined(CMD_TEST2_SINGLEWORD_NOGLOB)
  3870. if (command->cmd_type == CMD_TEST2_SINGLEWORD_NOGLOB
  3871. && strcmp(ctx->word.data, "]]") == 0
  3872. ) {
  3873. /* allow "[[ ]] >file" etc */
  3874. command->cmd_type = CMD_SINGLEWORD_NOGLOB;
  3875. } else
  3876. # endif
  3877. if (!command->argv /* if it's the first word... */
  3878. # if ENABLE_HUSH_LOOPS
  3879. && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
  3880. && ctx->ctx_res_w != RES_IN
  3881. # endif
  3882. # if ENABLE_HUSH_CASE
  3883. && ctx->ctx_res_w != RES_CASE
  3884. # endif
  3885. ) {
  3886. const struct reserved_combo *reserved;
  3887. reserved = reserved_word(ctx);
  3888. debug_printf_parse("checking for reserved-ness: %d\n", !!reserved);
  3889. if (reserved) {
  3890. # if ENABLE_HUSH_LINENO_VAR
  3891. /* Case:
  3892. * "while ...; do
  3893. * cmd ..."
  3894. * If we don't close the pipe _now_, immediately after "do", lineno logic
  3895. * sees "cmd" as starting at "do" - i.e., at the previous line.
  3896. */
  3897. if (0
  3898. IF_HUSH_IF(|| reserved->res == RES_THEN)
  3899. IF_HUSH_IF(|| reserved->res == RES_ELIF)
  3900. IF_HUSH_IF(|| reserved->res == RES_ELSE)
  3901. IF_HUSH_LOOPS(|| reserved->res == RES_DO)
  3902. ) {
  3903. done_pipe(ctx, PIPE_SEQ);
  3904. }
  3905. # endif
  3906. o_reset_to_empty_unquoted(&ctx->word);
  3907. debug_printf_parse("done_word return %d\n",
  3908. (ctx->ctx_res_w == RES_SNTX));
  3909. return (ctx->ctx_res_w == RES_SNTX);
  3910. }
  3911. # if defined(CMD_TEST2_SINGLEWORD_NOGLOB)
  3912. if (strcmp(ctx->word.data, "[[") == 0) {
  3913. command->cmd_type = CMD_TEST2_SINGLEWORD_NOGLOB;
  3914. } else
  3915. # endif
  3916. # if defined(CMD_SINGLEWORD_NOGLOB)
  3917. if (0
  3918. /* In bash, local/export/readonly are special, args
  3919. * are assignments and therefore expansion of them
  3920. * should be "one-word" expansion:
  3921. * $ export i=`echo 'a b'` # one arg: "i=a b"
  3922. * compare with:
  3923. * $ ls i=`echo 'a b'` # two args: "i=a" and "b"
  3924. * ls: cannot access i=a: No such file or directory
  3925. * ls: cannot access b: No such file or directory
  3926. * Note: bash 3.2.33(1) does this only if export word
  3927. * itself is not quoted:
  3928. * $ export i=`echo 'aaa bbb'`; echo "$i"
  3929. * aaa bbb
  3930. * $ "export" i=`echo 'aaa bbb'`; echo "$i"
  3931. * aaa
  3932. */
  3933. IF_HUSH_LOCAL( || strcmp(ctx->word.data, "local") == 0)
  3934. IF_HUSH_EXPORT( || strcmp(ctx->word.data, "export") == 0)
  3935. IF_HUSH_READONLY(|| strcmp(ctx->word.data, "readonly") == 0)
  3936. ) {
  3937. command->cmd_type = CMD_SINGLEWORD_NOGLOB;
  3938. }
  3939. # else
  3940. { /* empty block to pair "if ... else" */ }
  3941. # endif
  3942. }
  3943. #endif /* HAS_KEYWORDS */
  3944. if (command->group) {
  3945. /* "{ echo foo; } echo bar" - bad */
  3946. syntax_error_at(ctx->word.data);
  3947. debug_printf_parse("done_word return 1: syntax error, "
  3948. "groups and arglists don't mix\n");
  3949. return 1;
  3950. }
  3951. /* If this word wasn't an assignment, next ones definitely
  3952. * can't be assignments. Even if they look like ones. */
  3953. if (ctx->is_assignment != DEFINITELY_ASSIGNMENT
  3954. && ctx->is_assignment != WORD_IS_KEYWORD
  3955. ) {
  3956. ctx->is_assignment = NOT_ASSIGNMENT;
  3957. } else {
  3958. if (ctx->is_assignment == DEFINITELY_ASSIGNMENT) {
  3959. command->assignment_cnt++;
  3960. debug_printf_parse("++assignment_cnt=%d\n", command->assignment_cnt);
  3961. }
  3962. debug_printf_parse("ctx->is_assignment was:'%s'\n", assignment_flag[ctx->is_assignment]);
  3963. ctx->is_assignment = MAYBE_ASSIGNMENT;
  3964. }
  3965. debug_printf_parse("ctx->is_assignment='%s'\n", assignment_flag[ctx->is_assignment]);
  3966. command->argv = add_string_to_strings(command->argv, xstrdup(ctx->word.data));
  3967. debug_print_strings("word appended to argv", command->argv);
  3968. }
  3969. #if ENABLE_HUSH_LOOPS
  3970. if (ctx->ctx_res_w == RES_FOR) {
  3971. if (ctx->word.has_quoted_part
  3972. || endofname(command->argv[0])[0] != '\0'
  3973. ) {
  3974. /* bash says just "not a valid identifier" */
  3975. syntax_error("not a valid identifier in for");
  3976. return 1;
  3977. }
  3978. /* Force FOR to have just one word (variable name) */
  3979. /* NB: basically, this makes hush see "for v in ..."
  3980. * syntax as if it is "for v; in ...". FOR and IN become
  3981. * two pipe structs in parse tree. */
  3982. done_pipe(ctx, PIPE_SEQ);
  3983. }
  3984. #endif
  3985. #if ENABLE_HUSH_CASE
  3986. /* Force CASE to have just one word */
  3987. if (ctx->ctx_res_w == RES_CASE) {
  3988. done_pipe(ctx, PIPE_SEQ);
  3989. }
  3990. #endif
  3991. o_reset_to_empty_unquoted(&ctx->word);
  3992. debug_printf_parse("done_word return 0\n");
  3993. return 0;
  3994. }
  3995. /* Peek ahead in the input to find out if we have a "&n" construct,
  3996. * as in "2>&1", that represents duplicating a file descriptor.
  3997. * Return:
  3998. * REDIRFD_CLOSE if >&- "close fd" construct is seen,
  3999. * REDIRFD_SYNTAX_ERR if syntax error,
  4000. * REDIRFD_TO_FILE if no & was seen,
  4001. * or the number found.
  4002. */
  4003. #if BB_MMU
  4004. #define parse_redir_right_fd(as_string, input) \
  4005. parse_redir_right_fd(input)
  4006. #endif
  4007. static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
  4008. {
  4009. int ch, d, ok;
  4010. ch = i_peek(input);
  4011. if (ch != '&')
  4012. return REDIRFD_TO_FILE;
  4013. ch = i_getch(input); /* get the & */
  4014. nommu_addchr(as_string, ch);
  4015. ch = i_peek(input);
  4016. if (ch == '-') {
  4017. ch = i_getch(input);
  4018. nommu_addchr(as_string, ch);
  4019. return REDIRFD_CLOSE;
  4020. }
  4021. d = 0;
  4022. ok = 0;
  4023. while (ch != EOF && isdigit(ch)) {
  4024. d = d*10 + (ch-'0');
  4025. ok = 1;
  4026. ch = i_getch(input);
  4027. nommu_addchr(as_string, ch);
  4028. ch = i_peek(input);
  4029. }
  4030. if (ok) return d;
  4031. //TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
  4032. bb_simple_error_msg("ambiguous redirect");
  4033. return REDIRFD_SYNTAX_ERR;
  4034. }
  4035. /* Return code is 0 normal, 1 if a syntax error is detected
  4036. */
  4037. static int parse_redirect(struct parse_context *ctx,
  4038. int fd,
  4039. redir_type style,
  4040. struct in_str *input)
  4041. {
  4042. struct command *command = ctx->command;
  4043. struct redir_struct *redir;
  4044. struct redir_struct **redirp;
  4045. int dup_num;
  4046. dup_num = REDIRFD_TO_FILE;
  4047. if (style != REDIRECT_HEREDOC) {
  4048. /* Check for a '>&1' type redirect */
  4049. dup_num = parse_redir_right_fd(&ctx->as_string, input);
  4050. if (dup_num == REDIRFD_SYNTAX_ERR)
  4051. return 1;
  4052. } else {
  4053. int ch = i_peek_and_eat_bkslash_nl(input);
  4054. dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
  4055. if (dup_num) { /* <<-... */
  4056. ch = i_getch(input);
  4057. nommu_addchr(&ctx->as_string, ch);
  4058. ch = i_peek(input);
  4059. }
  4060. }
  4061. if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
  4062. int ch = i_peek_and_eat_bkslash_nl(input);
  4063. if (ch == '|') {
  4064. /* >|FILE redirect ("clobbering" >).
  4065. * Since we do not support "set -o noclobber" yet,
  4066. * >| and > are the same for now. Just eat |.
  4067. */
  4068. ch = i_getch(input);
  4069. nommu_addchr(&ctx->as_string, ch);
  4070. }
  4071. }
  4072. /* Create a new redir_struct and append it to the linked list */
  4073. redirp = &command->redirects;
  4074. while ((redir = *redirp) != NULL) {
  4075. redirp = &(redir->next);
  4076. }
  4077. *redirp = redir = xzalloc(sizeof(*redir));
  4078. /* redir->next = NULL; */
  4079. /* redir->rd_filename = NULL; */
  4080. redir->rd_type = style;
  4081. redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
  4082. debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
  4083. redir_table[style].descrip);
  4084. redir->rd_dup = dup_num;
  4085. if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
  4086. /* Erik had a check here that the file descriptor in question
  4087. * is legit; I postpone that to "run time"
  4088. * A "-" representation of "close me" shows up as a -3 here */
  4089. debug_printf_parse("duplicating redirect '%d>&%d'\n",
  4090. redir->rd_fd, redir->rd_dup);
  4091. } else {
  4092. #if 0 /* Instead we emit error message at run time */
  4093. if (ctx->pending_redirect) {
  4094. /* For example, "cmd > <file" */
  4095. syntax_error("invalid redirect");
  4096. }
  4097. #endif
  4098. /* Set ctx->pending_redirect, so we know what to do at the
  4099. * end of the next parsed word. */
  4100. ctx->pending_redirect = redir;
  4101. }
  4102. return 0;
  4103. }
  4104. /* If a redirect is immediately preceded by a number, that number is
  4105. * supposed to tell which file descriptor to redirect. This routine
  4106. * looks for such preceding numbers. In an ideal world this routine
  4107. * needs to handle all the following classes of redirects...
  4108. * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
  4109. * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
  4110. * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
  4111. * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
  4112. *
  4113. * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
  4114. * "2.7 Redirection
  4115. * ... If n is quoted, the number shall not be recognized as part of
  4116. * the redirection expression. For example:
  4117. * echo \2>a
  4118. * writes the character 2 into file a"
  4119. * We are getting it right by setting ->has_quoted_part on any \<char>
  4120. *
  4121. * A -1 return means no valid number was found,
  4122. * the caller should use the appropriate default for this redirection.
  4123. */
  4124. static int redirect_opt_num(o_string *o)
  4125. {
  4126. int num;
  4127. if (o->data == NULL)
  4128. return -1;
  4129. num = bb_strtou(o->data, NULL, 10);
  4130. if (errno || num < 0)
  4131. return -1;
  4132. o_reset_to_empty_unquoted(o);
  4133. return num;
  4134. }
  4135. #if BB_MMU
  4136. #define fetch_till_str(as_string, input, word, skip_tabs) \
  4137. fetch_till_str(input, word, skip_tabs)
  4138. #endif
  4139. static char *fetch_till_str(o_string *as_string,
  4140. struct in_str *input,
  4141. const char *word,
  4142. int heredoc_flags)
  4143. {
  4144. o_string heredoc = NULL_O_STRING;
  4145. unsigned past_EOL;
  4146. int prev = 0; /* not \ */
  4147. int ch;
  4148. /* Starting with "" is necessary for this case:
  4149. * cat <<EOF
  4150. *
  4151. * xxx
  4152. * EOF
  4153. */
  4154. heredoc.data = xzalloc(1); /* start as "", not as NULL */
  4155. goto jump_in;
  4156. while (1) {
  4157. ch = i_getch(input);
  4158. if (ch != EOF)
  4159. nommu_addchr(as_string, ch);
  4160. if (ch == '\n' || ch == EOF) {
  4161. check_heredoc_end:
  4162. if ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\') {
  4163. /* End-of-line, and not a line continuation */
  4164. if (strcmp(heredoc.data + past_EOL, word) == 0) {
  4165. heredoc.data[past_EOL] = '\0';
  4166. debug_printf_heredoc("parsed '%s' heredoc '%s'\n", word, heredoc.data);
  4167. return heredoc.data;
  4168. }
  4169. if (ch == '\n') {
  4170. /* This is a new line.
  4171. * Remember position and backslash-escaping status.
  4172. */
  4173. o_addchr(&heredoc, ch);
  4174. prev = ch;
  4175. jump_in:
  4176. past_EOL = heredoc.length;
  4177. /* Get 1st char of next line, possibly skipping leading tabs */
  4178. do {
  4179. ch = i_getch(input);
  4180. if (ch != EOF)
  4181. nommu_addchr(as_string, ch);
  4182. } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
  4183. /* If this immediately ended the line,
  4184. * go back to end-of-line checks.
  4185. */
  4186. if (ch == '\n')
  4187. goto check_heredoc_end;
  4188. }
  4189. } else {
  4190. /* Backslash-line continuation in an unquoted
  4191. * heredoc. This does not need special handling
  4192. * for heredoc body (unquoted heredocs are
  4193. * expanded on "execution" and that would take
  4194. * care of this case too), but not the case
  4195. * of line continuation *in terminator*:
  4196. * cat <<EOF
  4197. * Ok1
  4198. * EO\
  4199. * F
  4200. */
  4201. heredoc.data[--heredoc.length] = '\0';
  4202. prev = 0; /* not '\' */
  4203. continue;
  4204. }
  4205. }
  4206. if (ch == EOF) {
  4207. o_free(&heredoc);
  4208. return NULL; /* error */
  4209. }
  4210. o_addchr(&heredoc, ch);
  4211. nommu_addchr(as_string, ch);
  4212. if (prev == '\\' && ch == '\\')
  4213. /* Correctly handle foo\\<eol> (not a line cont.) */
  4214. prev = 0; /* not '\' */
  4215. else
  4216. prev = ch;
  4217. }
  4218. }
  4219. /* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
  4220. * and load them all. There should be exactly heredoc_cnt of them.
  4221. */
  4222. #if BB_MMU
  4223. #define fetch_heredocs(as_string, pi, heredoc_cnt, input) \
  4224. fetch_heredocs(pi, heredoc_cnt, input)
  4225. #endif
  4226. static int fetch_heredocs(o_string *as_string, struct pipe *pi, int heredoc_cnt, struct in_str *input)
  4227. {
  4228. while (pi && heredoc_cnt) {
  4229. int i;
  4230. struct command *cmd = pi->cmds;
  4231. debug_printf_heredoc("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
  4232. pi->num_cmds,
  4233. cmd->argv ? cmd->argv[0] : "NONE"
  4234. );
  4235. for (i = 0; i < pi->num_cmds; i++) {
  4236. struct redir_struct *redir = cmd->redirects;
  4237. debug_printf_heredoc("fetch_heredocs: %d cmd argv0:'%s'\n",
  4238. i, cmd->argv ? cmd->argv[0] : "NONE");
  4239. while (redir) {
  4240. if (redir->rd_type == REDIRECT_HEREDOC) {
  4241. char *p;
  4242. redir->rd_type = REDIRECT_HEREDOC2;
  4243. /* redir->rd_dup is (ab)used to indicate <<- */
  4244. p = fetch_till_str(as_string, input,
  4245. redir->rd_filename, redir->rd_dup);
  4246. if (!p) {
  4247. syntax_error("unexpected EOF in here document");
  4248. return -1;
  4249. }
  4250. free(redir->rd_filename);
  4251. redir->rd_filename = p;
  4252. heredoc_cnt--;
  4253. }
  4254. redir = redir->next;
  4255. }
  4256. if (cmd->group) {
  4257. //bb_error_msg("%s:%u heredoc_cnt:%d", __func__, __LINE__, heredoc_cnt);
  4258. heredoc_cnt = fetch_heredocs(as_string, cmd->group, heredoc_cnt, input);
  4259. //bb_error_msg("%s:%u heredoc_cnt:%d", __func__, __LINE__, heredoc_cnt);
  4260. if (heredoc_cnt < 0)
  4261. return heredoc_cnt; /* error */
  4262. }
  4263. cmd++;
  4264. }
  4265. pi = pi->next;
  4266. }
  4267. return heredoc_cnt;
  4268. }
  4269. static int run_list(struct pipe *pi);
  4270. #if BB_MMU
  4271. #define parse_stream(pstring, heredoc_cnt_ptr, input, end_trigger) \
  4272. parse_stream(heredoc_cnt_ptr, input, end_trigger)
  4273. #endif
  4274. static struct pipe *parse_stream(char **pstring,
  4275. int *heredoc_cnt_ptr,
  4276. struct in_str *input,
  4277. int end_trigger);
  4278. /* Returns number of heredocs not yet consumed,
  4279. * or -1 on error.
  4280. */
  4281. static int parse_group(struct parse_context *ctx,
  4282. struct in_str *input, int ch)
  4283. {
  4284. /* ctx->word contains characters seen prior to ( or {.
  4285. * Typically it's empty, but for function defs,
  4286. * it contains function name (without '()'). */
  4287. #if BB_MMU
  4288. # define as_string NULL
  4289. #else
  4290. char *as_string = NULL;
  4291. #endif
  4292. struct pipe *pipe_list;
  4293. int heredoc_cnt = 0;
  4294. int endch;
  4295. struct command *command = ctx->command;
  4296. debug_printf_parse("parse_group entered\n");
  4297. #if ENABLE_HUSH_FUNCTIONS
  4298. if (ch == '(' && !ctx->word.has_quoted_part) {
  4299. if (ctx->word.length)
  4300. if (done_word(ctx))
  4301. return -1;
  4302. if (!command->argv)
  4303. goto skip; /* (... */
  4304. if (command->argv[1]) { /* word word ... (... */
  4305. syntax_error_unexpected_ch('(');
  4306. return -1;
  4307. }
  4308. /* it is "word(..." or "word (..." */
  4309. do
  4310. ch = i_getch(input);
  4311. while (ch == ' ' || ch == '\t');
  4312. if (ch != ')') {
  4313. syntax_error_unexpected_ch(ch);
  4314. return -1;
  4315. }
  4316. nommu_addchr(&ctx->as_string, ch);
  4317. do
  4318. ch = i_getch(input);
  4319. while (ch == ' ' || ch == '\t' || ch == '\n');
  4320. if (ch != '{' && ch != '(') {
  4321. syntax_error_unexpected_ch(ch);
  4322. return -1;
  4323. }
  4324. nommu_addchr(&ctx->as_string, ch);
  4325. command->cmd_type = CMD_FUNCDEF;
  4326. goto skip;
  4327. }
  4328. #endif
  4329. #if 0 /* Prevented by caller */
  4330. if (command->argv /* word [word]{... */
  4331. || ctx->word.length /* word{... */
  4332. || ctx->word.has_quoted_part /* ""{... */
  4333. ) {
  4334. syntax_error(NULL);
  4335. debug_printf_parse("parse_group return -1: "
  4336. "syntax error, groups and arglists don't mix\n");
  4337. return -1;
  4338. }
  4339. #endif
  4340. IF_HUSH_FUNCTIONS(skip:)
  4341. endch = '}';
  4342. if (ch == '(') {
  4343. endch = ')';
  4344. IF_HUSH_FUNCTIONS(if (command->cmd_type != CMD_FUNCDEF))
  4345. command->cmd_type = CMD_SUBSHELL;
  4346. } else {
  4347. /* bash does not allow "{echo...", requires whitespace */
  4348. ch = i_peek(input);
  4349. if (ch != ' ' && ch != '\t' && ch != '\n'
  4350. && ch != '(' /* but "{(..." is allowed (without whitespace) */
  4351. ) {
  4352. syntax_error_unexpected_ch(ch);
  4353. return -1;
  4354. }
  4355. if (ch != '(') {
  4356. ch = i_getch(input);
  4357. nommu_addchr(&ctx->as_string, ch);
  4358. }
  4359. }
  4360. debug_printf_heredoc("calling parse_stream, heredoc_cnt:%d\n", heredoc_cnt);
  4361. pipe_list = parse_stream(&as_string, &heredoc_cnt, input, endch);
  4362. debug_printf_heredoc("parse_stream returned: heredoc_cnt:%d\n", heredoc_cnt);
  4363. #if !BB_MMU
  4364. if (as_string)
  4365. o_addstr(&ctx->as_string, as_string);
  4366. #endif
  4367. /* empty ()/{} or parse error? */
  4368. if (!pipe_list || pipe_list == ERR_PTR) {
  4369. /* parse_stream already emitted error msg */
  4370. if (!BB_MMU)
  4371. free(as_string);
  4372. debug_printf_parse("parse_group return -1: "
  4373. "parse_stream returned %p\n", pipe_list);
  4374. return -1;
  4375. }
  4376. #if !BB_MMU
  4377. as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
  4378. command->group_as_string = as_string;
  4379. debug_printf_parse("end of group, remembering as:'%s'\n",
  4380. command->group_as_string);
  4381. #endif
  4382. #if ENABLE_HUSH_FUNCTIONS
  4383. /* Convert "f() (cmds)" to "f() {(cmds)}" */
  4384. if (command->cmd_type == CMD_FUNCDEF && endch == ')') {
  4385. struct command *cmd2;
  4386. cmd2 = xzalloc(sizeof(*cmd2));
  4387. cmd2->cmd_type = CMD_SUBSHELL;
  4388. cmd2->group = pipe_list;
  4389. # if !BB_MMU
  4390. //UNTESTED!
  4391. cmd2->group_as_string = command->group_as_string;
  4392. command->group_as_string = xasprintf("(%s)", command->group_as_string);
  4393. # endif
  4394. pipe_list = new_pipe();
  4395. pipe_list->cmds = cmd2;
  4396. pipe_list->num_cmds = 1;
  4397. }
  4398. #endif
  4399. command->group = pipe_list;
  4400. debug_printf_parse("parse_group return %d\n", heredoc_cnt);
  4401. return heredoc_cnt;
  4402. /* command remains "open", available for possible redirects */
  4403. #undef as_string
  4404. }
  4405. #if ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS
  4406. /* Subroutines for copying $(...) and `...` things */
  4407. /* '...' */
  4408. static int add_till_single_quote(o_string *dest, struct in_str *input)
  4409. {
  4410. while (1) {
  4411. int ch = i_getch(input);
  4412. if (ch == EOF) {
  4413. syntax_error_unterm_ch('\'');
  4414. return 0;
  4415. }
  4416. if (ch == '\'')
  4417. return 1;
  4418. o_addchr(dest, ch);
  4419. }
  4420. }
  4421. static int add_till_single_quote_dquoted(o_string *dest, struct in_str *input)
  4422. {
  4423. while (1) {
  4424. int ch = i_getch(input);
  4425. if (ch == EOF) {
  4426. syntax_error_unterm_ch('\'');
  4427. return 0;
  4428. }
  4429. if (ch == '\'')
  4430. return 1;
  4431. o_addqchr(dest, ch);
  4432. }
  4433. }
  4434. /* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
  4435. static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote);
  4436. static int add_till_double_quote(o_string *dest, struct in_str *input)
  4437. {
  4438. while (1) {
  4439. int ch = i_getch(input);
  4440. if (ch == EOF) {
  4441. syntax_error_unterm_ch('"');
  4442. return 0;
  4443. }
  4444. if (ch == '"')
  4445. return 1;
  4446. if (ch == '\\') { /* \x. Copy both chars. */
  4447. o_addchr(dest, ch);
  4448. ch = i_getch(input);
  4449. }
  4450. o_addchr(dest, ch);
  4451. if (ch == '`') {
  4452. if (!add_till_backquote(dest, input, /*in_dquote:*/ 1))
  4453. return 0;
  4454. o_addchr(dest, ch);
  4455. continue;
  4456. }
  4457. //if (ch == '$') ...
  4458. }
  4459. }
  4460. /* Process `cmd` - copy contents until "`" is seen. Complicated by
  4461. * \` quoting.
  4462. * "Within the backquoted style of command substitution, backslash
  4463. * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
  4464. * The search for the matching backquote shall be satisfied by the first
  4465. * backquote found without a preceding backslash; during this search,
  4466. * if a non-escaped backquote is encountered within a shell comment,
  4467. * a here-document, an embedded command substitution of the $(command)
  4468. * form, or a quoted string, undefined results occur. A single-quoted
  4469. * or double-quoted string that begins, but does not end, within the
  4470. * "`...`" sequence produces undefined results."
  4471. * Example Output
  4472. * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
  4473. */
  4474. static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote)
  4475. {
  4476. while (1) {
  4477. int ch = i_getch(input);
  4478. if (ch == '`')
  4479. return 1;
  4480. if (ch == '\\') {
  4481. /* \x. Copy both unless it is \`, \$, \\ and maybe \" */
  4482. ch = i_getch(input);
  4483. if (ch != '`'
  4484. && ch != '$'
  4485. && ch != '\\'
  4486. && (!in_dquote || ch != '"')
  4487. ) {
  4488. o_addchr(dest, '\\');
  4489. }
  4490. }
  4491. if (ch == EOF) {
  4492. syntax_error_unterm_ch('`');
  4493. return 0;
  4494. }
  4495. o_addchr(dest, ch);
  4496. }
  4497. }
  4498. /* Process $(cmd) - copy contents until ")" is seen. Complicated by
  4499. * quoting and nested ()s.
  4500. * "With the $(command) style of command substitution, all characters
  4501. * following the open parenthesis to the matching closing parenthesis
  4502. * constitute the command. Any valid shell script can be used for command,
  4503. * except a script consisting solely of redirections which produces
  4504. * unspecified results."
  4505. * Example Output
  4506. * echo $(echo '(TEST)' BEST) (TEST) BEST
  4507. * echo $(echo 'TEST)' BEST) TEST) BEST
  4508. * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
  4509. *
  4510. * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
  4511. * can contain arbitrary constructs, just like $(cmd).
  4512. * In bash compat mode, it needs to also be able to stop on ':' or '/'
  4513. * for ${var:N[:M]} and ${var/P[/R]} parsing.
  4514. */
  4515. #define DOUBLE_CLOSE_CHAR_FLAG 0x80
  4516. static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
  4517. {
  4518. int ch;
  4519. char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
  4520. # if BASH_SUBSTR || BASH_PATTERN_SUBST
  4521. char end_char2 = end_ch >> 8;
  4522. # endif
  4523. end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
  4524. # if ENABLE_HUSH_INTERACTIVE
  4525. G.promptmode = 1; /* PS2 */
  4526. # endif
  4527. debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
  4528. while (1) {
  4529. ch = i_getch(input);
  4530. if (ch == EOF) {
  4531. syntax_error_unterm_ch(end_ch);
  4532. return 0;
  4533. }
  4534. if (ch == end_ch
  4535. # if BASH_SUBSTR || BASH_PATTERN_SUBST
  4536. || ch == end_char2
  4537. # endif
  4538. ) {
  4539. if (!dbl)
  4540. break;
  4541. /* we look for closing )) of $((EXPR)) */
  4542. if (i_peek_and_eat_bkslash_nl(input) == end_ch) {
  4543. i_getch(input); /* eat second ')' */
  4544. break;
  4545. }
  4546. }
  4547. o_addchr(dest, ch);
  4548. //bb_error_msg("%s:o_addchr('%c')", __func__, ch);
  4549. if (ch == '(' || ch == '{') {
  4550. ch = (ch == '(' ? ')' : '}');
  4551. if (!add_till_closing_bracket(dest, input, ch))
  4552. return 0;
  4553. o_addchr(dest, ch);
  4554. continue;
  4555. }
  4556. if (ch == '\'') {
  4557. if (!add_till_single_quote(dest, input))
  4558. return 0;
  4559. o_addchr(dest, ch);
  4560. continue;
  4561. }
  4562. if (ch == '"') {
  4563. if (!add_till_double_quote(dest, input))
  4564. return 0;
  4565. o_addchr(dest, ch);
  4566. continue;
  4567. }
  4568. if (ch == '`') {
  4569. if (!add_till_backquote(dest, input, /*in_dquote:*/ 0))
  4570. return 0;
  4571. o_addchr(dest, ch);
  4572. continue;
  4573. }
  4574. if (ch == '\\') {
  4575. /* \x. Copy verbatim. Important for \(, \) */
  4576. ch = i_getch(input);
  4577. if (ch == EOF) {
  4578. syntax_error_unterm_ch(end_ch);
  4579. return 0;
  4580. }
  4581. # if 0
  4582. if (ch == '\n') {
  4583. /* "backslash+newline", ignore both */
  4584. o_delchr(dest); /* undo insertion of '\' */
  4585. continue;
  4586. }
  4587. # endif
  4588. o_addchr(dest, ch);
  4589. //bb_error_msg("%s:o_addchr('%c') after '\\'", __func__, ch);
  4590. continue;
  4591. }
  4592. }
  4593. debug_printf_parse("%s return '%s' ch:'%c'\n", __func__, dest->data, ch);
  4594. return ch;
  4595. }
  4596. #endif /* ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS */
  4597. /* Return code: 0 for OK, 1 for syntax error */
  4598. #if BB_MMU
  4599. #define parse_dollar(as_string, dest, input, quote_mask) \
  4600. parse_dollar(dest, input, quote_mask)
  4601. #define as_string NULL
  4602. #endif
  4603. static int parse_dollar(o_string *as_string,
  4604. o_string *dest,
  4605. struct in_str *input, unsigned char quote_mask)
  4606. {
  4607. int ch = i_peek_and_eat_bkslash_nl(input); /* first character after the $ */
  4608. debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
  4609. if (isalpha(ch)) {
  4610. make_var:
  4611. ch = i_getch(input);
  4612. nommu_addchr(as_string, ch);
  4613. /*make_var1:*/
  4614. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4615. while (1) {
  4616. debug_printf_parse(": '%c'\n", ch);
  4617. o_addchr(dest, ch | quote_mask);
  4618. quote_mask = 0;
  4619. ch = i_peek_and_eat_bkslash_nl(input);
  4620. if (!isalnum(ch) && ch != '_') {
  4621. /* End of variable name reached */
  4622. break;
  4623. }
  4624. ch = i_getch(input);
  4625. nommu_addchr(as_string, ch);
  4626. }
  4627. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4628. } else if (isdigit(ch)) {
  4629. make_one_char_var:
  4630. ch = i_getch(input);
  4631. nommu_addchr(as_string, ch);
  4632. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4633. debug_printf_parse(": '%c'\n", ch);
  4634. o_addchr(dest, ch | quote_mask);
  4635. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4636. } else switch (ch) {
  4637. case '$': /* pid */
  4638. case '!': /* last bg pid */
  4639. case '?': /* last exit code */
  4640. case '#': /* number of args */
  4641. case '*': /* args */
  4642. case '@': /* args */
  4643. case '-': /* $- option flags set by set builtin or shell options (-i etc) */
  4644. goto make_one_char_var;
  4645. case '{': {
  4646. char len_single_ch;
  4647. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4648. ch = i_getch(input); /* eat '{' */
  4649. nommu_addchr(as_string, ch);
  4650. ch = i_getch_and_eat_bkslash_nl(input); /* first char after '{' */
  4651. /* It should be ${?}, or ${#var},
  4652. * or even ${?+subst} - operator acting on a special variable,
  4653. * or the beginning of variable name.
  4654. */
  4655. if (ch == EOF
  4656. || (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) /* not one of those */
  4657. ) {
  4658. bad_dollar_syntax:
  4659. syntax_error_unterm_str("${name}");
  4660. debug_printf_parse("parse_dollar return 0: unterminated ${name}\n");
  4661. return 0;
  4662. }
  4663. nommu_addchr(as_string, ch);
  4664. len_single_ch = ch;
  4665. ch |= quote_mask;
  4666. /* It's possible to just call add_till_closing_bracket() at this point.
  4667. * However, this regresses some of our testsuite cases
  4668. * which check invalid constructs like ${%}.
  4669. * Oh well... let's check that the var name part is fine... */
  4670. while (1) {
  4671. unsigned pos;
  4672. o_addchr(dest, ch);
  4673. debug_printf_parse(": '%c'\n", ch);
  4674. ch = i_getch(input);
  4675. nommu_addchr(as_string, ch);
  4676. if (ch == '}')
  4677. break;
  4678. if (!isalnum(ch) && ch != '_') {
  4679. unsigned end_ch;
  4680. unsigned char last_ch;
  4681. /* handle parameter expansions
  4682. * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
  4683. */
  4684. if (!strchr(VAR_SUBST_OPS, ch)) { /* ${var<bad_char>... */
  4685. if (len_single_ch != '#'
  4686. /*|| !strchr(SPECIAL_VARS_STR, ch) - disallow errors like ${#+} ? */
  4687. || i_peek(input) != '}'
  4688. ) {
  4689. goto bad_dollar_syntax;
  4690. }
  4691. /* else: it's "length of C" ${#C} op,
  4692. * where C is a single char
  4693. * special var name, e.g. ${#!}.
  4694. */
  4695. }
  4696. /* Eat everything until closing '}' (or ':') */
  4697. end_ch = '}';
  4698. if (BASH_SUBSTR
  4699. && ch == ':'
  4700. && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
  4701. ) {
  4702. /* It's ${var:N[:M]} thing */
  4703. end_ch = '}' * 0x100 + ':';
  4704. }
  4705. if (BASH_PATTERN_SUBST
  4706. && ch == '/'
  4707. ) {
  4708. /* It's ${var/[/]pattern[/repl]} thing */
  4709. if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
  4710. i_getch(input);
  4711. nommu_addchr(as_string, '/');
  4712. ch = '\\';
  4713. }
  4714. end_ch = '}' * 0x100 + '/';
  4715. }
  4716. o_addchr(dest, ch);
  4717. /* The pattern can't be empty.
  4718. * IOW: if the first char after "${v//" is a slash,
  4719. * it does not terminate the pattern - it's the first char of the pattern:
  4720. * v=/dev/ram; echo ${v////-} prints -dev-ram (pattern is "/")
  4721. * v=/dev/ram; echo ${v///r/-} prints /dev-am (pattern is "/r")
  4722. */
  4723. if (i_peek(input) == '/') {
  4724. o_addchr(dest, i_getch(input));
  4725. }
  4726. again:
  4727. if (!BB_MMU)
  4728. pos = dest->length;
  4729. #if ENABLE_HUSH_DOLLAR_OPS
  4730. last_ch = add_till_closing_bracket(dest, input, end_ch);
  4731. if (last_ch == 0) /* error? */
  4732. return 0;
  4733. #else
  4734. # error Simple code to only allow ${var} is not implemented
  4735. #endif
  4736. if (as_string) {
  4737. o_addstr(as_string, dest->data + pos);
  4738. o_addchr(as_string, last_ch);
  4739. }
  4740. if ((BASH_SUBSTR || BASH_PATTERN_SUBST)
  4741. && (end_ch & 0xff00)
  4742. ) {
  4743. /* close the first block: */
  4744. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4745. /* while parsing N from ${var:N[:M]}
  4746. * or pattern from ${var/[/]pattern[/repl]} */
  4747. if ((end_ch & 0xff) == last_ch) {
  4748. /* got ':' or '/'- parse the rest */
  4749. end_ch = '}';
  4750. goto again;
  4751. }
  4752. /* got '}' */
  4753. if (BASH_SUBSTR && end_ch == '}' * 0x100 + ':') {
  4754. /* it's ${var:N} - emulate :999999999 */
  4755. o_addstr(dest, "999999999");
  4756. } /* else: it's ${var/[/]pattern} */
  4757. }
  4758. break;
  4759. }
  4760. len_single_ch = 0; /* it can't be ${#C} op */
  4761. }
  4762. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4763. break;
  4764. }
  4765. #if ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_TICK
  4766. case '(': {
  4767. unsigned pos;
  4768. ch = i_getch(input);
  4769. nommu_addchr(as_string, ch);
  4770. # if ENABLE_FEATURE_SH_MATH
  4771. if (i_peek_and_eat_bkslash_nl(input) == '(') {
  4772. ch = i_getch(input);
  4773. nommu_addchr(as_string, ch);
  4774. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4775. o_addchr(dest, quote_mask | '+');
  4776. if (!BB_MMU)
  4777. pos = dest->length;
  4778. if (!add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG))
  4779. return 0; /* error */
  4780. if (as_string) {
  4781. o_addstr(as_string, dest->data + pos);
  4782. o_addchr(as_string, ')');
  4783. o_addchr(as_string, ')');
  4784. }
  4785. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4786. break;
  4787. }
  4788. # endif
  4789. # if ENABLE_HUSH_TICK
  4790. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4791. o_addchr(dest, quote_mask | '`');
  4792. if (!BB_MMU)
  4793. pos = dest->length;
  4794. if (!add_till_closing_bracket(dest, input, ')'))
  4795. return 0; /* error */
  4796. if (as_string) {
  4797. o_addstr(as_string, dest->data + pos);
  4798. o_addchr(as_string, ')');
  4799. }
  4800. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4801. # endif
  4802. break;
  4803. }
  4804. #endif
  4805. case '_':
  4806. goto make_var;
  4807. #if 0
  4808. /* TODO: $_: */
  4809. /* $_ Shell or shell script name; or last argument of last command
  4810. * (if last command wasn't a pipe; if it was, bash sets $_ to "");
  4811. * but in command's env, set to full pathname used to invoke it */
  4812. ch = i_getch(input);
  4813. nommu_addchr(as_string, ch);
  4814. ch = i_peek_and_eat_bkslash_nl(input);
  4815. if (isalnum(ch)) { /* it's $_name or $_123 */
  4816. ch = '_';
  4817. goto make_var1;
  4818. }
  4819. /* else: it's $_ */
  4820. #endif
  4821. default:
  4822. o_addQchr(dest, '$');
  4823. }
  4824. debug_printf_parse("parse_dollar return 1 (ok)\n");
  4825. return 1;
  4826. #undef as_string
  4827. }
  4828. #if BB_MMU
  4829. #define encode_string(as_string, dest, input, dquote_end) \
  4830. encode_string(dest, input, dquote_end)
  4831. #define as_string NULL
  4832. #endif
  4833. static int encode_string(o_string *as_string,
  4834. o_string *dest,
  4835. struct in_str *input,
  4836. int dquote_end)
  4837. {
  4838. int ch;
  4839. int next;
  4840. again:
  4841. ch = i_getch(input);
  4842. if (ch != EOF)
  4843. nommu_addchr(as_string, ch);
  4844. if (ch == dquote_end) { /* may be only '"' or EOF */
  4845. debug_printf_parse("encode_string return 1 (ok)\n");
  4846. return 1;
  4847. }
  4848. /* note: can't move it above ch == dquote_end check! */
  4849. if (ch == EOF) {
  4850. syntax_error_unterm_ch('"');
  4851. return 0; /* error */
  4852. }
  4853. next = '\0';
  4854. if (ch != '\n') {
  4855. next = i_peek(input);
  4856. }
  4857. debug_printf_parse("\" ch=%c (%d) escape=%d\n",
  4858. ch, ch, !!(dest->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
  4859. if (ch == '\\') {
  4860. if (next == EOF) {
  4861. /* Testcase: in interactive shell a file with
  4862. * echo "unterminated string\<eof>
  4863. * is sourced.
  4864. */
  4865. syntax_error_unterm_ch('"');
  4866. return 0; /* error */
  4867. }
  4868. /* bash:
  4869. * "The backslash retains its special meaning [in "..."]
  4870. * only when followed by one of the following characters:
  4871. * $, `, ", \, or <newline>. A double quote may be quoted
  4872. * within double quotes by preceding it with a backslash."
  4873. * NB: in (unquoted) heredoc, above does not apply to ",
  4874. * therefore we check for it by "next == dquote_end" cond.
  4875. */
  4876. if (next == dquote_end || strchr("$`\\\n", next)) {
  4877. ch = i_getch(input); /* eat next */
  4878. if (ch == '\n')
  4879. goto again; /* skip \<newline> */
  4880. } /* else: ch remains == '\\', and we double it below: */
  4881. o_addqchr(dest, ch); /* \c if c is a glob char, else just c */
  4882. nommu_addchr(as_string, ch);
  4883. goto again;
  4884. }
  4885. if (ch == '$') {
  4886. if (!parse_dollar(as_string, dest, input, /*quote_mask:*/ 0x80)) {
  4887. debug_printf_parse("encode_string return 0: "
  4888. "parse_dollar returned 0 (error)\n");
  4889. return 0;
  4890. }
  4891. goto again;
  4892. }
  4893. #if ENABLE_HUSH_TICK
  4894. if (ch == '`') {
  4895. //unsigned pos = dest->length;
  4896. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4897. o_addchr(dest, 0x80 | '`');
  4898. if (!add_till_backquote(dest, input, /*in_dquote:*/ dquote_end == '"'))
  4899. return 0; /* error */
  4900. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4901. //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
  4902. goto again;
  4903. }
  4904. #endif
  4905. o_addQchr(dest, ch);
  4906. goto again;
  4907. #undef as_string
  4908. }
  4909. /*
  4910. * Scan input until EOF or end_trigger char.
  4911. * Return a list of pipes to execute, or NULL on EOF
  4912. * or if end_trigger character is met.
  4913. * On syntax error, exit if shell is not interactive,
  4914. * reset parsing machinery and start parsing anew,
  4915. * or return ERR_PTR.
  4916. */
  4917. static struct pipe *parse_stream(char **pstring,
  4918. int *heredoc_cnt_ptr,
  4919. struct in_str *input,
  4920. int end_trigger)
  4921. {
  4922. struct parse_context ctx;
  4923. int heredoc_cnt;
  4924. /* Single-quote triggers a bypass of the main loop until its mate is
  4925. * found. When recursing, quote state is passed in via ctx.word.o_expflags.
  4926. */
  4927. debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
  4928. end_trigger ? end_trigger : 'X');
  4929. debug_enter();
  4930. initialize_context(&ctx);
  4931. /* If very first arg is "" or '', ctx.word.data may end up NULL.
  4932. * Preventing this:
  4933. */
  4934. ctx.word.data = xzalloc(1); /* start as "", not as NULL */
  4935. /* We used to separate words on $IFS here. This was wrong.
  4936. * $IFS is used only for word splitting when $var is expanded,
  4937. * here we should use blank chars as separators, not $IFS
  4938. */
  4939. heredoc_cnt = 0;
  4940. while (1) {
  4941. const char *is_blank;
  4942. const char *is_special;
  4943. int ch;
  4944. int next;
  4945. int redir_fd;
  4946. redir_type redir_style;
  4947. ch = i_getch(input);
  4948. debug_printf_parse(": ch=%c (%d) escape=%d\n",
  4949. ch, ch, !!(ctx.word.o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
  4950. if (ch == EOF) {
  4951. struct pipe *pi;
  4952. if (heredoc_cnt) {
  4953. syntax_error_unterm_str("here document");
  4954. goto parse_error_exitcode1;
  4955. }
  4956. if (end_trigger == ')') {
  4957. syntax_error_unterm_ch('(');
  4958. goto parse_error_exitcode1;
  4959. }
  4960. if (end_trigger == '}') {
  4961. syntax_error_unterm_ch('{');
  4962. goto parse_error_exitcode1;
  4963. }
  4964. if (done_word(&ctx)) {
  4965. goto parse_error_exitcode1;
  4966. }
  4967. o_free_and_set_NULL(&ctx.word);
  4968. done_pipe(&ctx, PIPE_SEQ);
  4969. pi = ctx.list_head;
  4970. /* If we got nothing... */
  4971. /* (this makes bare "&" cmd a no-op.
  4972. * bash says: "syntax error near unexpected token '&'") */
  4973. if (pi->num_cmds == 0
  4974. IF_HAS_KEYWORDS(&& pi->res_word == RES_NONE)
  4975. ) {
  4976. free_pipe_list(pi);
  4977. pi = NULL;
  4978. }
  4979. #if !BB_MMU
  4980. debug_printf_parse("as_string1 '%s'\n", ctx.as_string.data);
  4981. if (pstring)
  4982. *pstring = ctx.as_string.data;
  4983. else
  4984. o_free(&ctx.as_string);
  4985. #endif
  4986. // heredoc_cnt must be 0 here anyway
  4987. //if (heredoc_cnt_ptr)
  4988. // *heredoc_cnt_ptr = heredoc_cnt;
  4989. debug_leave();
  4990. debug_printf_heredoc("parse_stream return heredoc_cnt:%d\n", heredoc_cnt);
  4991. debug_printf_parse("parse_stream return %p\n", pi);
  4992. return pi;
  4993. }
  4994. /* Handle "'" and "\" first, as they won't play nice with
  4995. * i_peek_and_eat_bkslash_nl() anyway:
  4996. * echo z\\
  4997. * and
  4998. * echo '\
  4999. * '
  5000. * would break.
  5001. */
  5002. if (ch == '\\') {
  5003. ch = i_getch(input);
  5004. if (ch == '\n')
  5005. continue; /* drop \<newline>, get next char */
  5006. nommu_addchr(&ctx.as_string, '\\');
  5007. o_addchr(&ctx.word, '\\');
  5008. if (ch == EOF) {
  5009. /* Testcase: eval 'echo Ok\' */
  5010. /* bash-4.3.43 was removing backslash,
  5011. * but 4.4.19 retains it, most other shells too
  5012. */
  5013. continue; /* get next char */
  5014. }
  5015. /* Example: echo Hello \2>file
  5016. * we need to know that word 2 is quoted
  5017. */
  5018. ctx.word.has_quoted_part = 1;
  5019. nommu_addchr(&ctx.as_string, ch);
  5020. o_addchr(&ctx.word, ch);
  5021. continue; /* get next char */
  5022. }
  5023. nommu_addchr(&ctx.as_string, ch);
  5024. if (ch == '\'') {
  5025. ctx.word.has_quoted_part = 1;
  5026. next = i_getch(input);
  5027. if (next == '\'' && !ctx.pending_redirect)
  5028. goto insert_empty_quoted_str_marker;
  5029. ch = next;
  5030. while (1) {
  5031. if (ch == EOF) {
  5032. syntax_error_unterm_ch('\'');
  5033. goto parse_error_exitcode1;
  5034. }
  5035. nommu_addchr(&ctx.as_string, ch);
  5036. if (ch == '\'')
  5037. break;
  5038. if (ch == SPECIAL_VAR_SYMBOL) {
  5039. /* Convert raw ^C to corresponding special variable reference */
  5040. o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
  5041. o_addchr(&ctx.word, SPECIAL_VAR_QUOTED_SVS);
  5042. }
  5043. o_addqchr(&ctx.word, ch);
  5044. ch = i_getch(input);
  5045. }
  5046. continue; /* get next char */
  5047. }
  5048. next = '\0';
  5049. if (ch != '\n')
  5050. next = i_peek_and_eat_bkslash_nl(input);
  5051. is_special = "{}<>&|();#" /* special outside of "str" */
  5052. "$\"" IF_HUSH_TICK("`") /* always special */
  5053. SPECIAL_VAR_SYMBOL_STR;
  5054. #if defined(CMD_TEST2_SINGLEWORD_NOGLOB)
  5055. if (ctx.command->cmd_type == CMD_TEST2_SINGLEWORD_NOGLOB) {
  5056. /* In [[ ]], {}<>&|() are not special */
  5057. is_special += 8;
  5058. } else
  5059. #endif
  5060. /* Are { and } special here? */
  5061. if (ctx.command->argv /* word [word]{... - non-special */
  5062. || ctx.word.length /* word{... - non-special */
  5063. || ctx.word.has_quoted_part /* ""{... - non-special */
  5064. || (next != ';' /* }; - special */
  5065. && next != ')' /* }) - special */
  5066. && next != '(' /* {( - special */
  5067. && next != '&' /* }& and }&& ... - special */
  5068. && next != '|' /* }|| ... - special */
  5069. && !strchr(defifs, next) /* {word - non-special */
  5070. )
  5071. ) {
  5072. /* They are not special, skip "{}" */
  5073. is_special += 2;
  5074. }
  5075. is_special = strchr(is_special, ch);
  5076. is_blank = strchr(defifs, ch);
  5077. if (!is_special && !is_blank) { /* ordinary char */
  5078. ordinary_char:
  5079. o_addQchr(&ctx.word, ch);
  5080. if ((ctx.is_assignment == MAYBE_ASSIGNMENT
  5081. || ctx.is_assignment == WORD_IS_KEYWORD)
  5082. && ch == '='
  5083. && endofname(ctx.word.data)[0] == '='
  5084. ) {
  5085. ctx.is_assignment = DEFINITELY_ASSIGNMENT;
  5086. debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
  5087. }
  5088. continue;
  5089. }
  5090. if (is_blank) {
  5091. #if ENABLE_HUSH_LINENO_VAR
  5092. /* Case:
  5093. * "while ...; do<whitespace><newline>
  5094. * cmd ..."
  5095. * would think that "cmd" starts in <whitespace> -
  5096. * i.e., at the previous line.
  5097. * We need to skip all whitespace before newlines.
  5098. */
  5099. while (ch != '\n') {
  5100. next = i_peek(input);
  5101. if (next != ' ' && next != '\t' && next != '\n')
  5102. break; /* next char is not ws */
  5103. ch = i_getch(input);
  5104. }
  5105. /* ch == last eaten whitespace char */
  5106. #endif
  5107. if (done_word(&ctx)) {
  5108. goto parse_error_exitcode1;
  5109. }
  5110. if (ch == '\n') {
  5111. /* Is this a case when newline is simply ignored?
  5112. * Some examples:
  5113. * "cmd | <newline> cmd ..."
  5114. * "case ... in <newline> word) ..."
  5115. */
  5116. if (IS_NULL_CMD(ctx.command)
  5117. && ctx.word.length == 0
  5118. && !ctx.word.has_quoted_part
  5119. && heredoc_cnt == 0
  5120. ) {
  5121. /* This newline can be ignored. But...
  5122. * Without check #1, interactive shell
  5123. * ignores even bare <newline>,
  5124. * and shows the continuation prompt:
  5125. * ps1_prompt$ <enter>
  5126. * ps2> _ <=== wrong, should be ps1
  5127. * Without check #2, "cmd & <newline>"
  5128. * is similarly mistreated.
  5129. * (BTW, this makes "cmd & cmd"
  5130. * and "cmd && cmd" non-orthogonal.
  5131. * Really, ask yourself, why
  5132. * "cmd && <newline>" doesn't start
  5133. * cmd but waits for more input?
  5134. * The only reason is that it might be
  5135. * a "cmd1 && <nl> cmd2 &" construct,
  5136. * cmd1 may need to run in BG).
  5137. */
  5138. struct pipe *pi = ctx.list_head;
  5139. if (pi->num_cmds != 0 /* check #1 */
  5140. && pi->followup != PIPE_BG /* check #2 */
  5141. ) {
  5142. continue;
  5143. }
  5144. }
  5145. /* Treat newline as a command separator. */
  5146. done_pipe(&ctx, PIPE_SEQ);
  5147. debug_printf_heredoc("heredoc_cnt:%d\n", heredoc_cnt);
  5148. if (heredoc_cnt) {
  5149. heredoc_cnt = fetch_heredocs(&ctx.as_string, ctx.list_head, heredoc_cnt, input);
  5150. if (heredoc_cnt != 0)
  5151. goto parse_error_exitcode1;
  5152. }
  5153. ctx.is_assignment = MAYBE_ASSIGNMENT;
  5154. debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
  5155. ch = ';';
  5156. /* note: if (is_blank) continue;
  5157. * will still trigger for us */
  5158. }
  5159. }
  5160. /* "cmd}" or "cmd }..." without semicolon or &:
  5161. * } is an ordinary char in this case, even inside { cmd; }
  5162. * Pathological example: { ""}; } should exec "}" cmd
  5163. */
  5164. if (ch == '}') {
  5165. if (ctx.word.length != 0 /* word} */
  5166. || ctx.word.has_quoted_part /* ""} */
  5167. ) {
  5168. goto ordinary_char;
  5169. }
  5170. if (!IS_NULL_CMD(ctx.command)) { /* cmd } */
  5171. /* Generally, there should be semicolon: "cmd; }"
  5172. * However, bash allows to omit it if "cmd" is
  5173. * a group. Examples:
  5174. * { { echo 1; } }
  5175. * {(echo 1)}
  5176. * { echo 0 >&2 | { echo 1; } }
  5177. * { while false; do :; done }
  5178. * { case a in b) ;; esac }
  5179. */
  5180. if (ctx.command->group)
  5181. goto term_group;
  5182. goto ordinary_char;
  5183. }
  5184. if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
  5185. /* Can't be an end of {cmd}, skip the check */
  5186. goto skip_end_trigger;
  5187. /* else: } does terminate a group */
  5188. }
  5189. term_group:
  5190. if (end_trigger && end_trigger == ch
  5191. && (ch != ';' || heredoc_cnt == 0)
  5192. #if ENABLE_HUSH_CASE
  5193. && (ch != ')'
  5194. || ctx.ctx_res_w != RES_MATCH
  5195. || (!ctx.word.has_quoted_part && strcmp(ctx.word.data, "esac") == 0)
  5196. )
  5197. #endif
  5198. ) {
  5199. if (done_word(&ctx)) {
  5200. goto parse_error_exitcode1;
  5201. }
  5202. done_pipe(&ctx, PIPE_SEQ);
  5203. ctx.is_assignment = MAYBE_ASSIGNMENT;
  5204. debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
  5205. /* Do we sit outside of any if's, loops or case's? */
  5206. if (!HAS_KEYWORDS
  5207. IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
  5208. ) {
  5209. o_free_and_set_NULL(&ctx.word);
  5210. #if !BB_MMU
  5211. debug_printf_parse("as_string2 '%s'\n", ctx.as_string.data);
  5212. if (pstring)
  5213. *pstring = ctx.as_string.data;
  5214. else
  5215. o_free(&ctx.as_string);
  5216. #endif
  5217. if (ch != ';' && IS_NULL_PIPE(ctx.list_head)) {
  5218. /* Example: bare "{ }", "()" */
  5219. G.last_exitcode = 2; /* bash compat */
  5220. syntax_error_unexpected_ch(ch);
  5221. goto parse_error;
  5222. }
  5223. if (heredoc_cnt_ptr)
  5224. *heredoc_cnt_ptr = heredoc_cnt;
  5225. debug_printf_heredoc("parse_stream return heredoc_cnt:%d\n", heredoc_cnt);
  5226. debug_printf_parse("parse_stream return %p: "
  5227. "end_trigger char found\n",
  5228. ctx.list_head);
  5229. debug_leave();
  5230. return ctx.list_head;
  5231. }
  5232. }
  5233. if (is_blank)
  5234. continue;
  5235. /* Catch <, > before deciding whether this word is
  5236. * an assignment. a=1 2>z b=2: b=2 is still assignment */
  5237. switch (ch) {
  5238. case '>':
  5239. redir_fd = redirect_opt_num(&ctx.word);
  5240. if (done_word(&ctx)) {
  5241. goto parse_error_exitcode1;
  5242. }
  5243. redir_style = REDIRECT_OVERWRITE;
  5244. if (next == '>') {
  5245. redir_style = REDIRECT_APPEND;
  5246. ch = i_getch(input);
  5247. nommu_addchr(&ctx.as_string, ch);
  5248. }
  5249. #if 0
  5250. else if (next == '(') {
  5251. syntax_error(">(process) not supported");
  5252. goto parse_error_exitcode1;
  5253. }
  5254. #endif
  5255. if (parse_redirect(&ctx, redir_fd, redir_style, input))
  5256. goto parse_error_exitcode1;
  5257. continue; /* get next char */
  5258. case '<':
  5259. redir_fd = redirect_opt_num(&ctx.word);
  5260. if (done_word(&ctx)) {
  5261. goto parse_error_exitcode1;
  5262. }
  5263. redir_style = REDIRECT_INPUT;
  5264. if (next == '<') {
  5265. redir_style = REDIRECT_HEREDOC;
  5266. heredoc_cnt++;
  5267. debug_printf_heredoc("++heredoc_cnt=%d\n", heredoc_cnt);
  5268. ch = i_getch(input);
  5269. nommu_addchr(&ctx.as_string, ch);
  5270. } else if (next == '>') {
  5271. redir_style = REDIRECT_IO;
  5272. ch = i_getch(input);
  5273. nommu_addchr(&ctx.as_string, ch);
  5274. }
  5275. #if 0
  5276. else if (next == '(') {
  5277. syntax_error("<(process) not supported");
  5278. goto parse_error_exitcode1;
  5279. }
  5280. #endif
  5281. if (parse_redirect(&ctx, redir_fd, redir_style, input))
  5282. goto parse_error_exitcode1;
  5283. continue; /* get next char */
  5284. case '#':
  5285. if (ctx.word.length == 0 && !ctx.word.has_quoted_part) {
  5286. /* skip "#comment" */
  5287. /* note: we do not add it to &ctx.as_string */
  5288. /* TODO: in bash:
  5289. * comment inside $() goes to the next \n, even inside quoted string (!):
  5290. * cmd "$(cmd2 #comment)" - syntax error
  5291. * cmd "`cmd2 #comment`" - ok
  5292. * We accept both (comment ends where command subst ends, in both cases).
  5293. */
  5294. while (1) {
  5295. ch = i_peek(input);
  5296. if (ch == '\n') {
  5297. nommu_addchr(&ctx.as_string, '\n');
  5298. break;
  5299. }
  5300. ch = i_getch(input);
  5301. if (ch == EOF)
  5302. break;
  5303. }
  5304. continue; /* get next char */
  5305. }
  5306. break;
  5307. }
  5308. skip_end_trigger:
  5309. if (ctx.is_assignment == MAYBE_ASSIGNMENT
  5310. /* check that we are not in word in "a=1 2>word b=1": */
  5311. && !ctx.pending_redirect
  5312. ) {
  5313. /* ch is a special char and thus this word
  5314. * cannot be an assignment */
  5315. ctx.is_assignment = NOT_ASSIGNMENT;
  5316. debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
  5317. }
  5318. /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
  5319. switch (ch) {
  5320. case SPECIAL_VAR_SYMBOL:
  5321. /* Convert raw ^C to corresponding special variable reference */
  5322. o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
  5323. o_addchr(&ctx.word, SPECIAL_VAR_QUOTED_SVS);
  5324. /* fall through */
  5325. case '#':
  5326. /* non-comment #: "echo a#b" etc */
  5327. o_addchr(&ctx.word, ch);
  5328. continue; /* get next char */
  5329. case '$':
  5330. if (!parse_dollar(&ctx.as_string, &ctx.word, input, /*quote_mask:*/ 0)) {
  5331. debug_printf_parse("parse_stream parse error: "
  5332. "parse_dollar returned 0 (error)\n");
  5333. goto parse_error_exitcode1;
  5334. }
  5335. continue; /* get next char */
  5336. case '"':
  5337. ctx.word.has_quoted_part = 1;
  5338. if (next == '"' && !ctx.pending_redirect) {
  5339. i_getch(input); /* eat second " */
  5340. insert_empty_quoted_str_marker:
  5341. nommu_addchr(&ctx.as_string, next);
  5342. o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
  5343. o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
  5344. continue; /* get next char */
  5345. }
  5346. if (ctx.is_assignment == NOT_ASSIGNMENT)
  5347. ctx.word.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
  5348. if (!encode_string(&ctx.as_string, &ctx.word, input, '"'))
  5349. goto parse_error_exitcode1;
  5350. ctx.word.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
  5351. continue; /* get next char */
  5352. #if ENABLE_HUSH_TICK
  5353. case '`': {
  5354. USE_FOR_NOMMU(unsigned pos;)
  5355. o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
  5356. o_addchr(&ctx.word, '`');
  5357. USE_FOR_NOMMU(pos = ctx.word.length;)
  5358. if (!add_till_backquote(&ctx.word, input, /*in_dquote:*/ 0))
  5359. goto parse_error_exitcode1;
  5360. # if !BB_MMU
  5361. o_addstr(&ctx.as_string, ctx.word.data + pos);
  5362. o_addchr(&ctx.as_string, '`');
  5363. # endif
  5364. o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
  5365. //debug_printf_subst("SUBST RES3 '%s'\n", ctx.word.data + pos);
  5366. continue; /* get next char */
  5367. }
  5368. #endif
  5369. case ';':
  5370. #if ENABLE_HUSH_CASE
  5371. case_semi:
  5372. #endif
  5373. if (done_word(&ctx)) {
  5374. goto parse_error_exitcode1;
  5375. }
  5376. done_pipe(&ctx, PIPE_SEQ);
  5377. #if ENABLE_HUSH_CASE
  5378. /* Eat multiple semicolons, detect
  5379. * whether it means something special */
  5380. while (1) {
  5381. ch = i_peek_and_eat_bkslash_nl(input);
  5382. if (ch != ';')
  5383. break;
  5384. ch = i_getch(input);
  5385. nommu_addchr(&ctx.as_string, ch);
  5386. if (ctx.ctx_res_w == RES_CASE_BODY) {
  5387. ctx.ctx_dsemicolon = 1;
  5388. ctx.ctx_res_w = RES_MATCH;
  5389. break;
  5390. }
  5391. }
  5392. #endif
  5393. new_cmd:
  5394. /* We just finished a cmd. New one may start
  5395. * with an assignment */
  5396. ctx.is_assignment = MAYBE_ASSIGNMENT;
  5397. debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
  5398. continue; /* get next char */
  5399. case '&':
  5400. if (done_word(&ctx)) {
  5401. goto parse_error_exitcode1;
  5402. }
  5403. if (next == '&') {
  5404. ch = i_getch(input);
  5405. nommu_addchr(&ctx.as_string, ch);
  5406. done_pipe(&ctx, PIPE_AND);
  5407. } else {
  5408. done_pipe(&ctx, PIPE_BG);
  5409. }
  5410. goto new_cmd;
  5411. case '|':
  5412. if (done_word(&ctx)) {
  5413. goto parse_error_exitcode1;
  5414. }
  5415. #if ENABLE_HUSH_CASE
  5416. if (ctx.ctx_res_w == RES_MATCH)
  5417. break; /* we are in case's "word | word)" */
  5418. #endif
  5419. if (next == '|') { /* || */
  5420. ch = i_getch(input);
  5421. nommu_addchr(&ctx.as_string, ch);
  5422. done_pipe(&ctx, PIPE_OR);
  5423. } else {
  5424. /* we could pick up a file descriptor choice here
  5425. * with redirect_opt_num(), but bash doesn't do it.
  5426. * "echo foo 2| cat" yields "foo 2". */
  5427. done_command(&ctx);
  5428. }
  5429. goto new_cmd;
  5430. case '(':
  5431. #if ENABLE_HUSH_CASE
  5432. /* "case... in [(]word)..." - skip '(' */
  5433. if (ctx.ctx_res_w == RES_MATCH
  5434. && ctx.command->argv == NULL /* not (word|(... */
  5435. && ctx.word.length == 0 /* not word(... */
  5436. && ctx.word.has_quoted_part == 0 /* not ""(... */
  5437. ) {
  5438. continue; /* get next char */
  5439. }
  5440. #endif
  5441. /* fall through */
  5442. case '{': {
  5443. int n = parse_group(&ctx, input, ch);
  5444. if (n < 0) {
  5445. goto parse_error_exitcode1;
  5446. }
  5447. debug_printf_heredoc("parse_group done, needs heredocs:%d\n", n);
  5448. heredoc_cnt += n;
  5449. goto new_cmd;
  5450. }
  5451. case ')':
  5452. #if ENABLE_HUSH_CASE
  5453. if (ctx.ctx_res_w == RES_MATCH)
  5454. goto case_semi;
  5455. #endif
  5456. case '}':
  5457. /* proper use of this character is caught by end_trigger:
  5458. * if we see {, we call parse_group(..., end_trigger='}')
  5459. * and it will match } earlier (not here). */
  5460. G.last_exitcode = 2;
  5461. syntax_error_unexpected_ch(ch);
  5462. goto parse_error;
  5463. default:
  5464. if (HUSH_DEBUG)
  5465. bb_error_msg_and_die("BUG: unexpected %c", ch);
  5466. }
  5467. } /* while (1) */
  5468. parse_error_exitcode1:
  5469. G.last_exitcode = 1;
  5470. parse_error:
  5471. {
  5472. struct parse_context *pctx;
  5473. IF_HAS_KEYWORDS(struct parse_context *p2;)
  5474. /* Clean up allocated tree.
  5475. * Sample for finding leaks on syntax error recovery path.
  5476. * Run it from interactive shell, watch pmap `pidof hush`.
  5477. * while if false; then false; fi; do break; fi
  5478. * Samples to catch leaks at execution:
  5479. * while if (true | { true;}); then echo ok; fi; do break; done
  5480. * while if (true | { true;}); then echo ok; fi; do (if echo ok; break; then :; fi) | cat; break; done
  5481. */
  5482. pctx = &ctx;
  5483. do {
  5484. /* Update pipe/command counts,
  5485. * otherwise freeing may miss some */
  5486. done_pipe(pctx, PIPE_SEQ);
  5487. debug_printf_clean("freeing list %p from ctx %p\n",
  5488. pctx->list_head, pctx);
  5489. debug_print_tree(pctx->list_head, 0);
  5490. free_pipe_list(pctx->list_head);
  5491. debug_printf_clean("freed list %p\n", pctx->list_head);
  5492. #if !BB_MMU
  5493. o_free(&pctx->as_string);
  5494. #endif
  5495. IF_HAS_KEYWORDS(p2 = pctx->stack;)
  5496. if (pctx != &ctx) {
  5497. free(pctx);
  5498. }
  5499. IF_HAS_KEYWORDS(pctx = p2;)
  5500. } while (HAS_KEYWORDS && pctx);
  5501. o_free(&ctx.word);
  5502. #if !BB_MMU
  5503. if (pstring)
  5504. *pstring = NULL;
  5505. #endif
  5506. debug_leave();
  5507. return ERR_PTR;
  5508. }
  5509. }
  5510. /*** Execution routines ***/
  5511. /* Expansion can recurse, need forward decls: */
  5512. #if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
  5513. #define expand_string_to_string(str, EXP_flags, do_unbackslash) \
  5514. expand_string_to_string(str)
  5515. #endif
  5516. static char *expand_string_to_string(const char *str, int EXP_flags, int do_unbackslash);
  5517. #if ENABLE_HUSH_TICK
  5518. static int process_command_subs(o_string *dest, const char *s);
  5519. #endif
  5520. static int expand_vars_to_list(o_string *output, int n, char *arg);
  5521. /* expand_strvec_to_strvec() takes a list of strings, expands
  5522. * all variable references within and returns a pointer to
  5523. * a list of expanded strings, possibly with larger number
  5524. * of strings. (Think VAR="a b"; echo $VAR).
  5525. * This new list is allocated as a single malloc block.
  5526. * NULL-terminated list of char* pointers is at the beginning of it,
  5527. * followed by strings themselves.
  5528. * Caller can deallocate entire list by single free(list). */
  5529. /* A horde of its helpers come first: */
  5530. static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
  5531. {
  5532. while (--len >= 0) {
  5533. char c = *str++;
  5534. #if ENABLE_HUSH_BRACE_EXPANSION
  5535. if (c == '{' || c == '}') {
  5536. /* { -> \{, } -> \} */
  5537. o_addchr(o, '\\');
  5538. /* And now we want to add { or } and continue:
  5539. * o_addchr(o, c);
  5540. * continue;
  5541. * luckily, just falling through achieves this.
  5542. */
  5543. }
  5544. #endif
  5545. o_addchr(o, c);
  5546. if (c == '\\') {
  5547. /* \z -> \\\z; \<eol> -> \\<eol> */
  5548. o_addchr(o, '\\');
  5549. if (len) {
  5550. len--;
  5551. o_addchr(o, '\\');
  5552. o_addchr(o, *str++);
  5553. }
  5554. }
  5555. }
  5556. }
  5557. /* Store given string, finalizing the word and starting new one whenever
  5558. * we encounter IFS char(s). This is used for expanding variable values.
  5559. * End-of-string does NOT finalize word: think about 'echo -$VAR-'.
  5560. * Return in output->ended_in_ifs:
  5561. * 1 - ended with IFS char, else 0 (this includes case of empty str).
  5562. */
  5563. static int expand_on_ifs(o_string *output, int n, const char *str)
  5564. {
  5565. int last_is_ifs = 0;
  5566. while (1) {
  5567. int word_len;
  5568. if (!*str) /* EOL - do not finalize word */
  5569. break;
  5570. word_len = strcspn(str, G.ifs);
  5571. if (word_len) {
  5572. /* We have WORD_LEN leading non-IFS chars */
  5573. if (!(output->o_expflags & EXP_FLAG_GLOB)) {
  5574. o_addblock(output, str, word_len);
  5575. } else {
  5576. /* Protect backslashes against globbing up :)
  5577. * Example: "v='\*'; echo b$v" prints "b\*"
  5578. * (and does not try to glob on "*")
  5579. */
  5580. o_addblock_duplicate_backslash(output, str, word_len);
  5581. /*/ Why can't we do it easier? */
  5582. /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
  5583. /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
  5584. }
  5585. last_is_ifs = 0;
  5586. str += word_len;
  5587. if (!*str) /* EOL - do not finalize word */
  5588. break;
  5589. }
  5590. /* We know str here points to at least one IFS char */
  5591. last_is_ifs = 1;
  5592. str += strspn(str, G.ifs_whitespace); /* skip IFS whitespace chars */
  5593. if (!*str) /* EOL - do not finalize word */
  5594. break;
  5595. if (G.ifs_whitespace != G.ifs /* usually false ($IFS is usually all whitespace), */
  5596. && strchr(G.ifs, *str) /* the second check would fail */
  5597. ) {
  5598. /* This is a non-whitespace $IFS char */
  5599. /* Skip it and IFS whitespace chars, start new word */
  5600. str++;
  5601. str += strspn(str, G.ifs_whitespace);
  5602. goto new_word;
  5603. }
  5604. /* Start new word... but not always! */
  5605. /* Case "v=' a'; echo ''$v": we do need to finalize empty word: */
  5606. if (output->has_quoted_part
  5607. /*
  5608. * Case "v=' a'; echo $v":
  5609. * here nothing precedes the space in $v expansion,
  5610. * therefore we should not finish the word
  5611. * (IOW: if there *is* word to finalize, only then do it):
  5612. * It's okay if this accesses the byte before first argv[]:
  5613. * past call to o_save_ptr() cleared it to zero byte
  5614. * (grep for -prev-ifs-check-).
  5615. */
  5616. || output->data[output->length - 1]
  5617. ) {
  5618. new_word:
  5619. o_addchr(output, '\0');
  5620. debug_print_list("expand_on_ifs", output, n);
  5621. n = o_save_ptr(output, n);
  5622. }
  5623. }
  5624. output->ended_in_ifs = last_is_ifs;
  5625. debug_print_list("expand_on_ifs[1]", output, n);
  5626. return n;
  5627. }
  5628. /* Helper to expand $((...)) and heredoc body. These act as if
  5629. * they are in double quotes, with the exception that they are not :).
  5630. * Just the rules are similar: "expand only $var and `cmd`"
  5631. *
  5632. * Returns malloced string.
  5633. * As an optimization, we return NULL if expansion is not needed.
  5634. */
  5635. static char *encode_then_expand_string(const char *str)
  5636. {
  5637. char *exp_str;
  5638. struct in_str input;
  5639. o_string dest = NULL_O_STRING;
  5640. const char *cp;
  5641. cp = str;
  5642. for (;;) {
  5643. if (!*cp) return NULL; /* string has no special chars */
  5644. if (*cp == '$') break;
  5645. if (*cp == '\\') break;
  5646. #if ENABLE_HUSH_TICK
  5647. if (*cp == '`') break;
  5648. #endif
  5649. cp++;
  5650. }
  5651. /* We need to expand. Example:
  5652. * echo $(($a + `echo 1`)) $((1 + $((2)) ))
  5653. */
  5654. setup_string_in_str(&input, str);
  5655. encode_string(NULL, &dest, &input, EOF);
  5656. //TODO: error check (encode_string returns 0 on error)?
  5657. //bb_error_msg("'%s' -> '%s'", str, dest.data);
  5658. exp_str = expand_string_to_string(dest.data,
  5659. EXP_FLAG_ESC_GLOB_CHARS,
  5660. /*unbackslash:*/ 1
  5661. );
  5662. //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
  5663. o_free(&dest);
  5664. return exp_str;
  5665. }
  5666. static const char *first_special_char_in_vararg(const char *cp)
  5667. {
  5668. for (;;) {
  5669. if (!*cp) return NULL; /* string has no special chars */
  5670. if (*cp == '$') return cp;
  5671. if (*cp == '\\') return cp;
  5672. if (*cp == '\'') return cp;
  5673. if (*cp == '"') return cp;
  5674. #if ENABLE_HUSH_TICK
  5675. if (*cp == '`') return cp;
  5676. #endif
  5677. /* dquoted "${x:+ARG}" should not glob, therefore
  5678. * '*' et al require some non-literal processing: */
  5679. if (*cp == '*') return cp;
  5680. if (*cp == '?') return cp;
  5681. if (*cp == '[') return cp;
  5682. cp++;
  5683. }
  5684. }
  5685. /* Expanding ARG in ${var#ARG}, ${var%ARG}, or ${var/ARG/ARG}.
  5686. * These can contain single- and double-quoted strings,
  5687. * and treated as if the ARG string is initially unquoted. IOW:
  5688. * ${var#ARG} and "${var#ARG}" treat ARG the same (ARG can even be
  5689. * a dquoted string: "${var#"zz"}"), the difference only comes later
  5690. * (word splitting and globbing of the ${var...} result).
  5691. */
  5692. #if !BASH_PATTERN_SUBST
  5693. #define encode_then_expand_vararg(str, handle_squotes, do_unbackslash) \
  5694. encode_then_expand_vararg(str, handle_squotes)
  5695. #endif
  5696. static char *encode_then_expand_vararg(const char *str, int handle_squotes, int do_unbackslash)
  5697. {
  5698. #if !BASH_PATTERN_SUBST && ENABLE_HUSH_CASE
  5699. const int do_unbackslash = 0;
  5700. #endif
  5701. char *exp_str;
  5702. struct in_str input;
  5703. o_string dest = NULL_O_STRING;
  5704. if (!first_special_char_in_vararg(str)) {
  5705. /* string has no special chars */
  5706. return NULL;
  5707. }
  5708. setup_string_in_str(&input, str);
  5709. dest.data = xzalloc(1); /* start as "", not as NULL */
  5710. exp_str = NULL;
  5711. for (;;) {
  5712. int ch;
  5713. ch = i_getch(&input);
  5714. debug_printf_parse("%s: ch=%c (%d) escape=%d\n",
  5715. __func__, ch, ch, !!dest.o_expflags);
  5716. if (!dest.o_expflags) {
  5717. if (ch == EOF)
  5718. break;
  5719. if (handle_squotes && ch == '\'') {
  5720. if (!add_till_single_quote_dquoted(&dest, &input))
  5721. goto ret; /* error */
  5722. continue;
  5723. }
  5724. }
  5725. if (ch == EOF) {
  5726. syntax_error_unterm_ch('"');
  5727. goto ret; /* error */
  5728. }
  5729. if (ch == '"') {
  5730. dest.o_expflags ^= EXP_FLAG_ESC_GLOB_CHARS;
  5731. continue;
  5732. }
  5733. if (ch == '\\') {
  5734. ch = i_getch(&input);
  5735. if (ch == EOF) {
  5736. //example? error message? syntax_error_unterm_ch('"');
  5737. debug_printf_parse("%s: error: \\<eof>\n", __func__);
  5738. goto ret;
  5739. }
  5740. o_addqchr(&dest, ch);
  5741. continue;
  5742. }
  5743. if (ch == '$') {
  5744. if (!parse_dollar(NULL, &dest, &input, /*quote_mask:*/ 0x80)) {
  5745. debug_printf_parse("%s: error: parse_dollar returned 0 (error)\n", __func__);
  5746. goto ret;
  5747. }
  5748. continue;
  5749. }
  5750. #if ENABLE_HUSH_TICK
  5751. if (ch == '`') {
  5752. //unsigned pos = dest->length;
  5753. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  5754. o_addchr(&dest, 0x80 | '`');
  5755. if (!add_till_backquote(&dest, &input,
  5756. /*in_dquote:*/ dest.o_expflags /* nonzero if EXP_FLAG_ESC_GLOB_CHARS set */
  5757. )
  5758. ) {
  5759. goto ret; /* error */
  5760. }
  5761. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  5762. //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
  5763. continue;
  5764. }
  5765. #endif
  5766. o_addQchr(&dest, ch);
  5767. } /* for (;;) */
  5768. debug_printf_parse("encode: '%s' -> '%s'\n", str, dest.data);
  5769. exp_str = expand_string_to_string(dest.data,
  5770. do_unbackslash ? EXP_FLAG_ESC_GLOB_CHARS : 0,
  5771. do_unbackslash
  5772. );
  5773. ret:
  5774. debug_printf_parse("expand: '%s' -> '%s'\n", dest.data, exp_str);
  5775. o_free(&dest);
  5776. return exp_str;
  5777. }
  5778. /* Expanding ARG in ${var+ARG}, ${var-ARG}
  5779. */
  5780. static int encode_then_append_var_plusminus(o_string *output, int n,
  5781. char *str, int dquoted)
  5782. {
  5783. struct in_str input;
  5784. o_string dest = NULL_O_STRING;
  5785. if (!first_special_char_in_vararg(str)
  5786. && '\0' == str[strcspn(str, G.ifs)]
  5787. ) {
  5788. /* string has no special chars
  5789. * && string has no $IFS chars
  5790. */
  5791. if (dquoted) {
  5792. /* Prints 1 (quoted expansion is a "" word, not nothing):
  5793. * set -- "${notexist-}"; echo $#
  5794. */
  5795. output->has_quoted_part = 1;
  5796. }
  5797. return expand_vars_to_list(output, n, str);
  5798. }
  5799. setup_string_in_str(&input, str);
  5800. for (;;) {
  5801. int ch;
  5802. ch = i_getch(&input);
  5803. debug_printf_parse("%s: ch=%c (%d) escape=%x\n",
  5804. __func__, ch, ch, dest.o_expflags);
  5805. if (!dest.o_expflags) {
  5806. if (ch == EOF)
  5807. break;
  5808. if (!dquoted && strchr(G.ifs, ch)) {
  5809. /* PREFIX${x:d${e}f ...} and we met space: expand "d${e}f" and start new word.
  5810. * do not assume we are at the start of the word (PREFIX above).
  5811. */
  5812. if (dest.data) {
  5813. n = expand_vars_to_list(output, n, dest.data);
  5814. o_free_and_set_NULL(&dest);
  5815. o_addchr(output, '\0');
  5816. n = o_save_ptr(output, n); /* create next word */
  5817. } else
  5818. if (output->length != o_get_last_ptr(output, n)
  5819. || output->has_quoted_part
  5820. ) {
  5821. /* For these cases:
  5822. * f() { for i; do echo "|$i|"; done; }; x=x
  5823. * f a${x:+ }b # 1st condition
  5824. * |a|
  5825. * |b|
  5826. * f ""${x:+ }b # 2nd condition
  5827. * ||
  5828. * |b|
  5829. */
  5830. o_addchr(output, '\0');
  5831. n = o_save_ptr(output, n); /* create next word */
  5832. }
  5833. continue;
  5834. }
  5835. if (!dquoted && ch == '\'') {
  5836. if (!add_till_single_quote_dquoted(&dest, &input))
  5837. goto ret; /* error */
  5838. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  5839. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  5840. continue;
  5841. }
  5842. }
  5843. if (ch == EOF) {
  5844. syntax_error_unterm_ch('"');
  5845. goto ret; /* error */
  5846. }
  5847. if (ch == '"') {
  5848. dest.o_expflags ^= EXP_FLAG_ESC_GLOB_CHARS;
  5849. if (dest.o_expflags) {
  5850. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  5851. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  5852. }
  5853. continue;
  5854. }
  5855. if (ch == '\\') {
  5856. ch = i_getch(&input);
  5857. if (ch == EOF) {
  5858. //example? error message? syntax_error_unterm_ch('"');
  5859. debug_printf_parse("%s: error: \\<eof>\n", __func__);
  5860. goto ret;
  5861. }
  5862. o_addqchr(&dest, ch);
  5863. continue;
  5864. }
  5865. if (ch == '$') {
  5866. if (!parse_dollar(NULL, &dest, &input, /*quote_mask:*/ (dest.o_expflags || dquoted) ? 0x80 : 0)) {
  5867. debug_printf_parse("%s: error: parse_dollar returned 0 (error)\n", __func__);
  5868. goto ret;
  5869. }
  5870. continue;
  5871. }
  5872. #if ENABLE_HUSH_TICK
  5873. if (ch == '`') {
  5874. //unsigned pos = dest->length;
  5875. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  5876. o_addchr(&dest, (dest.o_expflags || dquoted) ? 0x80 | '`' : '`');
  5877. if (!add_till_backquote(&dest, &input,
  5878. /*in_dquote:*/ dest.o_expflags /* nonzero if EXP_FLAG_ESC_GLOB_CHARS set */
  5879. )
  5880. ) {
  5881. goto ret; /* error */
  5882. }
  5883. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  5884. //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
  5885. continue;
  5886. }
  5887. #endif
  5888. if (dquoted) {
  5889. /* Always glob-protect if in dquotes:
  5890. * x=x; echo "${x:+/bin/c*}" - prints: /bin/c*
  5891. * x=x; echo "${x:+"/bin/c*"}" - prints: /bin/c*
  5892. */
  5893. o_addqchr(&dest, ch);
  5894. } else {
  5895. /* Glob-protect only if char is quoted:
  5896. * x=x; echo ${x:+/bin/c*} - prints many filenames
  5897. * x=x; echo ${x:+"/bin/c*"} - prints: /bin/c*
  5898. */
  5899. o_addQchr(&dest, ch);
  5900. }
  5901. } /* for (;;) */
  5902. if (dest.data) {
  5903. n = expand_vars_to_list(output, n, dest.data);
  5904. }
  5905. ret:
  5906. o_free(&dest);
  5907. return n;
  5908. }
  5909. #if ENABLE_FEATURE_SH_MATH
  5910. static arith_t expand_and_evaluate_arith(const char *arg, const char **errmsg_p)
  5911. {
  5912. arith_state_t math_state;
  5913. arith_t res;
  5914. char *exp_str;
  5915. math_state.lookupvar = get_local_var_value;
  5916. math_state.setvar = set_local_var_from_halves;
  5917. //math_state.endofname = endofname;
  5918. exp_str = encode_then_expand_string(arg);
  5919. res = arith(&math_state, exp_str ? exp_str : arg);
  5920. free(exp_str);
  5921. if (errmsg_p)
  5922. *errmsg_p = math_state.errmsg;
  5923. if (math_state.errmsg)
  5924. msg_and_die_if_script(math_state.errmsg);
  5925. return res;
  5926. }
  5927. #endif
  5928. #if BASH_PATTERN_SUBST
  5929. /* ${var/[/]pattern[/repl]} helpers */
  5930. static char *strstr_pattern(char *val, const char *pattern, int *size)
  5931. {
  5932. while (1) {
  5933. char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
  5934. debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
  5935. if (end) {
  5936. *size = end - val;
  5937. return val;
  5938. }
  5939. if (*val == '\0')
  5940. return NULL;
  5941. /* Optimization: if "*pat" did not match the start of "string",
  5942. * we know that "tring", "ring" etc will not match too:
  5943. */
  5944. if (pattern[0] == '*')
  5945. return NULL;
  5946. val++;
  5947. }
  5948. }
  5949. static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
  5950. {
  5951. char *result = NULL;
  5952. unsigned res_len = 0;
  5953. unsigned repl_len = strlen(repl);
  5954. /* Null pattern never matches, including if "var" is empty */
  5955. if (!pattern[0])
  5956. return result; /* NULL, no replaces happened */
  5957. while (1) {
  5958. int size;
  5959. char *s = strstr_pattern(val, pattern, &size);
  5960. if (!s)
  5961. break;
  5962. result = xrealloc(result, res_len + (s - val) + repl_len + 1);
  5963. strcpy(mempcpy(result + res_len, val, s - val), repl);
  5964. res_len += (s - val) + repl_len;
  5965. debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
  5966. val = s + size;
  5967. if (exp_op == '/')
  5968. break;
  5969. }
  5970. if (*val && result) {
  5971. result = xrealloc(result, res_len + strlen(val) + 1);
  5972. strcpy(result + res_len, val);
  5973. debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
  5974. }
  5975. debug_printf_varexp("result:'%s'\n", result);
  5976. return result;
  5977. }
  5978. #endif /* BASH_PATTERN_SUBST */
  5979. static int append_str_maybe_ifs_split(o_string *output, int n,
  5980. int first_ch, const char *val)
  5981. {
  5982. if (!(first_ch & 0x80)) { /* unquoted $VAR */
  5983. debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val,
  5984. !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
  5985. if (val && val[0])
  5986. n = expand_on_ifs(output, n, val);
  5987. } else { /* quoted "$VAR" */
  5988. output->has_quoted_part = 1;
  5989. debug_printf_expand("quoted '%s', output->o_escape:%d\n", val,
  5990. !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
  5991. if (val && val[0])
  5992. o_addQstr(output, val);
  5993. }
  5994. return n;
  5995. }
  5996. /* Handle <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
  5997. */
  5998. static NOINLINE int expand_one_var(o_string *output, int n,
  5999. int first_ch, char *arg, char **pp)
  6000. {
  6001. const char *val;
  6002. char *to_be_freed;
  6003. char *p;
  6004. char *var;
  6005. char exp_op;
  6006. char exp_save = exp_save; /* for compiler */
  6007. char *exp_saveptr; /* points to expansion operator */
  6008. char *exp_word = exp_word; /* for compiler */
  6009. char arg0;
  6010. val = NULL;
  6011. to_be_freed = NULL;
  6012. p = *pp;
  6013. *p = '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
  6014. var = arg;
  6015. exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
  6016. arg0 = arg[0];
  6017. arg[0] = (arg0 & 0x7f);
  6018. exp_op = 0;
  6019. if (arg[0] == '#' && arg[1] /* ${#...} but not ${#} */
  6020. && (!exp_saveptr /* and ( not(${#<op_char>...}) */
  6021. || (arg[2] == '\0' && strchr(SPECIAL_VARS_STR, arg[1])) /* or ${#C} "len of $C" ) */
  6022. ) /* NB: skipping ^^^specvar check mishandles ${#::2} */
  6023. ) {
  6024. /* It must be length operator: ${#var} */
  6025. var++;
  6026. exp_op = 'L';
  6027. } else {
  6028. /* Maybe handle parameter expansion */
  6029. if (exp_saveptr /* if 2nd char is one of expansion operators */
  6030. && strchr(NUMERIC_SPECVARS_STR, arg[0]) /* 1st char is special variable */
  6031. ) {
  6032. /* ${?:0}, ${#[:]%0} etc */
  6033. exp_saveptr = var + 1;
  6034. } else {
  6035. /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
  6036. exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
  6037. }
  6038. exp_op = exp_save = *exp_saveptr;
  6039. if (exp_op) {
  6040. exp_word = exp_saveptr + 1;
  6041. if (exp_op == ':') {
  6042. exp_op = *exp_word++;
  6043. //TODO: try ${var:} and ${var:bogus} in non-bash config
  6044. if (BASH_SUBSTR
  6045. && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
  6046. ) {
  6047. /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
  6048. exp_op = ':';
  6049. exp_word--;
  6050. }
  6051. }
  6052. *exp_saveptr = '\0';
  6053. } /* else: it's not an expansion op, but bare ${var} */
  6054. }
  6055. /* Look up the variable in question */
  6056. if (isdigit(var[0])) {
  6057. /* parse_dollar should have vetted var for us */
  6058. int nn = xatoi_positive(var);
  6059. if (nn < G.global_argc)
  6060. val = G.global_argv[nn];
  6061. /* else val remains NULL: $N with too big N */
  6062. } else {
  6063. switch (var[0]) {
  6064. case '$': /* pid */
  6065. val = utoa(G.root_pid);
  6066. break;
  6067. case '!': /* bg pid */
  6068. val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
  6069. break;
  6070. case '?': /* exitcode */
  6071. val = utoa(G.last_exitcode);
  6072. break;
  6073. case '#': /* argc */
  6074. val = utoa(G.global_argc ? G.global_argc-1 : 0);
  6075. break;
  6076. case '-': { /* active options */
  6077. /* Check set_mode() to see what option chars we support */
  6078. char *cp;
  6079. val = cp = G.optstring_buf;
  6080. if (G.o_opt[OPT_O_ERREXIT])
  6081. *cp++ = 'e';
  6082. if (G_interactive_fd)
  6083. *cp++ = 'i';
  6084. if (G_x_mode)
  6085. *cp++ = 'x';
  6086. /* If G.o_opt[OPT_O_NOEXEC] is true,
  6087. * commands read but are not executed,
  6088. * so $- can not execute too, 'n' is never seen in $-.
  6089. */
  6090. if (G.opt_c)
  6091. *cp++ = 'c';
  6092. if (G.opt_s)
  6093. *cp++ = 's';
  6094. *cp = '\0';
  6095. break;
  6096. }
  6097. default:
  6098. val = get_local_var_value(var);
  6099. }
  6100. }
  6101. /* Handle any expansions */
  6102. if (exp_op == 'L') {
  6103. reinit_unicode_for_hush();
  6104. debug_printf_expand("expand: length(%s)=", val);
  6105. val = utoa(val ? unicode_strlen(val) : 0);
  6106. debug_printf_expand("%s\n", val);
  6107. } else if (exp_op) {
  6108. if (exp_op == '%' || exp_op == '#') {
  6109. /* Standard-mandated substring removal ops:
  6110. * ${parameter%word} - remove smallest suffix pattern
  6111. * ${parameter%%word} - remove largest suffix pattern
  6112. * ${parameter#word} - remove smallest prefix pattern
  6113. * ${parameter##word} - remove largest prefix pattern
  6114. *
  6115. * Word is expanded to produce a glob pattern.
  6116. * Then var's value is matched to it and matching part removed.
  6117. */
  6118. /* bash compat: if x is "" and no shrinking of it is possible,
  6119. * inner ${...} is not evaluated. Example:
  6120. * unset b; : ${a%${b=B}}; echo $b
  6121. * assignment b=B only happens if $a is not "".
  6122. */
  6123. if (val && val[0]) {
  6124. char *t;
  6125. char *exp_exp_word;
  6126. char *loc;
  6127. unsigned scan_flags = pick_scan(exp_op, *exp_word);
  6128. if (exp_op == *exp_word) /* ## or %% */
  6129. exp_word++;
  6130. debug_printf_expand("expand: exp_word:'%s'\n", exp_word);
  6131. exp_exp_word = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 0);
  6132. if (exp_exp_word)
  6133. exp_word = exp_exp_word;
  6134. debug_printf_expand("expand: exp_word:'%s'\n", exp_word);
  6135. /*
  6136. * HACK ALERT. We depend here on the fact that
  6137. * G.global_argv and results of utoa and get_local_var_value
  6138. * are actually in writable memory:
  6139. * scan_and_match momentarily stores NULs there.
  6140. */
  6141. t = (char*)val;
  6142. loc = scan_and_match(t, exp_word, scan_flags);
  6143. debug_printf_expand("op:%c str:'%s' pat:'%s' res:'%s'\n", exp_op, t, exp_word, loc);
  6144. free(exp_exp_word);
  6145. if (loc) { /* match was found */
  6146. if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
  6147. val = loc; /* take right part */
  6148. else /* %[%] */
  6149. val = to_be_freed = xstrndup(val, loc - val); /* left */
  6150. }
  6151. }
  6152. }
  6153. #if BASH_PATTERN_SUBST
  6154. else if (exp_op == '/' || exp_op == '\\') {
  6155. /* It's ${var/[/]pattern[/repl]} thing.
  6156. * Note that in encoded form it has TWO parts:
  6157. * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
  6158. * and if // is used, it is encoded as \:
  6159. * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
  6160. */
  6161. /* bash compat: if var is "", both pattern and repl
  6162. * are still evaluated, if it is unset, then not:
  6163. * unset b; a=; : ${a/z/${b=3}}; echo $b # b=3
  6164. * unset b; unset a; : ${a/z/${b=3}}; echo $b # b not set
  6165. */
  6166. if (val /*&& val[0]*/) {
  6167. /* pattern uses non-standard expansion.
  6168. * repl should be unbackslashed and globbed
  6169. * by the usual expansion rules:
  6170. * >az >bz
  6171. * v='a bz'; echo "${v/a*z/a*z}" #prints "a*z"
  6172. * v='a bz'; echo "${v/a*z/\z}" #prints "z"
  6173. * v='a bz'; echo ${v/a*z/a*z} #prints "az"
  6174. * v='a bz'; echo ${v/a*z/\z} #prints "z"
  6175. * (note that a*z _pattern_ is never globbed!)
  6176. */
  6177. char *pattern, *repl, *t;
  6178. pattern = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 0);
  6179. if (!pattern)
  6180. pattern = xstrdup(exp_word);
  6181. debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
  6182. *p++ = SPECIAL_VAR_SYMBOL;
  6183. exp_word = p;
  6184. p = strchr(p, SPECIAL_VAR_SYMBOL);
  6185. *p = '\0';
  6186. repl = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 1);
  6187. debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
  6188. /* HACK ALERT. We depend here on the fact that
  6189. * G.global_argv and results of utoa and get_local_var_value
  6190. * are actually in writable memory:
  6191. * replace_pattern momentarily stores NULs there. */
  6192. t = (char*)val;
  6193. to_be_freed = replace_pattern(t,
  6194. pattern,
  6195. (repl ? repl : exp_word),
  6196. exp_op);
  6197. if (to_be_freed) /* at least one replace happened */
  6198. val = to_be_freed;
  6199. free(pattern);
  6200. free(repl);
  6201. } else {
  6202. /* Unset variable always gives nothing */
  6203. // a=; echo ${a/*/w} # "w"
  6204. // unset a; echo ${a/*/w} # ""
  6205. /* Just skip "replace" part */
  6206. *p++ = SPECIAL_VAR_SYMBOL;
  6207. p = strchr(p, SPECIAL_VAR_SYMBOL);
  6208. *p = '\0';
  6209. }
  6210. }
  6211. #endif /* BASH_PATTERN_SUBST */
  6212. else if (exp_op == ':') {
  6213. #if BASH_SUBSTR && ENABLE_FEATURE_SH_MATH
  6214. /* It's ${var:N[:M]} bashism.
  6215. * Note that in encoded form it has TWO parts:
  6216. * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
  6217. */
  6218. arith_t beg, len;
  6219. unsigned vallen;
  6220. const char *errmsg;
  6221. beg = expand_and_evaluate_arith(exp_word, &errmsg);
  6222. if (errmsg)
  6223. goto empty_result;
  6224. debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
  6225. *p++ = SPECIAL_VAR_SYMBOL;
  6226. exp_word = p;
  6227. p = strchr(p, SPECIAL_VAR_SYMBOL);
  6228. *p = '\0';
  6229. vallen = val ? strlen(val) : 0;
  6230. if (beg < 0) {
  6231. /* negative beg counts from the end */
  6232. beg = (arith_t)vallen + beg;
  6233. }
  6234. /* If expansion will be empty, do not even evaluate len */
  6235. if (!val || beg < 0 || beg > vallen) {
  6236. /* Why > vallen, not >=? bash:
  6237. * unset b; a=ab; : ${a:2:${b=3}}; echo $b # "", b=3 (!!!)
  6238. * unset b; a=a; : ${a:2:${b=3}}; echo $b # "", b not set
  6239. */
  6240. goto empty_result;
  6241. }
  6242. len = expand_and_evaluate_arith(exp_word, &errmsg);
  6243. if (errmsg)
  6244. goto empty_result;
  6245. debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
  6246. debug_printf_varexp("from val:'%s'\n", val);
  6247. if (len < 0) {
  6248. /* in bash, len=-n means strlen()-n */
  6249. len = (arith_t)vallen - beg + len;
  6250. if (len < 0) /* bash compat */
  6251. msg_and_die_if_script("%s: substring expression < 0", var);
  6252. }
  6253. if (len <= 0 || !val /*|| beg >= vallen*/) {
  6254. empty_result:
  6255. val = NULL;
  6256. } else {
  6257. /* Paranoia. What if user entered 9999999999999
  6258. * which fits in arith_t but not int? */
  6259. if (len > INT_MAX)
  6260. len = INT_MAX;
  6261. val = to_be_freed = xstrndup(val + beg, len);
  6262. }
  6263. debug_printf_varexp("val:'%s'\n", val);
  6264. #else /* not (HUSH_SUBSTR_EXPANSION && FEATURE_SH_MATH) */
  6265. msg_and_die_if_script("malformed ${%s:...}", var);
  6266. val = NULL;
  6267. #endif
  6268. } else { /* one of "-=+?" */
  6269. /* Standard-mandated substitution ops:
  6270. * ${var?word} - indicate error if unset
  6271. * If var is unset, word (or a message indicating it is unset
  6272. * if word is null) is written to standard error
  6273. * and the shell exits with a non-zero exit status.
  6274. * Otherwise, the value of var is substituted.
  6275. * ${var-word} - use default value
  6276. * If var is unset, word is substituted.
  6277. * ${var=word} - assign and use default value
  6278. * If var is unset, word is assigned to var.
  6279. * In all cases, final value of var is substituted.
  6280. * ${var+word} - use alternative value
  6281. * If var is unset, null is substituted.
  6282. * Otherwise, word is substituted.
  6283. *
  6284. * Word is subjected to tilde expansion, parameter expansion,
  6285. * command substitution, and arithmetic expansion.
  6286. * If word is not needed, it is not expanded.
  6287. *
  6288. * Colon forms (${var:-word}, ${var:=word} etc) do the same,
  6289. * but also treat null var as if it is unset.
  6290. *
  6291. * Word-splitting and single quote behavior:
  6292. *
  6293. * $ f() { for i; do echo "|$i|"; done; }
  6294. *
  6295. * $ x=; f ${x:?'x y' z}; echo $?
  6296. * bash: x: x y z # neither f nor "echo $?" executes
  6297. * (if interactive, bash does not exit, but merely aborts to prompt. $? is set to 1)
  6298. * $ x=; f "${x:?'x y' z}"
  6299. * bash: x: x y z # dash prints: dash: x: 'x y' z
  6300. *
  6301. * $ x=; f ${x:='x y' z}
  6302. * |x|
  6303. * |y|
  6304. * |z|
  6305. * $ x=; f "${x:='x y' z}"
  6306. * |'x y' z|
  6307. *
  6308. * $ x=x; f ${x:+'x y' z}
  6309. * |x y|
  6310. * |z|
  6311. * $ x=x; f "${x:+'x y' z}"
  6312. * |'x y' z|
  6313. *
  6314. * $ x=; f ${x:-'x y' z}
  6315. * |x y|
  6316. * |z|
  6317. * $ x=; f "${x:-'x y' z}"
  6318. * |'x y' z|
  6319. */
  6320. int use_word = (!val || ((exp_save == ':') && !val[0]));
  6321. if (exp_op == '+')
  6322. use_word = !use_word;
  6323. debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
  6324. (exp_save == ':') ? "true" : "false", use_word);
  6325. if (use_word) {
  6326. if (exp_op == '+' || exp_op == '-') {
  6327. /* ${var+word} - use alternative value */
  6328. /* ${var-word} - use default value */
  6329. n = encode_then_append_var_plusminus(output, n, exp_word,
  6330. /*dquoted:*/ (arg0 & 0x80)
  6331. );
  6332. val = NULL;
  6333. } else {
  6334. /* ${var?word} - indicate error if unset */
  6335. /* ${var=word} - assign and use default value */
  6336. to_be_freed = encode_then_expand_vararg(exp_word,
  6337. /*handle_squotes:*/ !(arg0 & 0x80),
  6338. /*unbackslash:*/ 0
  6339. );
  6340. if (to_be_freed)
  6341. exp_word = to_be_freed;
  6342. if (exp_op == '?') {
  6343. /* mimic bash message */
  6344. msg_and_die_if_script("%s: %s",
  6345. var,
  6346. exp_word[0]
  6347. ? exp_word
  6348. : "parameter null or not set"
  6349. /* ash has more specific messages, a-la: */
  6350. /*: (exp_save == ':' ? "parameter null or not set" : "parameter not set")*/
  6351. );
  6352. //TODO: how interactive bash aborts expansion mid-command?
  6353. //It aborts the entire line, returns to prompt:
  6354. // $ f() { for i; do echo "|$i|"; done; }; x=; f "${x:?'x y' z}"; echo YO
  6355. // bash: x: x y z
  6356. // $
  6357. // ("echo YO" is not executed, neither the f function call)
  6358. } else {
  6359. val = exp_word;
  6360. }
  6361. if (exp_op == '=') {
  6362. /* ${var=[word]} or ${var:=[word]} */
  6363. if (isdigit(var[0]) || var[0] == '#') {
  6364. /* mimic bash message */
  6365. msg_and_die_if_script("$%s: cannot assign in this way", var);
  6366. val = NULL;
  6367. } else {
  6368. char *new_var = xasprintf("%s=%s", var, val);
  6369. set_local_var(new_var, /*flag:*/ 0);
  6370. }
  6371. }
  6372. }
  6373. }
  6374. } /* one of "-=+?" */
  6375. *exp_saveptr = exp_save;
  6376. } /* if (exp_op) */
  6377. arg[0] = arg0;
  6378. *pp = p;
  6379. n = append_str_maybe_ifs_split(output, n, first_ch, val);
  6380. free(to_be_freed);
  6381. return n;
  6382. }
  6383. /* Expand all variable references in given string, adding words to list[]
  6384. * at n, n+1,... positions. Return updated n (so that list[n] is next one
  6385. * to be filled). This routine is extremely tricky: has to deal with
  6386. * variables/parameters with whitespace, $* and $@, and constructs like
  6387. * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
  6388. static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
  6389. {
  6390. /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
  6391. * expansion of right-hand side of assignment == 1-element expand.
  6392. */
  6393. char cant_be_null = 0; /* only bit 0x80 matters */
  6394. char *p;
  6395. debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
  6396. !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
  6397. debug_print_list("expand_vars_to_list[0]", output, n);
  6398. while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
  6399. char first_ch;
  6400. #if ENABLE_FEATURE_SH_MATH
  6401. char arith_buf[sizeof(arith_t)*3 + 2];
  6402. #endif
  6403. if (output->ended_in_ifs) {
  6404. o_addchr(output, '\0');
  6405. n = o_save_ptr(output, n);
  6406. output->ended_in_ifs = 0;
  6407. }
  6408. o_addblock(output, arg, p - arg);
  6409. debug_print_list("expand_vars_to_list[1]", output, n);
  6410. arg = ++p;
  6411. p = strchr(p, SPECIAL_VAR_SYMBOL);
  6412. /* Fetch special var name (if it is indeed one of them)
  6413. * and quote bit, force the bit on if singleword expansion -
  6414. * important for not getting v=$@ expand to many words. */
  6415. first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
  6416. /* Is this variable quoted and thus expansion can't be null?
  6417. * "$@" is special. Even if quoted, it can still
  6418. * expand to nothing (not even an empty string),
  6419. * thus it is excluded. */
  6420. if ((first_ch & 0x7f) != '@')
  6421. cant_be_null |= first_ch;
  6422. switch (first_ch & 0x7f) {
  6423. /* Highest bit in first_ch indicates that var is double-quoted */
  6424. case '*':
  6425. case '@': {
  6426. int i;
  6427. if (!G.global_argv[1])
  6428. break;
  6429. i = 1;
  6430. cant_be_null |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
  6431. if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
  6432. while (G.global_argv[i]) {
  6433. n = expand_on_ifs(output, n, G.global_argv[i]);
  6434. debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
  6435. if (G.global_argv[i++][0] && G.global_argv[i]) {
  6436. /* this argv[] is not empty and not last:
  6437. * put terminating NUL, start new word */
  6438. o_addchr(output, '\0');
  6439. debug_print_list("expand_vars_to_list[2]", output, n);
  6440. n = o_save_ptr(output, n);
  6441. debug_print_list("expand_vars_to_list[3]", output, n);
  6442. }
  6443. }
  6444. } else
  6445. /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
  6446. * and in this case should treat it like '$*' - see 'else...' below */
  6447. if (first_ch == (char)('@'|0x80) /* quoted $@ */
  6448. && !(output->o_expflags & EXP_FLAG_SINGLEWORD) /* not v="$@" case */
  6449. ) {
  6450. while (1) {
  6451. o_addQstr(output, G.global_argv[i]);
  6452. if (++i >= G.global_argc)
  6453. break;
  6454. o_addchr(output, '\0');
  6455. debug_print_list("expand_vars_to_list[4]", output, n);
  6456. n = o_save_ptr(output, n);
  6457. }
  6458. } else { /* quoted $* (or v="$@" case): add as one word */
  6459. while (1) {
  6460. o_addQstr(output, G.global_argv[i]);
  6461. if (!G.global_argv[++i])
  6462. break;
  6463. if (G.ifs[0])
  6464. o_addchr(output, G.ifs[0]);
  6465. }
  6466. output->has_quoted_part = 1;
  6467. }
  6468. break;
  6469. }
  6470. case SPECIAL_VAR_SYMBOL: {
  6471. /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
  6472. /* "Empty variable", used to make "" etc to not disappear */
  6473. output->has_quoted_part = 1;
  6474. cant_be_null = 0x80;
  6475. arg++;
  6476. break;
  6477. }
  6478. case SPECIAL_VAR_QUOTED_SVS:
  6479. /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_QUOTED_SVS><SPECIAL_VAR_SYMBOL> */
  6480. /* "^C variable", represents literal ^C char (possible in scripts) */
  6481. o_addchr(output, SPECIAL_VAR_SYMBOL);
  6482. arg++;
  6483. break;
  6484. #if ENABLE_HUSH_TICK
  6485. case '`': {
  6486. /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
  6487. o_string subst_result = NULL_O_STRING;
  6488. *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
  6489. arg++;
  6490. /* Can't just stuff it into output o_string,
  6491. * expanded result may need to be globbed
  6492. * and $IFS-split */
  6493. debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
  6494. G.last_exitcode = process_command_subs(&subst_result, arg);
  6495. G.expand_exitcode = G.last_exitcode;
  6496. debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
  6497. n = append_str_maybe_ifs_split(output, n, first_ch, subst_result.data);
  6498. o_free(&subst_result);
  6499. break;
  6500. }
  6501. #endif
  6502. #if ENABLE_FEATURE_SH_MATH
  6503. case '+': {
  6504. /* <SPECIAL_VAR_SYMBOL>+arith<SPECIAL_VAR_SYMBOL> */
  6505. arith_t res;
  6506. arg++; /* skip '+' */
  6507. *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
  6508. debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
  6509. res = expand_and_evaluate_arith(arg, NULL);
  6510. debug_printf_subst("ARITH RES '"ARITH_FMT"'\n", res);
  6511. sprintf(arith_buf, ARITH_FMT, res);
  6512. if (res < 0
  6513. && first_ch == (char)('+'|0x80)
  6514. /* && (output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS) */
  6515. ) {
  6516. /* Quoted negative ariths, like filename[0"$((-9))"],
  6517. * should not be interpreted as glob ranges.
  6518. * Convert leading '-' to '\-':
  6519. */
  6520. o_grow_by(output, 1);
  6521. output->data[output->length++] = '\\';
  6522. }
  6523. o_addstr(output, arith_buf);
  6524. break;
  6525. }
  6526. #endif
  6527. default:
  6528. /* <SPECIAL_VAR_SYMBOL>varname[ops]<SPECIAL_VAR_SYMBOL> */
  6529. n = expand_one_var(output, n, first_ch, arg, &p);
  6530. break;
  6531. } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
  6532. /* Restore NULL'ed SPECIAL_VAR_SYMBOL.
  6533. * Do the check to avoid writing to a const string. */
  6534. if (*p != SPECIAL_VAR_SYMBOL)
  6535. *p = SPECIAL_VAR_SYMBOL;
  6536. arg = ++p;
  6537. } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
  6538. if (*arg) {
  6539. /* handle trailing string */
  6540. if (output->ended_in_ifs) {
  6541. o_addchr(output, '\0');
  6542. n = o_save_ptr(output, n);
  6543. }
  6544. debug_print_list("expand_vars_to_list[a]", output, n);
  6545. /* this part is literal, and it was already pre-quoted
  6546. * if needed (much earlier), do not use o_addQstr here!
  6547. */
  6548. o_addstr(output, arg);
  6549. debug_print_list("expand_vars_to_list[b]", output, n);
  6550. } else
  6551. if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
  6552. && !(cant_be_null & 0x80) /* and all vars were not quoted */
  6553. && !output->has_quoted_part
  6554. ) {
  6555. n--;
  6556. /* allow to reuse list[n] later without re-growth */
  6557. output->has_empty_slot = 1;
  6558. }
  6559. return n;
  6560. }
  6561. static char **expand_variables(char **argv, unsigned expflags)
  6562. {
  6563. int n;
  6564. char **list;
  6565. o_string output = NULL_O_STRING;
  6566. output.o_expflags = expflags;
  6567. n = 0;
  6568. for (;;) {
  6569. /* go to next list[n] */
  6570. output.ended_in_ifs = 0;
  6571. n = o_save_ptr(&output, n);
  6572. if (!*argv)
  6573. break;
  6574. /* expand argv[i] */
  6575. n = expand_vars_to_list(&output, n, *argv++);
  6576. /* if (!output->has_empty_slot) -- need this?? */
  6577. o_addchr(&output, '\0');
  6578. }
  6579. debug_print_list("expand_variables", &output, n);
  6580. /* output.data (malloced in one block) gets returned in "list" */
  6581. list = o_finalize_list(&output, n);
  6582. debug_print_strings("expand_variables[1]", list);
  6583. return list;
  6584. }
  6585. static char **expand_strvec_to_strvec(char **argv)
  6586. {
  6587. return expand_variables(argv, EXP_FLAG_GLOB | EXP_FLAG_ESC_GLOB_CHARS);
  6588. }
  6589. #if defined(CMD_SINGLEWORD_NOGLOB) || defined(CMD_TEST2_SINGLEWORD_NOGLOB)
  6590. static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
  6591. {
  6592. return expand_variables(argv, EXP_FLAG_SINGLEWORD);
  6593. }
  6594. #endif
  6595. /* Used for expansion of right hand of assignments,
  6596. * $((...)), heredocs, variable expansion parts.
  6597. *
  6598. * NB: should NOT do globbing!
  6599. * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*"
  6600. */
  6601. static char *expand_string_to_string(const char *str, int EXP_flags, int do_unbackslash)
  6602. {
  6603. #if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
  6604. const int do_unbackslash = 1;
  6605. const int EXP_flags = EXP_FLAG_ESC_GLOB_CHARS;
  6606. #endif
  6607. char *argv[2], **list;
  6608. debug_printf_expand("string_to_string<='%s'\n", str);
  6609. /* This is generally an optimization, but it also
  6610. * handles "", which otherwise trips over !list[0] check below.
  6611. * (is this ever happens that we actually get str="" here?)
  6612. */
  6613. if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
  6614. //TODO: Can use on strings with \ too, just unbackslash() them?
  6615. debug_printf_expand("string_to_string(fast)=>'%s'\n", str);
  6616. return xstrdup(str);
  6617. }
  6618. argv[0] = (char*)str;
  6619. argv[1] = NULL;
  6620. list = expand_variables(argv, EXP_flags | EXP_FLAG_SINGLEWORD);
  6621. if (!list[0]) {
  6622. /* Example where it happens:
  6623. * x=; echo ${x:-"$@"}
  6624. */
  6625. ((char*)list)[0] = '\0';
  6626. } else {
  6627. if (HUSH_DEBUG)
  6628. if (list[1])
  6629. bb_simple_error_msg_and_die("BUG in varexp2");
  6630. /* actually, just move string 2*sizeof(char*) bytes back */
  6631. overlapping_strcpy((char*)list, list[0]);
  6632. if (do_unbackslash)
  6633. unbackslash((char*)list);
  6634. }
  6635. debug_printf_expand("string_to_string=>'%s'\n", (char*)list);
  6636. return (char*)list;
  6637. }
  6638. #if 0
  6639. static char* expand_strvec_to_string(char **argv)
  6640. {
  6641. char **list;
  6642. list = expand_variables(argv, EXP_FLAG_SINGLEWORD);
  6643. /* Convert all NULs to spaces */
  6644. if (list[0]) {
  6645. int n = 1;
  6646. while (list[n]) {
  6647. if (HUSH_DEBUG)
  6648. if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
  6649. bb_error_msg_and_die("BUG in varexp3");
  6650. /* bash uses ' ' regardless of $IFS contents */
  6651. list[n][-1] = ' ';
  6652. n++;
  6653. }
  6654. }
  6655. overlapping_strcpy((char*)list, list[0] ? list[0] : "");
  6656. debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
  6657. return (char*)list;
  6658. }
  6659. #endif
  6660. static char **expand_assignments(char **argv, int count)
  6661. {
  6662. int i;
  6663. char **p;
  6664. G.expanded_assignments = p = NULL;
  6665. /* Expand assignments into one string each */
  6666. for (i = 0; i < count; i++) {
  6667. p = add_string_to_strings(p,
  6668. expand_string_to_string(argv[i],
  6669. EXP_FLAG_ESC_GLOB_CHARS,
  6670. /*unbackslash:*/ 1
  6671. )
  6672. );
  6673. G.expanded_assignments = p;
  6674. }
  6675. G.expanded_assignments = NULL;
  6676. return p;
  6677. }
  6678. static void switch_off_special_sigs(unsigned mask)
  6679. {
  6680. unsigned sig = 0;
  6681. while ((mask >>= 1) != 0) {
  6682. sig++;
  6683. if (!(mask & 1))
  6684. continue;
  6685. #if ENABLE_HUSH_TRAP
  6686. if (G_traps) {
  6687. if (G_traps[sig] && !G_traps[sig][0])
  6688. /* trap is '', has to remain SIG_IGN */
  6689. continue;
  6690. free(G_traps[sig]);
  6691. G_traps[sig] = NULL;
  6692. }
  6693. #endif
  6694. /* We are here only if no trap or trap was not '' */
  6695. install_sighandler(sig, SIG_DFL);
  6696. }
  6697. }
  6698. #if BB_MMU
  6699. /* never called */
  6700. void re_execute_shell(char ***to_free, const char *s,
  6701. char *g_argv0, char **g_argv,
  6702. char **builtin_argv) NORETURN;
  6703. static void reset_traps_to_defaults(void)
  6704. {
  6705. /* This function is always called in a child shell
  6706. * after fork (not vfork, NOMMU doesn't use this function).
  6707. */
  6708. IF_HUSH_TRAP(unsigned sig;)
  6709. unsigned mask;
  6710. /* Child shells are not interactive.
  6711. * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
  6712. * Testcase: (while :; do :; done) + ^Z should background.
  6713. * Same goes for SIGTERM, SIGHUP, SIGINT.
  6714. */
  6715. mask = (G.special_sig_mask & SPECIAL_INTERACTIVE_SIGS) | G_fatal_sig_mask;
  6716. if (!G_traps && !mask)
  6717. return; /* already no traps and no special sigs */
  6718. /* Switch off special sigs */
  6719. switch_off_special_sigs(mask);
  6720. # if ENABLE_HUSH_JOB
  6721. G_fatal_sig_mask = 0;
  6722. # endif
  6723. G.special_sig_mask &= ~SPECIAL_INTERACTIVE_SIGS;
  6724. /* SIGQUIT,SIGCHLD and maybe SPECIAL_JOBSTOP_SIGS
  6725. * remain set in G.special_sig_mask */
  6726. # if ENABLE_HUSH_TRAP
  6727. if (!G_traps)
  6728. return;
  6729. /* Reset all sigs to default except ones with empty traps */
  6730. for (sig = 0; sig < NSIG; sig++) {
  6731. if (!G_traps[sig])
  6732. continue; /* no trap: nothing to do */
  6733. if (!G_traps[sig][0])
  6734. continue; /* empty trap: has to remain SIG_IGN */
  6735. /* sig has non-empty trap, reset it: */
  6736. free(G_traps[sig]);
  6737. G_traps[sig] = NULL;
  6738. /* There is no signal for trap 0 (EXIT) */
  6739. if (sig == 0)
  6740. continue;
  6741. install_sighandler(sig, pick_sighandler(sig));
  6742. }
  6743. # endif
  6744. }
  6745. #else /* !BB_MMU */
  6746. static void re_execute_shell(char ***to_free, const char *s,
  6747. char *g_argv0, char **g_argv,
  6748. char **builtin_argv) NORETURN;
  6749. static void re_execute_shell(char ***to_free, const char *s,
  6750. char *g_argv0, char **g_argv,
  6751. char **builtin_argv)
  6752. {
  6753. # define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
  6754. /* delims + 2 * (number of bytes in printed hex numbers) */
  6755. char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
  6756. char *heredoc_argv[4];
  6757. struct variable *cur;
  6758. # if ENABLE_HUSH_FUNCTIONS
  6759. struct function *funcp;
  6760. # endif
  6761. char **argv, **pp;
  6762. unsigned cnt;
  6763. unsigned long long empty_trap_mask;
  6764. if (!g_argv0) { /* heredoc */
  6765. argv = heredoc_argv;
  6766. argv[0] = (char *) G.argv0_for_re_execing;
  6767. argv[1] = (char *) "-<";
  6768. argv[2] = (char *) s;
  6769. argv[3] = NULL;
  6770. pp = &argv[3]; /* used as pointer to empty environment */
  6771. goto do_exec;
  6772. }
  6773. cnt = 0;
  6774. pp = builtin_argv;
  6775. if (pp) while (*pp++)
  6776. cnt++;
  6777. empty_trap_mask = 0;
  6778. if (G_traps) {
  6779. int sig;
  6780. for (sig = 1; sig < NSIG; sig++) {
  6781. if (G_traps[sig] && !G_traps[sig][0])
  6782. empty_trap_mask |= 1LL << sig;
  6783. }
  6784. }
  6785. sprintf(param_buf, NOMMU_HACK_FMT
  6786. , (unsigned) G.root_pid
  6787. , (unsigned) G.root_ppid
  6788. , (unsigned) G.last_bg_pid
  6789. , (unsigned) G.last_exitcode
  6790. , cnt
  6791. , empty_trap_mask
  6792. IF_HUSH_LOOPS(, G.depth_of_loop)
  6793. );
  6794. # undef NOMMU_HACK_FMT
  6795. /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
  6796. * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
  6797. */
  6798. cnt += 6;
  6799. for (cur = G.top_var; cur; cur = cur->next) {
  6800. if (!cur->flg_export || cur->flg_read_only)
  6801. cnt += 2;
  6802. }
  6803. # if ENABLE_HUSH_FUNCTIONS
  6804. for (funcp = G.top_func; funcp; funcp = funcp->next)
  6805. cnt += 3;
  6806. # endif
  6807. pp = g_argv;
  6808. while (*pp++)
  6809. cnt++;
  6810. *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
  6811. *pp++ = (char *) G.argv0_for_re_execing;
  6812. *pp++ = param_buf;
  6813. for (cur = G.top_var; cur; cur = cur->next) {
  6814. if (strcmp(cur->varstr, hush_version_str) == 0)
  6815. continue;
  6816. if (cur->flg_read_only) {
  6817. *pp++ = (char *) "-R";
  6818. *pp++ = cur->varstr;
  6819. } else if (!cur->flg_export) {
  6820. *pp++ = (char *) "-V";
  6821. *pp++ = cur->varstr;
  6822. }
  6823. }
  6824. # if ENABLE_HUSH_FUNCTIONS
  6825. for (funcp = G.top_func; funcp; funcp = funcp->next) {
  6826. *pp++ = (char *) "-F";
  6827. *pp++ = funcp->name;
  6828. *pp++ = funcp->body_as_string;
  6829. }
  6830. # endif
  6831. /* We can pass activated traps here. Say, -Tnn:trap_string
  6832. *
  6833. * However, POSIX says that subshells reset signals with traps
  6834. * to SIG_DFL.
  6835. * I tested bash-3.2 and it not only does that with true subshells
  6836. * of the form ( list ), but with any forked children shells.
  6837. * I set trap "echo W" WINCH; and then tried:
  6838. *
  6839. * { echo 1; sleep 20; echo 2; } &
  6840. * while true; do echo 1; sleep 20; echo 2; break; done &
  6841. * true | { echo 1; sleep 20; echo 2; } | cat
  6842. *
  6843. * In all these cases sending SIGWINCH to the child shell
  6844. * did not run the trap. If I add trap "echo V" WINCH;
  6845. * _inside_ group (just before echo 1), it works.
  6846. *
  6847. * I conclude it means we don't need to pass active traps here.
  6848. */
  6849. *pp++ = (char *) "-c";
  6850. *pp++ = (char *) s;
  6851. if (builtin_argv) {
  6852. while (*++builtin_argv)
  6853. *pp++ = *builtin_argv;
  6854. *pp++ = (char *) "";
  6855. }
  6856. *pp++ = g_argv0;
  6857. while (*g_argv)
  6858. *pp++ = *g_argv++;
  6859. /* *pp = NULL; - is already there */
  6860. pp = environ;
  6861. do_exec:
  6862. debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
  6863. /* Don't propagate SIG_IGN to the child */
  6864. if (SPECIAL_JOBSTOP_SIGS != 0)
  6865. switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
  6866. execve(bb_busybox_exec_path, argv, pp);
  6867. /* Fallback. Useful for init=/bin/hush usage etc */
  6868. if (argv[0][0] == '/')
  6869. execve(argv[0], argv, pp);
  6870. xfunc_error_retval = 127;
  6871. bb_simple_error_msg_and_die("can't re-execute the shell");
  6872. }
  6873. #endif /* !BB_MMU */
  6874. static int run_and_free_list(struct pipe *pi);
  6875. /* Executing from string: eval, sh -c '...'
  6876. * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
  6877. * end_trigger controls how often we stop parsing
  6878. * NUL: parse all, execute, return
  6879. * ';': parse till ';' or newline, execute, repeat till EOF
  6880. */
  6881. static void parse_and_run_stream(struct in_str *inp, int end_trigger)
  6882. {
  6883. /* Why we need empty flag?
  6884. * An obscure corner case "false; ``; echo $?":
  6885. * empty command in `` should still set $? to 0.
  6886. * But we can't just set $? to 0 at the start,
  6887. * this breaks "false; echo `echo $?`" case.
  6888. */
  6889. bool empty = 1;
  6890. while (1) {
  6891. struct pipe *pipe_list;
  6892. #if ENABLE_HUSH_INTERACTIVE
  6893. if (end_trigger == ';') {
  6894. G.promptmode = 0; /* PS1 */
  6895. debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
  6896. }
  6897. #endif
  6898. pipe_list = parse_stream(NULL, NULL, inp, end_trigger);
  6899. if (!pipe_list || pipe_list == ERR_PTR) { /* EOF/error */
  6900. /* If we are in "big" script
  6901. * (not in `cmd` or something similar)...
  6902. */
  6903. if (pipe_list == ERR_PTR && end_trigger == ';') {
  6904. /* Discard cached input (rest of line) */
  6905. int ch = inp->last_char;
  6906. while (ch != EOF && ch != '\n') {
  6907. //bb_error_msg("Discarded:'%c'", ch);
  6908. ch = i_getch(inp);
  6909. }
  6910. /* Force prompt */
  6911. inp->p = NULL;
  6912. /* This stream isn't empty */
  6913. empty = 0;
  6914. continue;
  6915. }
  6916. if (!pipe_list && empty)
  6917. G.last_exitcode = 0;
  6918. break;
  6919. }
  6920. debug_print_tree(pipe_list, 0);
  6921. debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
  6922. run_and_free_list(pipe_list);
  6923. empty = 0;
  6924. if (G_flag_return_in_progress == 1)
  6925. break;
  6926. }
  6927. }
  6928. static void parse_and_run_string(const char *s)
  6929. {
  6930. struct in_str input;
  6931. //IF_HUSH_LINENO_VAR(unsigned sv = G.parse_lineno;)
  6932. setup_string_in_str(&input, s);
  6933. parse_and_run_stream(&input, '\0');
  6934. //IF_HUSH_LINENO_VAR(G.parse_lineno = sv;)
  6935. }
  6936. static void parse_and_run_file(HFILE *fp)
  6937. {
  6938. struct in_str input;
  6939. IF_HUSH_LINENO_VAR(unsigned sv = G.parse_lineno;)
  6940. IF_HUSH_LINENO_VAR(G.parse_lineno = 1;)
  6941. setup_file_in_str(&input, fp);
  6942. parse_and_run_stream(&input, ';');
  6943. IF_HUSH_LINENO_VAR(G.parse_lineno = sv;)
  6944. }
  6945. #if ENABLE_HUSH_TICK
  6946. static int generate_stream_from_string(const char *s, pid_t *pid_p)
  6947. {
  6948. pid_t pid;
  6949. int channel[2];
  6950. # if !BB_MMU
  6951. char **to_free = NULL;
  6952. # endif
  6953. xpipe(channel);
  6954. pid = BB_MMU ? xfork() : xvfork();
  6955. if (pid == 0) { /* child */
  6956. disable_restore_tty_pgrp_on_exit();
  6957. /* Process substitution is not considered to be usual
  6958. * 'command execution'.
  6959. * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
  6960. */
  6961. bb_signals(0
  6962. + (1 << SIGTSTP)
  6963. + (1 << SIGTTIN)
  6964. + (1 << SIGTTOU)
  6965. , SIG_IGN);
  6966. close(channel[0]); /* NB: close _first_, then move fd! */
  6967. xmove_fd(channel[1], 1);
  6968. # if ENABLE_HUSH_TRAP
  6969. /* Awful hack for `trap` or $(trap).
  6970. *
  6971. * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
  6972. * contains an example where "trap" is executed in a subshell:
  6973. *
  6974. * save_traps=$(trap)
  6975. * ...
  6976. * eval "$save_traps"
  6977. *
  6978. * Standard does not say that "trap" in subshell shall print
  6979. * parent shell's traps. It only says that its output
  6980. * must have suitable form, but then, in the above example
  6981. * (which is not supposed to be normative), it implies that.
  6982. *
  6983. * bash (and probably other shell) does implement it
  6984. * (traps are reset to defaults, but "trap" still shows them),
  6985. * but as a result, "trap" logic is hopelessly messed up:
  6986. *
  6987. * # trap
  6988. * trap -- 'echo Ho' SIGWINCH <--- we have a handler
  6989. * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
  6990. * # true | trap <--- trap is in subshell - no output (ditto)
  6991. * # echo `true | trap` <--- in subshell - output (but traps are reset!)
  6992. * trap -- 'echo Ho' SIGWINCH
  6993. * # echo `(trap)` <--- in subshell in subshell - output
  6994. * trap -- 'echo Ho' SIGWINCH
  6995. * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
  6996. * trap -- 'echo Ho' SIGWINCH
  6997. *
  6998. * The rules when to forget and when to not forget traps
  6999. * get really complex and nonsensical.
  7000. *
  7001. * Our solution: ONLY bare $(trap) or `trap` is special.
  7002. */
  7003. s = skip_whitespace(s);
  7004. if (is_prefixed_with(s, "trap")
  7005. && skip_whitespace(s + 4)[0] == '\0'
  7006. ) {
  7007. static const char *const argv[] = { NULL, NULL };
  7008. builtin_trap((char**)argv);
  7009. fflush_all(); /* important */
  7010. _exit(0);
  7011. }
  7012. # endif
  7013. # if BB_MMU
  7014. /* Prevent it from trying to handle ctrl-z etc */
  7015. IF_HUSH_JOB(G.run_list_level = 1;)
  7016. CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
  7017. reset_traps_to_defaults();
  7018. IF_HUSH_MODE_X(G.x_mode_depth++;)
  7019. //bb_error_msg("%s: ++x_mode_depth=%d", __func__, G.x_mode_depth);
  7020. parse_and_run_string(s);
  7021. _exit(G.last_exitcode);
  7022. # else
  7023. /* We re-execute after vfork on NOMMU. This makes this script safe:
  7024. * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
  7025. * huge=`cat BIG` # was blocking here forever
  7026. * echo OK
  7027. */
  7028. re_execute_shell(&to_free,
  7029. s,
  7030. G.global_argv[0],
  7031. G.global_argv + 1,
  7032. NULL);
  7033. # endif
  7034. }
  7035. /* parent */
  7036. *pid_p = pid;
  7037. # if ENABLE_HUSH_FAST
  7038. G.count_SIGCHLD++;
  7039. //bb_error_msg("[%d] fork in generate_stream_from_string:"
  7040. // " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
  7041. // getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
  7042. # endif
  7043. enable_restore_tty_pgrp_on_exit();
  7044. # if !BB_MMU
  7045. free(to_free);
  7046. # endif
  7047. close(channel[1]);
  7048. return channel[0];
  7049. }
  7050. /* Return code is exit status of the process that is run. */
  7051. static int process_command_subs(o_string *dest, const char *s)
  7052. {
  7053. FILE *fp;
  7054. pid_t pid;
  7055. int status, ch, eol_cnt;
  7056. fp = xfdopen_for_read(generate_stream_from_string(s, &pid));
  7057. /* Now send results of command back into original context */
  7058. eol_cnt = 0;
  7059. while ((ch = getc(fp)) != EOF) {
  7060. if (ch == '\0')
  7061. continue;
  7062. if (ch == '\n') {
  7063. eol_cnt++;
  7064. continue;
  7065. }
  7066. while (eol_cnt) {
  7067. o_addchr(dest, '\n');
  7068. eol_cnt--;
  7069. }
  7070. o_addQchr(dest, ch);
  7071. }
  7072. debug_printf("done reading from `cmd` pipe, closing it\n");
  7073. fclose(fp);
  7074. /* We need to extract exitcode. Test case
  7075. * "true; echo `sleep 1; false` $?"
  7076. * should print 1 */
  7077. safe_waitpid(pid, &status, 0);
  7078. debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
  7079. return WEXITSTATUS(status);
  7080. }
  7081. #endif /* ENABLE_HUSH_TICK */
  7082. static void setup_heredoc(struct redir_struct *redir)
  7083. {
  7084. struct fd_pair pair;
  7085. pid_t pid;
  7086. int len, written;
  7087. /* the _body_ of heredoc (misleading field name) */
  7088. const char *heredoc = redir->rd_filename;
  7089. char *expanded;
  7090. #if !BB_MMU
  7091. char **to_free;
  7092. #endif
  7093. expanded = NULL;
  7094. if (!(redir->rd_dup & HEREDOC_QUOTED)) {
  7095. expanded = encode_then_expand_string(heredoc);
  7096. if (expanded)
  7097. heredoc = expanded;
  7098. }
  7099. len = strlen(heredoc);
  7100. close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
  7101. xpiped_pair(pair);
  7102. xmove_fd(pair.rd, redir->rd_fd);
  7103. /* Try writing without forking. Newer kernels have
  7104. * dynamically growing pipes. Must use non-blocking write! */
  7105. ndelay_on(pair.wr);
  7106. while (1) {
  7107. written = write(pair.wr, heredoc, len);
  7108. if (written <= 0)
  7109. break;
  7110. len -= written;
  7111. if (len == 0) {
  7112. close(pair.wr);
  7113. free(expanded);
  7114. return;
  7115. }
  7116. heredoc += written;
  7117. }
  7118. ndelay_off(pair.wr);
  7119. /* Okay, pipe buffer was not big enough */
  7120. /* Note: we must not create a stray child (bastard? :)
  7121. * for the unsuspecting parent process. Child creates a grandchild
  7122. * and exits before parent execs the process which consumes heredoc
  7123. * (that exec happens after we return from this function) */
  7124. #if !BB_MMU
  7125. to_free = NULL;
  7126. #endif
  7127. pid = xvfork();
  7128. if (pid == 0) {
  7129. /* child */
  7130. disable_restore_tty_pgrp_on_exit();
  7131. pid = BB_MMU ? xfork() : xvfork();
  7132. if (pid != 0)
  7133. _exit(0);
  7134. /* grandchild */
  7135. close(redir->rd_fd); /* read side of the pipe */
  7136. #if BB_MMU
  7137. full_write(pair.wr, heredoc, len); /* may loop or block */
  7138. _exit(0);
  7139. #else
  7140. /* Delegate blocking writes to another process */
  7141. xmove_fd(pair.wr, STDOUT_FILENO);
  7142. re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
  7143. #endif
  7144. }
  7145. /* parent */
  7146. #if ENABLE_HUSH_FAST
  7147. G.count_SIGCHLD++;
  7148. //bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
  7149. #endif
  7150. enable_restore_tty_pgrp_on_exit();
  7151. #if !BB_MMU
  7152. free(to_free);
  7153. #endif
  7154. close(pair.wr);
  7155. free(expanded);
  7156. wait(NULL); /* wait till child has died */
  7157. }
  7158. struct squirrel {
  7159. int orig_fd;
  7160. int moved_to;
  7161. /* moved_to = n: fd was moved to n; restore back to orig_fd after redir */
  7162. /* moved_to = -1: fd was opened by redirect; close orig_fd after redir */
  7163. };
  7164. static struct squirrel *append_squirrel(struct squirrel *sq, int i, int orig, int moved)
  7165. {
  7166. sq = xrealloc(sq, (i + 2) * sizeof(sq[0]));
  7167. sq[i].orig_fd = orig;
  7168. sq[i].moved_to = moved;
  7169. sq[i+1].orig_fd = -1; /* end marker */
  7170. return sq;
  7171. }
  7172. static struct squirrel *add_squirrel(struct squirrel *sq, int fd, int avoid_fd)
  7173. {
  7174. int moved_to;
  7175. int i;
  7176. i = 0;
  7177. if (sq) for (; sq[i].orig_fd >= 0; i++) {
  7178. /* If we collide with an already moved fd... */
  7179. if (fd == sq[i].moved_to) {
  7180. sq[i].moved_to = dup_CLOEXEC(sq[i].moved_to, avoid_fd);
  7181. debug_printf_redir("redirect_fd %d: already busy, moving to %d\n", fd, sq[i].moved_to);
  7182. if (sq[i].moved_to < 0) /* what? */
  7183. xfunc_die();
  7184. return sq;
  7185. }
  7186. if (fd == sq[i].orig_fd) {
  7187. /* Example: echo Hello >/dev/null 1>&2 */
  7188. debug_printf_redir("redirect_fd %d: already moved\n", fd);
  7189. return sq;
  7190. }
  7191. }
  7192. /* If this fd is open, we move and remember it; if it's closed, moved_to = -1 */
  7193. moved_to = dup_CLOEXEC(fd, avoid_fd);
  7194. debug_printf_redir("redirect_fd %d: previous fd is moved to %d (-1 if it was closed)\n", fd, moved_to);
  7195. if (moved_to < 0 && errno != EBADF)
  7196. xfunc_die();
  7197. return append_squirrel(sq, i, fd, moved_to);
  7198. }
  7199. static struct squirrel *add_squirrel_closed(struct squirrel *sq, int fd)
  7200. {
  7201. int i;
  7202. i = 0;
  7203. if (sq) for (; sq[i].orig_fd >= 0; i++) {
  7204. /* If we collide with an already moved fd... */
  7205. if (fd == sq[i].orig_fd) {
  7206. /* Examples:
  7207. * "echo 3>FILE 3>&- 3>FILE"
  7208. * "echo 3>&- 3>FILE"
  7209. * No need for last redirect to insert
  7210. * another "need to close 3" indicator.
  7211. */
  7212. debug_printf_redir("redirect_fd %d: already moved or closed\n", fd);
  7213. return sq;
  7214. }
  7215. }
  7216. debug_printf_redir("redirect_fd %d: previous fd was closed\n", fd);
  7217. return append_squirrel(sq, i, fd, -1);
  7218. }
  7219. /* fd: redirect wants this fd to be used (e.g. 3>file).
  7220. * Move all conflicting internally used fds,
  7221. * and remember them so that we can restore them later.
  7222. */
  7223. static int save_fd_on_redirect(int fd, int avoid_fd, struct squirrel **sqp)
  7224. {
  7225. if (avoid_fd < 9) /* the important case here is that it can be -1 */
  7226. avoid_fd = 9;
  7227. #if ENABLE_HUSH_INTERACTIVE
  7228. if (fd != 0 /* don't trigger for G_interactive_fd == 0 (that's "not interactive" flag) */
  7229. && fd == G_interactive_fd
  7230. ) {
  7231. /* Testcase: "ls -l /proc/$$/fd 255>&-" should work */
  7232. G_interactive_fd = xdup_CLOEXEC_and_close(G_interactive_fd, avoid_fd);
  7233. debug_printf_redir("redirect_fd %d: matches interactive_fd, moving it to %d\n", fd, G_interactive_fd);
  7234. return 1; /* "we closed fd" */
  7235. }
  7236. #endif
  7237. /* Are we called from setup_redirects(squirrel==NULL)
  7238. * in redirect in a [v]forked child?
  7239. */
  7240. if (sqp == NULL) {
  7241. /* No need to move script fds.
  7242. * For NOMMU case, it's actively wrong: we'd change ->fd
  7243. * fields in memory for the parent, but parent's fds
  7244. * aren't moved, it would use wrong fd!
  7245. * Reproducer: "cmd 3>FILE" in script.
  7246. * If we would call move_HFILEs_on_redirect(), child would:
  7247. * fcntl64(3, F_DUPFD_CLOEXEC, 10) = 10
  7248. * close(3) = 0
  7249. * and change ->fd to 10 if fd#3 is a script fd. WRONG.
  7250. */
  7251. //bb_error_msg("sqp == NULL: [v]forked child");
  7252. return 0;
  7253. }
  7254. /* If this one of script's fds? */
  7255. if (move_HFILEs_on_redirect(fd, avoid_fd))
  7256. return 1; /* yes. "we closed fd" (actually moved it) */
  7257. /* Are we called for "exec 3>FILE"? Came through
  7258. * redirect_and_varexp_helper(squirrel=ERR_PTR) -> setup_redirects(ERR_PTR)
  7259. * This case used to fail for this script:
  7260. * exec 3>FILE
  7261. * echo Ok
  7262. * ...100000 more lines...
  7263. * echo Ok
  7264. * as follows:
  7265. * read(3, "exec 3>FILE\necho Ok\necho Ok"..., 1024) = 1024
  7266. * open("FILE", O_WRONLY|O_CREAT|O_TRUNC|O_LARGEFILE, 0666) = 4
  7267. * dup2(4, 3) = 3
  7268. * ^^^^^^^^ oops, we lost fd#3 opened to our script!
  7269. * close(4) = 0
  7270. * write(1, "Ok\n", 3) = 3
  7271. * ... = 3
  7272. * write(1, "Ok\n", 3) = 3
  7273. * read(3, 0x94fbc08, 1024) = -1 EBADF (Bad file descriptor)
  7274. * ^^^^^^^^ oops, wrong fd!!!
  7275. * With this case separate from sqp == NULL and *after* move_HFILEs,
  7276. * it now works:
  7277. */
  7278. if (sqp == ERR_PTR) {
  7279. /* Don't preserve redirected fds: exec is _meant_ to change these */
  7280. //bb_error_msg("sqp == ERR_PTR: exec >FILE");
  7281. return 0;
  7282. }
  7283. /* Check whether it collides with any open fds (e.g. stdio), save fds as needed */
  7284. *sqp = add_squirrel(*sqp, fd, avoid_fd);
  7285. return 0; /* "we did not close fd" */
  7286. }
  7287. static void restore_redirects(struct squirrel *sq)
  7288. {
  7289. if (sq) {
  7290. int i;
  7291. for (i = 0; sq[i].orig_fd >= 0; i++) {
  7292. if (sq[i].moved_to >= 0) {
  7293. /* We simply die on error */
  7294. debug_printf_redir("restoring redirected fd from %d to %d\n", sq[i].moved_to, sq[i].orig_fd);
  7295. xmove_fd(sq[i].moved_to, sq[i].orig_fd);
  7296. } else {
  7297. /* cmd1 9>FILE; cmd2_should_see_fd9_closed */
  7298. debug_printf_redir("restoring redirected fd %d: closing it\n", sq[i].orig_fd);
  7299. close(sq[i].orig_fd);
  7300. }
  7301. }
  7302. free(sq);
  7303. }
  7304. if (G.HFILE_stdin
  7305. && G.HFILE_stdin->fd > STDIN_FILENO
  7306. /* we compare > STDIN, not == STDIN, since hfgetc()
  7307. * closes fd and sets ->fd to -1 if EOF is reached.
  7308. * Testcase: echo 'pwd' | hush
  7309. */
  7310. ) {
  7311. /* Testcase: interactive "read r <FILE; echo $r; read r; echo $r".
  7312. * Redirect moves ->fd to e.g. 10,
  7313. * and it is not restored above (we do not restore script fds
  7314. * after redirects, we just use new, "moved" fds).
  7315. * However for stdin, get_user_input() -> read_line_input(),
  7316. * and read builtin, depend on fd == STDIN_FILENO.
  7317. */
  7318. debug_printf_redir("restoring %d to stdin\n", G.HFILE_stdin->fd);
  7319. xmove_fd(G.HFILE_stdin->fd, STDIN_FILENO);
  7320. G.HFILE_stdin->fd = STDIN_FILENO;
  7321. }
  7322. /* If moved, G_interactive_fd stays on new fd, not restoring it */
  7323. }
  7324. #if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
  7325. static void close_saved_fds_and_FILE_fds(void)
  7326. {
  7327. if (G_interactive_fd)
  7328. close(G_interactive_fd);
  7329. close_all_HFILE_list();
  7330. }
  7331. #endif
  7332. static int internally_opened_fd(int fd, struct squirrel *sq)
  7333. {
  7334. int i;
  7335. #if ENABLE_HUSH_INTERACTIVE
  7336. if (fd == G_interactive_fd)
  7337. return 1;
  7338. #endif
  7339. /* If this one of script's fds? */
  7340. if (fd_in_HFILEs(fd))
  7341. return 1;
  7342. if (sq) for (i = 0; sq[i].orig_fd >= 0; i++) {
  7343. if (fd == sq[i].moved_to)
  7344. return 1;
  7345. }
  7346. return 0;
  7347. }
  7348. /* squirrel != NULL means we squirrel away copies of stdin, stdout,
  7349. * and stderr if they are redirected. */
  7350. static int setup_redirects(struct command *prog, struct squirrel **sqp)
  7351. {
  7352. struct redir_struct *redir;
  7353. for (redir = prog->redirects; redir; redir = redir->next) {
  7354. int newfd;
  7355. int closed;
  7356. if (redir->rd_type == REDIRECT_HEREDOC2) {
  7357. /* "rd_fd<<HERE" case */
  7358. save_fd_on_redirect(redir->rd_fd, /*avoid:*/ 0, sqp);
  7359. /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
  7360. * of the heredoc */
  7361. debug_printf_redir("set heredoc '%s'\n",
  7362. redir->rd_filename);
  7363. setup_heredoc(redir);
  7364. continue;
  7365. }
  7366. if (redir->rd_dup == REDIRFD_TO_FILE) {
  7367. /* "rd_fd<*>file" case (<*> is <,>,>>,<>) */
  7368. char *p;
  7369. int mode;
  7370. if (redir->rd_filename == NULL) {
  7371. /* Examples:
  7372. * "cmd >" (no filename)
  7373. * "cmd > <file" (2nd redirect starts too early)
  7374. */
  7375. syntax_error("invalid redirect");
  7376. continue;
  7377. }
  7378. mode = redir_table[redir->rd_type].mode;
  7379. p = expand_string_to_string(redir->rd_filename,
  7380. EXP_FLAG_ESC_GLOB_CHARS, /*unbackslash:*/ 1);
  7381. newfd = open_or_warn(p, mode);
  7382. free(p);
  7383. if (newfd < 0) {
  7384. /* Error message from open_or_warn can be lost
  7385. * if stderr has been redirected, but bash
  7386. * and ash both lose it as well
  7387. * (though zsh doesn't!)
  7388. */
  7389. return 1;
  7390. }
  7391. if (newfd == redir->rd_fd && sqp) {
  7392. /* open() gave us precisely the fd we wanted.
  7393. * This means that this fd was not busy
  7394. * (not opened to anywhere).
  7395. * Remember to close it on restore:
  7396. */
  7397. *sqp = add_squirrel_closed(*sqp, newfd);
  7398. debug_printf_redir("redir to previously closed fd %d\n", newfd);
  7399. }
  7400. } else {
  7401. /* "rd_fd>&rd_dup" or "rd_fd>&-" case */
  7402. newfd = redir->rd_dup;
  7403. }
  7404. if (newfd == redir->rd_fd)
  7405. continue;
  7406. /* if "N>FILE": move newfd to redir->rd_fd */
  7407. /* if "N>&M": dup newfd to redir->rd_fd */
  7408. /* if "N>&-": close redir->rd_fd (newfd is REDIRFD_CLOSE) */
  7409. closed = save_fd_on_redirect(redir->rd_fd, /*avoid:*/ newfd, sqp);
  7410. if (newfd == REDIRFD_CLOSE) {
  7411. /* "N>&-" means "close me" */
  7412. if (!closed) {
  7413. /* ^^^ optimization: saving may already
  7414. * have closed it. If not... */
  7415. close(redir->rd_fd);
  7416. }
  7417. /* Sometimes we do another close on restore, getting EBADF.
  7418. * Consider "echo 3>FILE 3>&-"
  7419. * first redirect remembers "need to close 3",
  7420. * and second redirect closes 3! Restore code then closes 3 again.
  7421. */
  7422. } else {
  7423. /* if newfd is a script fd or saved fd, simulate EBADF */
  7424. if (internally_opened_fd(newfd, sqp && sqp != ERR_PTR ? *sqp : NULL)) {
  7425. //errno = EBADF;
  7426. //bb_perror_msg_and_die("can't duplicate file descriptor");
  7427. newfd = -1; /* same effect as code above */
  7428. }
  7429. xdup2(newfd, redir->rd_fd);
  7430. if (redir->rd_dup == REDIRFD_TO_FILE)
  7431. /* "rd_fd > FILE" */
  7432. close(newfd);
  7433. /* else: "rd_fd > rd_dup" */
  7434. }
  7435. }
  7436. return 0;
  7437. }
  7438. static char *find_in_path(const char *arg)
  7439. {
  7440. char *ret = NULL;
  7441. const char *PATH = get_local_var_value("PATH");
  7442. if (!PATH)
  7443. return NULL;
  7444. while (1) {
  7445. const char *end = strchrnul(PATH, ':');
  7446. int sz = end - PATH; /* must be int! */
  7447. free(ret);
  7448. if (sz != 0) {
  7449. ret = xasprintf("%.*s/%s", sz, PATH, arg);
  7450. } else {
  7451. /* We have xxx::yyyy in $PATH,
  7452. * it means "use current dir" */
  7453. ret = xstrdup(arg);
  7454. }
  7455. if (access(ret, F_OK) == 0)
  7456. break;
  7457. if (*end == '\0') {
  7458. free(ret);
  7459. return NULL;
  7460. }
  7461. PATH = end + 1;
  7462. }
  7463. return ret;
  7464. }
  7465. static const struct built_in_command *find_builtin_helper(const char *name,
  7466. const struct built_in_command *x,
  7467. const struct built_in_command *end)
  7468. {
  7469. while (x != end) {
  7470. if (strcmp(name, x->b_cmd) != 0) {
  7471. x++;
  7472. continue;
  7473. }
  7474. debug_printf_exec("found builtin '%s'\n", name);
  7475. return x;
  7476. }
  7477. return NULL;
  7478. }
  7479. static const struct built_in_command *find_builtin1(const char *name)
  7480. {
  7481. return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
  7482. }
  7483. static const struct built_in_command *find_builtin(const char *name)
  7484. {
  7485. const struct built_in_command *x = find_builtin1(name);
  7486. if (x)
  7487. return x;
  7488. return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
  7489. }
  7490. #if ENABLE_HUSH_JOB && EDITING_HAS_get_exe_name
  7491. static const char * FAST_FUNC get_builtin_name(int i)
  7492. {
  7493. if (/*i >= 0 && */ i < ARRAY_SIZE(bltins1)) {
  7494. return bltins1[i].b_cmd;
  7495. }
  7496. i -= ARRAY_SIZE(bltins1);
  7497. if (i < ARRAY_SIZE(bltins2)) {
  7498. return bltins2[i].b_cmd;
  7499. }
  7500. return NULL;
  7501. }
  7502. #endif
  7503. static void remove_nested_vars(void)
  7504. {
  7505. struct variable *cur;
  7506. struct variable **cur_pp;
  7507. cur_pp = &G.top_var;
  7508. while ((cur = *cur_pp) != NULL) {
  7509. if (cur->var_nest_level <= G.var_nest_level) {
  7510. cur_pp = &cur->next;
  7511. continue;
  7512. }
  7513. /* Unexport */
  7514. if (cur->flg_export) {
  7515. debug_printf_env("unexporting nested '%s'/%u\n", cur->varstr, cur->var_nest_level);
  7516. bb_unsetenv(cur->varstr);
  7517. }
  7518. /* Remove from global list */
  7519. *cur_pp = cur->next;
  7520. /* Free */
  7521. if (!cur->max_len) {
  7522. debug_printf_env("freeing nested '%s'/%u\n", cur->varstr, cur->var_nest_level);
  7523. free(cur->varstr);
  7524. }
  7525. free(cur);
  7526. }
  7527. }
  7528. static void enter_var_nest_level(void)
  7529. {
  7530. G.var_nest_level++;
  7531. debug_printf_env("var_nest_level++ %u\n", G.var_nest_level);
  7532. /* Try: f() { echo -n .; f; }; f
  7533. * struct variable::var_nest_level is uint16_t,
  7534. * thus limiting recursion to < 2^16.
  7535. * In any case, with 8 Mbyte stack SEGV happens
  7536. * not too long after 2^16 recursions anyway.
  7537. */
  7538. if (G.var_nest_level > 0xff00)
  7539. bb_error_msg_and_die("fatal recursion (depth %u)", G.var_nest_level);
  7540. }
  7541. static void leave_var_nest_level(void)
  7542. {
  7543. G.var_nest_level--;
  7544. debug_printf_env("var_nest_level-- %u\n", G.var_nest_level);
  7545. if (HUSH_DEBUG && (int)G.var_nest_level < 0)
  7546. bb_simple_error_msg_and_die("BUG: nesting underflow");
  7547. remove_nested_vars();
  7548. }
  7549. #if ENABLE_HUSH_FUNCTIONS
  7550. static struct function **find_function_slot(const char *name)
  7551. {
  7552. struct function *funcp;
  7553. struct function **funcpp = &G.top_func;
  7554. while ((funcp = *funcpp) != NULL) {
  7555. if (strcmp(name, funcp->name) == 0) {
  7556. debug_printf_exec("found function '%s'\n", name);
  7557. break;
  7558. }
  7559. funcpp = &funcp->next;
  7560. }
  7561. return funcpp;
  7562. }
  7563. static ALWAYS_INLINE const struct function *find_function(const char *name)
  7564. {
  7565. const struct function *funcp = *find_function_slot(name);
  7566. return funcp;
  7567. }
  7568. /* Note: takes ownership on name ptr */
  7569. static struct function *new_function(char *name)
  7570. {
  7571. struct function **funcpp = find_function_slot(name);
  7572. struct function *funcp = *funcpp;
  7573. if (funcp != NULL) {
  7574. struct command *cmd = funcp->parent_cmd;
  7575. debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
  7576. if (!cmd) {
  7577. debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
  7578. free(funcp->name);
  7579. /* Note: if !funcp->body, do not free body_as_string!
  7580. * This is a special case of "-F name body" function:
  7581. * body_as_string was not malloced! */
  7582. if (funcp->body) {
  7583. free_pipe_list(funcp->body);
  7584. # if !BB_MMU
  7585. free(funcp->body_as_string);
  7586. # endif
  7587. }
  7588. } else {
  7589. debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
  7590. cmd->argv[0] = funcp->name;
  7591. cmd->group = funcp->body;
  7592. # if !BB_MMU
  7593. cmd->group_as_string = funcp->body_as_string;
  7594. # endif
  7595. }
  7596. } else {
  7597. debug_printf_exec("remembering new function '%s'\n", name);
  7598. funcp = *funcpp = xzalloc(sizeof(*funcp));
  7599. /*funcp->next = NULL;*/
  7600. }
  7601. funcp->name = name;
  7602. return funcp;
  7603. }
  7604. # if ENABLE_HUSH_UNSET
  7605. static void unset_func(const char *name)
  7606. {
  7607. struct function **funcpp = find_function_slot(name);
  7608. struct function *funcp = *funcpp;
  7609. if (funcp != NULL) {
  7610. debug_printf_exec("freeing function '%s'\n", funcp->name);
  7611. *funcpp = funcp->next;
  7612. /* funcp is unlinked now, deleting it.
  7613. * Note: if !funcp->body, the function was created by
  7614. * "-F name body", do not free ->body_as_string
  7615. * and ->name as they were not malloced. */
  7616. if (funcp->body) {
  7617. free_pipe_list(funcp->body);
  7618. free(funcp->name);
  7619. # if !BB_MMU
  7620. free(funcp->body_as_string);
  7621. # endif
  7622. }
  7623. free(funcp);
  7624. }
  7625. }
  7626. # endif
  7627. # if BB_MMU
  7628. #define exec_function(to_free, funcp, argv) \
  7629. exec_function(funcp, argv)
  7630. # endif
  7631. static void exec_function(char ***to_free,
  7632. const struct function *funcp,
  7633. char **argv) NORETURN;
  7634. static void exec_function(char ***to_free,
  7635. const struct function *funcp,
  7636. char **argv)
  7637. {
  7638. # if BB_MMU
  7639. int n;
  7640. argv[0] = G.global_argv[0];
  7641. G.global_argv = argv;
  7642. G.global_argc = n = 1 + string_array_len(argv + 1);
  7643. // Example when we are here: "cmd | func"
  7644. // func will run with saved-redirect fds open.
  7645. // $ f() { echo /proc/self/fd/*; }
  7646. // $ true | f
  7647. // /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3
  7648. // stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ DIR fd for glob
  7649. // Same in script:
  7650. // $ . ./SCRIPT
  7651. // /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3 /proc/self/fd/4
  7652. // stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ opened ./SCRIPT DIR fd for glob
  7653. // They are CLOEXEC so external programs won't see them, but
  7654. // for "more correctness" we might want to close those extra fds here:
  7655. //? close_saved_fds_and_FILE_fds();
  7656. /* "we are in a function, ok to use return" */
  7657. G_flag_return_in_progress = -1;
  7658. enter_var_nest_level();
  7659. IF_HUSH_LOCAL(G.func_nest_level++;)
  7660. /* On MMU, funcp->body is always non-NULL */
  7661. n = run_list(funcp->body);
  7662. _exit(n);
  7663. # else
  7664. //? close_saved_fds_and_FILE_fds();
  7665. //TODO: check whether "true | func_with_return" works
  7666. re_execute_shell(to_free,
  7667. funcp->body_as_string,
  7668. G.global_argv[0],
  7669. argv + 1,
  7670. NULL);
  7671. # endif
  7672. }
  7673. static int run_function(const struct function *funcp, char **argv)
  7674. {
  7675. int rc;
  7676. save_arg_t sv;
  7677. smallint sv_flg;
  7678. save_and_replace_G_args(&sv, argv);
  7679. /* "We are in function, ok to use return" */
  7680. sv_flg = G_flag_return_in_progress;
  7681. G_flag_return_in_progress = -1;
  7682. /* Make "local" variables properly shadow previous ones */
  7683. IF_HUSH_LOCAL(enter_var_nest_level();)
  7684. IF_HUSH_LOCAL(G.func_nest_level++;)
  7685. /* On MMU, funcp->body is always non-NULL */
  7686. # if !BB_MMU
  7687. if (!funcp->body) {
  7688. /* Function defined by -F */
  7689. parse_and_run_string(funcp->body_as_string);
  7690. rc = G.last_exitcode;
  7691. } else
  7692. # endif
  7693. {
  7694. rc = run_list(funcp->body);
  7695. }
  7696. IF_HUSH_LOCAL(G.func_nest_level--;)
  7697. IF_HUSH_LOCAL(leave_var_nest_level();)
  7698. G_flag_return_in_progress = sv_flg;
  7699. # if ENABLE_HUSH_TRAP
  7700. debug_printf_exec("G.return_exitcode=-1\n");
  7701. G.return_exitcode = -1; /* invalidate stashed return value */
  7702. # endif
  7703. restore_G_args(&sv, argv);
  7704. return rc;
  7705. }
  7706. #endif /* ENABLE_HUSH_FUNCTIONS */
  7707. #if BB_MMU
  7708. #define exec_builtin(to_free, x, argv) \
  7709. exec_builtin(x, argv)
  7710. #else
  7711. #define exec_builtin(to_free, x, argv) \
  7712. exec_builtin(to_free, argv)
  7713. #endif
  7714. static void exec_builtin(char ***to_free,
  7715. const struct built_in_command *x,
  7716. char **argv) NORETURN;
  7717. static void exec_builtin(char ***to_free,
  7718. const struct built_in_command *x,
  7719. char **argv)
  7720. {
  7721. #if BB_MMU
  7722. int rcode;
  7723. //? close_saved_fds_and_FILE_fds();
  7724. rcode = x->b_function(argv);
  7725. fflush_all();
  7726. _exit(rcode);
  7727. #else
  7728. fflush_all();
  7729. /* On NOMMU, we must never block!
  7730. * Example: { sleep 99 | read line; } & echo Ok
  7731. */
  7732. re_execute_shell(to_free,
  7733. argv[0],
  7734. G.global_argv[0],
  7735. G.global_argv + 1,
  7736. argv);
  7737. #endif
  7738. }
  7739. static void execvp_or_die(char **argv) NORETURN;
  7740. static void execvp_or_die(char **argv)
  7741. {
  7742. int e;
  7743. debug_printf_exec("execing '%s'\n", argv[0]);
  7744. /* Don't propagate SIG_IGN to the child */
  7745. if (SPECIAL_JOBSTOP_SIGS != 0)
  7746. switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
  7747. execvp(argv[0], argv);
  7748. e = 2;
  7749. if (errno == EACCES) e = 126;
  7750. if (errno == ENOENT) e = 127;
  7751. bb_perror_msg("can't execute '%s'", argv[0]);
  7752. _exit(e);
  7753. }
  7754. #if ENABLE_HUSH_MODE_X
  7755. static void x_mode_print_optionally_squoted(const char *str)
  7756. {
  7757. unsigned len;
  7758. const char *cp;
  7759. cp = str;
  7760. /* the set of chars which-cause-string-to-be-squoted mimics bash */
  7761. /* test a char with: bash -c 'set -x; echo "CH"' */
  7762. if (str[strcspn(str, "\\\"'`$(){}[]<>;#&|~*?!^"
  7763. " " "\001\002\003\004\005\006\007"
  7764. "\010\011\012\013\014\015\016\017"
  7765. "\020\021\022\023\024\025\026\027"
  7766. "\030\031\032\033\034\035\036\037"
  7767. )
  7768. ] == '\0'
  7769. ) {
  7770. /* string has no special chars */
  7771. x_mode_addstr(str);
  7772. return;
  7773. }
  7774. cp = str;
  7775. for (;;) {
  7776. /* print '....' up to EOL or first squote */
  7777. len = (int)(strchrnul(cp, '\'') - cp);
  7778. if (len != 0) {
  7779. x_mode_addchr('\'');
  7780. x_mode_addblock(cp, len);
  7781. x_mode_addchr('\'');
  7782. cp += len;
  7783. }
  7784. if (*cp == '\0')
  7785. break;
  7786. /* string contains squote(s), print them as \' */
  7787. x_mode_addchr('\\');
  7788. x_mode_addchr('\'');
  7789. cp++;
  7790. }
  7791. }
  7792. static void dump_cmd_in_x_mode(char **argv)
  7793. {
  7794. if (G_x_mode && argv) {
  7795. unsigned n;
  7796. /* "+[+++...][ cmd...]\n\0" */
  7797. x_mode_prefix();
  7798. n = 0;
  7799. while (argv[n]) {
  7800. x_mode_addchr(' ');
  7801. if (argv[n][0] == '\0') {
  7802. x_mode_addchr('\'');
  7803. x_mode_addchr('\'');
  7804. } else {
  7805. x_mode_print_optionally_squoted(argv[n]);
  7806. }
  7807. n++;
  7808. }
  7809. x_mode_flush();
  7810. }
  7811. }
  7812. #else
  7813. # define dump_cmd_in_x_mode(argv) ((void)0)
  7814. #endif
  7815. #if ENABLE_HUSH_COMMAND
  7816. static void if_command_vV_print_and_exit(char opt_vV, char *cmd, const char *explanation)
  7817. {
  7818. char *to_free;
  7819. if (!opt_vV)
  7820. return;
  7821. to_free = NULL;
  7822. if (!explanation) {
  7823. char *path = getenv("PATH");
  7824. explanation = to_free = find_executable(cmd, &path); /* path == NULL is ok */
  7825. if (!explanation)
  7826. _exit(1); /* PROG was not found */
  7827. if (opt_vV != 'V')
  7828. cmd = to_free; /* -v PROG prints "/path/to/PROG" */
  7829. }
  7830. printf((opt_vV == 'V') ? "%s is %s\n" : "%s\n", cmd, explanation);
  7831. free(to_free);
  7832. fflush_all();
  7833. _exit(0);
  7834. }
  7835. #else
  7836. # define if_command_vV_print_and_exit(a,b,c) ((void)0)
  7837. #endif
  7838. #if BB_MMU
  7839. #define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
  7840. pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
  7841. #define pseudo_exec(nommu_save, command, argv_expanded) \
  7842. pseudo_exec(command, argv_expanded)
  7843. #endif
  7844. /* Called after [v]fork() in run_pipe, or from builtin_exec.
  7845. * Never returns.
  7846. * Don't exit() here. If you don't exec, use _exit instead.
  7847. * The at_exit handlers apparently confuse the calling process,
  7848. * in particular stdin handling. Not sure why? -- because of vfork! (vda)
  7849. */
  7850. static void pseudo_exec_argv(nommu_save_t *nommu_save,
  7851. char **argv, int assignment_cnt,
  7852. char **argv_expanded) NORETURN;
  7853. static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
  7854. char **argv, int assignment_cnt,
  7855. char **argv_expanded)
  7856. {
  7857. const struct built_in_command *x;
  7858. struct variable **sv_shadowed;
  7859. char **new_env;
  7860. IF_HUSH_COMMAND(char opt_vV = 0;)
  7861. IF_HUSH_FUNCTIONS(const struct function *funcp;)
  7862. new_env = expand_assignments(argv, assignment_cnt);
  7863. dump_cmd_in_x_mode(new_env);
  7864. if (!argv[assignment_cnt]) {
  7865. /* Case when we are here: ... | var=val | ...
  7866. * (note that we do not exit early, i.e., do not optimize out
  7867. * expand_assignments(): think about ... | var=`sleep 1` | ...
  7868. */
  7869. free_strings(new_env);
  7870. _exit(EXIT_SUCCESS);
  7871. }
  7872. sv_shadowed = G.shadowed_vars_pp;
  7873. #if BB_MMU
  7874. G.shadowed_vars_pp = NULL; /* "don't save, free them instead" */
  7875. #else
  7876. G.shadowed_vars_pp = &nommu_save->old_vars;
  7877. G.var_nest_level++;
  7878. #endif
  7879. set_vars_and_save_old(new_env);
  7880. G.shadowed_vars_pp = sv_shadowed;
  7881. if (argv_expanded) {
  7882. argv = argv_expanded;
  7883. } else {
  7884. argv = expand_strvec_to_strvec(argv + assignment_cnt);
  7885. #if !BB_MMU
  7886. nommu_save->argv = argv;
  7887. #endif
  7888. }
  7889. dump_cmd_in_x_mode(argv);
  7890. #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
  7891. if (strchr(argv[0], '/') != NULL)
  7892. goto skip;
  7893. #endif
  7894. #if ENABLE_HUSH_FUNCTIONS
  7895. /* Check if the command matches any functions (this goes before bltins) */
  7896. funcp = find_function(argv[0]);
  7897. if (funcp)
  7898. exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
  7899. #endif
  7900. #if ENABLE_HUSH_COMMAND
  7901. /* "command BAR": run BAR without looking it up among functions
  7902. * "command -v BAR": print "BAR" or "/path/to/BAR"; or exit 1
  7903. * "command -V BAR": print "BAR is {a function,a shell builtin,/path/to/BAR}"
  7904. */
  7905. while (strcmp(argv[0], "command") == 0 && argv[1]) {
  7906. char *p;
  7907. argv++;
  7908. p = *argv;
  7909. if (p[0] != '-' || !p[1])
  7910. continue; /* bash allows "command command command [-OPT] BAR" */
  7911. for (;;) {
  7912. p++;
  7913. switch (*p) {
  7914. case '\0':
  7915. argv++;
  7916. p = *argv;
  7917. if (p[0] != '-' || !p[1])
  7918. goto after_opts;
  7919. continue; /* next arg is also -opts, process it too */
  7920. case 'v':
  7921. case 'V':
  7922. opt_vV = *p;
  7923. continue;
  7924. default:
  7925. bb_error_msg_and_die("%s: %s: invalid option", "command", argv[0]);
  7926. }
  7927. }
  7928. }
  7929. after_opts:
  7930. # if ENABLE_HUSH_FUNCTIONS
  7931. if (opt_vV && find_function(argv[0]))
  7932. if_command_vV_print_and_exit(opt_vV, argv[0], "a function");
  7933. # endif
  7934. #endif
  7935. /* Check if the command matches any of the builtins.
  7936. * Depending on context, this might be redundant. But it's
  7937. * easier to waste a few CPU cycles than it is to figure out
  7938. * if this is one of those cases.
  7939. */
  7940. /* Why "BB_MMU ? :" difference in logic? -
  7941. * On NOMMU, it is more expensive to re-execute shell
  7942. * just in order to run echo or test builtin.
  7943. * It's better to skip it here and run corresponding
  7944. * non-builtin later. */
  7945. x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
  7946. if (x) {
  7947. if_command_vV_print_and_exit(opt_vV, argv[0], "a shell builtin");
  7948. exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
  7949. }
  7950. #if ENABLE_FEATURE_SH_STANDALONE
  7951. /* Check if the command matches any busybox applets */
  7952. {
  7953. int a = find_applet_by_name(argv[0]);
  7954. if (a >= 0) {
  7955. if_command_vV_print_and_exit(opt_vV, argv[0], "an applet");
  7956. # if BB_MMU /* see above why on NOMMU it is not allowed */
  7957. if (APPLET_IS_NOEXEC(a)) {
  7958. /* Do not leak open fds from opened script files etc.
  7959. * Testcase: interactive "ls -l /proc/self/fd"
  7960. * should not show tty fd open.
  7961. */
  7962. close_saved_fds_and_FILE_fds();
  7963. //FIXME: should also close saved redir fds
  7964. //This casuses test failures in
  7965. //redir_children_should_not_see_saved_fd_2.tests
  7966. //redir_children_should_not_see_saved_fd_3.tests
  7967. //if you replace "busybox find" with just "find" in them
  7968. /* Without this, "rm -i FILE" can't be ^C'ed: */
  7969. switch_off_special_sigs(G.special_sig_mask);
  7970. debug_printf_exec("running applet '%s'\n", argv[0]);
  7971. run_noexec_applet_and_exit(a, argv[0], argv);
  7972. }
  7973. # endif
  7974. /* Re-exec ourselves */
  7975. debug_printf_exec("re-execing applet '%s'\n", argv[0]);
  7976. /* Don't propagate SIG_IGN to the child */
  7977. if (SPECIAL_JOBSTOP_SIGS != 0)
  7978. switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
  7979. execv(bb_busybox_exec_path, argv);
  7980. /* If they called chroot or otherwise made the binary no longer
  7981. * executable, fall through */
  7982. }
  7983. }
  7984. #endif
  7985. #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
  7986. skip:
  7987. #endif
  7988. if_command_vV_print_and_exit(opt_vV, argv[0], NULL);
  7989. execvp_or_die(argv);
  7990. }
  7991. /* Called after [v]fork() in run_pipe
  7992. */
  7993. static void pseudo_exec(nommu_save_t *nommu_save,
  7994. struct command *command,
  7995. char **argv_expanded) NORETURN;
  7996. static void pseudo_exec(nommu_save_t *nommu_save,
  7997. struct command *command,
  7998. char **argv_expanded)
  7999. {
  8000. #if ENABLE_HUSH_FUNCTIONS
  8001. if (command->cmd_type == CMD_FUNCDEF) {
  8002. /* Ignore funcdefs in pipes:
  8003. * true | f() { cmd }
  8004. */
  8005. _exit(0);
  8006. }
  8007. #endif
  8008. if (command->argv) {
  8009. pseudo_exec_argv(nommu_save, command->argv,
  8010. command->assignment_cnt, argv_expanded);
  8011. }
  8012. if (command->group) {
  8013. /* Cases when we are here:
  8014. * ( list )
  8015. * { list } &
  8016. * ... | ( list ) | ...
  8017. * ... | { list } | ...
  8018. */
  8019. #if BB_MMU
  8020. int rcode;
  8021. debug_printf_exec("pseudo_exec: run_list\n");
  8022. reset_traps_to_defaults();
  8023. rcode = run_list(command->group);
  8024. /* OK to leak memory by not calling free_pipe_list,
  8025. * since this process is about to exit */
  8026. _exit(rcode);
  8027. #else
  8028. re_execute_shell(&nommu_save->argv_from_re_execing,
  8029. command->group_as_string,
  8030. G.global_argv[0],
  8031. G.global_argv + 1,
  8032. NULL);
  8033. #endif
  8034. }
  8035. /* Case when we are here: ... | >file */
  8036. debug_printf_exec("pseudo_exec'ed null command\n");
  8037. _exit(EXIT_SUCCESS);
  8038. }
  8039. #if ENABLE_HUSH_JOB
  8040. static const char *get_cmdtext(struct pipe *pi)
  8041. {
  8042. char **argv;
  8043. char *p;
  8044. int len;
  8045. /* This is subtle. ->cmdtext is created only on first backgrounding.
  8046. * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
  8047. * On subsequent bg argv is trashed, but we won't use it */
  8048. if (pi->cmdtext)
  8049. return pi->cmdtext;
  8050. argv = pi->cmds[0].argv;
  8051. if (!argv) {
  8052. pi->cmdtext = xzalloc(1);
  8053. return pi->cmdtext;
  8054. }
  8055. len = 0;
  8056. do {
  8057. len += strlen(*argv) + 1;
  8058. } while (*++argv);
  8059. p = xmalloc(len);
  8060. pi->cmdtext = p;
  8061. argv = pi->cmds[0].argv;
  8062. do {
  8063. p = stpcpy(p, *argv);
  8064. *p++ = ' ';
  8065. } while (*++argv);
  8066. p[-1] = '\0';
  8067. return pi->cmdtext;
  8068. }
  8069. static void remove_job_from_table(struct pipe *pi)
  8070. {
  8071. struct pipe *prev_pipe;
  8072. if (pi == G.job_list) {
  8073. G.job_list = pi->next;
  8074. } else {
  8075. prev_pipe = G.job_list;
  8076. while (prev_pipe->next != pi)
  8077. prev_pipe = prev_pipe->next;
  8078. prev_pipe->next = pi->next;
  8079. }
  8080. G.last_jobid = 0;
  8081. if (G.job_list)
  8082. G.last_jobid = G.job_list->jobid;
  8083. }
  8084. static void delete_finished_job(struct pipe *pi)
  8085. {
  8086. remove_job_from_table(pi);
  8087. free_pipe(pi);
  8088. }
  8089. static void clean_up_last_dead_job(void)
  8090. {
  8091. if (G.job_list && !G.job_list->alive_cmds)
  8092. delete_finished_job(G.job_list);
  8093. }
  8094. static void insert_job_into_table(struct pipe *pi)
  8095. {
  8096. struct pipe *job, **jobp;
  8097. int i;
  8098. clean_up_last_dead_job();
  8099. /* Find the end of the list, and find next job ID to use */
  8100. i = 0;
  8101. jobp = &G.job_list;
  8102. while ((job = *jobp) != NULL) {
  8103. if (job->jobid > i)
  8104. i = job->jobid;
  8105. jobp = &job->next;
  8106. }
  8107. pi->jobid = i + 1;
  8108. /* Create a new job struct at the end */
  8109. job = *jobp = xmemdup(pi, sizeof(*pi));
  8110. job->next = NULL;
  8111. job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
  8112. /* Cannot copy entire pi->cmds[] vector! This causes double frees */
  8113. for (i = 0; i < pi->num_cmds; i++) {
  8114. job->cmds[i].pid = pi->cmds[i].pid;
  8115. /* all other fields are not used and stay zero */
  8116. }
  8117. job->cmdtext = xstrdup(get_cmdtext(pi));
  8118. if (G_interactive_fd)
  8119. printf("[%u] %u %s\n", job->jobid, (unsigned)job->cmds[0].pid, job->cmdtext);
  8120. G.last_jobid = job->jobid;
  8121. }
  8122. #endif /* JOB */
  8123. static int job_exited_or_stopped(struct pipe *pi)
  8124. {
  8125. int rcode, i;
  8126. if (pi->alive_cmds != pi->stopped_cmds)
  8127. return -1;
  8128. /* All processes in fg pipe have exited or stopped */
  8129. rcode = 0;
  8130. i = pi->num_cmds;
  8131. while (--i >= 0) {
  8132. rcode = pi->cmds[i].cmd_exitcode;
  8133. /* usually last process gives overall exitstatus,
  8134. * but with "set -o pipefail", last *failed* process does */
  8135. if (G.o_opt[OPT_O_PIPEFAIL] == 0 || rcode != 0)
  8136. break;
  8137. }
  8138. IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
  8139. return rcode;
  8140. }
  8141. static int process_wait_result(struct pipe *fg_pipe, pid_t childpid, int status)
  8142. {
  8143. #if ENABLE_HUSH_JOB
  8144. struct pipe *pi;
  8145. #endif
  8146. int i, dead;
  8147. dead = WIFEXITED(status) || WIFSIGNALED(status);
  8148. #if DEBUG_JOBS
  8149. if (WIFSTOPPED(status))
  8150. debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
  8151. childpid, WSTOPSIG(status), WEXITSTATUS(status));
  8152. if (WIFSIGNALED(status))
  8153. debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
  8154. childpid, WTERMSIG(status), WEXITSTATUS(status));
  8155. if (WIFEXITED(status))
  8156. debug_printf_jobs("pid %d exited, exitcode %d\n",
  8157. childpid, WEXITSTATUS(status));
  8158. #endif
  8159. /* Were we asked to wait for a fg pipe? */
  8160. if (fg_pipe) {
  8161. i = fg_pipe->num_cmds;
  8162. while (--i >= 0) {
  8163. int rcode;
  8164. debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
  8165. if (fg_pipe->cmds[i].pid != childpid)
  8166. continue;
  8167. if (dead) {
  8168. int ex;
  8169. fg_pipe->cmds[i].pid = 0;
  8170. fg_pipe->alive_cmds--;
  8171. ex = WEXITSTATUS(status);
  8172. /* bash prints killer signal's name for *last*
  8173. * process in pipe (prints just newline for SIGINT/SIGPIPE).
  8174. * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
  8175. */
  8176. if (WIFSIGNALED(status)) {
  8177. int sig = WTERMSIG(status);
  8178. #if ENABLE_HUSH_JOB
  8179. if (G.run_list_level == 1
  8180. /* ^^^^^ Do not print in nested contexts, example:
  8181. * echo `sleep 1; sh -c 'kill -9 $$'` - prints "137", NOT "Killed 137"
  8182. */
  8183. && i == fg_pipe->num_cmds-1
  8184. ) {
  8185. /* strsignal() is for bash compat. ~600 bloat versus bbox's get_signame() */
  8186. puts(sig == SIGINT || sig == SIGPIPE ? "" : strsignal(sig));
  8187. }
  8188. #endif
  8189. /* TODO: if (WCOREDUMP(status)) + " (core dumped)"; */
  8190. /* MIPS has 128 sigs (1..128), if sig==128,
  8191. * 128 + sig would result in exitcode 256 -> 0!
  8192. */
  8193. ex = 128 | sig;
  8194. }
  8195. fg_pipe->cmds[i].cmd_exitcode = ex;
  8196. } else {
  8197. fg_pipe->stopped_cmds++;
  8198. }
  8199. debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
  8200. fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
  8201. rcode = job_exited_or_stopped(fg_pipe);
  8202. if (rcode >= 0) {
  8203. /* Note: *non-interactive* bash does not continue if all processes in fg pipe
  8204. * are stopped. Testcase: "cat | cat" in a script (not on command line!)
  8205. * and "killall -STOP cat" */
  8206. if (G_interactive_fd) {
  8207. #if ENABLE_HUSH_JOB
  8208. if (fg_pipe->alive_cmds != 0)
  8209. insert_job_into_table(fg_pipe);
  8210. #endif
  8211. return rcode;
  8212. }
  8213. if (fg_pipe->alive_cmds == 0)
  8214. return rcode;
  8215. }
  8216. /* There are still running processes in the fg_pipe */
  8217. return -1;
  8218. }
  8219. /* It wasn't in fg_pipe, look for process in bg pipes */
  8220. }
  8221. #if ENABLE_HUSH_JOB
  8222. /* We were asked to wait for bg or orphaned children */
  8223. /* No need to remember exitcode in this case */
  8224. for (pi = G.job_list; pi; pi = pi->next) {
  8225. for (i = 0; i < pi->num_cmds; i++) {
  8226. if (pi->cmds[i].pid == childpid)
  8227. goto found_pi_and_prognum;
  8228. }
  8229. }
  8230. /* Happens when shell is used as init process (init=/bin/sh) */
  8231. debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
  8232. return -1; /* this wasn't a process from fg_pipe */
  8233. found_pi_and_prognum:
  8234. if (dead) {
  8235. /* child exited */
  8236. int rcode = WEXITSTATUS(status);
  8237. if (WIFSIGNALED(status))
  8238. /* NB: not 128 + sig, MIPS has sig 128 */
  8239. rcode = 128 | WTERMSIG(status);
  8240. pi->cmds[i].cmd_exitcode = rcode;
  8241. if (G.last_bg_pid == pi->cmds[i].pid)
  8242. G.last_bg_pid_exitcode = rcode;
  8243. pi->cmds[i].pid = 0;
  8244. pi->alive_cmds--;
  8245. if (!pi->alive_cmds) {
  8246. # if ENABLE_HUSH_BASH_COMPAT
  8247. G.dead_job_exitcode = job_exited_or_stopped(pi);
  8248. # endif
  8249. if (G_interactive_fd) {
  8250. printf(JOB_STATUS_FORMAT, pi->jobid,
  8251. "Done", pi->cmdtext);
  8252. delete_finished_job(pi);
  8253. } else {
  8254. /*
  8255. * bash deletes finished jobs from job table only in interactive mode,
  8256. * after "jobs" cmd, or if pid of a new process matches one of the old ones
  8257. * (see cleanup_dead_jobs(), delete_old_job(), J_NOTIFIED in bash source).
  8258. * Testcase script: "(exit 3) & sleep 1; wait %1; echo $?" prints 3 in bash.
  8259. * We only retain one "dead" job, if it's the single job on the list.
  8260. * This covers most of real-world scenarios where this is useful.
  8261. */
  8262. if (pi != G.job_list)
  8263. delete_finished_job(pi);
  8264. }
  8265. }
  8266. } else {
  8267. /* child stopped */
  8268. pi->stopped_cmds++;
  8269. }
  8270. #endif
  8271. return -1; /* this wasn't a process from fg_pipe */
  8272. }
  8273. /* Check to see if any processes have exited -- if they have,
  8274. * figure out why and see if a job has completed.
  8275. *
  8276. * If non-NULL fg_pipe: wait for its completion or stop.
  8277. * Return its exitcode or zero if stopped.
  8278. *
  8279. * Alternatively (fg_pipe == NULL, waitfor_pid != 0):
  8280. * waitpid(WNOHANG), if waitfor_pid exits or stops, return exitcode+1,
  8281. * else return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
  8282. * or 0 if no children changed status.
  8283. *
  8284. * Alternatively (fg_pipe == NULL, waitfor_pid == 0),
  8285. * return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
  8286. * or 0 if no children changed status.
  8287. */
  8288. static int checkjobs(struct pipe *fg_pipe, pid_t waitfor_pid)
  8289. {
  8290. int attributes;
  8291. int status;
  8292. int rcode = 0;
  8293. debug_printf_jobs("checkjobs %p\n", fg_pipe);
  8294. attributes = WUNTRACED;
  8295. if (fg_pipe == NULL)
  8296. attributes |= WNOHANG;
  8297. errno = 0;
  8298. #if ENABLE_HUSH_FAST
  8299. if (G.handled_SIGCHLD == G.count_SIGCHLD) {
  8300. //bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
  8301. //getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
  8302. /* There was neither fork nor SIGCHLD since last waitpid */
  8303. /* Avoid doing waitpid syscall if possible */
  8304. if (!G.we_have_children) {
  8305. errno = ECHILD;
  8306. return -1;
  8307. }
  8308. if (fg_pipe == NULL) { /* is WNOHANG set? */
  8309. /* We have children, but they did not exit
  8310. * or stop yet (we saw no SIGCHLD) */
  8311. return 0;
  8312. }
  8313. /* else: !WNOHANG, waitpid will block, can't short-circuit */
  8314. }
  8315. #endif
  8316. /* Do we do this right?
  8317. * bash-3.00# sleep 20 | false
  8318. * <ctrl-Z pressed>
  8319. * [3]+ Stopped sleep 20 | false
  8320. * bash-3.00# echo $?
  8321. * 1 <========== bg pipe is not fully done, but exitcode is already known!
  8322. * [hush 1.14.0: yes we do it right]
  8323. */
  8324. while (1) {
  8325. pid_t childpid;
  8326. #if ENABLE_HUSH_FAST
  8327. int i;
  8328. i = G.count_SIGCHLD;
  8329. #endif
  8330. childpid = waitpid(-1, &status, attributes);
  8331. if (childpid <= 0) {
  8332. if (childpid && errno != ECHILD)
  8333. bb_simple_perror_msg("waitpid");
  8334. #if ENABLE_HUSH_FAST
  8335. else { /* Until next SIGCHLD, waitpid's are useless */
  8336. G.we_have_children = (childpid == 0);
  8337. G.handled_SIGCHLD = i;
  8338. //bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
  8339. }
  8340. #endif
  8341. /* ECHILD (no children), or 0 (no change in children status) */
  8342. rcode = childpid;
  8343. break;
  8344. }
  8345. rcode = process_wait_result(fg_pipe, childpid, status);
  8346. if (rcode >= 0) {
  8347. /* fg_pipe exited or stopped */
  8348. break;
  8349. }
  8350. if (childpid == waitfor_pid) { /* "wait PID" */
  8351. debug_printf_exec("childpid==waitfor_pid:%d status:0x%08x\n", childpid, status);
  8352. rcode = WEXITSTATUS(status);
  8353. if (WIFSIGNALED(status))
  8354. rcode = 128 | WTERMSIG(status);
  8355. if (WIFSTOPPED(status))
  8356. /* bash: "cmd & wait $!" and cmd stops: $? = 128 | stopsig */
  8357. rcode = 128 | WSTOPSIG(status);
  8358. rcode++;
  8359. break; /* "wait PID" called us, give it exitcode+1 */
  8360. }
  8361. #if ENABLE_HUSH_BASH_COMPAT
  8362. if (-1 == waitfor_pid /* "wait -n" (wait for any one job) */
  8363. && G.dead_job_exitcode >= 0 /* some job did finish */
  8364. ) {
  8365. debug_printf_exec("waitfor_pid:-1\n");
  8366. rcode = G.dead_job_exitcode + 1;
  8367. break;
  8368. }
  8369. #endif
  8370. /* This wasn't one of our processes, or */
  8371. /* fg_pipe still has running processes, do waitpid again */
  8372. } /* while (waitpid succeeds)... */
  8373. return rcode;
  8374. }
  8375. #if ENABLE_HUSH_JOB
  8376. static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
  8377. {
  8378. pid_t p;
  8379. int rcode = checkjobs(fg_pipe, 0 /*(no pid to wait for)*/);
  8380. if (G_saved_tty_pgrp) {
  8381. /* Job finished, move the shell to the foreground */
  8382. p = getpgrp(); /* our process group id */
  8383. debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
  8384. tcsetpgrp(G_interactive_fd, p);
  8385. }
  8386. return rcode;
  8387. }
  8388. #endif
  8389. /* Start all the jobs, but don't wait for anything to finish.
  8390. * See checkjobs().
  8391. *
  8392. * Return code is normally -1, when the caller has to wait for children
  8393. * to finish to determine the exit status of the pipe. If the pipe
  8394. * is a simple builtin command, however, the action is done by the
  8395. * time run_pipe returns, and the exit code is provided as the
  8396. * return value.
  8397. *
  8398. * Returns -1 only if started some children. IOW: we have to
  8399. * mask out retvals of builtins etc with 0xff!
  8400. *
  8401. * The only case when we do not need to [v]fork is when the pipe
  8402. * is single, non-backgrounded, non-subshell command. Examples:
  8403. * cmd ; ... { list } ; ...
  8404. * cmd && ... { list } && ...
  8405. * cmd || ... { list } || ...
  8406. * If it is, then we can run cmd as a builtin, NOFORK,
  8407. * or (if SH_STANDALONE) an applet, and we can run the { list }
  8408. * with run_list. If it isn't one of these, we fork and exec cmd.
  8409. *
  8410. * Cases when we must fork:
  8411. * non-single: cmd | cmd
  8412. * backgrounded: cmd & { list } &
  8413. * subshell: ( list ) [&]
  8414. */
  8415. #if !ENABLE_HUSH_MODE_X
  8416. #define redirect_and_varexp_helper(command, sqp, argv_expanded) \
  8417. redirect_and_varexp_helper(command, sqp)
  8418. #endif
  8419. static int redirect_and_varexp_helper(
  8420. struct command *command,
  8421. struct squirrel **sqp,
  8422. char **argv_expanded)
  8423. {
  8424. /* Assignments occur before redirects. Try:
  8425. * a=`sleep 1` sleep 2 3>/qwe/rty
  8426. */
  8427. char **new_env = expand_assignments(command->argv, command->assignment_cnt);
  8428. dump_cmd_in_x_mode(new_env);
  8429. dump_cmd_in_x_mode(argv_expanded);
  8430. /* this takes ownership of new_env[i] elements, and frees new_env: */
  8431. set_vars_and_save_old(new_env);
  8432. return setup_redirects(command, sqp);
  8433. }
  8434. static NOINLINE int run_pipe(struct pipe *pi)
  8435. {
  8436. static const char *const null_ptr = NULL;
  8437. int cmd_no;
  8438. int next_infd;
  8439. struct command *command;
  8440. char **argv_expanded;
  8441. char **argv;
  8442. struct squirrel *squirrel = NULL;
  8443. int rcode;
  8444. debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
  8445. debug_enter();
  8446. /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
  8447. * Result should be 3 lines: q w e, qwe, q w e
  8448. */
  8449. if (G.ifs_whitespace != G.ifs)
  8450. free(G.ifs_whitespace);
  8451. G.ifs = get_local_var_value("IFS");
  8452. if (G.ifs) {
  8453. char *p;
  8454. G.ifs_whitespace = (char*)G.ifs;
  8455. p = skip_whitespace(G.ifs);
  8456. if (*p) {
  8457. /* Not all $IFS is whitespace */
  8458. char *d;
  8459. int len = p - G.ifs;
  8460. p = skip_non_whitespace(p);
  8461. G.ifs_whitespace = xmalloc(len + strlen(p) + 1); /* can overestimate */
  8462. d = mempcpy(G.ifs_whitespace, G.ifs, len);
  8463. while (*p) {
  8464. if (isspace(*p))
  8465. *d++ = *p;
  8466. p++;
  8467. }
  8468. *d = '\0';
  8469. }
  8470. } else {
  8471. G.ifs = defifs;
  8472. G.ifs_whitespace = (char*)G.ifs;
  8473. }
  8474. IF_HUSH_JOB(pi->pgrp = -1;)
  8475. pi->stopped_cmds = 0;
  8476. command = &pi->cmds[0];
  8477. argv_expanded = NULL;
  8478. if (pi->num_cmds != 1
  8479. || pi->followup == PIPE_BG
  8480. || command->cmd_type == CMD_SUBSHELL
  8481. ) {
  8482. goto must_fork;
  8483. }
  8484. pi->alive_cmds = 1;
  8485. debug_printf_exec(": group:%p argv:'%s'\n",
  8486. command->group, command->argv ? command->argv[0] : "NONE");
  8487. if (command->group) {
  8488. #if ENABLE_HUSH_FUNCTIONS
  8489. if (command->cmd_type == CMD_FUNCDEF) {
  8490. /* "executing" func () { list } */
  8491. struct function *funcp;
  8492. funcp = new_function(command->argv[0]);
  8493. /* funcp->name is already set to argv[0] */
  8494. funcp->body = command->group;
  8495. # if !BB_MMU
  8496. funcp->body_as_string = command->group_as_string;
  8497. command->group_as_string = NULL;
  8498. # endif
  8499. command->group = NULL;
  8500. command->argv[0] = NULL;
  8501. debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
  8502. funcp->parent_cmd = command;
  8503. command->child_func = funcp;
  8504. debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
  8505. debug_leave();
  8506. return EXIT_SUCCESS;
  8507. }
  8508. #endif
  8509. /* { list } */
  8510. debug_printf_exec("non-subshell group\n");
  8511. rcode = 1; /* exitcode if redir failed */
  8512. if (setup_redirects(command, &squirrel) == 0) {
  8513. debug_printf_exec(": run_list\n");
  8514. //FIXME: we need to pass squirrel down into run_list()
  8515. //for SH_STANDALONE case, or else this construct:
  8516. // { find /proc/self/fd; true; } >FILE; cmd2
  8517. //has no way of closing saved fd#1 for "find",
  8518. //and in SH_STANDALONE mode, "find" is not execed,
  8519. //therefore CLOEXEC on saved fd does not help.
  8520. rcode = run_list(command->group) & 0xff;
  8521. }
  8522. restore_redirects(squirrel);
  8523. IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
  8524. debug_leave();
  8525. debug_printf_exec("run_pipe: return %d\n", rcode);
  8526. return rcode;
  8527. }
  8528. argv = command->argv ? command->argv : (char **) &null_ptr;
  8529. {
  8530. const struct built_in_command *x;
  8531. IF_HUSH_FUNCTIONS(const struct function *funcp;)
  8532. IF_NOT_HUSH_FUNCTIONS(enum { funcp = 0 };)
  8533. struct variable **sv_shadowed;
  8534. struct variable *old_vars;
  8535. #if ENABLE_HUSH_LINENO_VAR
  8536. G.execute_lineno = command->lineno;
  8537. #endif
  8538. if (argv[command->assignment_cnt] == NULL) {
  8539. /* Assignments, but no command.
  8540. * Ensure redirects take effect (that is, create files).
  8541. * Try "a=t >file"
  8542. */
  8543. unsigned i;
  8544. G.expand_exitcode = 0;
  8545. only_assignments:
  8546. rcode = setup_redirects(command, &squirrel);
  8547. restore_redirects(squirrel);
  8548. /* Set shell variables */
  8549. i = 0;
  8550. while (i < command->assignment_cnt) {
  8551. char *p = expand_string_to_string(argv[i],
  8552. EXP_FLAG_ESC_GLOB_CHARS,
  8553. /*unbackslash:*/ 1
  8554. );
  8555. #if ENABLE_HUSH_MODE_X
  8556. if (G_x_mode) {
  8557. char *eq;
  8558. if (i == 0)
  8559. x_mode_prefix();
  8560. x_mode_addchr(' ');
  8561. eq = strchrnul(p, '=');
  8562. if (*eq) eq++;
  8563. x_mode_addblock(p, (eq - p));
  8564. x_mode_print_optionally_squoted(eq);
  8565. x_mode_flush();
  8566. }
  8567. #endif
  8568. debug_printf_env("set shell var:'%s'->'%s'\n", *argv, p);
  8569. if (set_local_var(p, /*flag:*/ 0)) {
  8570. /* assignment to readonly var / putenv error? */
  8571. rcode = 1;
  8572. }
  8573. i++;
  8574. }
  8575. /* Redirect error sets $? to 1. Otherwise,
  8576. * if evaluating assignment value set $?, retain it.
  8577. * Else, clear $?:
  8578. * false; q=`exit 2`; echo $? - should print 2
  8579. * false; x=1; echo $? - should print 0
  8580. * Because of the 2nd case, we can't just use G.last_exitcode.
  8581. */
  8582. if (rcode == 0)
  8583. rcode = G.expand_exitcode;
  8584. IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
  8585. debug_leave();
  8586. debug_printf_exec("run_pipe: return %d\n", rcode);
  8587. return rcode;
  8588. }
  8589. /* Expand the rest into (possibly) many strings each */
  8590. #if defined(CMD_TEST2_SINGLEWORD_NOGLOB)
  8591. if (command->cmd_type == CMD_TEST2_SINGLEWORD_NOGLOB)
  8592. argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
  8593. else
  8594. #endif
  8595. #if defined(CMD_SINGLEWORD_NOGLOB)
  8596. if (command->cmd_type == CMD_SINGLEWORD_NOGLOB)
  8597. argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
  8598. else
  8599. #endif
  8600. argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
  8601. /* If someone gives us an empty string: `cmd with empty output` */
  8602. if (!argv_expanded[0]) {
  8603. free(argv_expanded);
  8604. /* `false` still has to set exitcode 1 */
  8605. G.expand_exitcode = G.last_exitcode;
  8606. goto only_assignments;
  8607. }
  8608. old_vars = NULL;
  8609. sv_shadowed = G.shadowed_vars_pp;
  8610. /* Check if argv[0] matches any functions (this goes before bltins) */
  8611. IF_HUSH_FUNCTIONS(funcp = find_function(argv_expanded[0]);)
  8612. IF_HUSH_FUNCTIONS(x = NULL;)
  8613. IF_HUSH_FUNCTIONS(if (!funcp))
  8614. x = find_builtin(argv_expanded[0]);
  8615. if (x || funcp) {
  8616. if (x && x->b_function == builtin_exec && argv_expanded[1] == NULL) {
  8617. debug_printf("exec with redirects only\n");
  8618. /*
  8619. * Variable assignments are executed, but then "forgotten":
  8620. * a=`sleep 1;echo A` exec 3>&-; echo $a
  8621. * sleeps, but prints nothing.
  8622. */
  8623. enter_var_nest_level();
  8624. G.shadowed_vars_pp = &old_vars;
  8625. rcode = redirect_and_varexp_helper(command,
  8626. /*squirrel:*/ ERR_PTR,
  8627. argv_expanded
  8628. );
  8629. G.shadowed_vars_pp = sv_shadowed;
  8630. /* rcode=1 can be if redir file can't be opened */
  8631. goto clean_up_and_ret1;
  8632. }
  8633. /* Bump var nesting, or this will leak exported $a:
  8634. * a=b true; env | grep ^a=
  8635. */
  8636. enter_var_nest_level();
  8637. /* Collect all variables "shadowed" by helper
  8638. * (IOW: old vars overridden by "var1=val1 var2=val2 cmd..." syntax)
  8639. * into old_vars list:
  8640. */
  8641. G.shadowed_vars_pp = &old_vars;
  8642. rcode = redirect_and_varexp_helper(command, &squirrel, argv_expanded);
  8643. if (rcode == 0) {
  8644. if (!funcp) {
  8645. /* Do not collect *to old_vars list* vars shadowed
  8646. * by e.g. "local VAR" builtin (collect them
  8647. * in the previously nested list instead):
  8648. * don't want them to be restored immediately
  8649. * after "local" completes.
  8650. */
  8651. G.shadowed_vars_pp = sv_shadowed;
  8652. debug_printf_exec(": builtin '%s' '%s'...\n",
  8653. x->b_cmd, argv_expanded[1]);
  8654. fflush_all();
  8655. rcode = x->b_function(argv_expanded) & 0xff;
  8656. fflush_all();
  8657. }
  8658. #if ENABLE_HUSH_FUNCTIONS
  8659. else {
  8660. debug_printf_exec(": function '%s' '%s'...\n",
  8661. funcp->name, argv_expanded[1]);
  8662. rcode = run_function(funcp, argv_expanded) & 0xff;
  8663. /*
  8664. * But do collect *to old_vars list* vars shadowed
  8665. * within function execution. To that end, restore
  8666. * this pointer _after_ function run:
  8667. */
  8668. G.shadowed_vars_pp = sv_shadowed;
  8669. }
  8670. #endif
  8671. }
  8672. } else
  8673. if (ENABLE_FEATURE_SH_NOFORK && NUM_APPLETS > 1) {
  8674. int n = find_applet_by_name(argv_expanded[0]);
  8675. if (n < 0 || !APPLET_IS_NOFORK(n))
  8676. goto must_fork;
  8677. enter_var_nest_level();
  8678. /* Collect all variables "shadowed" by helper into old_vars list */
  8679. G.shadowed_vars_pp = &old_vars;
  8680. rcode = redirect_and_varexp_helper(command, &squirrel, argv_expanded);
  8681. G.shadowed_vars_pp = sv_shadowed;
  8682. if (rcode == 0) {
  8683. debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
  8684. argv_expanded[0], argv_expanded[1]);
  8685. /*
  8686. * Note: signals (^C) can't interrupt here.
  8687. * We remember them and they will be acted upon
  8688. * after applet returns.
  8689. * This makes applets which can run for a long time
  8690. * and/or wait for user input ineligible for NOFORK:
  8691. * for example, "yes" or "rm" (rm -i waits for input).
  8692. */
  8693. rcode = run_nofork_applet(n, argv_expanded);
  8694. }
  8695. } else
  8696. goto must_fork;
  8697. restore_redirects(squirrel);
  8698. clean_up_and_ret1:
  8699. leave_var_nest_level();
  8700. add_vars(old_vars);
  8701. /*
  8702. * Try "usleep 99999999" + ^C + "echo $?"
  8703. * with FEATURE_SH_NOFORK=y.
  8704. */
  8705. if (!funcp) {
  8706. /* It was builtin or nofork.
  8707. * if this would be a real fork/execed program,
  8708. * it should have died if a fatal sig was received.
  8709. * But OTOH, there was no separate process,
  8710. * the sig was sent to _shell_, not to non-existing
  8711. * child.
  8712. * Let's just handle ^C only, this one is obvious:
  8713. * we aren't ok with exitcode 0 when ^C was pressed
  8714. * during builtin/nofork.
  8715. */
  8716. if (sigismember(&G.pending_set, SIGINT))
  8717. rcode = 128 | SIGINT;
  8718. }
  8719. free(argv_expanded);
  8720. IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
  8721. debug_leave();
  8722. debug_printf_exec("run_pipe return %d\n", rcode);
  8723. return rcode;
  8724. }
  8725. must_fork:
  8726. /* NB: argv_expanded may already be created, and that
  8727. * might include `cmd` runs! Do not rerun it! We *must*
  8728. * use argv_expanded if it's non-NULL */
  8729. /* Going to fork a child per each pipe member */
  8730. pi->alive_cmds = 0;
  8731. next_infd = 0;
  8732. cmd_no = 0;
  8733. while (cmd_no < pi->num_cmds) {
  8734. struct fd_pair pipefds;
  8735. #if !BB_MMU
  8736. int sv_var_nest_level = G.var_nest_level;
  8737. volatile nommu_save_t nommu_save;
  8738. nommu_save.old_vars = NULL;
  8739. nommu_save.argv = NULL;
  8740. nommu_save.argv_from_re_execing = NULL;
  8741. #endif
  8742. command = &pi->cmds[cmd_no];
  8743. cmd_no++;
  8744. if (command->argv) {
  8745. debug_printf_exec(": pipe member '%s' '%s'...\n",
  8746. command->argv[0], command->argv[1]);
  8747. } else {
  8748. debug_printf_exec(": pipe member with no argv\n");
  8749. }
  8750. /* pipes are inserted between pairs of commands */
  8751. pipefds.rd = 0;
  8752. pipefds.wr = 1;
  8753. if (cmd_no < pi->num_cmds)
  8754. xpiped_pair(pipefds);
  8755. #if ENABLE_HUSH_LINENO_VAR
  8756. G.execute_lineno = command->lineno;
  8757. #endif
  8758. command->pid = BB_MMU ? fork() : vfork();
  8759. if (!command->pid) { /* child */
  8760. #if ENABLE_HUSH_JOB
  8761. disable_restore_tty_pgrp_on_exit();
  8762. CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
  8763. /* Every child adds itself to new process group
  8764. * with pgid == pid_of_first_child_in_pipe */
  8765. if (G.run_list_level == 1 && G_interactive_fd) {
  8766. pid_t pgrp;
  8767. pgrp = pi->pgrp;
  8768. if (pgrp < 0) /* true for 1st process only */
  8769. pgrp = getpid();
  8770. if (setpgid(0, pgrp) == 0
  8771. && pi->followup != PIPE_BG
  8772. && G_saved_tty_pgrp /* we have ctty */
  8773. ) {
  8774. /* We do it in *every* child, not just first,
  8775. * to avoid races */
  8776. tcsetpgrp(G_interactive_fd, pgrp);
  8777. }
  8778. }
  8779. #endif
  8780. if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
  8781. /* 1st cmd in backgrounded pipe
  8782. * should have its stdin /dev/null'ed */
  8783. close(0);
  8784. if (open(bb_dev_null, O_RDONLY))
  8785. xopen("/", O_RDONLY);
  8786. } else {
  8787. xmove_fd(next_infd, 0);
  8788. }
  8789. xmove_fd(pipefds.wr, 1);
  8790. if (pipefds.rd > 1)
  8791. close(pipefds.rd);
  8792. /* Like bash, explicit redirects override pipes,
  8793. * and the pipe fd (fd#1) is available for dup'ing:
  8794. * "cmd1 2>&1 | cmd2": fd#1 is duped to fd#2, thus stderr
  8795. * of cmd1 goes into pipe.
  8796. */
  8797. if (setup_redirects(command, NULL)) {
  8798. /* Happens when redir file can't be opened:
  8799. * $ hush -c 'echo FOO >&2 | echo BAR 3>/qwe/rty; echo BAZ'
  8800. * FOO
  8801. * hush: can't open '/qwe/rty': No such file or directory
  8802. * BAZ
  8803. * (echo BAR is not executed, it hits _exit(1) below)
  8804. */
  8805. _exit(1);
  8806. }
  8807. /* Stores to nommu_save list of env vars putenv'ed
  8808. * (NOMMU, on MMU we don't need that) */
  8809. /* cast away volatility... */
  8810. pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
  8811. /* pseudo_exec() does not return */
  8812. }
  8813. /* parent or error */
  8814. #if ENABLE_HUSH_FAST
  8815. G.count_SIGCHLD++;
  8816. //bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
  8817. #endif
  8818. enable_restore_tty_pgrp_on_exit();
  8819. #if !BB_MMU
  8820. /* Clean up after vforked child */
  8821. free(nommu_save.argv);
  8822. free(nommu_save.argv_from_re_execing);
  8823. G.var_nest_level = sv_var_nest_level;
  8824. remove_nested_vars();
  8825. add_vars(nommu_save.old_vars);
  8826. #endif
  8827. free(argv_expanded);
  8828. argv_expanded = NULL;
  8829. if (command->pid < 0) { /* [v]fork failed */
  8830. /* Clearly indicate, was it fork or vfork */
  8831. bb_simple_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
  8832. } else {
  8833. pi->alive_cmds++;
  8834. #if ENABLE_HUSH_JOB
  8835. /* Second and next children need to know pid of first one */
  8836. if (pi->pgrp < 0)
  8837. pi->pgrp = command->pid;
  8838. #endif
  8839. }
  8840. if (cmd_no > 1)
  8841. close(next_infd);
  8842. if (cmd_no < pi->num_cmds)
  8843. close(pipefds.wr);
  8844. /* Pass read (output) pipe end to next iteration */
  8845. next_infd = pipefds.rd;
  8846. }
  8847. if (!pi->alive_cmds) {
  8848. debug_leave();
  8849. debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
  8850. return 1;
  8851. }
  8852. debug_leave();
  8853. debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
  8854. return -1;
  8855. }
  8856. /* NB: called by pseudo_exec, and therefore must not modify any
  8857. * global data until exec/_exit (we can be a child after vfork!) */
  8858. static int run_list(struct pipe *pi)
  8859. {
  8860. #if ENABLE_HUSH_CASE
  8861. char *case_word = NULL;
  8862. #endif
  8863. #if ENABLE_HUSH_LOOPS
  8864. struct pipe *loop_top = NULL;
  8865. char **for_lcur = NULL;
  8866. char **for_list = NULL;
  8867. #endif
  8868. smallint last_followup;
  8869. smalluint rcode;
  8870. #if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
  8871. smalluint cond_code = 0;
  8872. #else
  8873. enum { cond_code = 0 };
  8874. #endif
  8875. #if HAS_KEYWORDS
  8876. smallint rword; /* RES_foo */
  8877. smallint last_rword; /* ditto */
  8878. #endif
  8879. debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
  8880. debug_enter();
  8881. #if ENABLE_HUSH_LOOPS
  8882. /* Check syntax for "for" */
  8883. {
  8884. struct pipe *cpipe;
  8885. for (cpipe = pi; cpipe; cpipe = cpipe->next) {
  8886. if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
  8887. continue;
  8888. /* current word is FOR or IN (BOLD in comments below) */
  8889. if (cpipe->next == NULL) {
  8890. syntax_error("malformed for");
  8891. debug_leave();
  8892. debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
  8893. return 1;
  8894. }
  8895. /* "FOR v; do ..." and "for v IN a b; do..." are ok */
  8896. if (cpipe->next->res_word == RES_DO)
  8897. continue;
  8898. /* next word is not "do". It must be "in" then ("FOR v in ...") */
  8899. if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
  8900. || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
  8901. ) {
  8902. syntax_error("malformed for");
  8903. debug_leave();
  8904. debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
  8905. return 1;
  8906. }
  8907. }
  8908. }
  8909. #endif
  8910. /* Past this point, all code paths should jump to ret: label
  8911. * in order to return, no direct "return" statements please.
  8912. * This helps to ensure that no memory is leaked. */
  8913. #if ENABLE_HUSH_JOB
  8914. G.run_list_level++;
  8915. #endif
  8916. #if HAS_KEYWORDS
  8917. rword = RES_NONE;
  8918. last_rword = RES_XXXX;
  8919. #endif
  8920. last_followup = PIPE_SEQ;
  8921. rcode = G.last_exitcode;
  8922. /* Go through list of pipes, (maybe) executing them. */
  8923. for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
  8924. int r;
  8925. int sv_errexit_depth;
  8926. if (G.flag_SIGINT)
  8927. break;
  8928. if (G_flag_return_in_progress == 1)
  8929. break;
  8930. IF_HAS_KEYWORDS(rword = pi->res_word;)
  8931. debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
  8932. rword, cond_code, last_rword);
  8933. sv_errexit_depth = G.errexit_depth;
  8934. if (
  8935. #if ENABLE_HUSH_IF
  8936. rword == RES_IF || rword == RES_ELIF ||
  8937. #endif
  8938. pi->followup != PIPE_SEQ
  8939. ) {
  8940. G.errexit_depth++;
  8941. }
  8942. #if ENABLE_HUSH_LOOPS
  8943. if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
  8944. && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
  8945. ) {
  8946. /* start of a loop: remember where loop starts */
  8947. loop_top = pi;
  8948. G.depth_of_loop++;
  8949. }
  8950. #endif
  8951. /* Still in the same "if...", "then..." or "do..." branch? */
  8952. if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
  8953. if ((rcode == 0 && last_followup == PIPE_OR)
  8954. || (rcode != 0 && last_followup == PIPE_AND)
  8955. ) {
  8956. /* It is "<true> || CMD" or "<false> && CMD"
  8957. * and we should not execute CMD */
  8958. debug_printf_exec("skipped cmd because of || or &&\n");
  8959. last_followup = pi->followup;
  8960. goto dont_check_jobs_but_continue;
  8961. }
  8962. }
  8963. last_followup = pi->followup;
  8964. IF_HAS_KEYWORDS(last_rword = rword;)
  8965. #if ENABLE_HUSH_IF
  8966. if (cond_code) {
  8967. if (rword == RES_THEN) {
  8968. /* if false; then ... fi has exitcode 0! */
  8969. G.last_exitcode = rcode = EXIT_SUCCESS;
  8970. /* "if <false> THEN cmd": skip cmd */
  8971. continue;
  8972. }
  8973. } else {
  8974. if (rword == RES_ELSE || rword == RES_ELIF) {
  8975. /* "if <true> then ... ELSE/ELIF cmd":
  8976. * skip cmd and all following ones */
  8977. break;
  8978. }
  8979. }
  8980. #endif
  8981. #if ENABLE_HUSH_LOOPS
  8982. if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
  8983. if (!for_lcur) {
  8984. /* first loop through for */
  8985. static const char encoded_dollar_at[] ALIGN1 = {
  8986. SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
  8987. }; /* encoded representation of "$@" */
  8988. static const char *const encoded_dollar_at_argv[] = {
  8989. encoded_dollar_at, NULL
  8990. }; /* argv list with one element: "$@" */
  8991. char **vals;
  8992. G.last_exitcode = rcode = EXIT_SUCCESS;
  8993. vals = (char**)encoded_dollar_at_argv;
  8994. if (pi->next->res_word == RES_IN) {
  8995. /* if no variable values after "in" we skip "for" */
  8996. if (!pi->next->cmds[0].argv) {
  8997. debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
  8998. break;
  8999. }
  9000. vals = pi->next->cmds[0].argv;
  9001. } /* else: "for var; do..." -> assume "$@" list */
  9002. /* create list of variable values */
  9003. debug_print_strings("for_list made from", vals);
  9004. for_list = expand_strvec_to_strvec(vals);
  9005. for_lcur = for_list;
  9006. debug_print_strings("for_list", for_list);
  9007. }
  9008. if (!*for_lcur) {
  9009. /* "for" loop is over, clean up */
  9010. free(for_list);
  9011. for_list = NULL;
  9012. for_lcur = NULL;
  9013. break;
  9014. }
  9015. /* Insert next value from for_lcur */
  9016. /* note: *for_lcur already has quotes removed, $var expanded, etc */
  9017. set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*flag:*/ 0);
  9018. continue;
  9019. }
  9020. if (rword == RES_IN) {
  9021. continue; /* "for v IN list;..." - "in" has no cmds anyway */
  9022. }
  9023. if (rword == RES_DONE) {
  9024. continue; /* "done" has no cmds too */
  9025. }
  9026. #endif
  9027. #if ENABLE_HUSH_CASE
  9028. if (rword == RES_CASE) {
  9029. debug_printf_exec("CASE cond_code:%d\n", cond_code);
  9030. case_word = expand_string_to_string(pi->cmds->argv[0],
  9031. EXP_FLAG_ESC_GLOB_CHARS, /*unbackslash:*/ 1);
  9032. debug_printf_exec("CASE word1:'%s'\n", case_word);
  9033. //unbackslash(case_word);
  9034. //debug_printf_exec("CASE word2:'%s'\n", case_word);
  9035. continue;
  9036. }
  9037. if (rword == RES_MATCH) {
  9038. char **argv;
  9039. debug_printf_exec("MATCH cond_code:%d\n", cond_code);
  9040. if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
  9041. break;
  9042. /* all prev words didn't match, does this one match? */
  9043. argv = pi->cmds->argv;
  9044. while (*argv) {
  9045. char *pattern;
  9046. debug_printf_exec("expand_string_to_string('%s')\n", *argv);
  9047. pattern = expand_string_to_string(*argv,
  9048. EXP_FLAG_ESC_GLOB_CHARS,
  9049. /*unbackslash:*/ 0
  9050. );
  9051. /* TODO: which FNM_xxx flags to use? */
  9052. cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
  9053. debug_printf_exec("fnmatch(pattern:'%s',str:'%s'):%d\n",
  9054. pattern, case_word, cond_code);
  9055. free(pattern);
  9056. if (cond_code == 0) {
  9057. /* match! we will execute this branch */
  9058. free(case_word);
  9059. case_word = NULL; /* make future "word)" stop */
  9060. break;
  9061. }
  9062. argv++;
  9063. }
  9064. continue;
  9065. }
  9066. if (rword == RES_CASE_BODY) { /* inside of a case branch */
  9067. debug_printf_exec("CASE_BODY cond_code:%d\n", cond_code);
  9068. if (cond_code != 0)
  9069. continue; /* not matched yet, skip this pipe */
  9070. }
  9071. if (rword == RES_ESAC) {
  9072. debug_printf_exec("ESAC cond_code:%d\n", cond_code);
  9073. if (case_word) {
  9074. /* "case" did not match anything: still set $? (to 0) */
  9075. G.last_exitcode = rcode = EXIT_SUCCESS;
  9076. }
  9077. }
  9078. #endif
  9079. /* Just pressing <enter> in shell should check for jobs.
  9080. * OTOH, in non-interactive shell this is useless
  9081. * and only leads to extra job checks */
  9082. if (pi->num_cmds == 0) {
  9083. if (G_interactive_fd)
  9084. goto check_jobs_and_continue;
  9085. continue;
  9086. }
  9087. /* After analyzing all keywords and conditions, we decided
  9088. * to execute this pipe. NB: have to do checkjobs(NULL)
  9089. * after run_pipe to collect any background children,
  9090. * even if list execution is to be stopped. */
  9091. debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
  9092. #if ENABLE_HUSH_LOOPS
  9093. G.flag_break_continue = 0;
  9094. #endif
  9095. rcode = r = run_pipe(pi); /* NB: rcode is a smalluint, r is int */
  9096. if (r != -1) {
  9097. /* We ran a builtin, function, or group.
  9098. * rcode is already known
  9099. * and we don't need to wait for anything. */
  9100. debug_printf_exec(": builtin/func exitcode %d\n", rcode);
  9101. G.last_exitcode = rcode;
  9102. check_and_run_traps();
  9103. #if ENABLE_HUSH_TRAP && ENABLE_HUSH_FUNCTIONS
  9104. rcode = G.last_exitcode; /* "return" in trap can change it, read back */
  9105. #endif
  9106. #if ENABLE_HUSH_LOOPS
  9107. /* Was it "break" or "continue"? */
  9108. if (G.flag_break_continue) {
  9109. smallint fbc = G.flag_break_continue;
  9110. /* We might fall into outer *loop*,
  9111. * don't want to break it too */
  9112. if (loop_top) {
  9113. G.depth_break_continue--;
  9114. if (G.depth_break_continue == 0)
  9115. G.flag_break_continue = 0;
  9116. /* else: e.g. "continue 2" should *break* once, *then* continue */
  9117. } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
  9118. if (G.depth_break_continue != 0 || fbc == BC_BREAK) {
  9119. checkjobs(NULL, 0 /*(no pid to wait for)*/);
  9120. break;
  9121. }
  9122. /* "continue": simulate end of loop */
  9123. rword = RES_DONE;
  9124. continue;
  9125. }
  9126. #endif
  9127. if (G_flag_return_in_progress == 1) {
  9128. checkjobs(NULL, 0 /*(no pid to wait for)*/);
  9129. break;
  9130. }
  9131. } else if (pi->followup == PIPE_BG) {
  9132. /* What does bash do with attempts to background builtins? */
  9133. /* even bash 3.2 doesn't do that well with nested bg:
  9134. * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
  9135. * I'm NOT treating inner &'s as jobs */
  9136. #if ENABLE_HUSH_JOB
  9137. if (G.run_list_level == 1)
  9138. insert_job_into_table(pi);
  9139. #endif
  9140. /* Last command's pid goes to $! */
  9141. G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
  9142. G.last_bg_pid_exitcode = 0;
  9143. debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
  9144. /* Check pi->pi_inverted? "! sleep 1 & echo $?": bash says 1. dash and ash say 0 */
  9145. rcode = EXIT_SUCCESS;
  9146. goto check_traps;
  9147. } else {
  9148. #if ENABLE_HUSH_JOB
  9149. if (G.run_list_level == 1 && G_interactive_fd) {
  9150. /* Waits for completion, then fg's main shell */
  9151. rcode = checkjobs_and_fg_shell(pi);
  9152. debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
  9153. goto check_traps;
  9154. }
  9155. #endif
  9156. /* This one just waits for completion */
  9157. rcode = checkjobs(pi, 0 /*(no pid to wait for)*/);
  9158. debug_printf_exec(": checkjobs exitcode %d\n", rcode);
  9159. check_traps:
  9160. G.last_exitcode = rcode;
  9161. check_and_run_traps();
  9162. #if ENABLE_HUSH_TRAP && ENABLE_HUSH_FUNCTIONS
  9163. rcode = G.last_exitcode; /* "return" in trap can change it, read back */
  9164. #endif
  9165. }
  9166. /* Handle "set -e" */
  9167. if (rcode != 0 && G.o_opt[OPT_O_ERREXIT]) {
  9168. debug_printf_exec("ERREXIT:1 errexit_depth:%d\n", G.errexit_depth);
  9169. if (G.errexit_depth == 0)
  9170. hush_exit(rcode);
  9171. }
  9172. G.errexit_depth = sv_errexit_depth;
  9173. /* Analyze how result affects subsequent commands */
  9174. #if ENABLE_HUSH_IF
  9175. if (rword == RES_IF || rword == RES_ELIF)
  9176. cond_code = rcode;
  9177. #endif
  9178. check_jobs_and_continue:
  9179. checkjobs(NULL, 0 /*(no pid to wait for)*/);
  9180. dont_check_jobs_but_continue: ;
  9181. #if ENABLE_HUSH_LOOPS
  9182. /* Beware of "while false; true; do ..."! */
  9183. if (pi->next
  9184. && (pi->next->res_word == RES_DO || pi->next->res_word == RES_DONE)
  9185. /* check for RES_DONE is needed for "while ...; do \n done" case */
  9186. ) {
  9187. if (rword == RES_WHILE) {
  9188. if (rcode) {
  9189. /* "while false; do...done" - exitcode 0 */
  9190. G.last_exitcode = rcode = EXIT_SUCCESS;
  9191. debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
  9192. break;
  9193. }
  9194. }
  9195. if (rword == RES_UNTIL) {
  9196. if (!rcode) {
  9197. debug_printf_exec(": until expr is true: breaking\n");
  9198. break;
  9199. }
  9200. }
  9201. }
  9202. #endif
  9203. } /* for (pi) */
  9204. #if ENABLE_HUSH_JOB
  9205. G.run_list_level--;
  9206. #endif
  9207. #if ENABLE_HUSH_LOOPS
  9208. if (loop_top)
  9209. G.depth_of_loop--;
  9210. free(for_list);
  9211. #endif
  9212. #if ENABLE_HUSH_CASE
  9213. free(case_word);
  9214. #endif
  9215. debug_leave();
  9216. debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
  9217. return rcode;
  9218. }
  9219. /* Select which version we will use */
  9220. static int run_and_free_list(struct pipe *pi)
  9221. {
  9222. int rcode = 0;
  9223. debug_printf_exec("run_and_free_list entered\n");
  9224. if (!G.o_opt[OPT_O_NOEXEC]) {
  9225. debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
  9226. rcode = run_list(pi);
  9227. }
  9228. /* free_pipe_list has the side effect of clearing memory.
  9229. * In the long run that function can be merged with run_list,
  9230. * but doing that now would hobble the debugging effort. */
  9231. free_pipe_list(pi);
  9232. debug_printf_exec("run_and_free_list return %d\n", rcode);
  9233. return rcode;
  9234. }
  9235. static void install_sighandlers(unsigned mask)
  9236. {
  9237. sighandler_t old_handler;
  9238. unsigned sig = 0;
  9239. while ((mask >>= 1) != 0) {
  9240. sig++;
  9241. if (!(mask & 1))
  9242. continue;
  9243. old_handler = install_sighandler(sig, pick_sighandler(sig));
  9244. /* POSIX allows shell to re-enable SIGCHLD
  9245. * even if it was SIG_IGN on entry.
  9246. * Therefore we skip IGN check for it:
  9247. */
  9248. if (sig == SIGCHLD)
  9249. continue;
  9250. /* Interactive bash re-enables SIGHUP which is SIG_IGNed on entry.
  9251. * Try:
  9252. * trap '' hup; bash; echo RET # type "kill -hup $$", see SIGHUP having effect
  9253. * trap '' hup; bash -c 'kill -hup $$; echo ALIVE' # here SIGHUP is SIG_IGNed
  9254. */
  9255. if (sig == SIGHUP && G_interactive_fd)
  9256. continue;
  9257. /* Unless one of the above signals, is it SIG_IGN? */
  9258. if (old_handler == SIG_IGN) {
  9259. /* oops... restore back to IGN, and record this fact */
  9260. install_sighandler(sig, old_handler);
  9261. #if ENABLE_HUSH_TRAP
  9262. if (!G_traps)
  9263. G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
  9264. free(G_traps[sig]);
  9265. G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
  9266. #endif
  9267. }
  9268. }
  9269. }
  9270. /* Called a few times only (or even once if "sh -c") */
  9271. static void install_special_sighandlers(void)
  9272. {
  9273. unsigned mask;
  9274. /* Which signals are shell-special? */
  9275. mask = (1 << SIGQUIT) | (1 << SIGCHLD);
  9276. if (G_interactive_fd) {
  9277. mask |= SPECIAL_INTERACTIVE_SIGS;
  9278. if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
  9279. mask |= SPECIAL_JOBSTOP_SIGS;
  9280. }
  9281. /* Careful, do not re-install handlers we already installed */
  9282. if (G.special_sig_mask != mask) {
  9283. unsigned diff = mask & ~G.special_sig_mask;
  9284. G.special_sig_mask = mask;
  9285. install_sighandlers(diff);
  9286. }
  9287. }
  9288. #if ENABLE_HUSH_JOB
  9289. /* helper */
  9290. /* Set handlers to restore tty pgrp and exit */
  9291. static void install_fatal_sighandlers(void)
  9292. {
  9293. unsigned mask;
  9294. /* We will restore tty pgrp on these signals */
  9295. mask = 0
  9296. /*+ (1 << SIGILL ) * HUSH_DEBUG*/
  9297. /*+ (1 << SIGFPE ) * HUSH_DEBUG*/
  9298. + (1 << SIGBUS ) * HUSH_DEBUG
  9299. + (1 << SIGSEGV) * HUSH_DEBUG
  9300. /*+ (1 << SIGTRAP) * HUSH_DEBUG*/
  9301. + (1 << SIGABRT)
  9302. /* bash 3.2 seems to handle these just like 'fatal' ones */
  9303. + (1 << SIGPIPE)
  9304. + (1 << SIGALRM)
  9305. /* if we are interactive, SIGHUP, SIGTERM and SIGINT are special sigs.
  9306. * if we aren't interactive... but in this case
  9307. * we never want to restore pgrp on exit, and this fn is not called
  9308. */
  9309. /*+ (1 << SIGHUP )*/
  9310. /*+ (1 << SIGTERM)*/
  9311. /*+ (1 << SIGINT )*/
  9312. ;
  9313. G_fatal_sig_mask = mask;
  9314. install_sighandlers(mask);
  9315. }
  9316. #endif
  9317. static int set_mode(int state, char mode, const char *o_opt)
  9318. {
  9319. int idx;
  9320. switch (mode) {
  9321. case 'n':
  9322. G.o_opt[OPT_O_NOEXEC] = state;
  9323. break;
  9324. case 'x':
  9325. IF_HUSH_MODE_X(G_x_mode = state;)
  9326. IF_HUSH_MODE_X(if (G.x_mode_fd <= 0) G.x_mode_fd = dup_CLOEXEC(2, 10);)
  9327. break;
  9328. case 'e':
  9329. G.o_opt[OPT_O_ERREXIT] = state;
  9330. break;
  9331. case 'o':
  9332. if (!o_opt) {
  9333. /* "set -o" or "set +o" without parameter.
  9334. * in bash, set -o produces this output:
  9335. * pipefail off
  9336. * and set +o:
  9337. * set +o pipefail
  9338. * We always use the second form.
  9339. */
  9340. const char *p = o_opt_strings;
  9341. idx = 0;
  9342. while (*p) {
  9343. printf("set %co %s\n", (G.o_opt[idx] ? '-' : '+'), p);
  9344. idx++;
  9345. p += strlen(p) + 1;
  9346. }
  9347. break;
  9348. }
  9349. idx = index_in_strings(o_opt_strings, o_opt);
  9350. if (idx >= 0) {
  9351. G.o_opt[idx] = state;
  9352. break;
  9353. }
  9354. /* fall through to error */
  9355. default:
  9356. return EXIT_FAILURE;
  9357. }
  9358. return EXIT_SUCCESS;
  9359. }
  9360. int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  9361. int hush_main(int argc, char **argv)
  9362. {
  9363. pid_t cached_getpid;
  9364. enum {
  9365. OPT_login = (1 << 0),
  9366. };
  9367. unsigned flags;
  9368. #if !BB_MMU
  9369. unsigned builtin_argc = 0;
  9370. #endif
  9371. char **e;
  9372. struct variable *cur_var;
  9373. struct variable *shell_ver;
  9374. INIT_G();
  9375. if (EXIT_SUCCESS != 0) /* if EXIT_SUCCESS == 0, it is already done */
  9376. G.last_exitcode = EXIT_SUCCESS;
  9377. #if ENABLE_HUSH_TRAP
  9378. # if ENABLE_HUSH_FUNCTIONS
  9379. G.return_exitcode = -1;
  9380. # endif
  9381. G.pre_trap_exitcode = -1;
  9382. #endif
  9383. #if ENABLE_HUSH_FAST
  9384. G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
  9385. #endif
  9386. #if !BB_MMU
  9387. G.argv0_for_re_execing = argv[0];
  9388. #endif
  9389. cached_getpid = getpid(); /* for tcsetpgrp() during init */
  9390. G.root_pid = cached_getpid; /* for $PID (NOMMU can override via -$HEXPID:HEXPPID:...) */
  9391. G.root_ppid = getppid(); /* for $PPID (NOMMU can override) */
  9392. /* Deal with HUSH_VERSION */
  9393. debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
  9394. unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
  9395. shell_ver = xzalloc(sizeof(*shell_ver));
  9396. shell_ver->flg_export = 1;
  9397. shell_ver->flg_read_only = 1;
  9398. /* Code which handles ${var<op>...} needs writable values for all variables,
  9399. * therefore we xstrdup: */
  9400. shell_ver->varstr = xstrdup(hush_version_str);
  9401. /* Create shell local variables from the values
  9402. * currently living in the environment */
  9403. G.top_var = shell_ver;
  9404. cur_var = G.top_var;
  9405. e = environ;
  9406. if (e) while (*e) {
  9407. char *value = strchr(*e, '=');
  9408. if (value) { /* paranoia */
  9409. cur_var->next = xzalloc(sizeof(*cur_var));
  9410. cur_var = cur_var->next;
  9411. cur_var->varstr = *e;
  9412. cur_var->max_len = strlen(*e);
  9413. cur_var->flg_export = 1;
  9414. }
  9415. e++;
  9416. }
  9417. /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
  9418. debug_printf_env("putenv '%s'\n", shell_ver->varstr);
  9419. putenv(shell_ver->varstr);
  9420. /* Export PWD */
  9421. set_pwd_var(SETFLAG_EXPORT);
  9422. #if BASH_HOSTNAME_VAR
  9423. /* Set (but not export) HOSTNAME unless already set */
  9424. if (!get_local_var_value("HOSTNAME")) {
  9425. struct utsname uts;
  9426. uname(&uts);
  9427. set_local_var_from_halves("HOSTNAME", uts.nodename);
  9428. }
  9429. #endif
  9430. /* IFS is not inherited from the parent environment */
  9431. set_local_var_from_halves("IFS", defifs);
  9432. if (!get_local_var_value("PATH"))
  9433. set_local_var_from_halves("PATH", bb_default_root_path);
  9434. /* PS1/PS2 are set later, if we determine that we are interactive */
  9435. /* bash also exports SHLVL and _,
  9436. * and sets (but doesn't export) the following variables:
  9437. * BASH=/bin/bash
  9438. * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
  9439. * BASH_VERSION='3.2.0(1)-release'
  9440. * HOSTTYPE=i386
  9441. * MACHTYPE=i386-pc-linux-gnu
  9442. * OSTYPE=linux-gnu
  9443. * PPID=<NNNNN> - we also do it elsewhere
  9444. * EUID=<NNNNN>
  9445. * UID=<NNNNN>
  9446. * GROUPS=()
  9447. * LINES=<NNN>
  9448. * COLUMNS=<NNN>
  9449. * BASH_ARGC=()
  9450. * BASH_ARGV=()
  9451. * BASH_LINENO=()
  9452. * BASH_SOURCE=()
  9453. * DIRSTACK=()
  9454. * PIPESTATUS=([0]="0")
  9455. * HISTFILE=/<xxx>/.bash_history
  9456. * HISTFILESIZE=500
  9457. * HISTSIZE=500
  9458. * MAILCHECK=60
  9459. * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
  9460. * SHELL=/bin/bash
  9461. * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
  9462. * TERM=dumb
  9463. * OPTERR=1
  9464. * OPTIND=1
  9465. * PS4='+ '
  9466. */
  9467. #if NUM_SCRIPTS > 0
  9468. if (argc < 0) {
  9469. char *script = get_script_content(-argc - 1);
  9470. G.global_argv = argv;
  9471. G.global_argc = string_array_len(argv);
  9472. //install_special_sighandlers(); - needed?
  9473. parse_and_run_string(script);
  9474. goto final_return;
  9475. }
  9476. #endif
  9477. /* Initialize some more globals to non-zero values */
  9478. die_func = restore_ttypgrp_and__exit;
  9479. /* Shell is non-interactive at first. We need to call
  9480. * install_special_sighandlers() if we are going to execute "sh <script>",
  9481. * "sh -c <cmds>" or login shell's /etc/profile and friends.
  9482. * If we later decide that we are interactive, we run install_special_sighandlers()
  9483. * in order to intercept (more) signals.
  9484. */
  9485. /* Parse options */
  9486. /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
  9487. flags = (argv[0] && argv[0][0] == '-') ? OPT_login : 0;
  9488. while (1) {
  9489. int opt = getopt(argc, argv, "+cexinsl"
  9490. #if !BB_MMU
  9491. "<:$:R:V:"
  9492. # if ENABLE_HUSH_FUNCTIONS
  9493. "F:"
  9494. # endif
  9495. #endif
  9496. );
  9497. if (opt <= 0)
  9498. break;
  9499. switch (opt) {
  9500. case 'c':
  9501. /* Note: -c is not an option with param!
  9502. * "hush -c -l SCRIPT" is valid. "hush -cSCRIPT" is not.
  9503. */
  9504. G.opt_c = 1;
  9505. break;
  9506. case 'i':
  9507. /* Well, we cannot just declare interactiveness,
  9508. * we have to have some stuff (ctty, etc) */
  9509. /* G_interactive_fd++; */
  9510. break;
  9511. case 's':
  9512. G.opt_s = 1;
  9513. break;
  9514. case 'l':
  9515. flags |= OPT_login;
  9516. break;
  9517. #if !BB_MMU
  9518. case '<': /* "big heredoc" support */
  9519. full_write1_str(optarg);
  9520. _exit(0);
  9521. case '$': {
  9522. unsigned long long empty_trap_mask;
  9523. G.root_pid = bb_strtou(optarg, &optarg, 16);
  9524. optarg++;
  9525. G.root_ppid = bb_strtou(optarg, &optarg, 16);
  9526. optarg++;
  9527. G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
  9528. optarg++;
  9529. G.last_exitcode = bb_strtou(optarg, &optarg, 16);
  9530. optarg++;
  9531. builtin_argc = bb_strtou(optarg, &optarg, 16);
  9532. optarg++;
  9533. empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
  9534. if (empty_trap_mask != 0) {
  9535. IF_HUSH_TRAP(int sig;)
  9536. install_special_sighandlers();
  9537. # if ENABLE_HUSH_TRAP
  9538. G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
  9539. for (sig = 1; sig < NSIG; sig++) {
  9540. if (empty_trap_mask & (1LL << sig)) {
  9541. G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
  9542. install_sighandler(sig, SIG_IGN);
  9543. }
  9544. }
  9545. # endif
  9546. }
  9547. # if ENABLE_HUSH_LOOPS
  9548. optarg++;
  9549. G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
  9550. # endif
  9551. /* Suppress "killed by signal" message, -$ hack is used
  9552. * for subshells: echo `sh -c 'kill -9 $$'`
  9553. * should be silent.
  9554. */
  9555. IF_HUSH_JOB(G.run_list_level = 1;)
  9556. # if ENABLE_HUSH_FUNCTIONS
  9557. /* nommu uses re-exec trick for "... | func | ...",
  9558. * should allow "return".
  9559. * This accidentally allows returns in subshells.
  9560. */
  9561. G_flag_return_in_progress = -1;
  9562. # endif
  9563. break;
  9564. }
  9565. case 'R':
  9566. case 'V':
  9567. set_local_var(xstrdup(optarg), opt == 'R' ? SETFLAG_MAKE_RO : 0);
  9568. break;
  9569. # if ENABLE_HUSH_FUNCTIONS
  9570. case 'F': {
  9571. struct function *funcp = new_function(optarg);
  9572. /* funcp->name is already set to optarg */
  9573. /* funcp->body is set to NULL. It's a special case. */
  9574. funcp->body_as_string = argv[optind];
  9575. optind++;
  9576. break;
  9577. }
  9578. # endif
  9579. #endif
  9580. case 'n':
  9581. case 'x':
  9582. case 'e':
  9583. if (set_mode(1, opt, NULL) == 0) /* no error */
  9584. break;
  9585. default:
  9586. bb_show_usage();
  9587. }
  9588. } /* option parsing loop */
  9589. /* Skip options. Try "hush -l": $1 should not be "-l"! */
  9590. G.global_argc = argc - (optind - 1);
  9591. G.global_argv = argv + (optind - 1);
  9592. G.global_argv[0] = argv[0];
  9593. /* If we are login shell... */
  9594. if (flags & OPT_login) {
  9595. const char *hp = NULL;
  9596. HFILE *input;
  9597. debug_printf("sourcing /etc/profile\n");
  9598. input = hfopen("/etc/profile");
  9599. run_profile:
  9600. if (input != NULL) {
  9601. install_special_sighandlers();
  9602. parse_and_run_file(input);
  9603. hfclose(input);
  9604. }
  9605. /* bash: after sourcing /etc/profile,
  9606. * tries to source (in the given order):
  9607. * ~/.bash_profile, ~/.bash_login, ~/.profile,
  9608. * stopping on first found. --noprofile turns this off.
  9609. * bash also sources ~/.bash_logout on exit.
  9610. * If called as sh, skips .bash_XXX files.
  9611. */
  9612. if (!hp) { /* unless we looped on the "goto" already */
  9613. hp = get_local_var_value("HOME");
  9614. if (hp && hp[0]) {
  9615. debug_printf("sourcing ~/.profile\n");
  9616. hp = concat_path_file(hp, ".profile");
  9617. input = hfopen(hp);
  9618. free((char*)hp);
  9619. goto run_profile;
  9620. }
  9621. }
  9622. }
  9623. /* -c takes effect *after* -l */
  9624. if (G.opt_c) {
  9625. /* Possibilities:
  9626. * sh ... -c 'script'
  9627. * sh ... -c 'script' ARG0 [ARG1...]
  9628. * On NOMMU, if builtin_argc != 0,
  9629. * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
  9630. * "" needs to be replaced with NULL
  9631. * and BARGV vector fed to builtin function.
  9632. * Note: the form without ARG0 never happens:
  9633. * sh ... -c 'builtin' BARGV... ""
  9634. */
  9635. char *script;
  9636. install_special_sighandlers();
  9637. G.global_argc--;
  9638. G.global_argv++;
  9639. #if !BB_MMU
  9640. if (builtin_argc) {
  9641. /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
  9642. const struct built_in_command *x;
  9643. x = find_builtin(G.global_argv[0]);
  9644. if (x) { /* paranoia */
  9645. argv = G.global_argv;
  9646. G.global_argc -= builtin_argc + 1; /* skip [BARGV...] "" */
  9647. G.global_argv += builtin_argc + 1;
  9648. G.global_argv[-1] = NULL; /* replace "" */
  9649. G.last_exitcode = x->b_function(argv);
  9650. }
  9651. goto final_return;
  9652. }
  9653. #endif
  9654. script = G.global_argv[0];
  9655. if (!script)
  9656. bb_error_msg_and_die(bb_msg_requires_arg, "-c");
  9657. if (!G.global_argv[1]) {
  9658. /* -c 'script' (no params): prevent empty $0 */
  9659. G.global_argv[0] = argv[0];
  9660. } else { /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
  9661. G.global_argc--;
  9662. G.global_argv++;
  9663. }
  9664. parse_and_run_string(script);
  9665. goto final_return;
  9666. }
  9667. /* -s is: hush -s ARGV1 ARGV2 (no SCRIPT) */
  9668. if (!G.opt_s && G.global_argv[1]) {
  9669. HFILE *input;
  9670. /*
  9671. * "bash <script>" (which is never interactive (unless -i?))
  9672. * sources $BASH_ENV here (without scanning $PATH).
  9673. * If called as sh, does the same but with $ENV.
  9674. * Also NB, per POSIX, $ENV should undergo parameter expansion.
  9675. */
  9676. G.global_argc--;
  9677. G.global_argv++;
  9678. debug_printf("running script '%s'\n", G.global_argv[0]);
  9679. xfunc_error_retval = 127; /* for "hush /does/not/exist" case */
  9680. input = hfopen(G.global_argv[0]);
  9681. if (!input) {
  9682. bb_simple_perror_msg_and_die(G.global_argv[0]);
  9683. }
  9684. xfunc_error_retval = 1;
  9685. install_special_sighandlers();
  9686. parse_and_run_file(input);
  9687. #if ENABLE_FEATURE_CLEAN_UP
  9688. hfclose(input);
  9689. #endif
  9690. goto final_return;
  9691. }
  9692. /* "implicit" -s: bare interactive hush shows 's' in $- */
  9693. G.opt_s = 1;
  9694. /* Up to here, shell was non-interactive. Now it may become one.
  9695. * NB: don't forget to (re)run install_special_sighandlers() as needed.
  9696. */
  9697. /* A shell is interactive if the '-i' flag was given,
  9698. * or if all of the following conditions are met:
  9699. * no -c command
  9700. * no arguments remaining or the -s flag given
  9701. * standard input is a terminal
  9702. * standard output is a terminal
  9703. * Refer to Posix.2, the description of the 'sh' utility.
  9704. */
  9705. #if ENABLE_HUSH_JOB
  9706. if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
  9707. G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
  9708. debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
  9709. if (G_saved_tty_pgrp < 0)
  9710. G_saved_tty_pgrp = 0;
  9711. /* try to dup stdin to high fd#, >= 255 */
  9712. G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, 254);
  9713. if (G_interactive_fd < 0) {
  9714. /* try to dup to any fd */
  9715. G_interactive_fd = dup(STDIN_FILENO);
  9716. if (G_interactive_fd < 0) {
  9717. /* give up */
  9718. G_interactive_fd = 0;
  9719. G_saved_tty_pgrp = 0;
  9720. }
  9721. }
  9722. }
  9723. debug_printf("interactive_fd:%d\n", G_interactive_fd);
  9724. if (G_interactive_fd) {
  9725. close_on_exec_on(G_interactive_fd);
  9726. if (G_saved_tty_pgrp) {
  9727. /* If we were run as 'hush &', sleep until we are
  9728. * in the foreground (tty pgrp == our pgrp).
  9729. * If we get started under a job aware app (like bash),
  9730. * make sure we are now in charge so we don't fight over
  9731. * who gets the foreground */
  9732. while (1) {
  9733. pid_t shell_pgrp = getpgrp();
  9734. G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
  9735. if (G_saved_tty_pgrp == shell_pgrp)
  9736. break;
  9737. /* send TTIN to ourself (should stop us) */
  9738. kill(- shell_pgrp, SIGTTIN);
  9739. }
  9740. }
  9741. /* Install more signal handlers */
  9742. install_special_sighandlers();
  9743. if (G_saved_tty_pgrp) {
  9744. /* Set other signals to restore saved_tty_pgrp */
  9745. install_fatal_sighandlers();
  9746. /* Put ourselves in our own process group
  9747. * (bash, too, does this only if ctty is available) */
  9748. bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
  9749. /* Grab control of the terminal */
  9750. tcsetpgrp(G_interactive_fd, cached_getpid);
  9751. }
  9752. enable_restore_tty_pgrp_on_exit();
  9753. # if ENABLE_FEATURE_EDITING
  9754. G.line_input_state = new_line_input_t(FOR_SHELL);
  9755. # if EDITING_HAS_get_exe_name
  9756. G.line_input_state->get_exe_name = get_builtin_name;
  9757. # endif
  9758. # endif
  9759. # if ENABLE_HUSH_SAVEHISTORY && MAX_HISTORY > 0
  9760. {
  9761. const char *hp = get_local_var_value("HISTFILE");
  9762. if (!hp) {
  9763. hp = get_local_var_value("HOME");
  9764. if (hp)
  9765. hp = concat_path_file(hp, ".hush_history");
  9766. } else {
  9767. hp = xstrdup(hp);
  9768. }
  9769. if (hp) {
  9770. G.line_input_state->hist_file = hp;
  9771. //set_local_var(xasprintf("HISTFILE=%s", ...));
  9772. }
  9773. # if ENABLE_FEATURE_SH_HISTFILESIZE
  9774. hp = get_local_var_value("HISTFILESIZE");
  9775. G.line_input_state->max_history = size_from_HISTFILESIZE(hp);
  9776. # endif
  9777. }
  9778. # endif
  9779. } else {
  9780. install_special_sighandlers();
  9781. }
  9782. #elif ENABLE_HUSH_INTERACTIVE
  9783. /* No job control compiled in, only prompt/line editing */
  9784. if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
  9785. G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, 254);
  9786. if (G_interactive_fd < 0) {
  9787. /* try to dup to any fd */
  9788. G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, -1);
  9789. if (G_interactive_fd < 0)
  9790. /* give up */
  9791. G_interactive_fd = 0;
  9792. }
  9793. }
  9794. if (G_interactive_fd) {
  9795. close_on_exec_on(G_interactive_fd);
  9796. }
  9797. install_special_sighandlers();
  9798. #else
  9799. /* We have interactiveness code disabled */
  9800. install_special_sighandlers();
  9801. #endif
  9802. /* bash:
  9803. * if interactive but not a login shell, sources ~/.bashrc
  9804. * (--norc turns this off, --rcfile <file> overrides)
  9805. */
  9806. if (G_interactive_fd) {
  9807. #if ENABLE_HUSH_INTERACTIVE && ENABLE_FEATURE_EDITING_FANCY_PROMPT
  9808. /* Set (but not export) PS1/2 unless already set */
  9809. if (!get_local_var_value("PS1"))
  9810. set_local_var_from_halves("PS1", "\\w \\$ ");
  9811. if (!get_local_var_value("PS2"))
  9812. set_local_var_from_halves("PS2", "> ");
  9813. #endif
  9814. if (!ENABLE_FEATURE_SH_EXTRA_QUIET) {
  9815. /* note: ash and hush share this string */
  9816. printf("\n\n%s %s\n"
  9817. IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
  9818. "\n",
  9819. bb_banner,
  9820. "hush - the humble shell"
  9821. );
  9822. }
  9823. }
  9824. parse_and_run_file(hfopen(NULL)); /* stdin */
  9825. final_return:
  9826. hush_exit(G.last_exitcode);
  9827. }
  9828. /*
  9829. * Built-ins
  9830. */
  9831. static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
  9832. {
  9833. return 0;
  9834. }
  9835. #if ENABLE_HUSH_TEST || ENABLE_HUSH_ECHO || ENABLE_HUSH_PRINTF || ENABLE_HUSH_KILL
  9836. static NOINLINE int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
  9837. {
  9838. int argc = string_array_len(argv);
  9839. return applet_main_func(argc, argv);
  9840. }
  9841. #endif
  9842. #if ENABLE_HUSH_TEST || BASH_TEST2
  9843. static int FAST_FUNC builtin_test(char **argv)
  9844. {
  9845. return run_applet_main(argv, test_main);
  9846. }
  9847. #endif
  9848. #if ENABLE_HUSH_ECHO
  9849. static int FAST_FUNC builtin_echo(char **argv)
  9850. {
  9851. return run_applet_main(argv, echo_main);
  9852. }
  9853. #endif
  9854. #if ENABLE_HUSH_PRINTF
  9855. static int FAST_FUNC builtin_printf(char **argv)
  9856. {
  9857. return run_applet_main(argv, printf_main);
  9858. }
  9859. #endif
  9860. #if ENABLE_HUSH_HELP
  9861. static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
  9862. {
  9863. const struct built_in_command *x;
  9864. printf(
  9865. "Built-in commands:\n"
  9866. "------------------\n");
  9867. for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
  9868. if (x->b_descr)
  9869. printf("%-10s%s\n", x->b_cmd, x->b_descr);
  9870. }
  9871. return EXIT_SUCCESS;
  9872. }
  9873. #endif
  9874. #if MAX_HISTORY && ENABLE_FEATURE_EDITING
  9875. static int FAST_FUNC builtin_history(char **argv UNUSED_PARAM)
  9876. {
  9877. show_history(G.line_input_state);
  9878. return EXIT_SUCCESS;
  9879. }
  9880. #endif
  9881. static char **skip_dash_dash(char **argv)
  9882. {
  9883. argv++;
  9884. if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
  9885. argv++;
  9886. return argv;
  9887. }
  9888. static int FAST_FUNC builtin_cd(char **argv)
  9889. {
  9890. const char *newdir;
  9891. argv = skip_dash_dash(argv);
  9892. newdir = argv[0];
  9893. if (newdir == NULL) {
  9894. /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
  9895. * bash says "bash: cd: HOME not set" and does nothing
  9896. * (exitcode 1)
  9897. */
  9898. const char *home = get_local_var_value("HOME");
  9899. newdir = home ? home : "/";
  9900. }
  9901. if (chdir(newdir)) {
  9902. /* Mimic bash message exactly */
  9903. bb_perror_msg("cd: %s", newdir);
  9904. return EXIT_FAILURE;
  9905. }
  9906. /* Read current dir (get_cwd(1) is inside) and set PWD.
  9907. * Note: do not enforce exporting. If PWD was unset or unexported,
  9908. * set it again, but do not export. bash does the same.
  9909. */
  9910. set_pwd_var(/*flag:*/ 0);
  9911. return EXIT_SUCCESS;
  9912. }
  9913. static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
  9914. {
  9915. puts(get_cwd(0));
  9916. return EXIT_SUCCESS;
  9917. }
  9918. static int FAST_FUNC builtin_eval(char **argv)
  9919. {
  9920. argv = skip_dash_dash(argv);
  9921. if (!argv[0])
  9922. return EXIT_SUCCESS;
  9923. IF_HUSH_MODE_X(G.x_mode_depth++;)
  9924. //bb_error_msg("%s: ++x_mode_depth=%d", __func__, G.x_mode_depth);
  9925. if (!argv[1]) {
  9926. /* bash:
  9927. * eval "echo Hi; done" ("done" is syntax error):
  9928. * "echo Hi" will not execute too.
  9929. */
  9930. parse_and_run_string(argv[0]);
  9931. } else {
  9932. /* "The eval utility shall construct a command by
  9933. * concatenating arguments together, separating
  9934. * each with a <space> character."
  9935. */
  9936. char *str, *p;
  9937. unsigned len = 0;
  9938. char **pp = argv;
  9939. do
  9940. len += strlen(*pp) + 1;
  9941. while (*++pp);
  9942. str = p = xmalloc(len);
  9943. pp = argv;
  9944. for (;;) {
  9945. p = stpcpy(p, *pp);
  9946. pp++;
  9947. if (!*pp)
  9948. break;
  9949. *p++ = ' ';
  9950. }
  9951. parse_and_run_string(str);
  9952. free(str);
  9953. }
  9954. IF_HUSH_MODE_X(G.x_mode_depth--;)
  9955. //bb_error_msg("%s: --x_mode_depth=%d", __func__, G.x_mode_depth);
  9956. return G.last_exitcode;
  9957. }
  9958. static int FAST_FUNC builtin_exec(char **argv)
  9959. {
  9960. argv = skip_dash_dash(argv);
  9961. if (argv[0] == NULL)
  9962. return EXIT_SUCCESS; /* bash does this */
  9963. /* Careful: we can end up here after [v]fork. Do not restore
  9964. * tty pgrp then, only top-level shell process does that */
  9965. if (G_saved_tty_pgrp && getpid() == G.root_pid)
  9966. tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
  9967. /* Saved-redirect fds, script fds and G_interactive_fd are still
  9968. * open here. However, they are all CLOEXEC, and execv below
  9969. * closes them. Try interactive "exec ls -l /proc/self/fd",
  9970. * it should show no extra open fds in the "ls" process.
  9971. * If we'd try to run builtins/NOEXECs, this would need improving.
  9972. */
  9973. //close_saved_fds_and_FILE_fds();
  9974. /* TODO: if exec fails, bash does NOT exit! We do.
  9975. * We'll need to undo trap cleanup (it's inside execvp_or_die)
  9976. * and tcsetpgrp, and this is inherently racy.
  9977. */
  9978. execvp_or_die(argv);
  9979. }
  9980. static int FAST_FUNC builtin_exit(char **argv)
  9981. {
  9982. debug_printf_exec("%s()\n", __func__);
  9983. /* interactive bash:
  9984. * # trap "echo EEE" EXIT
  9985. * # exit
  9986. * exit
  9987. * There are stopped jobs.
  9988. * (if there are _stopped_ jobs, running ones don't count)
  9989. * # exit
  9990. * exit
  9991. * EEE (then bash exits)
  9992. *
  9993. * TODO: we can use G.exiting = -1 as indicator "last cmd was exit"
  9994. */
  9995. /* note: EXIT trap is run by hush_exit */
  9996. argv = skip_dash_dash(argv);
  9997. if (argv[0] == NULL) {
  9998. #if ENABLE_HUSH_TRAP
  9999. if (G.pre_trap_exitcode >= 0) /* "exit" in trap uses $? from before the trap */
  10000. hush_exit(G.pre_trap_exitcode);
  10001. #endif
  10002. hush_exit(G.last_exitcode);
  10003. }
  10004. /* mimic bash: exit 123abc == exit 255 + error msg */
  10005. xfunc_error_retval = 255;
  10006. /* bash: exit -2 == exit 254, no error msg */
  10007. hush_exit(xatoi(argv[0]) & 0xff);
  10008. }
  10009. #if ENABLE_HUSH_TYPE
  10010. /* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
  10011. static int FAST_FUNC builtin_type(char **argv)
  10012. {
  10013. int ret = EXIT_SUCCESS;
  10014. while (*++argv) {
  10015. const char *type;
  10016. char *path = NULL;
  10017. if (0) {} /* make conditional compile easier below */
  10018. /*else if (find_alias(*argv))
  10019. type = "an alias";*/
  10020. # if ENABLE_HUSH_FUNCTIONS
  10021. else if (find_function(*argv))
  10022. type = "a function";
  10023. # endif
  10024. else if (find_builtin(*argv))
  10025. type = "a shell builtin";
  10026. else if ((path = find_in_path(*argv)) != NULL)
  10027. type = path;
  10028. else {
  10029. bb_error_msg("type: %s: not found", *argv);
  10030. ret = EXIT_FAILURE;
  10031. continue;
  10032. }
  10033. printf("%s is %s\n", *argv, type);
  10034. free(path);
  10035. }
  10036. return ret;
  10037. }
  10038. #endif
  10039. #if ENABLE_HUSH_READ
  10040. /* Interruptibility of read builtin in bash
  10041. * (tested on bash-4.2.8 by sending signals (not by ^C)):
  10042. *
  10043. * Empty trap makes read ignore corresponding signal, for any signal.
  10044. *
  10045. * SIGINT:
  10046. * - terminates non-interactive shell;
  10047. * - interrupts read in interactive shell;
  10048. * if it has non-empty trap:
  10049. * - executes trap and returns to command prompt in interactive shell;
  10050. * - executes trap and returns to read in non-interactive shell;
  10051. * SIGTERM:
  10052. * - is ignored (does not interrupt) read in interactive shell;
  10053. * - terminates non-interactive shell;
  10054. * if it has non-empty trap:
  10055. * - executes trap and returns to read;
  10056. * SIGHUP:
  10057. * - terminates shell (regardless of interactivity);
  10058. * if it has non-empty trap:
  10059. * - executes trap and returns to read;
  10060. * SIGCHLD from children:
  10061. * - does not interrupt read regardless of interactivity:
  10062. * try: sleep 1 & read x; echo $x
  10063. */
  10064. static int FAST_FUNC builtin_read(char **argv)
  10065. {
  10066. const char *r;
  10067. struct builtin_read_params params;
  10068. memset(&params, 0, sizeof(params));
  10069. /* "!": do not abort on errors.
  10070. * Option string must start with "sr" to match BUILTIN_READ_xxx
  10071. */
  10072. params.read_flags = getopt32(argv,
  10073. # if BASH_READ_D
  10074. "!srn:p:t:u:d:", &params.opt_n, &params.opt_p, &params.opt_t, &params.opt_u, &params.opt_d
  10075. # else
  10076. "!srn:p:t:u:", &params.opt_n, &params.opt_p, &params.opt_t, &params.opt_u
  10077. # endif
  10078. );
  10079. if ((uint32_t)params.read_flags == (uint32_t)-1)
  10080. return EXIT_FAILURE;
  10081. argv += optind;
  10082. params.argv = argv;
  10083. params.setvar = set_local_var_from_halves;
  10084. params.ifs = get_local_var_value("IFS"); /* can be NULL */
  10085. again:
  10086. r = shell_builtin_read(&params);
  10087. if ((uintptr_t)r == 1 && errno == EINTR) {
  10088. unsigned sig = check_and_run_traps();
  10089. if (sig != SIGINT)
  10090. goto again;
  10091. }
  10092. if ((uintptr_t)r > 1) {
  10093. bb_simple_error_msg(r);
  10094. r = (char*)(uintptr_t)1;
  10095. }
  10096. return (uintptr_t)r;
  10097. }
  10098. #endif
  10099. #if ENABLE_HUSH_UMASK
  10100. static int FAST_FUNC builtin_umask(char **argv)
  10101. {
  10102. int rc;
  10103. mode_t mask;
  10104. rc = 1;
  10105. mask = umask(0);
  10106. argv = skip_dash_dash(argv);
  10107. if (argv[0]) {
  10108. mode_t old_mask = mask;
  10109. /* numeric umasks are taken as-is */
  10110. /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
  10111. if (!isdigit(argv[0][0]))
  10112. mask ^= 0777;
  10113. mask = bb_parse_mode(argv[0], mask);
  10114. if (!isdigit(argv[0][0]))
  10115. mask ^= 0777;
  10116. if ((unsigned)mask > 0777) {
  10117. mask = old_mask;
  10118. /* bash messages:
  10119. * bash: umask: 'q': invalid symbolic mode operator
  10120. * bash: umask: 999: octal number out of range
  10121. */
  10122. bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
  10123. rc = 0;
  10124. }
  10125. } else {
  10126. /* Mimic bash */
  10127. printf("%04o\n", (unsigned) mask);
  10128. /* fall through and restore mask which we set to 0 */
  10129. }
  10130. umask(mask);
  10131. return !rc; /* rc != 0 - success */
  10132. }
  10133. #endif
  10134. #if ENABLE_HUSH_EXPORT || ENABLE_HUSH_TRAP
  10135. static void print_escaped(const char *s)
  10136. {
  10137. if (*s == '\'')
  10138. goto squote;
  10139. do {
  10140. const char *p = strchrnul(s, '\'');
  10141. /* print 'xxxx', possibly just '' */
  10142. printf("'%.*s'", (int)(p - s), s);
  10143. if (*p == '\0')
  10144. break;
  10145. s = p;
  10146. squote:
  10147. /* s points to '; print "'''...'''" */
  10148. putchar('"');
  10149. do putchar('\''); while (*++s == '\'');
  10150. putchar('"');
  10151. } while (*s);
  10152. }
  10153. #endif
  10154. #if ENABLE_HUSH_EXPORT || ENABLE_HUSH_LOCAL || ENABLE_HUSH_READONLY
  10155. static int helper_export_local(char **argv, unsigned flags)
  10156. {
  10157. do {
  10158. char *name = *argv;
  10159. const char *name_end = endofname(name);
  10160. if (*name_end == '\0') {
  10161. struct variable *var, **vpp;
  10162. vpp = get_ptr_to_local_var(name, name_end - name);
  10163. var = vpp ? *vpp : NULL;
  10164. if (flags & SETFLAG_UNEXPORT) {
  10165. /* export -n NAME (without =VALUE) */
  10166. if (var) {
  10167. var->flg_export = 0;
  10168. debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
  10169. unsetenv(name);
  10170. } /* else: export -n NOT_EXISTING_VAR: no-op */
  10171. continue;
  10172. }
  10173. if (flags & SETFLAG_EXPORT) {
  10174. /* export NAME (without =VALUE) */
  10175. if (var) {
  10176. var->flg_export = 1;
  10177. debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
  10178. putenv(var->varstr);
  10179. continue;
  10180. }
  10181. }
  10182. if (flags & SETFLAG_MAKE_RO) {
  10183. /* readonly NAME (without =VALUE) */
  10184. if (var) {
  10185. var->flg_read_only = 1;
  10186. continue;
  10187. }
  10188. }
  10189. # if ENABLE_HUSH_LOCAL
  10190. /* Is this "local" bltin? */
  10191. if (!(flags & (SETFLAG_EXPORT|SETFLAG_UNEXPORT|SETFLAG_MAKE_RO))) {
  10192. unsigned lvl = flags >> SETFLAG_VARLVL_SHIFT;
  10193. if (var && var->var_nest_level == lvl) {
  10194. /* "local x=abc; ...; local x" - ignore second local decl */
  10195. continue;
  10196. }
  10197. }
  10198. # endif
  10199. /* Exporting non-existing variable.
  10200. * bash does not put it in environment,
  10201. * but remembers that it is exported,
  10202. * and does put it in env when it is set later.
  10203. * We just set it to "" and export.
  10204. */
  10205. /* Or, it's "local NAME" (without =VALUE).
  10206. * bash sets the value to "".
  10207. */
  10208. /* Or, it's "readonly NAME" (without =VALUE).
  10209. * bash remembers NAME and disallows its creation
  10210. * in the future.
  10211. */
  10212. name = xasprintf("%s=", name);
  10213. } else {
  10214. if (*name_end != '=') {
  10215. bb_error_msg("'%s': bad variable name", name);
  10216. /* do not parse following argv[]s: */
  10217. return 1;
  10218. }
  10219. /* (Un)exporting/making local NAME=VALUE */
  10220. name = xstrdup(name);
  10221. /* Testcase: export PS1='\w \$ ' */
  10222. unbackslash(name);
  10223. }
  10224. debug_printf_env("%s: set_local_var('%s')\n", __func__, name);
  10225. if (set_local_var(name, flags))
  10226. return EXIT_FAILURE;
  10227. } while (*++argv);
  10228. return EXIT_SUCCESS;
  10229. }
  10230. #endif
  10231. #if ENABLE_HUSH_EXPORT
  10232. static int FAST_FUNC builtin_export(char **argv)
  10233. {
  10234. unsigned opt_unexport;
  10235. # if ENABLE_HUSH_EXPORT_N
  10236. /* "!": do not abort on errors */
  10237. opt_unexport = getopt32(argv, "!n");
  10238. if (opt_unexport == (uint32_t)-1)
  10239. return EXIT_FAILURE;
  10240. argv += optind;
  10241. # else
  10242. opt_unexport = 0;
  10243. argv++;
  10244. # endif
  10245. if (argv[0] == NULL) {
  10246. char **e = environ;
  10247. if (e) {
  10248. while (*e) {
  10249. # if 0
  10250. puts(*e++);
  10251. # else
  10252. /* ash emits: export VAR='VAL'
  10253. * bash: declare -x VAR="VAL"
  10254. * we follow ash example */
  10255. const char *s = *e++;
  10256. const char *p = strchr(s, '=');
  10257. if (!p) /* wtf? take next variable */
  10258. continue;
  10259. /* export var= */
  10260. printf("export %.*s", (int)(p - s) + 1, s);
  10261. print_escaped(p + 1);
  10262. putchar('\n');
  10263. # endif
  10264. }
  10265. /*fflush_all(); - done after each builtin anyway */
  10266. }
  10267. return EXIT_SUCCESS;
  10268. }
  10269. return helper_export_local(argv, opt_unexport ? SETFLAG_UNEXPORT : SETFLAG_EXPORT);
  10270. }
  10271. #endif
  10272. #if ENABLE_HUSH_LOCAL
  10273. static int FAST_FUNC builtin_local(char **argv)
  10274. {
  10275. if (G.func_nest_level == 0) {
  10276. bb_error_msg("%s: not in a function", argv[0]);
  10277. return EXIT_FAILURE; /* bash compat */
  10278. }
  10279. argv++;
  10280. /* Since all builtins run in a nested variable level,
  10281. * need to use level - 1 here. Or else the variable will be removed at once
  10282. * after builtin returns.
  10283. */
  10284. return helper_export_local(argv, (G.var_nest_level - 1) << SETFLAG_VARLVL_SHIFT);
  10285. }
  10286. #endif
  10287. #if ENABLE_HUSH_READONLY
  10288. static int FAST_FUNC builtin_readonly(char **argv)
  10289. {
  10290. argv++;
  10291. if (*argv == NULL) {
  10292. /* bash: readonly [-p]: list all readonly VARs
  10293. * (-p has no effect in bash)
  10294. */
  10295. struct variable *e;
  10296. for (e = G.top_var; e; e = e->next) {
  10297. if (e->flg_read_only) {
  10298. //TODO: quote value: readonly VAR='VAL'
  10299. printf("readonly %s\n", e->varstr);
  10300. }
  10301. }
  10302. return EXIT_SUCCESS;
  10303. }
  10304. return helper_export_local(argv, SETFLAG_MAKE_RO);
  10305. }
  10306. #endif
  10307. #if ENABLE_HUSH_UNSET
  10308. /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
  10309. static int FAST_FUNC builtin_unset(char **argv)
  10310. {
  10311. int ret;
  10312. unsigned opts;
  10313. /* "!": do not abort on errors */
  10314. /* "+": stop at 1st non-option */
  10315. opts = getopt32(argv, "!+vf");
  10316. if (opts == (unsigned)-1)
  10317. return EXIT_FAILURE;
  10318. if (opts == 3) {
  10319. bb_simple_error_msg("unset: -v and -f are exclusive");
  10320. return EXIT_FAILURE;
  10321. }
  10322. argv += optind;
  10323. ret = EXIT_SUCCESS;
  10324. while (*argv) {
  10325. if (!(opts & 2)) { /* not -f */
  10326. if (unset_local_var(*argv)) {
  10327. /* unset <nonexistent_var> doesn't fail.
  10328. * Error is when one tries to unset RO var.
  10329. * Message was printed by unset_local_var. */
  10330. ret = EXIT_FAILURE;
  10331. }
  10332. }
  10333. # if ENABLE_HUSH_FUNCTIONS
  10334. else {
  10335. unset_func(*argv);
  10336. }
  10337. # endif
  10338. argv++;
  10339. }
  10340. return ret;
  10341. }
  10342. #endif
  10343. #if ENABLE_HUSH_SET
  10344. /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
  10345. * built-in 'set' handler
  10346. * SUSv3 says:
  10347. * set [-abCefhmnuvx] [-o option] [argument...]
  10348. * set [+abCefhmnuvx] [+o option] [argument...]
  10349. * set -- [argument...]
  10350. * set -o
  10351. * set +o
  10352. * Implementations shall support the options in both their hyphen and
  10353. * plus-sign forms. These options can also be specified as options to sh.
  10354. * Examples:
  10355. * Write out all variables and their values: set
  10356. * Set $1, $2, and $3 and set "$#" to 3: set c a b
  10357. * Turn on the -x and -v options: set -xv
  10358. * Unset all positional parameters: set --
  10359. * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
  10360. * Set the positional parameters to the expansion of x, even if x expands
  10361. * with a leading '-' or '+': set -- $x
  10362. *
  10363. * So far, we only support "set -- [argument...]" and some of the short names.
  10364. */
  10365. static int FAST_FUNC builtin_set(char **argv)
  10366. {
  10367. int n;
  10368. char **pp, **g_argv;
  10369. char *arg = *++argv;
  10370. if (arg == NULL) {
  10371. struct variable *e;
  10372. for (e = G.top_var; e; e = e->next)
  10373. puts(e->varstr);
  10374. return EXIT_SUCCESS;
  10375. }
  10376. do {
  10377. if (strcmp(arg, "--") == 0) {
  10378. ++argv;
  10379. goto set_argv;
  10380. }
  10381. if (arg[0] != '+' && arg[0] != '-')
  10382. break;
  10383. for (n = 1; arg[n]; ++n) {
  10384. if (set_mode((arg[0] == '-'), arg[n], argv[1])) {
  10385. bb_error_msg("%s: %s: invalid option", "set", arg);
  10386. return EXIT_FAILURE;
  10387. }
  10388. if (arg[n] == 'o' && argv[1])
  10389. argv++;
  10390. }
  10391. } while ((arg = *++argv) != NULL);
  10392. /* Now argv[0] is 1st argument */
  10393. if (arg == NULL)
  10394. return EXIT_SUCCESS;
  10395. set_argv:
  10396. /* NB: G.global_argv[0] ($0) is never freed/changed */
  10397. g_argv = G.global_argv;
  10398. if (G.global_args_malloced) {
  10399. pp = g_argv;
  10400. while (*++pp)
  10401. free(*pp);
  10402. g_argv[1] = NULL;
  10403. } else {
  10404. G.global_args_malloced = 1;
  10405. pp = xzalloc(sizeof(pp[0]) * 2);
  10406. pp[0] = g_argv[0]; /* retain $0 */
  10407. g_argv = pp;
  10408. }
  10409. /* This realloc's G.global_argv */
  10410. G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
  10411. G.global_argc = 1 + string_array_len(pp + 1);
  10412. return EXIT_SUCCESS;
  10413. }
  10414. #endif
  10415. static int FAST_FUNC builtin_shift(char **argv)
  10416. {
  10417. int n = 1;
  10418. argv = skip_dash_dash(argv);
  10419. if (argv[0]) {
  10420. n = bb_strtou(argv[0], NULL, 10);
  10421. if (errno || n < 0) {
  10422. /* shared string with ash.c */
  10423. bb_error_msg("Illegal number: %s", argv[0]);
  10424. /*
  10425. * ash aborts in this case.
  10426. * bash prints error message and set $? to 1.
  10427. * Interestingly, for "shift 99999" bash does not
  10428. * print error message, but does set $? to 1
  10429. * (and does no shifting at all).
  10430. */
  10431. }
  10432. }
  10433. if (n >= 0 && n < G.global_argc) {
  10434. if (G_global_args_malloced) {
  10435. int m = 1;
  10436. while (m <= n)
  10437. free(G.global_argv[m++]);
  10438. }
  10439. G.global_argc -= n;
  10440. memmove(&G.global_argv[1], &G.global_argv[n+1],
  10441. G.global_argc * sizeof(G.global_argv[0]));
  10442. return EXIT_SUCCESS;
  10443. }
  10444. return EXIT_FAILURE;
  10445. }
  10446. #if ENABLE_HUSH_GETOPTS
  10447. static int FAST_FUNC builtin_getopts(char **argv)
  10448. {
  10449. /* http://pubs.opengroup.org/onlinepubs/9699919799/utilities/getopts.html
  10450. TODO:
  10451. If a required argument is not found, and getopts is not silent,
  10452. a question mark (?) is placed in VAR, OPTARG is unset, and a
  10453. diagnostic message is printed. If getopts is silent, then a
  10454. colon (:) is placed in VAR and OPTARG is set to the option
  10455. character found.
  10456. Test that VAR is a valid variable name?
  10457. "Whenever the shell is invoked, OPTIND shall be initialized to 1"
  10458. */
  10459. char cbuf[2];
  10460. const char *cp, *optstring, *var;
  10461. int c, n, exitcode, my_opterr;
  10462. unsigned count;
  10463. optstring = *++argv;
  10464. if (!optstring || !(var = *++argv)) {
  10465. bb_simple_error_msg("usage: getopts OPTSTRING VAR [ARGS]");
  10466. return EXIT_FAILURE;
  10467. }
  10468. if (argv[1])
  10469. argv[0] = G.global_argv[0]; /* for error messages in getopt() */
  10470. else
  10471. argv = G.global_argv;
  10472. cbuf[1] = '\0';
  10473. my_opterr = 0;
  10474. if (optstring[0] != ':') {
  10475. cp = get_local_var_value("OPTERR");
  10476. /* 0 if "OPTERR=0", 1 otherwise */
  10477. my_opterr = (!cp || NOT_LONE_CHAR(cp, '0'));
  10478. }
  10479. /* getopts stops on first non-option. Add "+" to force that */
  10480. /*if (optstring[0] != '+')*/ {
  10481. char *s = alloca(strlen(optstring) + 2);
  10482. sprintf(s, "+%s", optstring);
  10483. optstring = s;
  10484. }
  10485. /* Naively, now we should just
  10486. * cp = get_local_var_value("OPTIND");
  10487. * optind = cp ? atoi(cp) : 0;
  10488. * optarg = NULL;
  10489. * opterr = my_opterr;
  10490. * c = getopt(string_array_len(argv), argv, optstring);
  10491. * and be done? Not so fast...
  10492. * Unlike normal getopt() usage in C programs, here
  10493. * each successive call will (usually) have the same argv[] CONTENTS,
  10494. * but not the ADDRESSES. Worse yet, it's possible that between
  10495. * invocations of "getopts", there will be calls to shell builtins
  10496. * which use getopt() internally. Example:
  10497. * while getopts "abc" RES -a -bc -abc de; do
  10498. * unset -ff func
  10499. * done
  10500. * This would not work correctly: getopt() call inside "unset"
  10501. * modifies internal libc state which is tracking position in
  10502. * multi-option strings ("-abc"). At best, it can skip options
  10503. * or return the same option infinitely. With glibc implementation
  10504. * of getopt(), it would use outright invalid pointers and return
  10505. * garbage even _without_ "unset" mangling internal state.
  10506. *
  10507. * We resort to resetting getopt() state and calling it N times,
  10508. * until we get Nth result (or failure).
  10509. * (N == G.getopt_count is reset to 0 whenever OPTIND is [un]set).
  10510. */
  10511. GETOPT_RESET();
  10512. count = 0;
  10513. n = string_array_len(argv);
  10514. do {
  10515. optarg = NULL;
  10516. opterr = (count < G.getopt_count) ? 0 : my_opterr;
  10517. c = getopt(n, argv, optstring);
  10518. if (c < 0)
  10519. break;
  10520. count++;
  10521. } while (count <= G.getopt_count);
  10522. /* Set OPTIND. Prevent resetting of the magic counter! */
  10523. set_local_var_from_halves("OPTIND", utoa(optind));
  10524. G.getopt_count = count; /* "next time, give me N+1'th result" */
  10525. GETOPT_RESET(); /* just in case */
  10526. /* Set OPTARG */
  10527. /* Always set or unset, never left as-is, even on exit/error:
  10528. * "If no option was found, or if the option that was found
  10529. * does not have an option-argument, OPTARG shall be unset."
  10530. */
  10531. cp = optarg;
  10532. if (c == '?') {
  10533. /* If ":optstring" and unknown option is seen,
  10534. * it is stored to OPTARG.
  10535. */
  10536. if (optstring[1] == ':') {
  10537. cbuf[0] = optopt;
  10538. cp = cbuf;
  10539. }
  10540. }
  10541. if (cp)
  10542. set_local_var_from_halves("OPTARG", cp);
  10543. else
  10544. unset_local_var("OPTARG");
  10545. /* Convert -1 to "?" */
  10546. exitcode = EXIT_SUCCESS;
  10547. if (c < 0) { /* -1: end of options */
  10548. exitcode = EXIT_FAILURE;
  10549. c = '?';
  10550. }
  10551. /* Set VAR */
  10552. cbuf[0] = c;
  10553. set_local_var_from_halves(var, cbuf);
  10554. return exitcode;
  10555. }
  10556. #endif
  10557. static int FAST_FUNC builtin_source(char **argv)
  10558. {
  10559. char *arg_path, *filename;
  10560. HFILE *input;
  10561. save_arg_t sv;
  10562. char *args_need_save;
  10563. #if ENABLE_HUSH_FUNCTIONS
  10564. smallint sv_flg;
  10565. #endif
  10566. argv = skip_dash_dash(argv);
  10567. filename = argv[0];
  10568. if (!filename) {
  10569. /* bash says: "bash: .: filename argument required" */
  10570. return 2; /* bash compat */
  10571. }
  10572. arg_path = NULL;
  10573. if (!strchr(filename, '/')) {
  10574. arg_path = find_in_path(filename);
  10575. if (arg_path)
  10576. filename = arg_path;
  10577. else if (!ENABLE_HUSH_BASH_SOURCE_CURDIR) {
  10578. errno = ENOENT;
  10579. bb_simple_perror_msg(filename);
  10580. return EXIT_FAILURE;
  10581. }
  10582. }
  10583. input = hfopen(filename);
  10584. free(arg_path);
  10585. if (!input) {
  10586. bb_perror_msg("%s", filename);
  10587. /* POSIX: non-interactive shell should abort here,
  10588. * not merely fail. So far no one complained :)
  10589. */
  10590. return EXIT_FAILURE;
  10591. }
  10592. #if ENABLE_HUSH_FUNCTIONS
  10593. sv_flg = G_flag_return_in_progress;
  10594. /* "we are inside sourced file, ok to use return" */
  10595. G_flag_return_in_progress = -1;
  10596. #endif
  10597. args_need_save = argv[1]; /* used as a boolean variable */
  10598. if (args_need_save)
  10599. save_and_replace_G_args(&sv, argv);
  10600. /* "false; . ./empty_line; echo Zero:$?" should print 0 */
  10601. G.last_exitcode = 0;
  10602. parse_and_run_file(input);
  10603. hfclose(input);
  10604. if (args_need_save) /* can't use argv[1] instead: "shift" can mangle it */
  10605. restore_G_args(&sv, argv);
  10606. #if ENABLE_HUSH_FUNCTIONS
  10607. G_flag_return_in_progress = sv_flg;
  10608. #endif
  10609. return G.last_exitcode;
  10610. }
  10611. #if ENABLE_HUSH_TRAP
  10612. static int FAST_FUNC builtin_trap(char **argv)
  10613. {
  10614. int sig;
  10615. char *new_cmd;
  10616. if (!G_traps)
  10617. G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
  10618. argv++;
  10619. if (!*argv) {
  10620. int i;
  10621. /* No args: print all trapped */
  10622. for (i = 0; i < NSIG; ++i) {
  10623. if (G_traps[i]) {
  10624. printf("trap -- ");
  10625. print_escaped(G_traps[i]);
  10626. /* note: bash adds "SIG", but only if invoked
  10627. * as "bash". If called as "sh", or if set -o posix,
  10628. * then it prints short signal names.
  10629. * We are printing short names: */
  10630. printf(" %s\n", get_signame(i));
  10631. }
  10632. }
  10633. /*fflush_all(); - done after each builtin anyway */
  10634. return EXIT_SUCCESS;
  10635. }
  10636. new_cmd = NULL;
  10637. /* If first arg is a number: reset all specified signals */
  10638. sig = bb_strtou(*argv, NULL, 10);
  10639. if (errno == 0) {
  10640. int ret;
  10641. process_sig_list:
  10642. ret = EXIT_SUCCESS;
  10643. while (*argv) {
  10644. sighandler_t handler;
  10645. sig = get_signum(*argv++);
  10646. if (sig < 0) {
  10647. ret = EXIT_FAILURE;
  10648. /* Mimic bash message exactly */
  10649. bb_error_msg("trap: %s: invalid signal specification", argv[-1]);
  10650. continue;
  10651. }
  10652. free(G_traps[sig]);
  10653. G_traps[sig] = xstrdup(new_cmd);
  10654. debug_printf("trap: setting SIG%s (%i) to '%s'\n",
  10655. get_signame(sig), sig, G_traps[sig]);
  10656. /* There is no signal for 0 (EXIT) */
  10657. if (sig == 0)
  10658. continue;
  10659. if (new_cmd)
  10660. handler = (new_cmd[0] ? record_pending_signo : SIG_IGN);
  10661. else
  10662. /* We are removing trap handler */
  10663. handler = pick_sighandler(sig);
  10664. install_sighandler(sig, handler);
  10665. }
  10666. return ret;
  10667. }
  10668. if (!argv[1]) { /* no second arg */
  10669. bb_simple_error_msg("trap: invalid arguments");
  10670. return EXIT_FAILURE;
  10671. }
  10672. /* First arg is "-": reset all specified to default */
  10673. /* First arg is "--": skip it, the rest is "handler SIGs..." */
  10674. /* Everything else: set arg as signal handler
  10675. * (includes "" case, which ignores signal) */
  10676. if (argv[0][0] == '-') {
  10677. if (argv[0][1] == '\0') { /* "-" */
  10678. /* new_cmd remains NULL: "reset these sigs" */
  10679. goto reset_traps;
  10680. }
  10681. if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
  10682. argv++;
  10683. }
  10684. /* else: "-something", no special meaning */
  10685. }
  10686. new_cmd = *argv;
  10687. reset_traps:
  10688. argv++;
  10689. goto process_sig_list;
  10690. }
  10691. #endif
  10692. #if ENABLE_HUSH_JOB
  10693. static struct pipe *parse_jobspec(const char *str)
  10694. {
  10695. struct pipe *pi;
  10696. unsigned jobnum;
  10697. if (sscanf(str, "%%%u", &jobnum) != 1) {
  10698. if (str[0] != '%'
  10699. || (str[1] != '%' && str[1] != '+' && str[1] != '\0')
  10700. ) {
  10701. bb_error_msg("bad argument '%s'", str);
  10702. return NULL;
  10703. }
  10704. /* It is "%%", "%+" or "%" - current job */
  10705. jobnum = G.last_jobid;
  10706. if (jobnum == 0) {
  10707. bb_simple_error_msg("no current job");
  10708. return NULL;
  10709. }
  10710. }
  10711. for (pi = G.job_list; pi; pi = pi->next) {
  10712. if (pi->jobid == jobnum) {
  10713. return pi;
  10714. }
  10715. }
  10716. bb_error_msg("%u: no such job", jobnum);
  10717. return NULL;
  10718. }
  10719. static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
  10720. {
  10721. struct pipe *job;
  10722. const char *status_string;
  10723. checkjobs(NULL, 0 /*(no pid to wait for)*/);
  10724. for (job = G.job_list; job; job = job->next) {
  10725. if (job->alive_cmds == job->stopped_cmds)
  10726. status_string = "Stopped";
  10727. else
  10728. status_string = "Running";
  10729. printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
  10730. }
  10731. clean_up_last_dead_job();
  10732. return EXIT_SUCCESS;
  10733. }
  10734. /* built-in 'fg' and 'bg' handler */
  10735. static int FAST_FUNC builtin_fg_bg(char **argv)
  10736. {
  10737. int i;
  10738. struct pipe *pi;
  10739. if (!G_interactive_fd)
  10740. return EXIT_FAILURE;
  10741. /* If they gave us no args, assume they want the last backgrounded task */
  10742. if (!argv[1]) {
  10743. for (pi = G.job_list; pi; pi = pi->next) {
  10744. if (pi->jobid == G.last_jobid) {
  10745. goto found;
  10746. }
  10747. }
  10748. bb_error_msg("%s: no current job", argv[0]);
  10749. return EXIT_FAILURE;
  10750. }
  10751. pi = parse_jobspec(argv[1]);
  10752. if (!pi)
  10753. return EXIT_FAILURE;
  10754. found:
  10755. /* TODO: bash prints a string representation
  10756. * of job being foregrounded (like "sleep 1 | cat") */
  10757. if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
  10758. /* Put the job into the foreground. */
  10759. tcsetpgrp(G_interactive_fd, pi->pgrp);
  10760. }
  10761. /* Restart the processes in the job */
  10762. debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
  10763. for (i = 0; i < pi->num_cmds; i++) {
  10764. debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
  10765. }
  10766. pi->stopped_cmds = 0;
  10767. i = kill(- pi->pgrp, SIGCONT);
  10768. if (i < 0) {
  10769. if (errno == ESRCH) {
  10770. delete_finished_job(pi);
  10771. return EXIT_SUCCESS;
  10772. }
  10773. bb_simple_perror_msg("kill (SIGCONT)");
  10774. }
  10775. if (argv[0][0] == 'f') {
  10776. remove_job_from_table(pi); /* FG job shouldn't be in job table */
  10777. return checkjobs_and_fg_shell(pi);
  10778. }
  10779. return EXIT_SUCCESS;
  10780. }
  10781. #endif
  10782. #if ENABLE_HUSH_KILL
  10783. static int FAST_FUNC builtin_kill(char **argv)
  10784. {
  10785. int ret = 0;
  10786. # if ENABLE_HUSH_JOB
  10787. if (argv[1] && strcmp(argv[1], "-l") != 0) {
  10788. int i = 1;
  10789. do {
  10790. struct pipe *pi;
  10791. char *dst;
  10792. int j, n;
  10793. if (argv[i][0] != '%')
  10794. continue;
  10795. /*
  10796. * "kill %N" - job kill
  10797. * Converting to pgrp / pid kill
  10798. */
  10799. pi = parse_jobspec(argv[i]);
  10800. if (!pi) {
  10801. /* Eat bad jobspec */
  10802. j = i;
  10803. do {
  10804. j++;
  10805. argv[j - 1] = argv[j];
  10806. } while (argv[j]);
  10807. ret = 1;
  10808. i--;
  10809. continue;
  10810. }
  10811. /*
  10812. * In jobs started under job control, we signal
  10813. * entire process group by kill -PGRP_ID.
  10814. * This happens, f.e., in interactive shell.
  10815. *
  10816. * Otherwise, we signal each child via
  10817. * kill PID1 PID2 PID3.
  10818. * Testcases:
  10819. * sh -c 'sleep 1|sleep 1 & kill %1'
  10820. * sh -c 'true|sleep 2 & sleep 1; kill %1'
  10821. * sh -c 'true|sleep 1 & sleep 2; kill %1'
  10822. */
  10823. n = G_interactive_fd ? 1 : pi->num_cmds;
  10824. dst = alloca(n * sizeof(int)*4);
  10825. argv[i] = dst;
  10826. if (G_interactive_fd)
  10827. dst += sprintf(dst, " -%u", (int)pi->pgrp);
  10828. else for (j = 0; j < n; j++) {
  10829. struct command *cmd = &pi->cmds[j];
  10830. /* Skip exited members of the job */
  10831. if (cmd->pid == 0)
  10832. continue;
  10833. /*
  10834. * kill_main has matching code to expect
  10835. * leading space. Needed to not confuse
  10836. * negative pids with "kill -SIGNAL_NO" syntax
  10837. */
  10838. dst += sprintf(dst, " %u", (int)cmd->pid);
  10839. }
  10840. *dst = '\0';
  10841. } while (argv[++i]);
  10842. }
  10843. # endif
  10844. if (argv[1] || ret == 0) {
  10845. ret = run_applet_main(argv, kill_main);
  10846. }
  10847. /* else: ret = 1, "kill %bad_jobspec" case */
  10848. return ret;
  10849. }
  10850. #endif
  10851. #if ENABLE_HUSH_WAIT
  10852. /* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
  10853. # if !ENABLE_HUSH_JOB
  10854. # define wait_for_child_or_signal(pipe,pid) wait_for_child_or_signal(pid)
  10855. # endif
  10856. static int wait_for_child_or_signal(struct pipe *waitfor_pipe, pid_t waitfor_pid)
  10857. {
  10858. int ret = 0;
  10859. for (;;) {
  10860. int sig;
  10861. sigset_t oldset;
  10862. if (!sigisemptyset(&G.pending_set))
  10863. goto check_sig;
  10864. /* waitpid is not interruptible by SA_RESTARTed
  10865. * signals which we use. Thus, this ugly dance:
  10866. */
  10867. /* Make sure possible SIGCHLD is stored in kernel's
  10868. * pending signal mask before we call waitpid.
  10869. * Or else we may race with SIGCHLD, lose it,
  10870. * and get stuck in sigsuspend...
  10871. */
  10872. sigfillset(&oldset); /* block all signals, remember old set */
  10873. sigprocmask2(SIG_SETMASK, &oldset);
  10874. if (!sigisemptyset(&G.pending_set)) {
  10875. /* Crap! we raced with some signal! */
  10876. goto restore;
  10877. }
  10878. /*errno = 0; - checkjobs does this */
  10879. /* Can't pass waitfor_pipe into checkjobs(): it won't be interruptible */
  10880. ret = checkjobs(NULL, waitfor_pid); /* waitpid(WNOHANG) inside */
  10881. debug_printf_exec("checkjobs:%d\n", ret);
  10882. # if ENABLE_HUSH_JOB
  10883. if (waitfor_pipe) {
  10884. int rcode = job_exited_or_stopped(waitfor_pipe);
  10885. debug_printf_exec("job_exited_or_stopped:%d\n", rcode);
  10886. if (rcode >= 0) {
  10887. ret = rcode;
  10888. sigprocmask(SIG_SETMASK, &oldset, NULL);
  10889. break;
  10890. }
  10891. }
  10892. # endif
  10893. /* if ECHILD, there are no children (ret is -1 or 0) */
  10894. /* if ret == 0, no children changed state */
  10895. /* if ret != 0, it's exitcode+1 of exited waitfor_pid child */
  10896. if (errno == ECHILD || ret) {
  10897. ret--;
  10898. if (ret < 0) /* if ECHILD, may need to fix "ret" */
  10899. ret = 0;
  10900. # if ENABLE_HUSH_BASH_COMPAT
  10901. if (waitfor_pid == -1 && errno == ECHILD) {
  10902. /* exitcode of "wait -n" with no children is 127, not 0 */
  10903. ret = 127;
  10904. }
  10905. # endif
  10906. sigprocmask(SIG_SETMASK, &oldset, NULL);
  10907. break;
  10908. }
  10909. /* Wait for SIGCHLD or any other signal */
  10910. /* It is vitally important for sigsuspend that SIGCHLD has non-DFL handler! */
  10911. /* Note: sigsuspend invokes signal handler */
  10912. sigsuspend(&oldset);
  10913. /* ^^^ add "sigdelset(&oldset, SIGCHLD)" before sigsuspend
  10914. * to make sure SIGCHLD is not masked off?
  10915. * It was reported that this:
  10916. * fn() { : | return; }
  10917. * shopt -s lastpipe
  10918. * fn
  10919. * exec hush SCRIPT
  10920. * under bash 4.4.23 runs SCRIPT with SIGCHLD masked,
  10921. * making "wait" commands in SCRIPT block forever.
  10922. */
  10923. restore:
  10924. sigprocmask(SIG_SETMASK, &oldset, NULL);
  10925. check_sig:
  10926. /* So, did we get a signal? */
  10927. sig = check_and_run_traps();
  10928. if (sig /*&& sig != SIGCHLD - always true */) {
  10929. /* Do this for any (non-ignored) signal, not only for ^C */
  10930. ret = 128 | sig;
  10931. break;
  10932. }
  10933. /* SIGCHLD, or no signal, or ignored one, such as SIGQUIT. Repeat */
  10934. }
  10935. return ret;
  10936. }
  10937. static int FAST_FUNC builtin_wait(char **argv)
  10938. {
  10939. int ret;
  10940. int status;
  10941. argv = skip_dash_dash(argv);
  10942. # if ENABLE_HUSH_BASH_COMPAT
  10943. if (argv[0] && strcmp(argv[0], "-n") == 0) {
  10944. /* wait -n */
  10945. /* (bash accepts "wait -n PID" too and ignores PID) */
  10946. G.dead_job_exitcode = -1;
  10947. return wait_for_child_or_signal(NULL, -1 /*no job, wait for one job*/);
  10948. }
  10949. # endif
  10950. if (argv[0] == NULL) {
  10951. /* Don't care about wait results */
  10952. /* Note 1: must wait until there are no more children */
  10953. /* Note 2: must be interruptible */
  10954. /* Examples:
  10955. * $ sleep 3 & sleep 6 & wait
  10956. * [1] 30934 sleep 3
  10957. * [2] 30935 sleep 6
  10958. * [1] Done sleep 3
  10959. * [2] Done sleep 6
  10960. * $ sleep 3 & sleep 6 & wait
  10961. * [1] 30936 sleep 3
  10962. * [2] 30937 sleep 6
  10963. * [1] Done sleep 3
  10964. * ^C <-- after ~4 sec from keyboard
  10965. * $
  10966. */
  10967. return wait_for_child_or_signal(NULL, 0 /*no job and no pid to wait for*/);
  10968. }
  10969. do {
  10970. pid_t pid = bb_strtou(*argv, NULL, 10);
  10971. if (errno || pid <= 0) {
  10972. # if ENABLE_HUSH_JOB
  10973. if (argv[0][0] == '%') {
  10974. struct pipe *wait_pipe;
  10975. ret = 127; /* bash compat for bad jobspecs */
  10976. wait_pipe = parse_jobspec(*argv);
  10977. if (wait_pipe) {
  10978. ret = job_exited_or_stopped(wait_pipe);
  10979. if (ret < 0) {
  10980. ret = wait_for_child_or_signal(wait_pipe, 0);
  10981. } else {
  10982. /* waiting on "last dead job" removes it */
  10983. clean_up_last_dead_job();
  10984. }
  10985. }
  10986. /* else: parse_jobspec() already emitted error msg */
  10987. continue;
  10988. }
  10989. # endif
  10990. /* mimic bash message */
  10991. bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
  10992. ret = EXIT_FAILURE;
  10993. continue; /* bash checks all argv[] */
  10994. }
  10995. /* Do we have such child? */
  10996. ret = waitpid(pid, &status, WNOHANG);
  10997. if (ret < 0) {
  10998. /* No */
  10999. ret = 127;
  11000. if (errno == ECHILD) {
  11001. if (pid == G.last_bg_pid) {
  11002. /* "wait $!" but last bg task has already exited. Try:
  11003. * (sleep 1; exit 3) & sleep 2; echo $?; wait $!; echo $?
  11004. * In bash it prints exitcode 0, then 3.
  11005. * In dash, it is 127.
  11006. */
  11007. ret = G.last_bg_pid_exitcode;
  11008. } else {
  11009. /* Example: "wait 1". mimic bash message */
  11010. bb_error_msg("wait: pid %u is not a child of this shell", (unsigned)pid);
  11011. }
  11012. } else {
  11013. /* ??? */
  11014. bb_perror_msg("wait %s", *argv);
  11015. }
  11016. continue; /* bash checks all argv[] */
  11017. }
  11018. if (ret == 0) {
  11019. /* Yes, and it still runs */
  11020. ret = wait_for_child_or_signal(NULL, pid);
  11021. } else {
  11022. /* Yes, and it just exited */
  11023. process_wait_result(NULL, pid, status);
  11024. ret = WEXITSTATUS(status);
  11025. if (WIFSIGNALED(status))
  11026. ret = 128 | WTERMSIG(status);
  11027. }
  11028. } while (*++argv);
  11029. return ret;
  11030. }
  11031. #endif
  11032. #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
  11033. static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
  11034. {
  11035. if (argv[1]) {
  11036. def = bb_strtou(argv[1], NULL, 10);
  11037. if (errno || def < def_min || argv[2]) {
  11038. bb_error_msg("%s: bad arguments", argv[0]);
  11039. def = UINT_MAX;
  11040. }
  11041. }
  11042. return def;
  11043. }
  11044. #endif
  11045. #if ENABLE_HUSH_LOOPS
  11046. static int FAST_FUNC builtin_break(char **argv)
  11047. {
  11048. unsigned depth;
  11049. if (G.depth_of_loop == 0) {
  11050. bb_error_msg("%s: only meaningful in a loop", argv[0]);
  11051. /* if we came from builtin_continue(), need to undo "= 1" */
  11052. G.flag_break_continue = 0;
  11053. return EXIT_SUCCESS; /* bash compat */
  11054. }
  11055. G.flag_break_continue++; /* BC_BREAK = 1, or BC_CONTINUE = 2 */
  11056. G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
  11057. if (depth == UINT_MAX)
  11058. G.flag_break_continue = BC_BREAK;
  11059. if (G.depth_of_loop < depth)
  11060. G.depth_break_continue = G.depth_of_loop;
  11061. return EXIT_SUCCESS;
  11062. }
  11063. static int FAST_FUNC builtin_continue(char **argv)
  11064. {
  11065. G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
  11066. return builtin_break(argv);
  11067. }
  11068. #endif
  11069. #if ENABLE_HUSH_FUNCTIONS
  11070. static int FAST_FUNC builtin_return(char **argv)
  11071. {
  11072. int rc;
  11073. if (G_flag_return_in_progress != -1) {
  11074. bb_error_msg("%s: not in a function or sourced script", argv[0]);
  11075. return EXIT_FAILURE; /* bash compat */
  11076. }
  11077. G_flag_return_in_progress = 1;
  11078. /* bash:
  11079. * out of range: wraps around at 256, does not error out
  11080. * non-numeric param:
  11081. * f() { false; return qwe; }; f; echo $?
  11082. * bash: return: qwe: numeric argument required <== we do this
  11083. * 255 <== we also do this
  11084. */
  11085. rc = parse_numeric_argv1(argv, G.last_exitcode, 0);
  11086. # if ENABLE_HUSH_TRAP
  11087. if (argv[1]) { /* "return ARG" inside a running trap sets $? */
  11088. debug_printf_exec("G.return_exitcode=%d\n", rc);
  11089. G.return_exitcode = rc;
  11090. }
  11091. # endif
  11092. return rc;
  11093. }
  11094. #endif
  11095. #if ENABLE_HUSH_TIMES
  11096. static int FAST_FUNC builtin_times(char **argv UNUSED_PARAM)
  11097. {
  11098. static const uint8_t times_tbl[] ALIGN1 = {
  11099. ' ', offsetof(struct tms, tms_utime),
  11100. '\n', offsetof(struct tms, tms_stime),
  11101. ' ', offsetof(struct tms, tms_cutime),
  11102. '\n', offsetof(struct tms, tms_cstime),
  11103. 0
  11104. };
  11105. const uint8_t *p;
  11106. unsigned clk_tck;
  11107. struct tms buf;
  11108. clk_tck = bb_clk_tck();
  11109. times(&buf);
  11110. p = times_tbl;
  11111. do {
  11112. unsigned sec, frac;
  11113. unsigned long t;
  11114. t = *(clock_t *)(((char *) &buf) + p[1]);
  11115. sec = t / clk_tck;
  11116. frac = t % clk_tck;
  11117. printf("%um%u.%03us%c",
  11118. sec / 60, sec % 60,
  11119. (frac * 1000) / clk_tck,
  11120. p[0]);
  11121. p += 2;
  11122. } while (*p);
  11123. return EXIT_SUCCESS;
  11124. }
  11125. #endif
  11126. #if ENABLE_HUSH_MEMLEAK
  11127. static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
  11128. {
  11129. void *p;
  11130. unsigned long l;
  11131. # ifdef M_TRIM_THRESHOLD
  11132. /* Optional. Reduces probability of false positives */
  11133. malloc_trim(0);
  11134. # endif
  11135. /* Crude attempt to find where "free memory" starts,
  11136. * sans fragmentation. */
  11137. p = malloc(240);
  11138. l = (unsigned long)p;
  11139. free(p);
  11140. p = malloc(3400);
  11141. if (l < (unsigned long)p) l = (unsigned long)p;
  11142. free(p);
  11143. # if 0 /* debug */
  11144. {
  11145. struct mallinfo mi = mallinfo();
  11146. printf("top alloc:0x%lx malloced:%d+%d=%d\n", l,
  11147. mi.arena, mi.hblkhd, mi.arena + mi.hblkhd);
  11148. }
  11149. # endif
  11150. if (!G.memleak_value)
  11151. G.memleak_value = l;
  11152. l -= G.memleak_value;
  11153. if ((long)l < 0)
  11154. l = 0;
  11155. l /= 1024;
  11156. if (l > 127)
  11157. l = 127;
  11158. /* Exitcode is "how many kilobytes we leaked since 1st call" */
  11159. return l;
  11160. }
  11161. #endif