hush.c 334 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162
  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_BASH_SOURCE_CURDIR
  131. //config: bool "'source' and '.' builtins search current directory after $PATH"
  132. //config: default n # do not encourage non-standard behavior
  133. //config: depends on HUSH_BASH_COMPAT
  134. //config: help
  135. //config: This is not compliant with standards. Avoid if possible.
  136. //config:
  137. //config:config HUSH_LINENO_VAR
  138. //config: bool "$LINENO variable (bashism)"
  139. //config: default y
  140. //config: depends on SHELL_HUSH
  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_DOLLAR_SQUOTE ENABLE_HUSH_BASH_COMPAT
  381. #define BASH_HOSTNAME_VAR ENABLE_HUSH_BASH_COMPAT
  382. #define BASH_EPOCH_VARS ENABLE_HUSH_BASH_COMPAT
  383. #define BASH_TEST2 (ENABLE_HUSH_BASH_COMPAT && ENABLE_HUSH_TEST)
  384. #define BASH_READ_D ENABLE_HUSH_BASH_COMPAT
  385. /* Build knobs */
  386. #define LEAK_HUNTING 0
  387. #define BUILD_AS_NOMMU 0
  388. /* Enable/disable sanity checks. Ok to enable in production,
  389. * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
  390. * Keeping 1 for now even in released versions.
  391. */
  392. #define HUSH_DEBUG 1
  393. /* Slightly bigger (+200 bytes), but faster hush.
  394. * So far it only enables a trick with counting SIGCHLDs and forks,
  395. * which allows us to do fewer waitpid's.
  396. * (we can detect a case where neither forks were done nor SIGCHLDs happened
  397. * and therefore waitpid will return the same result as last time)
  398. */
  399. #define ENABLE_HUSH_FAST 0
  400. /* TODO: implement simplified code for users which do not need ${var%...} ops
  401. * So far ${var%...} ops are always enabled:
  402. */
  403. #define ENABLE_HUSH_DOLLAR_OPS 1
  404. #if BUILD_AS_NOMMU
  405. # undef BB_MMU
  406. # undef USE_FOR_NOMMU
  407. # undef USE_FOR_MMU
  408. # define BB_MMU 0
  409. # define USE_FOR_NOMMU(...) __VA_ARGS__
  410. # define USE_FOR_MMU(...)
  411. #endif
  412. #include "NUM_APPLETS.h"
  413. #if NUM_APPLETS == 1
  414. /* STANDALONE does not make sense, and won't compile */
  415. # undef CONFIG_FEATURE_SH_STANDALONE
  416. # undef ENABLE_FEATURE_SH_STANDALONE
  417. # undef IF_FEATURE_SH_STANDALONE
  418. # undef IF_NOT_FEATURE_SH_STANDALONE
  419. # define ENABLE_FEATURE_SH_STANDALONE 0
  420. # define IF_FEATURE_SH_STANDALONE(...)
  421. # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
  422. #endif
  423. #if !ENABLE_HUSH_INTERACTIVE
  424. # undef ENABLE_FEATURE_EDITING
  425. # define ENABLE_FEATURE_EDITING 0
  426. # undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
  427. # define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
  428. # undef ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
  429. # define ENABLE_FEATURE_EDITING_SAVE_ON_EXIT 0
  430. #endif
  431. /* Do we support ANY keywords? */
  432. #if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
  433. # define HAS_KEYWORDS 1
  434. # define IF_HAS_KEYWORDS(...) __VA_ARGS__
  435. # define IF_HAS_NO_KEYWORDS(...)
  436. #else
  437. # define HAS_KEYWORDS 0
  438. # define IF_HAS_KEYWORDS(...)
  439. # define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
  440. #endif
  441. /* If you comment out one of these below, it will be #defined later
  442. * to perform debug printfs to stderr: */
  443. #define debug_printf(...) do {} while (0)
  444. /* Finer-grained debug switches */
  445. #define debug_printf_parse(...) do {} while (0)
  446. #define debug_printf_heredoc(...) do {} while (0)
  447. #define debug_print_tree(a, b) do {} while (0)
  448. #define debug_printf_exec(...) do {} while (0)
  449. #define debug_printf_env(...) do {} while (0)
  450. #define debug_printf_jobs(...) do {} while (0)
  451. #define debug_printf_expand(...) do {} while (0)
  452. #define debug_printf_varexp(...) do {} while (0)
  453. #define debug_printf_glob(...) do {} while (0)
  454. #define debug_printf_redir(...) do {} while (0)
  455. #define debug_printf_list(...) do {} while (0)
  456. #define debug_printf_subst(...) do {} while (0)
  457. #define debug_printf_prompt(...) do {} while (0)
  458. #define debug_printf_clean(...) do {} while (0)
  459. #define ERR_PTR ((void*)(long)1)
  460. #define JOB_STATUS_FORMAT "[%u] %-22s %.40s\n"
  461. #define _SPECIAL_VARS_STR "_*@$!?#-"
  462. #define SPECIAL_VARS_STR ("_*@$!?#-" + 1)
  463. #define NUMERIC_SPECVARS_STR ("_*@$!?#-" + 3)
  464. #if BASH_PATTERN_SUBST
  465. /* Support / and // replace ops */
  466. /* Note that // is stored as \ in "encoded" string representation */
  467. # define VAR_ENCODED_SUBST_OPS "\\/%#:-=+?"
  468. # define VAR_SUBST_OPS ("\\/%#:-=+?" + 1)
  469. # define MINUS_PLUS_EQUAL_QUESTION ("\\/%#:-=+?" + 5)
  470. #else
  471. # define VAR_ENCODED_SUBST_OPS "%#:-=+?"
  472. # define VAR_SUBST_OPS "%#:-=+?"
  473. # define MINUS_PLUS_EQUAL_QUESTION ("%#:-=+?" + 3)
  474. #endif
  475. #define SPECIAL_VAR_SYMBOL_STR "\3"
  476. #define SPECIAL_VAR_SYMBOL 3
  477. /* The "variable" with name "\1" emits string "\3". Testcase: "echo ^C" */
  478. #define SPECIAL_VAR_QUOTED_SVS 1
  479. struct variable;
  480. static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
  481. /* This supports saving pointers malloced in vfork child,
  482. * to be freed in the parent.
  483. */
  484. #if !BB_MMU
  485. typedef struct nommu_save_t {
  486. struct variable *old_vars;
  487. char **argv;
  488. char **argv_from_re_execing;
  489. } nommu_save_t;
  490. #endif
  491. enum {
  492. RES_NONE = 0,
  493. #if ENABLE_HUSH_IF
  494. RES_IF ,
  495. RES_THEN ,
  496. RES_ELIF ,
  497. RES_ELSE ,
  498. RES_FI ,
  499. #endif
  500. #if ENABLE_HUSH_LOOPS
  501. RES_FOR ,
  502. RES_WHILE ,
  503. RES_UNTIL ,
  504. RES_DO ,
  505. RES_DONE ,
  506. #endif
  507. #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
  508. RES_IN ,
  509. #endif
  510. #if ENABLE_HUSH_CASE
  511. RES_CASE ,
  512. /* three pseudo-keywords support contrived "case" syntax: */
  513. RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
  514. RES_MATCH , /* "word)" */
  515. RES_CASE_BODY, /* "this command is inside CASE" */
  516. RES_ESAC ,
  517. #endif
  518. RES_XXXX ,
  519. RES_SNTX
  520. };
  521. typedef struct o_string {
  522. char *data;
  523. int length; /* position where data is appended */
  524. int maxlen;
  525. int o_expflags;
  526. /* At least some part of the string was inside '' or "",
  527. * possibly empty one: word"", wo''rd etc. */
  528. smallint has_quoted_part;
  529. smallint has_empty_slot;
  530. smallint ended_in_ifs;
  531. } o_string;
  532. enum {
  533. EXP_FLAG_SINGLEWORD = 0x80, /* must be 0x80 */
  534. EXP_FLAG_GLOB = 0x2,
  535. /* Protect newly added chars against globbing
  536. * by prepending \ to *, ?, [, \ */
  537. EXP_FLAG_ESC_GLOB_CHARS = 0x1,
  538. };
  539. /* Used for initialization: o_string foo = NULL_O_STRING; */
  540. #define NULL_O_STRING { NULL }
  541. #ifndef debug_printf_parse
  542. static const char *const assignment_flag[] = {
  543. "MAYBE_ASSIGNMENT",
  544. "DEFINITELY_ASSIGNMENT",
  545. "NOT_ASSIGNMENT",
  546. "WORD_IS_KEYWORD",
  547. };
  548. #endif
  549. /* We almost can use standard FILE api, but we need an ability to move
  550. * its fd when redirects coincide with it. No api exists for that
  551. * (RFE for it at https://sourceware.org/bugzilla/show_bug.cgi?id=21902).
  552. * HFILE is our internal alternative. Only supports reading.
  553. * Since we now can, we incorporate linked list of all opened HFILEs
  554. * into the struct (used to be a separate mini-list).
  555. */
  556. typedef struct HFILE {
  557. char *cur;
  558. char *end;
  559. struct HFILE *next_hfile;
  560. int fd;
  561. char buf[1024];
  562. } HFILE;
  563. typedef struct in_str {
  564. const char *p;
  565. int peek_buf[2];
  566. int last_char;
  567. HFILE *file;
  568. } in_str;
  569. /* The descrip member of this structure is only used to make
  570. * debugging output pretty */
  571. static const struct {
  572. int32_t mode;
  573. signed char default_fd;
  574. char descrip[3];
  575. } redir_table[] ALIGN4 = {
  576. { O_RDONLY, 0, "<" },
  577. { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
  578. { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
  579. { O_CREAT|O_RDWR, 1, "<>" },
  580. { O_RDONLY, 0, "<<" },
  581. /* Should not be needed. Bogus default_fd helps in debugging */
  582. /* { O_RDONLY, 77, "<<" }, */
  583. };
  584. struct redir_struct {
  585. struct redir_struct *next;
  586. char *rd_filename; /* filename */
  587. int rd_fd; /* fd to redirect */
  588. /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
  589. int rd_dup;
  590. smallint rd_type; /* (enum redir_type) */
  591. /* note: for heredocs, rd_filename contains heredoc delimiter,
  592. * and subsequently heredoc itself; and rd_dup is a bitmask:
  593. * bit 0: do we need to trim leading tabs?
  594. * bit 1: is heredoc quoted (<<'delim' syntax) ?
  595. */
  596. };
  597. typedef enum redir_type {
  598. REDIRECT_INPUT = 0,
  599. REDIRECT_OVERWRITE = 1,
  600. REDIRECT_APPEND = 2,
  601. REDIRECT_IO = 3,
  602. REDIRECT_HEREDOC = 4,
  603. REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
  604. REDIRFD_CLOSE = -3,
  605. REDIRFD_SYNTAX_ERR = -2,
  606. REDIRFD_TO_FILE = -1,
  607. /* otherwise, rd_fd is redirected to rd_dup */
  608. HEREDOC_SKIPTABS = 1,
  609. HEREDOC_QUOTED = 2,
  610. } redir_type;
  611. struct command {
  612. pid_t pid; /* 0 if exited */
  613. unsigned assignment_cnt; /* how many argv[i] are assignments? */
  614. #if ENABLE_HUSH_LINENO_VAR
  615. unsigned lineno;
  616. #endif
  617. smallint cmd_type; /* CMD_xxx */
  618. #define CMD_NORMAL 0
  619. #define CMD_SUBSHELL 1
  620. #if BASH_TEST2
  621. /* used for "[[ EXPR ]]" */
  622. # define CMD_TEST2_SINGLEWORD_NOGLOB 2
  623. #endif
  624. #if BASH_TEST2 || ENABLE_HUSH_LOCAL || ENABLE_HUSH_EXPORT || ENABLE_HUSH_READONLY
  625. /* used to prevent word splitting and globbing in "export v=t*" */
  626. # define CMD_SINGLEWORD_NOGLOB 3
  627. #endif
  628. #if ENABLE_HUSH_FUNCTIONS
  629. # define CMD_FUNCDEF 4
  630. #endif
  631. smalluint cmd_exitcode;
  632. /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
  633. struct pipe *group;
  634. #if !BB_MMU
  635. char *group_as_string;
  636. #endif
  637. #if ENABLE_HUSH_FUNCTIONS
  638. struct function *child_func;
  639. /* This field is used to prevent a bug here:
  640. * while...do f1() {a;}; f1; f1() {b;}; f1; done
  641. * When we execute "f1() {a;}" cmd, we create new function and clear
  642. * cmd->group, cmd->group_as_string, cmd->argv[0].
  643. * When we execute "f1() {b;}", we notice that f1 exists,
  644. * and that its "parent cmd" struct is still "alive",
  645. * we put those fields back into cmd->xxx
  646. * (struct function has ->parent_cmd ptr to facilitate that).
  647. * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
  648. * Without this trick, loop would execute a;b;b;b;...
  649. * instead of correct sequence a;b;a;b;...
  650. * When command is freed, it severs the link
  651. * (sets ->child_func->parent_cmd to NULL).
  652. */
  653. #endif
  654. char **argv; /* command name and arguments */
  655. /* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
  656. * and on execution these are substituted with their values.
  657. * Substitution can make _several_ words out of one argv[n]!
  658. * Example: argv[0]=='.^C*^C.' here: echo .$*.
  659. * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
  660. */
  661. struct redir_struct *redirects; /* I/O redirections */
  662. };
  663. /* Is there anything in this command at all? */
  664. #define IS_NULL_CMD(cmd) \
  665. (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
  666. struct pipe {
  667. struct pipe *next;
  668. int num_cmds; /* total number of commands in pipe */
  669. int alive_cmds; /* number of commands running (not exited) */
  670. int stopped_cmds; /* number of commands alive, but stopped */
  671. #if ENABLE_HUSH_JOB
  672. unsigned jobid; /* job number */
  673. pid_t pgrp; /* process group ID for the job */
  674. char *cmdtext; /* name of job */
  675. #endif
  676. struct command *cmds; /* array of commands in pipe */
  677. smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
  678. IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
  679. IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
  680. };
  681. typedef enum pipe_style {
  682. PIPE_SEQ = 0,
  683. PIPE_AND = 1,
  684. PIPE_OR = 2,
  685. PIPE_BG = 3,
  686. } pipe_style;
  687. /* Is there anything in this pipe at all? */
  688. #define IS_NULL_PIPE(pi) \
  689. ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
  690. /* This holds pointers to the various results of parsing */
  691. struct parse_context {
  692. /* linked list of pipes */
  693. struct pipe *list_head;
  694. /* last pipe (being constructed right now) */
  695. struct pipe *pipe;
  696. /* last command in pipe (being constructed right now) */
  697. struct command *command;
  698. /* last redirect in command->redirects list */
  699. struct redir_struct *pending_redirect;
  700. o_string word;
  701. #if !BB_MMU
  702. o_string as_string;
  703. #endif
  704. smallint is_assignment; /* 0:maybe, 1:yes, 2:no, 3:keyword */
  705. #if HAS_KEYWORDS
  706. smallint ctx_res_w;
  707. smallint ctx_inverted; /* "! cmd | cmd" */
  708. #if ENABLE_HUSH_CASE
  709. smallint ctx_dsemicolon; /* ";;" seen */
  710. #endif
  711. /* bitmask of FLAG_xxx, for figuring out valid reserved words */
  712. int old_flag;
  713. /* group we are enclosed in:
  714. * example: "if pipe1; pipe2; then pipe3; fi"
  715. * when we see "if" or "then", we malloc and copy current context,
  716. * and make ->stack point to it. then we parse pipeN.
  717. * when closing "then" / fi" / whatever is found,
  718. * we move list_head into ->stack->command->group,
  719. * copy ->stack into current context, and delete ->stack.
  720. * (parsing of { list } and ( list ) doesn't use this method)
  721. */
  722. struct parse_context *stack;
  723. #endif
  724. };
  725. enum {
  726. MAYBE_ASSIGNMENT = 0,
  727. DEFINITELY_ASSIGNMENT = 1,
  728. NOT_ASSIGNMENT = 2,
  729. /* Not an assignment, but next word may be: "if v=xyz cmd;" */
  730. WORD_IS_KEYWORD = 3,
  731. };
  732. /* On program start, environ points to initial environment.
  733. * putenv adds new pointers into it, unsetenv removes them.
  734. * Neither of these (de)allocates the strings.
  735. * setenv allocates new strings in malloc space and does putenv,
  736. * and thus setenv is unusable (leaky) for shell's purposes */
  737. #define setenv(...) setenv_is_leaky_dont_use()
  738. struct variable {
  739. struct variable *next;
  740. char *varstr; /* points to "name=" portion */
  741. int max_len; /* if > 0, name is part of initial env; else name is malloced */
  742. uint16_t var_nest_level;
  743. smallint flg_export; /* putenv should be done on this var */
  744. smallint flg_read_only;
  745. };
  746. enum {
  747. BC_BREAK = 1,
  748. BC_CONTINUE = 2,
  749. };
  750. #if ENABLE_HUSH_FUNCTIONS
  751. struct function {
  752. struct function *next;
  753. char *name;
  754. struct command *parent_cmd;
  755. struct pipe *body;
  756. # if !BB_MMU
  757. char *body_as_string;
  758. # endif
  759. };
  760. #endif
  761. /* set -/+o OPT support. (TODO: make it optional)
  762. * bash supports the following opts:
  763. * allexport off
  764. * braceexpand on
  765. * emacs on
  766. * errexit off
  767. * errtrace off
  768. * functrace off
  769. * hashall on
  770. * histexpand off
  771. * history on
  772. * ignoreeof off
  773. * interactive-comments on
  774. * keyword off
  775. * monitor on
  776. * noclobber off
  777. * noexec off
  778. * noglob off
  779. * nolog off
  780. * notify off
  781. * nounset off
  782. * onecmd off
  783. * physical off
  784. * pipefail off
  785. * posix off
  786. * privileged off
  787. * verbose off
  788. * vi off
  789. * xtrace off
  790. */
  791. static const char o_opt_strings[] ALIGN1 =
  792. "pipefail\0"
  793. "noexec\0"
  794. "errexit\0"
  795. #if ENABLE_HUSH_MODE_X
  796. "xtrace\0"
  797. #endif
  798. ;
  799. enum {
  800. OPT_O_PIPEFAIL,
  801. OPT_O_NOEXEC,
  802. OPT_O_ERREXIT,
  803. #if ENABLE_HUSH_MODE_X
  804. OPT_O_XTRACE,
  805. #endif
  806. NUM_OPT_O
  807. };
  808. /* "Globals" within this file */
  809. /* Sorted roughly by size (smaller offsets == smaller code) */
  810. struct globals {
  811. /* interactive_fd != 0 means we are an interactive shell.
  812. * If we are, then saved_tty_pgrp can also be != 0, meaning
  813. * that controlling tty is available. With saved_tty_pgrp == 0,
  814. * job control still works, but terminal signals
  815. * (^C, ^Z, ^Y, ^\) won't work at all, and background
  816. * process groups can only be created with "cmd &".
  817. * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
  818. * to give tty to the foreground process group,
  819. * and will take it back when the group is stopped (^Z)
  820. * or killed (^C).
  821. */
  822. #if ENABLE_HUSH_INTERACTIVE
  823. /* 'interactive_fd' is a fd# open to ctty, if we have one
  824. * _AND_ if we decided to act interactively */
  825. int interactive_fd;
  826. IF_NOT_FEATURE_EDITING_FANCY_PROMPT(char *PS1;)
  827. # define G_interactive_fd (G.interactive_fd)
  828. #else
  829. # define G_interactive_fd 0
  830. #endif
  831. #if ENABLE_FEATURE_EDITING
  832. line_input_t *line_input_state;
  833. #endif
  834. pid_t root_pid;
  835. pid_t root_ppid;
  836. pid_t last_bg_pid;
  837. #if ENABLE_HUSH_RANDOM_SUPPORT
  838. random_t random_gen;
  839. #endif
  840. #if ENABLE_HUSH_JOB
  841. int run_list_level;
  842. unsigned last_jobid;
  843. pid_t saved_tty_pgrp;
  844. struct pipe *job_list;
  845. # define G_saved_tty_pgrp (G.saved_tty_pgrp)
  846. #else
  847. # define G_saved_tty_pgrp 0
  848. #endif
  849. /* How deeply are we in context where "set -e" is ignored */
  850. int errexit_depth;
  851. /* "set -e" rules (do we follow them correctly?):
  852. * Exit if pipe, list, or compound command exits with a non-zero status.
  853. * Shell does not exit if failed command is part of condition in
  854. * if/while, part of && or || list except the last command, any command
  855. * in a pipe but the last, or if the command's return value is being
  856. * inverted with !. If a compound command other than a subshell returns a
  857. * non-zero status because a command failed while -e was being ignored, the
  858. * shell does not exit. A trap on ERR, if set, is executed before the shell
  859. * exits [ERR is a bashism].
  860. *
  861. * If a compound command or function executes in a context where -e is
  862. * ignored, none of the commands executed within are affected by the -e
  863. * setting. If a compound command or function sets -e while executing in a
  864. * context where -e is ignored, that setting does not have any effect until
  865. * the compound command or the command containing the function call completes.
  866. */
  867. char o_opt[NUM_OPT_O];
  868. #if ENABLE_HUSH_MODE_X
  869. # define G_x_mode (G.o_opt[OPT_O_XTRACE])
  870. #else
  871. # define G_x_mode 0
  872. #endif
  873. char opt_s;
  874. char opt_c;
  875. #if ENABLE_HUSH_INTERACTIVE
  876. smallint promptmode; /* 0: PS1, 1: PS2 */
  877. #endif
  878. smallint flag_SIGINT;
  879. #if ENABLE_HUSH_LOOPS
  880. smallint flag_break_continue;
  881. #endif
  882. #if ENABLE_HUSH_FUNCTIONS
  883. /* 0: outside of a function (or sourced file)
  884. * -1: inside of a function, ok to use return builtin
  885. * 1: return is invoked, skip all till end of func
  886. */
  887. smallint flag_return_in_progress;
  888. # define G_flag_return_in_progress (G.flag_return_in_progress)
  889. #else
  890. # define G_flag_return_in_progress 0
  891. #endif
  892. smallint exiting; /* used to prevent EXIT trap recursion */
  893. /* These support $? */
  894. smalluint last_exitcode;
  895. smalluint expand_exitcode;
  896. smalluint last_bg_pid_exitcode;
  897. #if ENABLE_HUSH_SET
  898. /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
  899. smalluint global_args_malloced;
  900. # define G_global_args_malloced (G.global_args_malloced)
  901. #else
  902. # define G_global_args_malloced 0
  903. #endif
  904. #if ENABLE_HUSH_BASH_COMPAT
  905. int dead_job_exitcode; /* for "wait -n" */
  906. #endif
  907. /* how many non-NULL argv's we have. NB: $# + 1 */
  908. int global_argc;
  909. char **global_argv;
  910. #if !BB_MMU
  911. char *argv0_for_re_execing;
  912. #endif
  913. #if ENABLE_HUSH_LOOPS
  914. unsigned depth_break_continue;
  915. unsigned depth_of_loop;
  916. #endif
  917. #if ENABLE_HUSH_GETOPTS
  918. unsigned getopt_count;
  919. #endif
  920. const char *ifs;
  921. char *ifs_whitespace; /* = G.ifs or malloced */
  922. const char *cwd;
  923. struct variable *top_var;
  924. char **expanded_assignments;
  925. struct variable **shadowed_vars_pp;
  926. unsigned var_nest_level;
  927. #if ENABLE_HUSH_FUNCTIONS
  928. # if ENABLE_HUSH_LOCAL
  929. unsigned func_nest_level; /* solely to prevent "local v" in non-functions */
  930. # endif
  931. struct function *top_func;
  932. #endif
  933. /* Signal and trap handling */
  934. #if ENABLE_HUSH_FAST
  935. unsigned count_SIGCHLD;
  936. unsigned handled_SIGCHLD;
  937. smallint we_have_children;
  938. #endif
  939. #if ENABLE_HUSH_LINENO_VAR
  940. unsigned parse_lineno;
  941. unsigned execute_lineno;
  942. #endif
  943. HFILE *HFILE_list;
  944. HFILE *HFILE_stdin;
  945. /* Which signals have non-DFL handler (even with no traps set)?
  946. * Set at the start to:
  947. * (SIGQUIT + maybe SPECIAL_INTERACTIVE_SIGS + maybe SPECIAL_JOBSTOP_SIGS)
  948. * SPECIAL_INTERACTIVE_SIGS are cleared after fork.
  949. * The rest is cleared right before execv syscalls.
  950. * Other than these two times, never modified.
  951. */
  952. unsigned special_sig_mask;
  953. #if ENABLE_HUSH_JOB
  954. unsigned fatal_sig_mask;
  955. # define G_fatal_sig_mask (G.fatal_sig_mask)
  956. #else
  957. # define G_fatal_sig_mask 0
  958. #endif
  959. #if ENABLE_HUSH_TRAP
  960. int pre_trap_exitcode;
  961. # if ENABLE_HUSH_FUNCTIONS
  962. int return_exitcode;
  963. # endif
  964. char **traps; /* char *traps[NSIG] */
  965. # define G_traps G.traps
  966. #else
  967. # define G_traps ((char**)NULL)
  968. #endif
  969. sigset_t pending_set;
  970. #if ENABLE_HUSH_MEMLEAK
  971. unsigned long memleak_value;
  972. #endif
  973. #if ENABLE_HUSH_MODE_X
  974. unsigned x_mode_depth;
  975. /* "set -x" output should not be redirectable with subsequent 2>FILE.
  976. * We dup fd#2 to x_mode_fd when "set -x" is executed, and use it
  977. * for all subsequent output.
  978. */
  979. int x_mode_fd;
  980. o_string x_mode_buf;
  981. #endif
  982. #if HUSH_DEBUG >= 2
  983. int debug_indent;
  984. #endif
  985. struct sigaction sa;
  986. char optstring_buf[sizeof("eixcs")];
  987. #if BASH_EPOCH_VARS
  988. char epoch_buf[sizeof("%llu.nnnnnn") + sizeof(long long)*3];
  989. #endif
  990. #if ENABLE_FEATURE_EDITING
  991. char user_input_buf[CONFIG_FEATURE_EDITING_MAX_LEN];
  992. #endif
  993. };
  994. #define G (*ptr_to_globals)
  995. /* Not #defining name to G.name - this quickly gets unwieldy
  996. * (too many defines). Also, I actually prefer to see when a variable
  997. * is global, thus "G." prefix is a useful hint */
  998. #define INIT_G() do { \
  999. SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
  1000. /* memset(&G.sa, 0, sizeof(G.sa)); */ \
  1001. sigfillset(&G.sa.sa_mask); \
  1002. G.sa.sa_flags = SA_RESTART; \
  1003. } while (0)
  1004. /* Function prototypes for builtins */
  1005. static int builtin_cd(char **argv) FAST_FUNC;
  1006. #if ENABLE_HUSH_ECHO
  1007. static int builtin_echo(char **argv) FAST_FUNC;
  1008. #endif
  1009. static int builtin_eval(char **argv) FAST_FUNC;
  1010. static int builtin_exec(char **argv) FAST_FUNC;
  1011. static int builtin_exit(char **argv) FAST_FUNC;
  1012. #if ENABLE_HUSH_EXPORT
  1013. static int builtin_export(char **argv) FAST_FUNC;
  1014. #endif
  1015. #if ENABLE_HUSH_READONLY
  1016. static int builtin_readonly(char **argv) FAST_FUNC;
  1017. #endif
  1018. #if ENABLE_HUSH_JOB
  1019. static int builtin_fg_bg(char **argv) FAST_FUNC;
  1020. static int builtin_jobs(char **argv) FAST_FUNC;
  1021. #endif
  1022. #if ENABLE_HUSH_GETOPTS
  1023. static int builtin_getopts(char **argv) FAST_FUNC;
  1024. #endif
  1025. #if ENABLE_HUSH_HELP
  1026. static int builtin_help(char **argv) FAST_FUNC;
  1027. #endif
  1028. #if MAX_HISTORY && ENABLE_FEATURE_EDITING
  1029. static int builtin_history(char **argv) FAST_FUNC;
  1030. #endif
  1031. #if ENABLE_HUSH_LOCAL
  1032. static int builtin_local(char **argv) FAST_FUNC;
  1033. #endif
  1034. #if ENABLE_HUSH_MEMLEAK
  1035. static int builtin_memleak(char **argv) FAST_FUNC;
  1036. #endif
  1037. #if ENABLE_HUSH_PRINTF
  1038. static int builtin_printf(char **argv) FAST_FUNC;
  1039. #endif
  1040. static int builtin_pwd(char **argv) FAST_FUNC;
  1041. #if ENABLE_HUSH_READ
  1042. static int builtin_read(char **argv) FAST_FUNC;
  1043. #endif
  1044. #if ENABLE_HUSH_SET
  1045. static int builtin_set(char **argv) FAST_FUNC;
  1046. #endif
  1047. static int builtin_shift(char **argv) FAST_FUNC;
  1048. static int builtin_source(char **argv) FAST_FUNC;
  1049. #if ENABLE_HUSH_TEST || BASH_TEST2
  1050. static int builtin_test(char **argv) FAST_FUNC;
  1051. #endif
  1052. #if ENABLE_HUSH_TRAP
  1053. static int builtin_trap(char **argv) FAST_FUNC;
  1054. #endif
  1055. #if ENABLE_HUSH_TYPE
  1056. static int builtin_type(char **argv) FAST_FUNC;
  1057. #endif
  1058. #if ENABLE_HUSH_TIMES
  1059. static int builtin_times(char **argv) FAST_FUNC;
  1060. #endif
  1061. static int builtin_true(char **argv) FAST_FUNC;
  1062. #if ENABLE_HUSH_UMASK
  1063. static int builtin_umask(char **argv) FAST_FUNC;
  1064. #endif
  1065. #if ENABLE_HUSH_UNSET
  1066. static int builtin_unset(char **argv) FAST_FUNC;
  1067. #endif
  1068. #if ENABLE_HUSH_KILL
  1069. static int builtin_kill(char **argv) FAST_FUNC;
  1070. #endif
  1071. #if ENABLE_HUSH_WAIT
  1072. static int builtin_wait(char **argv) FAST_FUNC;
  1073. #endif
  1074. #if ENABLE_HUSH_LOOPS
  1075. static int builtin_break(char **argv) FAST_FUNC;
  1076. static int builtin_continue(char **argv) FAST_FUNC;
  1077. #endif
  1078. #if ENABLE_HUSH_FUNCTIONS
  1079. static int builtin_return(char **argv) FAST_FUNC;
  1080. #endif
  1081. /* Table of built-in functions. They can be forked or not, depending on
  1082. * context: within pipes, they fork. As simple commands, they do not.
  1083. * When used in non-forking context, they can change global variables
  1084. * in the parent shell process. If forked, of course they cannot.
  1085. * For example, 'unset foo | whatever' will parse and run, but foo will
  1086. * still be set at the end. */
  1087. struct built_in_command {
  1088. const char *b_cmd;
  1089. int (*b_function)(char **argv) FAST_FUNC;
  1090. #if ENABLE_HUSH_HELP
  1091. const char *b_descr;
  1092. # define BLTIN(cmd, func, help) { cmd, func, help }
  1093. #else
  1094. # define BLTIN(cmd, func, help) { cmd, func }
  1095. #endif
  1096. };
  1097. static const struct built_in_command bltins1[] ALIGN_PTR = {
  1098. BLTIN("." , builtin_source , "Run commands in file"),
  1099. BLTIN(":" , builtin_true , NULL),
  1100. #if ENABLE_HUSH_JOB
  1101. BLTIN("bg" , builtin_fg_bg , "Resume job in background"),
  1102. #endif
  1103. #if ENABLE_HUSH_LOOPS
  1104. BLTIN("break" , builtin_break , "Exit loop"),
  1105. #endif
  1106. BLTIN("cd" , builtin_cd , "Change directory"),
  1107. #if ENABLE_HUSH_LOOPS
  1108. BLTIN("continue" , builtin_continue, "Start new loop iteration"),
  1109. #endif
  1110. BLTIN("eval" , builtin_eval , "Construct and run shell command"),
  1111. BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
  1112. BLTIN("exit" , builtin_exit , NULL),
  1113. #if ENABLE_HUSH_EXPORT
  1114. BLTIN("export" , builtin_export , "Set environment variables"),
  1115. #endif
  1116. #if ENABLE_HUSH_JOB
  1117. BLTIN("fg" , builtin_fg_bg , "Bring job to foreground"),
  1118. #endif
  1119. #if ENABLE_HUSH_GETOPTS
  1120. BLTIN("getopts" , builtin_getopts , NULL),
  1121. #endif
  1122. #if ENABLE_HUSH_HELP
  1123. BLTIN("help" , builtin_help , NULL),
  1124. #endif
  1125. #if MAX_HISTORY && ENABLE_FEATURE_EDITING
  1126. BLTIN("history" , builtin_history , "Show history"),
  1127. #endif
  1128. #if ENABLE_HUSH_JOB
  1129. BLTIN("jobs" , builtin_jobs , "List jobs"),
  1130. #endif
  1131. #if ENABLE_HUSH_KILL
  1132. BLTIN("kill" , builtin_kill , "Send signals to processes"),
  1133. #endif
  1134. #if ENABLE_HUSH_LOCAL
  1135. BLTIN("local" , builtin_local , "Set local variables"),
  1136. #endif
  1137. #if ENABLE_HUSH_MEMLEAK
  1138. BLTIN("memleak" , builtin_memleak , NULL),
  1139. #endif
  1140. #if ENABLE_HUSH_READ
  1141. BLTIN("read" , builtin_read , "Input into variable"),
  1142. #endif
  1143. #if ENABLE_HUSH_READONLY
  1144. BLTIN("readonly" , builtin_readonly, "Make variables read-only"),
  1145. #endif
  1146. #if ENABLE_HUSH_FUNCTIONS
  1147. BLTIN("return" , builtin_return , "Return from function"),
  1148. #endif
  1149. #if ENABLE_HUSH_SET
  1150. BLTIN("set" , builtin_set , "Set positional parameters"),
  1151. #endif
  1152. BLTIN("shift" , builtin_shift , "Shift positional parameters"),
  1153. #if BASH_SOURCE
  1154. BLTIN("source" , builtin_source , NULL),
  1155. #endif
  1156. #if ENABLE_HUSH_TIMES
  1157. BLTIN("times" , builtin_times , NULL),
  1158. #endif
  1159. #if ENABLE_HUSH_TRAP
  1160. BLTIN("trap" , builtin_trap , "Trap signals"),
  1161. #endif
  1162. BLTIN("true" , builtin_true , NULL),
  1163. #if ENABLE_HUSH_TYPE
  1164. BLTIN("type" , builtin_type , "Show command type"),
  1165. #endif
  1166. #if ENABLE_HUSH_ULIMIT
  1167. BLTIN("ulimit" , shell_builtin_ulimit, "Control resource limits"),
  1168. #endif
  1169. #if ENABLE_HUSH_UMASK
  1170. BLTIN("umask" , builtin_umask , "Set file creation mask"),
  1171. #endif
  1172. #if ENABLE_HUSH_UNSET
  1173. BLTIN("unset" , builtin_unset , "Unset variables"),
  1174. #endif
  1175. #if ENABLE_HUSH_WAIT
  1176. BLTIN("wait" , builtin_wait , "Wait for process to finish"),
  1177. #endif
  1178. };
  1179. /* These builtins won't be used if we are on NOMMU and need to re-exec
  1180. * (it's cheaper to run an external program in this case):
  1181. */
  1182. static const struct built_in_command bltins2[] ALIGN_PTR = {
  1183. #if ENABLE_HUSH_TEST
  1184. BLTIN("[" , builtin_test , NULL),
  1185. #endif
  1186. #if BASH_TEST2
  1187. BLTIN("[[" , builtin_test , NULL),
  1188. #endif
  1189. #if ENABLE_HUSH_ECHO
  1190. BLTIN("echo" , builtin_echo , NULL),
  1191. #endif
  1192. #if ENABLE_HUSH_PRINTF
  1193. BLTIN("printf" , builtin_printf , NULL),
  1194. #endif
  1195. BLTIN("pwd" , builtin_pwd , NULL),
  1196. #if ENABLE_HUSH_TEST
  1197. BLTIN("test" , builtin_test , NULL),
  1198. #endif
  1199. };
  1200. /* Debug printouts.
  1201. */
  1202. #if HUSH_DEBUG >= 2
  1203. /* prevent disasters with G.debug_indent < 0 */
  1204. # define indent() fdprintf(2, "%*s", (G.debug_indent * 2) & 0xff, "")
  1205. # define debug_enter() (G.debug_indent++)
  1206. # define debug_leave() (G.debug_indent--)
  1207. #else
  1208. # define indent() ((void)0)
  1209. # define debug_enter() ((void)0)
  1210. # define debug_leave() ((void)0)
  1211. #endif
  1212. #ifndef debug_printf
  1213. # define debug_printf(...) (indent(), fdprintf(2, __VA_ARGS__))
  1214. #endif
  1215. #ifndef debug_printf_parse
  1216. # define debug_printf_parse(...) (indent(), fdprintf(2, __VA_ARGS__))
  1217. #endif
  1218. #ifndef debug_printf_heredoc
  1219. # define debug_printf_heredoc(...) (indent(), fdprintf(2, __VA_ARGS__))
  1220. #endif
  1221. #ifndef debug_printf_exec
  1222. #define debug_printf_exec(...) (indent(), fdprintf(2, __VA_ARGS__))
  1223. #endif
  1224. #ifndef debug_printf_env
  1225. # define debug_printf_env(...) (indent(), fdprintf(2, __VA_ARGS__))
  1226. #endif
  1227. #ifndef debug_printf_jobs
  1228. # define debug_printf_jobs(...) (indent(), fdprintf(2, __VA_ARGS__))
  1229. # define DEBUG_JOBS 1
  1230. #else
  1231. # define DEBUG_JOBS 0
  1232. #endif
  1233. #ifndef debug_printf_expand
  1234. # define debug_printf_expand(...) (indent(), fdprintf(2, __VA_ARGS__))
  1235. # define DEBUG_EXPAND 1
  1236. #else
  1237. # define DEBUG_EXPAND 0
  1238. #endif
  1239. #ifndef debug_printf_varexp
  1240. # define debug_printf_varexp(...) (indent(), fdprintf(2, __VA_ARGS__))
  1241. #endif
  1242. #ifndef debug_printf_glob
  1243. # define debug_printf_glob(...) (indent(), fdprintf(2, __VA_ARGS__))
  1244. # define DEBUG_GLOB 1
  1245. #else
  1246. # define DEBUG_GLOB 0
  1247. #endif
  1248. #ifndef debug_printf_redir
  1249. # define debug_printf_redir(...) (indent(), fdprintf(2, __VA_ARGS__))
  1250. #endif
  1251. #ifndef debug_printf_list
  1252. # define debug_printf_list(...) (indent(), fdprintf(2, __VA_ARGS__))
  1253. #endif
  1254. #ifndef debug_printf_subst
  1255. # define debug_printf_subst(...) (indent(), fdprintf(2, __VA_ARGS__))
  1256. #endif
  1257. #ifndef debug_printf_prompt
  1258. # define debug_printf_prompt(...) (indent(), fdprintf(2, __VA_ARGS__))
  1259. #endif
  1260. #ifndef debug_printf_clean
  1261. # define debug_printf_clean(...) (indent(), fdprintf(2, __VA_ARGS__))
  1262. # define DEBUG_CLEAN 1
  1263. #else
  1264. # define DEBUG_CLEAN 0
  1265. #endif
  1266. #if DEBUG_EXPAND
  1267. static void debug_print_strings(const char *prefix, char **vv)
  1268. {
  1269. indent();
  1270. fdprintf(2, "%s:\n", prefix);
  1271. while (*vv)
  1272. fdprintf(2, " '%s'\n", *vv++);
  1273. }
  1274. #else
  1275. # define debug_print_strings(prefix, vv) ((void)0)
  1276. #endif
  1277. /* Leak hunting. Use hush_leaktool.sh for post-processing.
  1278. */
  1279. #if LEAK_HUNTING
  1280. static void *xxmalloc(int lineno, size_t size)
  1281. {
  1282. void *ptr = xmalloc((size + 0xff) & ~0xff);
  1283. fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
  1284. return ptr;
  1285. }
  1286. static void *xxrealloc(int lineno, void *ptr, size_t size)
  1287. {
  1288. ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
  1289. fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
  1290. return ptr;
  1291. }
  1292. static char *xxstrdup(int lineno, const char *str)
  1293. {
  1294. char *ptr = xstrdup(str);
  1295. fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
  1296. return ptr;
  1297. }
  1298. static void xxfree(void *ptr)
  1299. {
  1300. fdprintf(2, "free %p\n", ptr);
  1301. free(ptr);
  1302. }
  1303. # define xmalloc(s) xxmalloc(__LINE__, s)
  1304. # define xrealloc(p, s) xxrealloc(__LINE__, p, s)
  1305. # define xstrdup(s) xxstrdup(__LINE__, s)
  1306. # define free(p) xxfree(p)
  1307. #endif
  1308. /* Syntax and runtime errors. They always abort scripts.
  1309. * In interactive use they usually discard unparsed and/or unexecuted commands
  1310. * and return to the prompt.
  1311. * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
  1312. */
  1313. #if HUSH_DEBUG < 2
  1314. # define msg_and_die_if_script(lineno, ...) msg_and_die_if_script(__VA_ARGS__)
  1315. # define syntax_error(lineno, msg) syntax_error(msg)
  1316. # define syntax_error_at(lineno, msg) syntax_error_at(msg)
  1317. # define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
  1318. # define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
  1319. # define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
  1320. #endif
  1321. static void die_if_script(void)
  1322. {
  1323. if (!G_interactive_fd) {
  1324. if (G.last_exitcode) /* sometines it's 2, not 1 (bash compat) */
  1325. xfunc_error_retval = G.last_exitcode;
  1326. xfunc_die();
  1327. }
  1328. }
  1329. static void msg_and_die_if_script(unsigned lineno, const char *fmt, ...)
  1330. {
  1331. va_list p;
  1332. #if HUSH_DEBUG >= 2
  1333. bb_error_msg("hush.c:%u", lineno);
  1334. #endif
  1335. va_start(p, fmt);
  1336. bb_verror_msg(fmt, p, NULL);
  1337. va_end(p);
  1338. die_if_script();
  1339. }
  1340. static void syntax_error(unsigned lineno UNUSED_PARAM, const char *msg)
  1341. {
  1342. if (msg)
  1343. bb_error_msg("syntax error: %s", msg);
  1344. else
  1345. bb_simple_error_msg("syntax error");
  1346. die_if_script();
  1347. }
  1348. static void syntax_error_at(unsigned lineno UNUSED_PARAM, const char *msg)
  1349. {
  1350. bb_error_msg("syntax error at '%s'", msg);
  1351. die_if_script();
  1352. }
  1353. static void syntax_error_unterm_str(unsigned lineno UNUSED_PARAM, const char *s)
  1354. {
  1355. bb_error_msg("syntax error: unterminated %s", s);
  1356. //? source4.tests fails: in bash, echo ${^} in script does not terminate the script
  1357. // die_if_script();
  1358. }
  1359. static void syntax_error_unterm_ch(unsigned lineno, char ch)
  1360. {
  1361. char msg[2] = { ch, '\0' };
  1362. syntax_error_unterm_str(lineno, msg);
  1363. }
  1364. static void syntax_error_unexpected_ch(unsigned lineno UNUSED_PARAM, int ch)
  1365. {
  1366. char msg[2];
  1367. msg[0] = ch;
  1368. msg[1] = '\0';
  1369. #if HUSH_DEBUG >= 2
  1370. bb_error_msg("hush.c:%u", lineno);
  1371. #endif
  1372. bb_error_msg("syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
  1373. die_if_script();
  1374. }
  1375. #if HUSH_DEBUG < 2
  1376. # undef msg_and_die_if_script
  1377. # undef syntax_error
  1378. # undef syntax_error_at
  1379. # undef syntax_error_unterm_ch
  1380. # undef syntax_error_unterm_str
  1381. # undef syntax_error_unexpected_ch
  1382. #else
  1383. # define msg_and_die_if_script(...) msg_and_die_if_script(__LINE__, __VA_ARGS__)
  1384. # define syntax_error(msg) syntax_error(__LINE__, msg)
  1385. # define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
  1386. # define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
  1387. # define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
  1388. # define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
  1389. #endif
  1390. /* Utility functions
  1391. */
  1392. /* Replace each \x with x in place, return ptr past NUL. */
  1393. static char *unbackslash(char *src)
  1394. {
  1395. char *dst = src = strchrnul(src, '\\');
  1396. while (1) {
  1397. if (*src == '\\') {
  1398. src++;
  1399. if (*src != '\0') {
  1400. /* \x -> x */
  1401. *dst++ = *src++;
  1402. continue;
  1403. }
  1404. /* else: "\<nul>". Do not delete this backslash.
  1405. * Testcase: eval 'echo ok\'
  1406. */
  1407. *dst++ = '\\';
  1408. /* fallthrough */
  1409. }
  1410. if ((*dst++ = *src++) == '\0')
  1411. break;
  1412. }
  1413. return dst;
  1414. }
  1415. static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
  1416. {
  1417. int i;
  1418. unsigned count1;
  1419. unsigned count2;
  1420. char **v;
  1421. v = strings;
  1422. count1 = 0;
  1423. if (v) {
  1424. while (*v) {
  1425. count1++;
  1426. v++;
  1427. }
  1428. }
  1429. count2 = 0;
  1430. v = add;
  1431. while (*v) {
  1432. count2++;
  1433. v++;
  1434. }
  1435. v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
  1436. v[count1 + count2] = NULL;
  1437. i = count2;
  1438. while (--i >= 0)
  1439. v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
  1440. return v;
  1441. }
  1442. #if LEAK_HUNTING
  1443. static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
  1444. {
  1445. char **ptr = add_strings_to_strings(strings, add, need_to_dup);
  1446. fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
  1447. return ptr;
  1448. }
  1449. #define add_strings_to_strings(strings, add, need_to_dup) \
  1450. xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
  1451. #endif
  1452. /* Note: takes ownership of "add" ptr (it is not strdup'ed) */
  1453. static char **add_string_to_strings(char **strings, char *add)
  1454. {
  1455. char *v[2];
  1456. v[0] = add;
  1457. v[1] = NULL;
  1458. return add_strings_to_strings(strings, v, /*dup:*/ 0);
  1459. }
  1460. #if LEAK_HUNTING
  1461. static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
  1462. {
  1463. char **ptr = add_string_to_strings(strings, add);
  1464. fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
  1465. return ptr;
  1466. }
  1467. #define add_string_to_strings(strings, add) \
  1468. xx_add_string_to_strings(__LINE__, strings, add)
  1469. #endif
  1470. static void free_strings(char **strings)
  1471. {
  1472. char **v;
  1473. if (!strings)
  1474. return;
  1475. v = strings;
  1476. while (*v) {
  1477. free(*v);
  1478. v++;
  1479. }
  1480. free(strings);
  1481. }
  1482. static int dup_CLOEXEC(int fd, int avoid_fd)
  1483. {
  1484. int newfd;
  1485. repeat:
  1486. newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
  1487. if (newfd >= 0) {
  1488. if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
  1489. fcntl(newfd, F_SETFD, FD_CLOEXEC);
  1490. } else { /* newfd < 0 */
  1491. if (errno == EBUSY)
  1492. goto repeat;
  1493. if (errno == EINTR)
  1494. goto repeat;
  1495. }
  1496. return newfd;
  1497. }
  1498. static int xdup_CLOEXEC_and_close(int fd, int avoid_fd)
  1499. {
  1500. int newfd;
  1501. repeat:
  1502. newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
  1503. if (newfd < 0) {
  1504. if (errno == EBUSY)
  1505. goto repeat;
  1506. if (errno == EINTR)
  1507. goto repeat;
  1508. /* fd was not open? */
  1509. if (errno == EBADF)
  1510. return fd;
  1511. xfunc_die();
  1512. }
  1513. if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
  1514. fcntl(newfd, F_SETFD, FD_CLOEXEC);
  1515. close(fd);
  1516. return newfd;
  1517. }
  1518. /* Manipulating HFILEs */
  1519. static HFILE *hfopen(const char *name)
  1520. {
  1521. HFILE *fp;
  1522. int fd;
  1523. fd = STDIN_FILENO;
  1524. if (name) {
  1525. fd = open(name, O_RDONLY | O_CLOEXEC);
  1526. if (fd < 0)
  1527. return NULL;
  1528. if (O_CLOEXEC == 0) /* ancient libc */
  1529. close_on_exec_on(fd);
  1530. }
  1531. fp = xmalloc(sizeof(*fp));
  1532. if (name == NULL)
  1533. G.HFILE_stdin = fp;
  1534. fp->fd = fd;
  1535. fp->cur = fp->end = fp->buf;
  1536. fp->next_hfile = G.HFILE_list;
  1537. G.HFILE_list = fp;
  1538. return fp;
  1539. }
  1540. static void hfclose(HFILE *fp)
  1541. {
  1542. HFILE **pp = &G.HFILE_list;
  1543. while (*pp) {
  1544. HFILE *cur = *pp;
  1545. if (cur == fp) {
  1546. *pp = cur->next_hfile;
  1547. break;
  1548. }
  1549. pp = &cur->next_hfile;
  1550. }
  1551. if (fp->fd >= 0)
  1552. close(fp->fd);
  1553. free(fp);
  1554. }
  1555. static int refill_HFILE_and_getc(HFILE *fp)
  1556. {
  1557. int n;
  1558. if (fp->fd < 0) {
  1559. /* Already saw EOF */
  1560. return EOF;
  1561. }
  1562. #if ENABLE_HUSH_INTERACTIVE && !ENABLE_FEATURE_EDITING
  1563. /* If user presses ^C, read() restarts after SIGINT (we use SA_RESTART).
  1564. * IOW: ^C will not immediately stop line input.
  1565. * But poll() is different: it does NOT restart after signals.
  1566. */
  1567. if (fp == G.HFILE_stdin) {
  1568. struct pollfd pfd[1];
  1569. pfd[0].fd = fp->fd;
  1570. pfd[0].events = POLLIN;
  1571. n = poll(pfd, 1, -1);
  1572. if (n < 0
  1573. /*&& errno == EINTR - assumed true */
  1574. && sigismember(&G.pending_set, SIGINT)
  1575. ) {
  1576. return '\0';
  1577. }
  1578. }
  1579. #else
  1580. /* if FEATURE_EDITING=y, we do not use this routine for interactive input */
  1581. #endif
  1582. /* Try to buffer more input */
  1583. n = safe_read(fp->fd, fp->buf, sizeof(fp->buf));
  1584. if (n < 0) {
  1585. bb_simple_perror_msg("read error");
  1586. n = 0;
  1587. }
  1588. fp->cur = fp->buf;
  1589. fp->end = fp->buf + n;
  1590. if (n == 0) {
  1591. /* EOF/error */
  1592. close(fp->fd);
  1593. fp->fd = -1;
  1594. return EOF;
  1595. }
  1596. return (unsigned char)(*fp->cur++);
  1597. }
  1598. /* Inlined for common case of non-empty buffer.
  1599. */
  1600. static ALWAYS_INLINE int hfgetc(HFILE *fp)
  1601. {
  1602. if (fp->cur < fp->end)
  1603. return (unsigned char)(*fp->cur++);
  1604. /* Buffer empty */
  1605. return refill_HFILE_and_getc(fp);
  1606. }
  1607. static int move_HFILEs_on_redirect(int fd, int avoid_fd)
  1608. {
  1609. HFILE *fl = G.HFILE_list;
  1610. while (fl) {
  1611. if (fd == fl->fd) {
  1612. /* We use it only on script files, they are all CLOEXEC */
  1613. fl->fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
  1614. debug_printf_redir("redirect_fd %d: matches a script fd, moving it to %d\n", fd, fl->fd);
  1615. return 1; /* "found and moved" */
  1616. }
  1617. fl = fl->next_hfile;
  1618. }
  1619. #if ENABLE_HUSH_MODE_X
  1620. if (G.x_mode_fd > 0 && fd == G.x_mode_fd) {
  1621. G.x_mode_fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
  1622. return 1; /* "found and moved" */
  1623. }
  1624. #endif
  1625. return 0; /* "not in the list" */
  1626. }
  1627. #if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
  1628. static void close_all_HFILE_list(void)
  1629. {
  1630. HFILE *fl = G.HFILE_list;
  1631. while (fl) {
  1632. /* hfclose would also free HFILE object.
  1633. * It is disastrous if we share memory with a vforked parent.
  1634. * I'm not sure we never come here after vfork.
  1635. * Therefore just close fd, nothing more.
  1636. *
  1637. * ">" instead of ">=": we don't close fd#0,
  1638. * interactive shell uses hfopen(NULL) as stdin input
  1639. * which has fl->fd == 0, but fd#0 gets redirected in pipes.
  1640. * If we'd close it here, then e.g. interactive "set | sort"
  1641. * with NOFORKed sort, would have sort's input fd closed.
  1642. */
  1643. if (fl->fd > 0)
  1644. /*hfclose(fl); - unsafe */
  1645. close(fl->fd);
  1646. fl = fl->next_hfile;
  1647. }
  1648. }
  1649. #endif
  1650. static int fd_in_HFILEs(int fd)
  1651. {
  1652. HFILE *fl = G.HFILE_list;
  1653. while (fl) {
  1654. if (fl->fd == fd)
  1655. return 1;
  1656. fl = fl->next_hfile;
  1657. }
  1658. return 0;
  1659. }
  1660. /* Helpers for setting new $n and restoring them back
  1661. */
  1662. typedef struct save_arg_t {
  1663. char *sv_argv0;
  1664. char **sv_g_argv;
  1665. int sv_g_argc;
  1666. IF_HUSH_SET(smallint sv_g_malloced;)
  1667. } save_arg_t;
  1668. static void save_and_replace_G_args(save_arg_t *sv, char **argv)
  1669. {
  1670. sv->sv_argv0 = argv[0];
  1671. sv->sv_g_argv = G.global_argv;
  1672. sv->sv_g_argc = G.global_argc;
  1673. IF_HUSH_SET(sv->sv_g_malloced = G.global_args_malloced;)
  1674. argv[0] = G.global_argv[0]; /* retain $0 */
  1675. G.global_argv = argv;
  1676. IF_HUSH_SET(G.global_args_malloced = 0;)
  1677. G.global_argc = 1 + string_array_len(argv + 1);
  1678. }
  1679. static void restore_G_args(save_arg_t *sv, char **argv)
  1680. {
  1681. #if ENABLE_HUSH_SET
  1682. if (G.global_args_malloced) {
  1683. /* someone ran "set -- arg1 arg2 ...", undo */
  1684. char **pp = G.global_argv;
  1685. while (*++pp) /* note: does not free $0 */
  1686. free(*pp);
  1687. free(G.global_argv);
  1688. }
  1689. #endif
  1690. argv[0] = sv->sv_argv0;
  1691. G.global_argv = sv->sv_g_argv;
  1692. G.global_argc = sv->sv_g_argc;
  1693. IF_HUSH_SET(G.global_args_malloced = sv->sv_g_malloced;)
  1694. }
  1695. /* Basic theory of signal handling in shell
  1696. * ========================================
  1697. * This does not describe what hush does, rather, it is current understanding
  1698. * what it _should_ do. If it doesn't, it's a bug.
  1699. * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
  1700. *
  1701. * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
  1702. * is finished or backgrounded. It is the same in interactive and
  1703. * non-interactive shells, and is the same regardless of whether
  1704. * a user trap handler is installed or a shell special one is in effect.
  1705. * ^C or ^Z from keyboard seems to execute "at once" because it usually
  1706. * backgrounds (i.e. stops) or kills all members of currently running
  1707. * pipe.
  1708. *
  1709. * Wait builtin is interruptible by signals for which user trap is set
  1710. * or by SIGINT in interactive shell.
  1711. *
  1712. * Trap handlers will execute even within trap handlers. (right?)
  1713. *
  1714. * User trap handlers are forgotten when subshell ("(cmd)") is entered,
  1715. * except for handlers set to '' (empty string).
  1716. *
  1717. * If job control is off, backgrounded commands ("cmd &")
  1718. * have SIGINT, SIGQUIT set to SIG_IGN.
  1719. *
  1720. * Commands which are run in command substitution ("`cmd`")
  1721. * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
  1722. *
  1723. * Ordinary commands have signals set to SIG_IGN/DFL as inherited
  1724. * by the shell from its parent.
  1725. *
  1726. * Signals which differ from SIG_DFL action
  1727. * (note: child (i.e., [v]forked) shell is not an interactive shell):
  1728. *
  1729. * SIGQUIT: ignore
  1730. * SIGTERM (interactive): ignore
  1731. * SIGHUP (interactive):
  1732. * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
  1733. * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
  1734. * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
  1735. * that all pipe members are stopped. Try this in bash:
  1736. * while :; do :; done - ^Z does not background it
  1737. * (while :; do :; done) - ^Z backgrounds it
  1738. * SIGINT (interactive): wait for last pipe, ignore the rest
  1739. * of the command line, show prompt. NB: ^C does not send SIGINT
  1740. * to interactive shell while shell is waiting for a pipe,
  1741. * since shell is bg'ed (is not in foreground process group).
  1742. * Example 1: this waits 5 sec, but does not execute ls:
  1743. * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
  1744. * Example 2: this does not wait and does not execute ls:
  1745. * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
  1746. * Example 3: this does not wait 5 sec, but executes ls:
  1747. * "sleep 5; ls -l" + press ^C
  1748. * Example 4: this does not wait and does not execute ls:
  1749. * "sleep 5 & wait; ls -l" + press ^C
  1750. *
  1751. * (What happens to signals which are IGN on shell start?)
  1752. * (What happens with signal mask on shell start?)
  1753. *
  1754. * Old implementation
  1755. * ==================
  1756. * We use in-kernel pending signal mask to determine which signals were sent.
  1757. * We block all signals which we don't want to take action immediately,
  1758. * i.e. we block all signals which need to have special handling as described
  1759. * above, and all signals which have traps set.
  1760. * After each pipe execution, we extract any pending signals via sigtimedwait()
  1761. * and act on them.
  1762. *
  1763. * unsigned special_sig_mask: a mask of such "special" signals
  1764. * sigset_t blocked_set: current blocked signal set
  1765. *
  1766. * "trap - SIGxxx":
  1767. * clear bit in blocked_set unless it is also in special_sig_mask
  1768. * "trap 'cmd' SIGxxx":
  1769. * set bit in blocked_set (even if 'cmd' is '')
  1770. * after [v]fork, if we plan to be a shell:
  1771. * unblock signals with special interactive handling
  1772. * (child shell is not interactive),
  1773. * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
  1774. * after [v]fork, if we plan to exec:
  1775. * POSIX says fork clears pending signal mask in child - no need to clear it.
  1776. * Restore blocked signal set to one inherited by shell just prior to exec.
  1777. *
  1778. * Note: as a result, we do not use signal handlers much. The only uses
  1779. * are to count SIGCHLDs
  1780. * and to restore tty pgrp on signal-induced exit.
  1781. *
  1782. * Note 2 (compat):
  1783. * Standard says "When a subshell is entered, traps that are not being ignored
  1784. * are set to the default actions". bash interprets it so that traps which
  1785. * are set to '' (ignore) are NOT reset to defaults. We do the same.
  1786. *
  1787. * Problem: the above approach makes it unwieldy to catch signals while
  1788. * we are in read builtin, or while we read commands from stdin:
  1789. * masked signals are not visible!
  1790. *
  1791. * New implementation
  1792. * ==================
  1793. * We record each signal we are interested in by installing signal handler
  1794. * for them - a bit like emulating kernel pending signal mask in userspace.
  1795. * We are interested in: signals which need to have special handling
  1796. * as described above, and all signals which have traps set.
  1797. * Signals are recorded in pending_set.
  1798. * After each pipe execution, we extract any pending signals
  1799. * and act on them.
  1800. *
  1801. * unsigned special_sig_mask: a mask of shell-special signals.
  1802. * unsigned fatal_sig_mask: a mask of signals on which we restore tty pgrp.
  1803. * char *traps[sig] if trap for sig is set (even if it's '').
  1804. * sigset_t pending_set: set of sigs we received.
  1805. *
  1806. * "trap - SIGxxx":
  1807. * if sig is in special_sig_mask, set handler back to:
  1808. * record_pending_signo, or to IGN if it's a tty stop signal
  1809. * if sig is in fatal_sig_mask, set handler back to sigexit.
  1810. * else: set handler back to SIG_DFL
  1811. * "trap 'cmd' SIGxxx":
  1812. * set handler to record_pending_signo.
  1813. * "trap '' SIGxxx":
  1814. * set handler to SIG_IGN.
  1815. * after [v]fork, if we plan to be a shell:
  1816. * set signals with special interactive handling to SIG_DFL
  1817. * (because child shell is not interactive),
  1818. * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
  1819. * after [v]fork, if we plan to exec:
  1820. * POSIX says fork clears pending signal mask in child - no need to clear it.
  1821. *
  1822. * To make wait builtin interruptible, we handle SIGCHLD as special signal,
  1823. * otherwise (if we leave it SIG_DFL) sigsuspend in wait builtin will not wake up on it.
  1824. *
  1825. * Note (compat):
  1826. * Standard says "When a subshell is entered, traps that are not being ignored
  1827. * are set to the default actions". bash interprets it so that traps which
  1828. * are set to '' (ignore) are NOT reset to defaults. We do the same.
  1829. */
  1830. enum {
  1831. SPECIAL_INTERACTIVE_SIGS = 0
  1832. | (1 << SIGTERM)
  1833. | (1 << SIGINT)
  1834. | (1 << SIGHUP)
  1835. ,
  1836. SPECIAL_JOBSTOP_SIGS = 0
  1837. #if ENABLE_HUSH_JOB
  1838. | (1 << SIGTTIN)
  1839. | (1 << SIGTTOU)
  1840. | (1 << SIGTSTP)
  1841. #endif
  1842. ,
  1843. };
  1844. static void record_pending_signo(int sig)
  1845. {
  1846. sigaddset(&G.pending_set, sig);
  1847. #if ENABLE_HUSH_FAST
  1848. if (sig == SIGCHLD) {
  1849. G.count_SIGCHLD++;
  1850. //bb_error_msg("[%d] SIGCHLD_handler: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
  1851. }
  1852. #endif
  1853. }
  1854. static sighandler_t install_sighandler(int sig, sighandler_t handler)
  1855. {
  1856. struct sigaction old_sa;
  1857. /* We could use signal() to install handlers... almost:
  1858. * except that we need to mask ALL signals while handlers run.
  1859. * I saw signal nesting in strace, race window isn't small.
  1860. * SA_RESTART is also needed, but in Linux, signal()
  1861. * sets SA_RESTART too.
  1862. */
  1863. /* memset(&G.sa, 0, sizeof(G.sa)); - already done */
  1864. /* sigfillset(&G.sa.sa_mask); - already done */
  1865. /* G.sa.sa_flags = SA_RESTART; - already done */
  1866. G.sa.sa_handler = handler;
  1867. sigaction(sig, &G.sa, &old_sa);
  1868. return old_sa.sa_handler;
  1869. }
  1870. static void hush_exit(int exitcode) NORETURN;
  1871. static void restore_ttypgrp_and__exit(void) NORETURN;
  1872. static void restore_ttypgrp_and__exit(void)
  1873. {
  1874. /* xfunc has failed! die die die */
  1875. /* no EXIT traps, this is an escape hatch! */
  1876. G.exiting = 1;
  1877. hush_exit(xfunc_error_retval);
  1878. }
  1879. #if ENABLE_HUSH_JOB
  1880. /* Needed only on some libc:
  1881. * It was observed that on exit(), fgetc'ed buffered data
  1882. * gets "unwound" via lseek(fd, -NUM, SEEK_CUR).
  1883. * With the net effect that even after fork(), not vfork(),
  1884. * exit() in NOEXECed applet in "sh SCRIPT":
  1885. * noexec_applet_here
  1886. * echo END_OF_SCRIPT
  1887. * lseeks fd in input FILE object from EOF to "e" in "echo END_OF_SCRIPT".
  1888. * This makes "echo END_OF_SCRIPT" executed twice.
  1889. * Similar problems can be seen with msg_and_die_if_script() -> xfunc_die()
  1890. * and in `cmd` handling.
  1891. * If set as die_func(), this makes xfunc_die() exit via _exit(), not exit():
  1892. */
  1893. static void fflush_and__exit(void) NORETURN;
  1894. static void fflush_and__exit(void)
  1895. {
  1896. fflush_all();
  1897. _exit(xfunc_error_retval);
  1898. }
  1899. /* After [v]fork, in child: do not restore tty pgrp on xfunc death */
  1900. # define disable_restore_tty_pgrp_on_exit() (die_func = fflush_and__exit)
  1901. /* After [v]fork, in parent: restore tty pgrp on xfunc death */
  1902. # define enable_restore_tty_pgrp_on_exit() (die_func = restore_ttypgrp_and__exit)
  1903. /* Restores tty foreground process group, and exits.
  1904. * May be called as signal handler for fatal signal
  1905. * (will resend signal to itself, producing correct exit state)
  1906. * or called directly with -EXITCODE.
  1907. * We also call it if xfunc is exiting.
  1908. */
  1909. static void sigexit(int sig) NORETURN;
  1910. static void sigexit(int sig)
  1911. {
  1912. /* Careful: we can end up here after [v]fork. Do not restore
  1913. * tty pgrp then, only top-level shell process does that */
  1914. if (G_saved_tty_pgrp && getpid() == G.root_pid) {
  1915. /* Disable all signals: job control, SIGPIPE, etc.
  1916. * Mostly paranoid measure, to prevent infinite SIGTTOU.
  1917. */
  1918. sigprocmask_allsigs(SIG_BLOCK);
  1919. tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
  1920. }
  1921. /* Not a signal, just exit */
  1922. if (sig <= 0)
  1923. _exit(- sig);
  1924. kill_myself_with_sig(sig); /* does not return */
  1925. }
  1926. #else
  1927. # define disable_restore_tty_pgrp_on_exit() ((void)0)
  1928. # define enable_restore_tty_pgrp_on_exit() ((void)0)
  1929. #endif
  1930. static sighandler_t pick_sighandler(unsigned sig)
  1931. {
  1932. sighandler_t handler = SIG_DFL;
  1933. if (sig < sizeof(unsigned)*8) {
  1934. unsigned sigmask = (1 << sig);
  1935. #if ENABLE_HUSH_JOB
  1936. /* is sig fatal? */
  1937. if (G_fatal_sig_mask & sigmask)
  1938. handler = sigexit;
  1939. else
  1940. #endif
  1941. /* sig has special handling? */
  1942. if (G.special_sig_mask & sigmask) {
  1943. handler = record_pending_signo;
  1944. /* TTIN/TTOU/TSTP can't be set to record_pending_signo
  1945. * in order to ignore them: they will be raised
  1946. * in an endless loop when we try to do some
  1947. * terminal ioctls! We do have to _ignore_ these.
  1948. */
  1949. if (SPECIAL_JOBSTOP_SIGS & sigmask)
  1950. handler = SIG_IGN;
  1951. }
  1952. }
  1953. return handler;
  1954. }
  1955. /* Restores tty foreground process group, and exits. */
  1956. static void hush_exit(int exitcode)
  1957. {
  1958. #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
  1959. save_history(G.line_input_state); /* may be NULL */
  1960. #endif
  1961. fflush_all();
  1962. if (G.exiting <= 0 && G_traps && G_traps[0] && G_traps[0][0]) {
  1963. char *argv[3];
  1964. /* argv[0] is unused */
  1965. argv[1] = xstrdup(G_traps[0]); /* copy, since EXIT trap handler may modify G_traps[0] */
  1966. argv[2] = NULL;
  1967. G.exiting = 1; /* prevent EXIT trap recursion */
  1968. /* Note: G_traps[0] is not cleared!
  1969. * "trap" will still show it, if executed
  1970. * in the handler */
  1971. builtin_eval(argv);
  1972. }
  1973. #if ENABLE_FEATURE_CLEAN_UP
  1974. {
  1975. struct variable *cur_var;
  1976. if (G.cwd != bb_msg_unknown)
  1977. free((char*)G.cwd);
  1978. cur_var = G.top_var;
  1979. while (cur_var) {
  1980. struct variable *tmp = cur_var;
  1981. if (!cur_var->max_len)
  1982. free(cur_var->varstr);
  1983. cur_var = cur_var->next;
  1984. free(tmp);
  1985. }
  1986. }
  1987. #endif
  1988. fflush_all();
  1989. #if ENABLE_HUSH_JOB
  1990. sigexit(- (exitcode & 0xff));
  1991. #else
  1992. _exit(exitcode);
  1993. #endif
  1994. }
  1995. //TODO: return a mask of ALL handled sigs?
  1996. static int check_and_run_traps(void)
  1997. {
  1998. int last_sig = 0;
  1999. while (1) {
  2000. int sig;
  2001. if (sigisemptyset(&G.pending_set))
  2002. break;
  2003. sig = 0;
  2004. do {
  2005. sig++;
  2006. if (sigismember(&G.pending_set, sig)) {
  2007. sigdelset(&G.pending_set, sig);
  2008. goto got_sig;
  2009. }
  2010. } while (sig < NSIG);
  2011. break;
  2012. got_sig:
  2013. #if ENABLE_HUSH_TRAP
  2014. if (G_traps && G_traps[sig]) {
  2015. debug_printf_exec("%s: sig:%d handler:'%s'\n", __func__, sig, G.traps[sig]);
  2016. if (G_traps[sig][0]) {
  2017. /* We have user-defined handler */
  2018. smalluint save_rcode;
  2019. int save_pre;
  2020. char *argv[3];
  2021. /* argv[0] is unused */
  2022. argv[1] = xstrdup(G_traps[sig]);
  2023. /* why strdup? trap can modify itself: trap 'trap "echo oops" INT' INT */
  2024. argv[2] = NULL;
  2025. save_pre = G.pre_trap_exitcode;
  2026. G.pre_trap_exitcode = save_rcode = G.last_exitcode;
  2027. builtin_eval(argv);
  2028. free(argv[1]);
  2029. G.pre_trap_exitcode = save_pre;
  2030. G.last_exitcode = save_rcode;
  2031. # if ENABLE_HUSH_FUNCTIONS
  2032. if (G.return_exitcode >= 0) {
  2033. debug_printf_exec("trap exitcode:%d\n", G.return_exitcode);
  2034. G.last_exitcode = G.return_exitcode;
  2035. }
  2036. # endif
  2037. last_sig = sig;
  2038. } /* else: "" trap, ignoring signal */
  2039. continue;
  2040. }
  2041. #endif
  2042. /* not a trap: special action */
  2043. switch (sig) {
  2044. case SIGINT:
  2045. debug_printf_exec("%s: sig:%d default SIGINT handler\n", __func__, sig);
  2046. G.flag_SIGINT = 1;
  2047. last_sig = sig;
  2048. break;
  2049. #if ENABLE_HUSH_JOB
  2050. case SIGHUP: {
  2051. //TODO: why are we doing this? ash and dash don't do this,
  2052. //they have no handler for SIGHUP at all,
  2053. //they rely on kernel to send SIGHUP+SIGCONT to orphaned process groups
  2054. struct pipe *job;
  2055. debug_printf_exec("%s: sig:%d default SIGHUP handler\n", __func__, sig);
  2056. /* bash is observed to signal whole process groups,
  2057. * not individual processes */
  2058. for (job = G.job_list; job; job = job->next) {
  2059. if (job->pgrp <= 0)
  2060. continue;
  2061. debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
  2062. if (kill(- job->pgrp, SIGHUP) == 0)
  2063. kill(- job->pgrp, SIGCONT);
  2064. }
  2065. sigexit(SIGHUP);
  2066. }
  2067. #endif
  2068. #if ENABLE_HUSH_FAST
  2069. case SIGCHLD:
  2070. debug_printf_exec("%s: sig:%d default SIGCHLD handler\n", __func__, sig);
  2071. G.count_SIGCHLD++;
  2072. //bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
  2073. /* Note:
  2074. * We don't do 'last_sig = sig' here -> NOT returning this sig.
  2075. * This simplifies wait builtin a bit.
  2076. */
  2077. break;
  2078. #endif
  2079. default: /* ignored: */
  2080. debug_printf_exec("%s: sig:%d default handling is to ignore\n", __func__, sig);
  2081. /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
  2082. /* Note:
  2083. * We don't do 'last_sig = sig' here -> NOT returning this sig.
  2084. * Example: wait is not interrupted by TERM
  2085. * in interactive shell, because TERM is ignored.
  2086. */
  2087. break;
  2088. }
  2089. }
  2090. return last_sig;
  2091. }
  2092. static const char *get_cwd(int force)
  2093. {
  2094. if (force || G.cwd == NULL) {
  2095. /* xrealloc_getcwd_or_warn(arg) calls free(arg),
  2096. * we must not try to free(bb_msg_unknown) */
  2097. if (G.cwd == bb_msg_unknown)
  2098. G.cwd = NULL;
  2099. G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
  2100. if (!G.cwd)
  2101. G.cwd = bb_msg_unknown;
  2102. }
  2103. return G.cwd;
  2104. }
  2105. /*
  2106. * Shell and environment variable support
  2107. */
  2108. static struct variable **get_ptr_to_local_var(const char *name, unsigned len)
  2109. {
  2110. struct variable **pp;
  2111. struct variable *cur;
  2112. pp = &G.top_var;
  2113. while ((cur = *pp) != NULL) {
  2114. if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
  2115. return pp;
  2116. pp = &cur->next;
  2117. }
  2118. return NULL;
  2119. }
  2120. static const char* FAST_FUNC get_local_var_value(const char *name)
  2121. {
  2122. struct variable **vpp;
  2123. unsigned len = strlen(name);
  2124. if (G.expanded_assignments) {
  2125. char **cpp = G.expanded_assignments;
  2126. while (*cpp) {
  2127. char *cp = *cpp;
  2128. if (strncmp(cp, name, len) == 0 && cp[len] == '=')
  2129. return cp + len + 1;
  2130. cpp++;
  2131. }
  2132. }
  2133. vpp = get_ptr_to_local_var(name, len);
  2134. if (vpp)
  2135. return (*vpp)->varstr + len + 1;
  2136. if (strcmp(name, "PPID") == 0)
  2137. return utoa(G.root_ppid);
  2138. // bash compat: UID? EUID?
  2139. #if ENABLE_HUSH_RANDOM_SUPPORT
  2140. if (strcmp(name, "RANDOM") == 0)
  2141. return utoa(next_random(&G.random_gen));
  2142. #endif
  2143. #if ENABLE_HUSH_LINENO_VAR
  2144. if (strcmp(name, "LINENO") == 0)
  2145. return utoa(G.execute_lineno);
  2146. #endif
  2147. #if BASH_EPOCH_VARS
  2148. {
  2149. const char *fmt = NULL;
  2150. if (strcmp(name, "EPOCHSECONDS") == 0)
  2151. fmt = "%llu";
  2152. else if (strcmp(name, "EPOCHREALTIME") == 0)
  2153. fmt = "%llu.%06u";
  2154. if (fmt) {
  2155. struct timeval tv;
  2156. xgettimeofday(&tv);
  2157. sprintf(G.epoch_buf, fmt, (unsigned long long)tv.tv_sec,
  2158. (unsigned)tv.tv_usec);
  2159. return G.epoch_buf;
  2160. }
  2161. }
  2162. #endif
  2163. return NULL;
  2164. }
  2165. #if ENABLE_HUSH_GETOPTS
  2166. static void handle_changed_special_names(const char *name, unsigned name_len)
  2167. {
  2168. if (name_len == 6) {
  2169. if (strncmp(name, "OPTIND", 6) == 0) {
  2170. G.getopt_count = 0;
  2171. return;
  2172. }
  2173. }
  2174. }
  2175. #else
  2176. /* Do not even bother evaluating arguments */
  2177. # define handle_changed_special_names(...) ((void)0)
  2178. #endif
  2179. /* str holds "NAME=VAL" and is expected to be malloced.
  2180. * We take ownership of it.
  2181. */
  2182. #define SETFLAG_EXPORT (1 << 0)
  2183. #define SETFLAG_UNEXPORT (1 << 1)
  2184. #define SETFLAG_MAKE_RO (1 << 2)
  2185. #define SETFLAG_VARLVL_SHIFT 3
  2186. static int set_local_var(char *str, unsigned flags)
  2187. {
  2188. struct variable **cur_pp;
  2189. struct variable *cur;
  2190. char *free_me = NULL;
  2191. char *eq_sign;
  2192. int name_len;
  2193. int retval;
  2194. unsigned local_lvl = (flags >> SETFLAG_VARLVL_SHIFT);
  2195. eq_sign = strchr(str, '=');
  2196. if (HUSH_DEBUG && !eq_sign)
  2197. bb_simple_error_msg_and_die("BUG in setvar");
  2198. name_len = eq_sign - str + 1; /* including '=' */
  2199. cur_pp = &G.top_var;
  2200. while ((cur = *cur_pp) != NULL) {
  2201. if (strncmp(cur->varstr, str, name_len) != 0) {
  2202. cur_pp = &cur->next;
  2203. continue;
  2204. }
  2205. /* We found an existing var with this name */
  2206. if (cur->flg_read_only) {
  2207. bb_error_msg("%s: readonly variable", str);
  2208. free(str);
  2209. //NOTE: in bash, assignment in "export READONLY_VAR=Z" fails, and sets $?=1,
  2210. //but export per se succeeds (does put the var in env). We don't mimic that.
  2211. return -1;
  2212. }
  2213. if (flags & SETFLAG_UNEXPORT) { // && cur->flg_export ?
  2214. debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
  2215. *eq_sign = '\0';
  2216. unsetenv(str);
  2217. *eq_sign = '=';
  2218. }
  2219. if (cur->var_nest_level < local_lvl) {
  2220. /* bash 3.2.33(1) and exported vars:
  2221. * # export z=z
  2222. * # f() { local z=a; env | grep ^z; }
  2223. * # f
  2224. * z=a
  2225. * # env | grep ^z
  2226. * z=z
  2227. */
  2228. if (cur->flg_export)
  2229. flags |= SETFLAG_EXPORT;
  2230. /* New variable is local ("local VAR=VAL" or
  2231. * "VAR=VAL cmd")
  2232. * and existing one is global, or local
  2233. * on a lower level that new one.
  2234. * Remove it from global variable list:
  2235. */
  2236. *cur_pp = cur->next;
  2237. if (G.shadowed_vars_pp) {
  2238. /* Save in "shadowed" list */
  2239. debug_printf_env("shadowing %s'%s'/%u by '%s'/%u\n",
  2240. cur->flg_export ? "exported " : "",
  2241. cur->varstr, cur->var_nest_level, str, local_lvl
  2242. );
  2243. cur->next = *G.shadowed_vars_pp;
  2244. *G.shadowed_vars_pp = cur;
  2245. } else {
  2246. /* Came from pseudo_exec_argv(), no need to save: delete it */
  2247. debug_printf_env("shadow-deleting %s'%s'/%u by '%s'/%u\n",
  2248. cur->flg_export ? "exported " : "",
  2249. cur->varstr, cur->var_nest_level, str, local_lvl
  2250. );
  2251. if (cur->max_len == 0) /* allocated "VAR=VAL"? */
  2252. free_me = cur->varstr; /* then free it later */
  2253. free(cur);
  2254. }
  2255. break;
  2256. }
  2257. if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
  2258. debug_printf_env("assignement '%s' does not change anything\n", str);
  2259. free_and_exp:
  2260. free(str);
  2261. goto exp;
  2262. }
  2263. /* Replace the value in the found "struct variable" */
  2264. if (cur->max_len != 0) {
  2265. if (cur->max_len >= strnlen(str, cur->max_len + 1)) {
  2266. /* This one is from startup env, reuse space */
  2267. debug_printf_env("reusing startup env for '%s'\n", str);
  2268. strcpy(cur->varstr, str);
  2269. goto free_and_exp;
  2270. }
  2271. /* Can't reuse */
  2272. cur->max_len = 0;
  2273. goto set_str_and_exp;
  2274. }
  2275. /* max_len == 0 signifies "malloced" var, which we can
  2276. * (and have to) free. But we can't free(cur->varstr) here:
  2277. * if cur->flg_export is 1, it is in the environment.
  2278. * We should either unsetenv+free, or wait until putenv,
  2279. * then putenv(new)+free(old).
  2280. */
  2281. free_me = cur->varstr;
  2282. goto set_str_and_exp;
  2283. }
  2284. /* Not found or shadowed - create new variable struct */
  2285. debug_printf_env("%s: alloc new var '%s'/%u\n", __func__, str, local_lvl);
  2286. cur = xzalloc(sizeof(*cur));
  2287. cur->var_nest_level = local_lvl;
  2288. cur->next = *cur_pp;
  2289. *cur_pp = cur;
  2290. set_str_and_exp:
  2291. cur->varstr = str;
  2292. exp:
  2293. #if !BB_MMU || ENABLE_HUSH_READONLY
  2294. if (flags & SETFLAG_MAKE_RO) {
  2295. cur->flg_read_only = 1;
  2296. }
  2297. #endif
  2298. if (flags & SETFLAG_EXPORT)
  2299. cur->flg_export = 1;
  2300. retval = 0;
  2301. if (cur->flg_export) {
  2302. if (flags & SETFLAG_UNEXPORT) {
  2303. cur->flg_export = 0;
  2304. /* unsetenv was already done */
  2305. } else {
  2306. debug_printf_env("%s: putenv '%s'/%u\n", __func__, cur->varstr, cur->var_nest_level);
  2307. retval = putenv(cur->varstr);
  2308. /* fall through to "free(free_me)" -
  2309. * only now we can free old exported malloced string
  2310. */
  2311. }
  2312. }
  2313. free(free_me);
  2314. handle_changed_special_names(cur->varstr, name_len - 1);
  2315. return retval;
  2316. }
  2317. static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
  2318. {
  2319. char *var = xasprintf("%s=%s", name, val);
  2320. set_local_var(var, /*flag:*/ 0);
  2321. }
  2322. /* Used at startup and after each cd */
  2323. static void set_pwd_var(unsigned flag)
  2324. {
  2325. set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)), flag);
  2326. }
  2327. #if ENABLE_HUSH_UNSET || ENABLE_HUSH_GETOPTS
  2328. static int unset_local_var_len(const char *name, int name_len)
  2329. {
  2330. struct variable *cur;
  2331. struct variable **cur_pp;
  2332. cur_pp = &G.top_var;
  2333. while ((cur = *cur_pp) != NULL) {
  2334. if (strncmp(cur->varstr, name, name_len) == 0
  2335. && cur->varstr[name_len] == '='
  2336. ) {
  2337. if (cur->flg_read_only) {
  2338. bb_error_msg("%s: readonly variable", name);
  2339. return EXIT_FAILURE;
  2340. }
  2341. *cur_pp = cur->next;
  2342. debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
  2343. bb_unsetenv(cur->varstr);
  2344. if (!cur->max_len)
  2345. free(cur->varstr);
  2346. free(cur);
  2347. break;
  2348. }
  2349. cur_pp = &cur->next;
  2350. }
  2351. /* Handle "unset LINENO" et al even if did not find the variable to unset */
  2352. handle_changed_special_names(name, name_len);
  2353. return EXIT_SUCCESS;
  2354. }
  2355. static int unset_local_var(const char *name)
  2356. {
  2357. return unset_local_var_len(name, strlen(name));
  2358. }
  2359. #endif
  2360. /*
  2361. * Helpers for "var1=val1 var2=val2 cmd" feature
  2362. */
  2363. static void add_vars(struct variable *var)
  2364. {
  2365. struct variable *next;
  2366. while (var) {
  2367. next = var->next;
  2368. var->next = G.top_var;
  2369. G.top_var = var;
  2370. if (var->flg_export) {
  2371. debug_printf_env("%s: restoring exported '%s'/%u\n", __func__, var->varstr, var->var_nest_level);
  2372. putenv(var->varstr);
  2373. } else {
  2374. debug_printf_env("%s: restoring variable '%s'/%u\n", __func__, var->varstr, var->var_nest_level);
  2375. }
  2376. var = next;
  2377. }
  2378. }
  2379. /* We put strings[i] into variable table and possibly putenv them.
  2380. * If variable is read only, we can free the strings[i]
  2381. * which attempts to overwrite it.
  2382. * The strings[] vector itself is freed.
  2383. */
  2384. static void set_vars_and_save_old(char **strings)
  2385. {
  2386. char **s;
  2387. if (!strings)
  2388. return;
  2389. s = strings;
  2390. while (*s) {
  2391. struct variable *var_p;
  2392. struct variable **var_pp;
  2393. char *eq;
  2394. eq = strchr(*s, '=');
  2395. if (HUSH_DEBUG && !eq)
  2396. bb_simple_error_msg_and_die("BUG in varexp4");
  2397. var_pp = get_ptr_to_local_var(*s, eq - *s);
  2398. if (var_pp) {
  2399. var_p = *var_pp;
  2400. if (var_p->flg_read_only) {
  2401. char **p;
  2402. bb_error_msg("%s: readonly variable", *s);
  2403. /*
  2404. * "VAR=V BLTIN" unsets VARs after BLTIN completes.
  2405. * If VAR is readonly, leaving it in the list
  2406. * after asssignment error (msg above)
  2407. * causes doubled error message later, on unset.
  2408. */
  2409. debug_printf_env("removing/freeing '%s' element\n", *s);
  2410. free(*s);
  2411. p = s;
  2412. do { *p = p[1]; p++; } while (*p);
  2413. goto next;
  2414. }
  2415. /* below, set_local_var() with nest level will
  2416. * "shadow" (remove) this variable from
  2417. * global linked list.
  2418. */
  2419. }
  2420. debug_printf_env("%s: env override '%s'/%u\n", __func__, *s, G.var_nest_level);
  2421. set_local_var(*s, (G.var_nest_level << SETFLAG_VARLVL_SHIFT) | SETFLAG_EXPORT);
  2422. s++;
  2423. next: ;
  2424. }
  2425. free(strings);
  2426. }
  2427. /*
  2428. * Unicode helper
  2429. */
  2430. static void reinit_unicode_for_hush(void)
  2431. {
  2432. /* Unicode support should be activated even if LANG is set
  2433. * _during_ shell execution, not only if it was set when
  2434. * shell was started. Therefore, re-check LANG every time:
  2435. */
  2436. if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
  2437. || ENABLE_UNICODE_USING_LOCALE
  2438. ) {
  2439. const char *s = get_local_var_value("LC_ALL");
  2440. if (!s) s = get_local_var_value("LC_CTYPE");
  2441. if (!s) s = get_local_var_value("LANG");
  2442. reinit_unicode(s);
  2443. }
  2444. }
  2445. /*
  2446. * in_str support (strings, and "strings" read from files).
  2447. */
  2448. #if ENABLE_HUSH_INTERACTIVE
  2449. /* To test correct lineedit/interactive behavior, type from command line:
  2450. * echo $P\
  2451. * \
  2452. * AT\
  2453. * H\
  2454. * \
  2455. * It exercises a lot of corner cases.
  2456. */
  2457. static const char *setup_prompt_string(void)
  2458. {
  2459. const char *prompt_str;
  2460. debug_printf_prompt("%s promptmode:%d\n", __func__, G.promptmode);
  2461. # if ENABLE_FEATURE_EDITING_FANCY_PROMPT
  2462. prompt_str = get_local_var_value(G.promptmode == 0 ? "PS1" : "PS2");
  2463. if (!prompt_str)
  2464. prompt_str = "";
  2465. # else
  2466. prompt_str = "> "; /* if PS2, else... */
  2467. if (G.promptmode == 0) { /* PS1 */
  2468. /* No fancy prompts supported, (re)generate "CURDIR $ " by hand */
  2469. free(G.PS1);
  2470. /* bash uses $PWD value, even if it is set by user.
  2471. * It uses current dir only if PWD is unset.
  2472. * We always use current dir. */
  2473. prompt_str = G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
  2474. }
  2475. # endif
  2476. debug_printf("prompt_str '%s'\n", prompt_str);
  2477. return prompt_str;
  2478. }
  2479. static int get_user_input(struct in_str *i)
  2480. {
  2481. # if ENABLE_FEATURE_EDITING
  2482. /* In EDITING case, this function reads next input line,
  2483. * saves it in i->p, then returns 1st char of it.
  2484. */
  2485. int r;
  2486. const char *prompt_str;
  2487. prompt_str = setup_prompt_string();
  2488. for (;;) {
  2489. reinit_unicode_for_hush();
  2490. G.flag_SIGINT = 0;
  2491. /* buglet: SIGINT will not make new prompt to appear _at once_,
  2492. * only after <Enter>. (^C works immediately) */
  2493. r = read_line_input(G.line_input_state, prompt_str,
  2494. G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1
  2495. );
  2496. /* read_line_input intercepts ^C, "convert" it to SIGINT */
  2497. if (r == 0) {
  2498. raise(SIGINT);
  2499. }
  2500. check_and_run_traps();
  2501. if (r != 0 && !G.flag_SIGINT)
  2502. break;
  2503. /* ^C or SIGINT: repeat */
  2504. /* bash prints ^C even on real SIGINT (non-kbd generated) */
  2505. write(STDOUT_FILENO, "^C\n", 3);
  2506. G.last_exitcode = 128 | SIGINT;
  2507. }
  2508. if (r < 0) {
  2509. /* EOF/error detected */
  2510. /* ^D on interactive input goes to next line before exiting: */
  2511. write(STDOUT_FILENO, "\n", 1);
  2512. i->p = NULL;
  2513. i->peek_buf[0] = r = EOF;
  2514. return r;
  2515. }
  2516. i->p = G.user_input_buf;
  2517. return (unsigned char)*i->p++;
  2518. # else
  2519. /* In !EDITING case, this function gets called for every char.
  2520. * Buffering happens deeper in the call chain, in hfgetc(i->file).
  2521. */
  2522. int r;
  2523. for (;;) {
  2524. G.flag_SIGINT = 0;
  2525. if (i->last_char == '\0' || i->last_char == '\n') {
  2526. const char *prompt_str = setup_prompt_string();
  2527. /* Why check_and_run_traps here? Try this interactively:
  2528. * $ trap 'echo INT' INT; (sleep 2; kill -INT $$) &
  2529. * $ <[enter], repeatedly...>
  2530. * Without check_and_run_traps, handler never runs.
  2531. */
  2532. check_and_run_traps();
  2533. fputs_stdout(prompt_str);
  2534. fflush_all();
  2535. }
  2536. r = hfgetc(i->file);
  2537. /* In !ENABLE_FEATURE_EDITING we don't use read_line_input,
  2538. * no ^C masking happens during fgetc, no special code for ^C:
  2539. * it generates SIGINT as usual.
  2540. */
  2541. check_and_run_traps();
  2542. if (r != '\0' && !G.flag_SIGINT)
  2543. break;
  2544. if (G.flag_SIGINT) {
  2545. /* ^C or SIGINT: repeat */
  2546. /* bash prints ^C even on real SIGINT (non-kbd generated) */
  2547. /* kernel prints "^C" itself, just print newline: */
  2548. write(STDOUT_FILENO, "\n", 1);
  2549. G.last_exitcode = 128 | SIGINT;
  2550. }
  2551. }
  2552. return r;
  2553. # endif
  2554. }
  2555. /* This is the magic location that prints prompts
  2556. * and gets data back from the user */
  2557. static int fgetc_interactive(struct in_str *i)
  2558. {
  2559. int ch;
  2560. /* If it's interactive stdin, get new line. */
  2561. if (G_interactive_fd && i->file == G.HFILE_stdin) {
  2562. /* Returns first char (or EOF), the rest is in i->p[] */
  2563. ch = get_user_input(i);
  2564. G.promptmode = 1; /* PS2 */
  2565. debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
  2566. } else {
  2567. /* Not stdin: script file, sourced file, etc */
  2568. do ch = hfgetc(i->file); while (ch == '\0');
  2569. }
  2570. return ch;
  2571. }
  2572. #else /* !INTERACTIVE */
  2573. static ALWAYS_INLINE int fgetc_interactive(struct in_str *i)
  2574. {
  2575. int ch;
  2576. do ch = hfgetc(i->file); while (ch == '\0');
  2577. return ch;
  2578. }
  2579. #endif /* !INTERACTIVE */
  2580. static int i_getch(struct in_str *i)
  2581. {
  2582. int ch;
  2583. if (!i->file) {
  2584. /* string-based in_str */
  2585. ch = (unsigned char)*i->p;
  2586. if (ch != '\0') {
  2587. i->p++;
  2588. i->last_char = ch;
  2589. return ch;
  2590. }
  2591. return EOF;
  2592. }
  2593. /* FILE-based in_str */
  2594. #if ENABLE_FEATURE_EDITING
  2595. /* This can be stdin, check line editing char[] buffer */
  2596. if (i->p && *i->p != '\0') {
  2597. ch = (unsigned char)*i->p++;
  2598. goto out;
  2599. }
  2600. #endif
  2601. /* peek_buf[] is an int array, not char. Can contain EOF. */
  2602. ch = i->peek_buf[0];
  2603. if (ch != 0) {
  2604. int ch2 = i->peek_buf[1];
  2605. i->peek_buf[0] = ch2;
  2606. if (ch2 == 0) /* very likely, avoid redundant write */
  2607. goto out;
  2608. i->peek_buf[1] = 0;
  2609. goto out;
  2610. }
  2611. ch = fgetc_interactive(i);
  2612. out:
  2613. debug_printf("file_get: got '%c' %d\n", ch, ch);
  2614. i->last_char = ch;
  2615. #if ENABLE_HUSH_LINENO_VAR
  2616. if (ch == '\n') {
  2617. G.parse_lineno++;
  2618. debug_printf_parse("G.parse_lineno++ = %u\n", G.parse_lineno);
  2619. }
  2620. #endif
  2621. return ch;
  2622. }
  2623. static int i_peek(struct in_str *i)
  2624. {
  2625. int ch;
  2626. if (!i->file) {
  2627. /* string-based in_str */
  2628. /* Doesn't report EOF on NUL. None of the callers care. */
  2629. return (unsigned char)*i->p;
  2630. }
  2631. /* FILE-based in_str */
  2632. #if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
  2633. /* This can be stdin, check line editing char[] buffer */
  2634. if (i->p && *i->p != '\0')
  2635. return (unsigned char)*i->p;
  2636. #endif
  2637. /* peek_buf[] is an int array, not char. Can contain EOF. */
  2638. ch = i->peek_buf[0];
  2639. if (ch != 0)
  2640. return ch;
  2641. /* Need to get a new char */
  2642. ch = fgetc_interactive(i);
  2643. debug_printf("file_peek: got '%c' %d\n", ch, ch);
  2644. /* Save it by either rolling back line editing buffer, or in i->peek_buf[0] */
  2645. #if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
  2646. if (i->p) {
  2647. i->p -= 1;
  2648. return ch;
  2649. }
  2650. #endif
  2651. i->peek_buf[0] = ch;
  2652. /*i->peek_buf[1] = 0; - already is */
  2653. return ch;
  2654. }
  2655. /* Only ever called if i_peek() was called, and did not return EOF.
  2656. * IOW: we know the previous peek saw an ordinary char, not EOF, not NUL,
  2657. * not end-of-line. Therefore we never need to read a new editing line here.
  2658. */
  2659. static int i_peek2(struct in_str *i)
  2660. {
  2661. int ch;
  2662. /* There are two cases when i->p[] buffer exists.
  2663. * (1) it's a string in_str.
  2664. * (2) It's a file, and we have a saved line editing buffer.
  2665. * In both cases, we know that i->p[0] exists and not NUL, and
  2666. * the peek2 result is in i->p[1].
  2667. */
  2668. if (i->p)
  2669. return (unsigned char)i->p[1];
  2670. /* Now we know it is a file-based in_str. */
  2671. /* peek_buf[] is an int array, not char. Can contain EOF. */
  2672. /* Is there 2nd char? */
  2673. ch = i->peek_buf[1];
  2674. if (ch == 0) {
  2675. /* We did not read it yet, get it now */
  2676. do ch = hfgetc(i->file); while (ch == '\0');
  2677. i->peek_buf[1] = ch;
  2678. }
  2679. debug_printf("file_peek2: got '%c' %d\n", ch, ch);
  2680. return ch;
  2681. }
  2682. static int i_getch_and_eat_bkslash_nl(struct in_str *input)
  2683. {
  2684. for (;;) {
  2685. int ch, ch2;
  2686. ch = i_getch(input);
  2687. if (ch != '\\')
  2688. return ch;
  2689. ch2 = i_peek(input);
  2690. if (ch2 != '\n')
  2691. return ch;
  2692. /* backslash+newline, skip it */
  2693. i_getch(input);
  2694. }
  2695. }
  2696. /* Note: this function _eats_ \<newline> pairs, safe to use plain
  2697. * i_getch() after it instead of i_getch_and_eat_bkslash_nl().
  2698. */
  2699. static int i_peek_and_eat_bkslash_nl(struct in_str *input)
  2700. {
  2701. for (;;) {
  2702. int ch, ch2;
  2703. ch = i_peek(input);
  2704. if (ch != '\\')
  2705. return ch;
  2706. ch2 = i_peek2(input);
  2707. if (ch2 != '\n')
  2708. return ch;
  2709. /* backslash+newline, skip it */
  2710. i_getch(input);
  2711. i_getch(input);
  2712. }
  2713. }
  2714. static void setup_file_in_str(struct in_str *i, HFILE *fp)
  2715. {
  2716. memset(i, 0, sizeof(*i));
  2717. i->file = fp;
  2718. /* i->p = NULL; */
  2719. }
  2720. static void setup_string_in_str(struct in_str *i, const char *s)
  2721. {
  2722. memset(i, 0, sizeof(*i));
  2723. /*i->file = NULL */;
  2724. i->p = s;
  2725. }
  2726. /*
  2727. * o_string support
  2728. */
  2729. #define B_CHUNK (32 * sizeof(char*))
  2730. static void o_reset_to_empty_unquoted(o_string *o)
  2731. {
  2732. o->length = 0;
  2733. o->has_quoted_part = 0;
  2734. if (o->data)
  2735. o->data[0] = '\0';
  2736. }
  2737. static void o_free_and_set_NULL(o_string *o)
  2738. {
  2739. free(o->data);
  2740. memset(o, 0, sizeof(*o));
  2741. }
  2742. static ALWAYS_INLINE void o_free(o_string *o)
  2743. {
  2744. free(o->data);
  2745. }
  2746. static void o_grow_by(o_string *o, int len)
  2747. {
  2748. if (o->length + len > o->maxlen) {
  2749. o->maxlen += (2 * len) | (B_CHUNK-1);
  2750. o->data = xrealloc(o->data, 1 + o->maxlen);
  2751. }
  2752. }
  2753. static void o_addchr(o_string *o, int ch)
  2754. {
  2755. debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
  2756. if (o->length < o->maxlen) {
  2757. /* likely. avoid o_grow_by() call */
  2758. add:
  2759. o->data[o->length] = ch;
  2760. o->length++;
  2761. o->data[o->length] = '\0';
  2762. return;
  2763. }
  2764. o_grow_by(o, 1);
  2765. goto add;
  2766. }
  2767. #if 0
  2768. /* Valid only if we know o_string is not empty */
  2769. static void o_delchr(o_string *o)
  2770. {
  2771. o->length--;
  2772. o->data[o->length] = '\0';
  2773. }
  2774. #endif
  2775. static void o_addblock(o_string *o, const char *str, int len)
  2776. {
  2777. o_grow_by(o, len);
  2778. ((char*)mempcpy(&o->data[o->length], str, len))[0] = '\0';
  2779. o->length += len;
  2780. }
  2781. static void o_addstr(o_string *o, const char *str)
  2782. {
  2783. o_addblock(o, str, strlen(str));
  2784. }
  2785. static void o_addstr_with_NUL(o_string *o, const char *str)
  2786. {
  2787. o_addblock(o, str, strlen(str) + 1);
  2788. }
  2789. #if !BB_MMU
  2790. static void nommu_addchr(o_string *o, int ch)
  2791. {
  2792. if (o)
  2793. o_addchr(o, ch);
  2794. }
  2795. #else
  2796. # define nommu_addchr(o, str) ((void)0)
  2797. #endif
  2798. #if ENABLE_HUSH_MODE_X
  2799. static void x_mode_addchr(int ch)
  2800. {
  2801. o_addchr(&G.x_mode_buf, ch);
  2802. }
  2803. static void x_mode_addstr(const char *str)
  2804. {
  2805. o_addstr(&G.x_mode_buf, str);
  2806. }
  2807. static void x_mode_addblock(const char *str, int len)
  2808. {
  2809. o_addblock(&G.x_mode_buf, str, len);
  2810. }
  2811. static void x_mode_prefix(void)
  2812. {
  2813. int n = G.x_mode_depth;
  2814. do x_mode_addchr('+'); while (--n >= 0);
  2815. }
  2816. static void x_mode_flush(void)
  2817. {
  2818. int len = G.x_mode_buf.length;
  2819. if (len <= 0)
  2820. return;
  2821. if (G.x_mode_fd > 0) {
  2822. G.x_mode_buf.data[len] = '\n';
  2823. full_write(G.x_mode_fd, G.x_mode_buf.data, len + 1);
  2824. }
  2825. G.x_mode_buf.length = 0;
  2826. }
  2827. #endif
  2828. /*
  2829. * HUSH_BRACE_EXPANSION code needs corresponding quoting on variable expansion side.
  2830. * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
  2831. * Apparently, on unquoted $v bash still does globbing
  2832. * ("v='*.txt'; echo $v" prints all .txt files),
  2833. * but NOT brace expansion! Thus, there should be TWO independent
  2834. * quoting mechanisms on $v expansion side: one protects
  2835. * $v from brace expansion, and other additionally protects "$v" against globbing.
  2836. * We have only second one.
  2837. */
  2838. #if ENABLE_HUSH_BRACE_EXPANSION
  2839. # define MAYBE_BRACES "{}"
  2840. #else
  2841. # define MAYBE_BRACES ""
  2842. #endif
  2843. /* My analysis of quoting semantics tells me that state information
  2844. * is associated with a destination, not a source.
  2845. */
  2846. static void o_addqchr(o_string *o, int ch)
  2847. {
  2848. int sz = 1;
  2849. /* '-' is included because of this case:
  2850. * >filename0 >filename1 >filename9; v='-'; echo filename[0"$v"9]
  2851. */
  2852. char *found = strchr("*?[-\\" MAYBE_BRACES, ch);
  2853. if (found)
  2854. sz++;
  2855. o_grow_by(o, sz);
  2856. if (found) {
  2857. o->data[o->length] = '\\';
  2858. o->length++;
  2859. }
  2860. o->data[o->length] = ch;
  2861. o->length++;
  2862. o->data[o->length] = '\0';
  2863. }
  2864. static void o_addQchr(o_string *o, int ch)
  2865. {
  2866. int sz = 1;
  2867. if ((o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)
  2868. && strchr("*?[-\\" MAYBE_BRACES, ch)
  2869. ) {
  2870. sz++;
  2871. o->data[o->length] = '\\';
  2872. o->length++;
  2873. }
  2874. o_grow_by(o, sz);
  2875. o->data[o->length] = ch;
  2876. o->length++;
  2877. o->data[o->length] = '\0';
  2878. }
  2879. static void o_addqblock(o_string *o, const char *str, int len)
  2880. {
  2881. while (len) {
  2882. char ch;
  2883. int sz;
  2884. int ordinary_cnt = strcspn(str, "*?[-\\" MAYBE_BRACES);
  2885. if (ordinary_cnt > len) /* paranoia */
  2886. ordinary_cnt = len;
  2887. o_addblock(o, str, ordinary_cnt);
  2888. if (ordinary_cnt == len)
  2889. return; /* NUL is already added by o_addblock */
  2890. str += ordinary_cnt;
  2891. len -= ordinary_cnt + 1; /* we are processing + 1 char below */
  2892. ch = *str++;
  2893. sz = 1;
  2894. if (ch) { /* it is necessarily one of "*?[-\\" MAYBE_BRACES */
  2895. sz++;
  2896. o->data[o->length] = '\\';
  2897. o->length++;
  2898. }
  2899. o_grow_by(o, sz);
  2900. o->data[o->length] = ch;
  2901. o->length++;
  2902. }
  2903. o->data[o->length] = '\0';
  2904. }
  2905. static void o_addQblock(o_string *o, const char *str, int len)
  2906. {
  2907. if (!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)) {
  2908. o_addblock(o, str, len);
  2909. return;
  2910. }
  2911. o_addqblock(o, str, len);
  2912. }
  2913. static void o_addQstr(o_string *o, const char *str)
  2914. {
  2915. o_addQblock(o, str, strlen(str));
  2916. }
  2917. /* A special kind of o_string for $VAR and `cmd` expansion.
  2918. * It contains char* list[] at the beginning, which is grown in 16 element
  2919. * increments. Actual string data starts at the next multiple of 16 * (char*).
  2920. * list[i] contains an INDEX (int!) into this string data.
  2921. * It means that if list[] needs to grow, data needs to be moved higher up
  2922. * but list[i]'s need not be modified.
  2923. * NB: remembering how many list[i]'s you have there is crucial.
  2924. * o_finalize_list() operation post-processes this structure - calculates
  2925. * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
  2926. */
  2927. #if DEBUG_EXPAND || DEBUG_GLOB
  2928. static void debug_print_list(const char *prefix, o_string *o, int n)
  2929. {
  2930. char **list = (char**)o->data;
  2931. int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
  2932. int i = 0;
  2933. indent();
  2934. fdprintf(2, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d glob:%d quoted:%d escape:%d\n",
  2935. prefix, list, n, string_start, o->length, o->maxlen,
  2936. !!(o->o_expflags & EXP_FLAG_GLOB),
  2937. o->has_quoted_part,
  2938. !!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
  2939. while (i < n) {
  2940. indent();
  2941. fdprintf(2, " list[%d]=%d '%s' %p\n", i, (int)(uintptr_t)list[i],
  2942. o->data + (int)(uintptr_t)list[i] + string_start,
  2943. o->data + (int)(uintptr_t)list[i] + string_start);
  2944. i++;
  2945. }
  2946. if (n) {
  2947. const char *p = o->data + (int)(uintptr_t)list[n - 1] + string_start;
  2948. indent();
  2949. fdprintf(2, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
  2950. }
  2951. }
  2952. #else
  2953. # define debug_print_list(prefix, o, n) ((void)0)
  2954. #endif
  2955. /* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
  2956. * in list[n] so that it points past last stored byte so far.
  2957. * It returns n+1. */
  2958. static int o_save_ptr_helper(o_string *o, int n)
  2959. {
  2960. char **list = (char**)o->data;
  2961. int string_start;
  2962. int string_len;
  2963. if (!o->has_empty_slot) {
  2964. string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
  2965. string_len = o->length - string_start;
  2966. if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
  2967. debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
  2968. /* list[n] points to string_start, make space for 16 more pointers */
  2969. o->maxlen += 0x10 * sizeof(list[0]);
  2970. o->data = xrealloc(o->data, o->maxlen + 1);
  2971. list = (char**)o->data;
  2972. memmove(list + n + 0x10, list + n, string_len);
  2973. /*
  2974. * expand_on_ifs() has a "previous argv[] ends in IFS?"
  2975. * check. (grep for -prev-ifs-check-).
  2976. * Ensure that argv[-1][last] is not garbage
  2977. * but zero bytes, to save index check there.
  2978. */
  2979. list[n + 0x10 - 1] = 0;
  2980. o->length += 0x10 * sizeof(list[0]);
  2981. } else {
  2982. debug_printf_list("list[%d]=%d string_start=%d\n",
  2983. n, string_len, string_start);
  2984. }
  2985. } else {
  2986. /* We have empty slot at list[n], reuse without growth */
  2987. string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
  2988. string_len = o->length - string_start;
  2989. debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
  2990. n, string_len, string_start);
  2991. o->has_empty_slot = 0;
  2992. }
  2993. o->has_quoted_part = 0;
  2994. list[n] = (char*)(uintptr_t)string_len;
  2995. return n + 1;
  2996. }
  2997. /* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
  2998. static int o_get_last_ptr(o_string *o, int n)
  2999. {
  3000. char **list = (char**)o->data;
  3001. int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
  3002. return ((int)(uintptr_t)list[n-1]) + string_start;
  3003. }
  3004. /*
  3005. * Globbing routines.
  3006. *
  3007. * Most words in commands need to be globbed, even ones which are
  3008. * (single or double) quoted. This stems from the possiblity of
  3009. * constructs like "abc"* and 'abc'* - these should be globbed.
  3010. * Having a different code path for fully-quoted strings ("abc",
  3011. * 'abc') would only help performance-wise, but we still need
  3012. * code for partially-quoted strings.
  3013. *
  3014. * Unfortunately, if we want to match bash and ash behavior in all cases,
  3015. * the logic can't be "shell-syntax argument is first transformed
  3016. * to a string, then globbed, and if globbing does not match anything,
  3017. * it is used verbatim". Here are two examples where it fails:
  3018. *
  3019. * echo 'b\*'?
  3020. *
  3021. * The globbing can't be avoided (because of '?' at the end).
  3022. * The glob pattern is: b\\\*? - IOW, both \ and * are literals
  3023. * and are glob-escaped. If this does not match, bash/ash print b\*?
  3024. * - IOW: they "unbackslash" the glob pattern.
  3025. * Now, look at this:
  3026. *
  3027. * v='\\\*'; echo b$v?
  3028. *
  3029. * The glob pattern is the same here: b\\\*? - the unquoted $v expansion
  3030. * should be used as glob pattern with no changes. However, if glob
  3031. * does not match, bash/ash print b\\\*? - NOT THE SAME as first example!
  3032. *
  3033. * ash implements this by having an encoded representation of the word
  3034. * to glob, which IS NOT THE SAME as the glob pattern - it has more data.
  3035. * Glob pattern is derived from it. If glob fails, the decision what result
  3036. * should be is made using that encoded representation. Not glob pattern.
  3037. */
  3038. #if ENABLE_HUSH_BRACE_EXPANSION
  3039. /* There in a GNU extension, GLOB_BRACE, but it is not usable:
  3040. * first, it processes even {a} (no commas), second,
  3041. * I didn't manage to make it return strings when they don't match
  3042. * existing files. Need to re-implement it.
  3043. */
  3044. /* Helper */
  3045. static int glob_needed(const char *s)
  3046. {
  3047. while (*s) {
  3048. if (*s == '\\') {
  3049. if (!s[1])
  3050. return 0;
  3051. s += 2;
  3052. continue;
  3053. }
  3054. if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
  3055. return 1;
  3056. s++;
  3057. }
  3058. return 0;
  3059. }
  3060. /* Return pointer to next closing brace or to comma */
  3061. static const char *next_brace_sub(const char *cp)
  3062. {
  3063. unsigned depth = 0;
  3064. cp++;
  3065. while (*cp != '\0') {
  3066. if (*cp == '\\') {
  3067. if (*++cp == '\0')
  3068. break;
  3069. cp++;
  3070. continue;
  3071. }
  3072. if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
  3073. break;
  3074. if (*cp++ == '{')
  3075. depth++;
  3076. }
  3077. return *cp != '\0' ? cp : NULL;
  3078. }
  3079. /* Recursive brace globber. Note: may garble pattern[]. */
  3080. static int glob_brace(char *pattern, o_string *o, int n)
  3081. {
  3082. char *new_pattern_buf;
  3083. const char *begin;
  3084. const char *next;
  3085. const char *rest;
  3086. const char *p;
  3087. size_t rest_len;
  3088. debug_printf_glob("glob_brace('%s')\n", pattern);
  3089. begin = pattern;
  3090. while (1) {
  3091. if (*begin == '\0')
  3092. goto simple_glob;
  3093. if (*begin == '{') {
  3094. /* Find the first sub-pattern and at the same time
  3095. * find the rest after the closing brace */
  3096. next = next_brace_sub(begin);
  3097. if (next == NULL) {
  3098. /* An illegal expression */
  3099. goto simple_glob;
  3100. }
  3101. if (*next == '}') {
  3102. /* "{abc}" with no commas - illegal
  3103. * brace expr, disregard and skip it */
  3104. begin = next + 1;
  3105. continue;
  3106. }
  3107. break;
  3108. }
  3109. if (*begin == '\\' && begin[1] != '\0')
  3110. begin++;
  3111. begin++;
  3112. }
  3113. debug_printf_glob("begin:%s\n", begin);
  3114. debug_printf_glob("next:%s\n", next);
  3115. /* Now find the end of the whole brace expression */
  3116. rest = next;
  3117. while (*rest != '}') {
  3118. rest = next_brace_sub(rest);
  3119. if (rest == NULL) {
  3120. /* An illegal expression */
  3121. goto simple_glob;
  3122. }
  3123. debug_printf_glob("rest:%s\n", rest);
  3124. }
  3125. rest_len = strlen(++rest) + 1;
  3126. /* We are sure the brace expression is well-formed */
  3127. /* Allocate working buffer large enough for our work */
  3128. new_pattern_buf = xmalloc(strlen(pattern));
  3129. /* We have a brace expression. BEGIN points to the opening {,
  3130. * NEXT points past the terminator of the first element, and REST
  3131. * points past the final }. We will accumulate result names from
  3132. * recursive runs for each brace alternative in the buffer using
  3133. * GLOB_APPEND. */
  3134. p = begin + 1;
  3135. while (1) {
  3136. /* Construct the new glob expression */
  3137. memcpy(
  3138. mempcpy(
  3139. mempcpy(new_pattern_buf,
  3140. /* We know the prefix for all sub-patterns */
  3141. pattern, begin - pattern),
  3142. p, next - p),
  3143. rest, rest_len);
  3144. /* Note: glob_brace() may garble new_pattern_buf[].
  3145. * That's why we re-copy prefix every time (1st memcpy above).
  3146. */
  3147. n = glob_brace(new_pattern_buf, o, n);
  3148. if (*next == '}') {
  3149. /* We saw the last entry */
  3150. break;
  3151. }
  3152. p = next + 1;
  3153. next = next_brace_sub(next);
  3154. }
  3155. free(new_pattern_buf);
  3156. return n;
  3157. simple_glob:
  3158. {
  3159. int gr;
  3160. glob_t globdata;
  3161. memset(&globdata, 0, sizeof(globdata));
  3162. gr = glob(pattern, 0, NULL, &globdata);
  3163. debug_printf_glob("glob('%s'):%d\n", pattern, gr);
  3164. if (gr != 0) {
  3165. if (gr == GLOB_NOMATCH) {
  3166. globfree(&globdata);
  3167. /* NB: garbles parameter */
  3168. unbackslash(pattern);
  3169. o_addstr_with_NUL(o, pattern);
  3170. debug_printf_glob("glob pattern '%s' is literal\n", pattern);
  3171. return o_save_ptr_helper(o, n);
  3172. }
  3173. if (gr == GLOB_NOSPACE)
  3174. bb_die_memory_exhausted();
  3175. /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
  3176. * but we didn't specify it. Paranoia again. */
  3177. bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
  3178. }
  3179. if (globdata.gl_pathv && globdata.gl_pathv[0]) {
  3180. char **argv = globdata.gl_pathv;
  3181. while (1) {
  3182. o_addstr_with_NUL(o, *argv);
  3183. n = o_save_ptr_helper(o, n);
  3184. argv++;
  3185. if (!*argv)
  3186. break;
  3187. }
  3188. }
  3189. globfree(&globdata);
  3190. }
  3191. return n;
  3192. }
  3193. /* Performs globbing on last list[],
  3194. * saving each result as a new list[].
  3195. */
  3196. static int perform_glob(o_string *o, int n)
  3197. {
  3198. char *pattern, *copy;
  3199. debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
  3200. if (!o->data)
  3201. return o_save_ptr_helper(o, n);
  3202. pattern = o->data + o_get_last_ptr(o, n);
  3203. debug_printf_glob("glob pattern '%s'\n", pattern);
  3204. if (!glob_needed(pattern)) {
  3205. /* unbackslash last string in o in place, fix length */
  3206. o->length = unbackslash(pattern) - o->data;
  3207. debug_printf_glob("glob pattern '%s' is literal\n", pattern);
  3208. return o_save_ptr_helper(o, n);
  3209. }
  3210. copy = xstrdup(pattern);
  3211. /* "forget" pattern in o */
  3212. o->length = pattern - o->data;
  3213. n = glob_brace(copy, o, n);
  3214. free(copy);
  3215. if (DEBUG_GLOB)
  3216. debug_print_list("perform_glob returning", o, n);
  3217. return n;
  3218. }
  3219. #else /* !HUSH_BRACE_EXPANSION */
  3220. /* Helper */
  3221. static int glob_needed(const char *s)
  3222. {
  3223. while (*s) {
  3224. if (*s == '\\') {
  3225. if (!s[1])
  3226. return 0;
  3227. s += 2;
  3228. continue;
  3229. }
  3230. if (*s == '*' || *s == '[' || *s == '?')
  3231. return 1;
  3232. s++;
  3233. }
  3234. return 0;
  3235. }
  3236. /* Performs globbing on last list[],
  3237. * saving each result as a new list[].
  3238. */
  3239. static int perform_glob(o_string *o, int n)
  3240. {
  3241. glob_t globdata;
  3242. int gr;
  3243. char *pattern;
  3244. debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
  3245. if (!o->data)
  3246. return o_save_ptr_helper(o, n);
  3247. pattern = o->data + o_get_last_ptr(o, n);
  3248. debug_printf_glob("glob pattern '%s'\n", pattern);
  3249. if (!glob_needed(pattern)) {
  3250. literal:
  3251. /* unbackslash last string in o in place, fix length */
  3252. o->length = unbackslash(pattern) - o->data;
  3253. debug_printf_glob("glob pattern '%s' is literal\n", pattern);
  3254. return o_save_ptr_helper(o, n);
  3255. }
  3256. memset(&globdata, 0, sizeof(globdata));
  3257. /* Can't use GLOB_NOCHECK: it does not unescape the string.
  3258. * If we glob "*.\*" and don't find anything, we need
  3259. * to fall back to using literal "*.*", but GLOB_NOCHECK
  3260. * will return "*.\*"!
  3261. */
  3262. gr = glob(pattern, 0, NULL, &globdata);
  3263. debug_printf_glob("glob('%s'):%d\n", pattern, gr);
  3264. if (gr != 0) {
  3265. if (gr == GLOB_NOMATCH) {
  3266. globfree(&globdata);
  3267. goto literal;
  3268. }
  3269. if (gr == GLOB_NOSPACE)
  3270. bb_die_memory_exhausted();
  3271. /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
  3272. * but we didn't specify it. Paranoia again. */
  3273. bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
  3274. }
  3275. if (globdata.gl_pathv && globdata.gl_pathv[0]) {
  3276. char **argv = globdata.gl_pathv;
  3277. /* "forget" pattern in o */
  3278. o->length = pattern - o->data;
  3279. while (1) {
  3280. o_addstr_with_NUL(o, *argv);
  3281. n = o_save_ptr_helper(o, n);
  3282. argv++;
  3283. if (!*argv)
  3284. break;
  3285. }
  3286. }
  3287. globfree(&globdata);
  3288. if (DEBUG_GLOB)
  3289. debug_print_list("perform_glob returning", o, n);
  3290. return n;
  3291. }
  3292. #endif /* !HUSH_BRACE_EXPANSION */
  3293. /* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered.
  3294. * Otherwise, just finish current list[] and start new */
  3295. static int o_save_ptr(o_string *o, int n)
  3296. {
  3297. if (o->o_expflags & EXP_FLAG_GLOB) {
  3298. /* If o->has_empty_slot, list[n] was already globbed
  3299. * (if it was requested back then when it was filled)
  3300. * so don't do that again! */
  3301. if (!o->has_empty_slot)
  3302. return perform_glob(o, n); /* o_save_ptr_helper is inside */
  3303. }
  3304. return o_save_ptr_helper(o, n);
  3305. }
  3306. /* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
  3307. static char **o_finalize_list(o_string *o, int n)
  3308. {
  3309. char **list;
  3310. int string_start;
  3311. if (DEBUG_EXPAND)
  3312. debug_print_list("finalized", o, n);
  3313. debug_printf_expand("finalized n:%d\n", n);
  3314. list = (char**)o->data;
  3315. string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
  3316. list[--n] = NULL;
  3317. while (n) {
  3318. n--;
  3319. list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
  3320. }
  3321. return list;
  3322. }
  3323. static void free_pipe_list(struct pipe *pi);
  3324. /* Returns pi->next - next pipe in the list */
  3325. static struct pipe *free_pipe(struct pipe *pi)
  3326. {
  3327. struct pipe *next;
  3328. int i;
  3329. debug_printf_clean("free_pipe (pid %d)\n", getpid());
  3330. for (i = 0; i < pi->num_cmds; i++) {
  3331. struct command *command;
  3332. struct redir_struct *r, *rnext;
  3333. command = &pi->cmds[i];
  3334. debug_printf_clean(" command %d:\n", i);
  3335. if (command->argv) {
  3336. if (DEBUG_CLEAN) {
  3337. int a;
  3338. char **p;
  3339. for (a = 0, p = command->argv; *p; a++, p++) {
  3340. debug_printf_clean(" argv[%d] = %s\n", a, *p);
  3341. }
  3342. }
  3343. free_strings(command->argv);
  3344. //command->argv = NULL;
  3345. }
  3346. /* not "else if": on syntax error, we may have both! */
  3347. if (command->group) {
  3348. debug_printf_clean(" begin group (cmd_type:%d)\n",
  3349. command->cmd_type);
  3350. free_pipe_list(command->group);
  3351. debug_printf_clean(" end group\n");
  3352. //command->group = NULL;
  3353. }
  3354. /* else is crucial here.
  3355. * If group != NULL, child_func is meaningless */
  3356. #if ENABLE_HUSH_FUNCTIONS
  3357. else if (command->child_func) {
  3358. debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
  3359. command->child_func->parent_cmd = NULL;
  3360. }
  3361. #endif
  3362. #if !BB_MMU
  3363. free(command->group_as_string);
  3364. //command->group_as_string = NULL;
  3365. #endif
  3366. for (r = command->redirects; r; r = rnext) {
  3367. debug_printf_clean(" redirect %d%s",
  3368. r->rd_fd, redir_table[r->rd_type].descrip);
  3369. /* guard against the case >$FOO, where foo is unset or blank */
  3370. if (r->rd_filename) {
  3371. debug_printf_clean(" fname:'%s'\n", r->rd_filename);
  3372. free(r->rd_filename);
  3373. //r->rd_filename = NULL;
  3374. }
  3375. debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
  3376. rnext = r->next;
  3377. free(r);
  3378. }
  3379. //command->redirects = NULL;
  3380. }
  3381. free(pi->cmds); /* children are an array, they get freed all at once */
  3382. //pi->cmds = NULL;
  3383. #if ENABLE_HUSH_JOB
  3384. free(pi->cmdtext);
  3385. //pi->cmdtext = NULL;
  3386. #endif
  3387. next = pi->next;
  3388. free(pi);
  3389. return next;
  3390. }
  3391. static void free_pipe_list(struct pipe *pi)
  3392. {
  3393. while (pi) {
  3394. #if HAS_KEYWORDS
  3395. debug_printf_clean("pipe reserved word %d\n", pi->res_word);
  3396. #endif
  3397. debug_printf_clean("pipe followup code %d\n", pi->followup);
  3398. pi = free_pipe(pi);
  3399. }
  3400. }
  3401. /*** Parsing routines ***/
  3402. #ifndef debug_print_tree
  3403. static void debug_print_tree(struct pipe *pi, int lvl)
  3404. {
  3405. static const char *const PIPE[] = {
  3406. [PIPE_SEQ] = "SEQ",
  3407. [PIPE_AND] = "AND",
  3408. [PIPE_OR ] = "OR" ,
  3409. [PIPE_BG ] = "BG" ,
  3410. };
  3411. static const char *RES[] = {
  3412. [RES_NONE ] = "NONE" ,
  3413. # if ENABLE_HUSH_IF
  3414. [RES_IF ] = "IF" ,
  3415. [RES_THEN ] = "THEN" ,
  3416. [RES_ELIF ] = "ELIF" ,
  3417. [RES_ELSE ] = "ELSE" ,
  3418. [RES_FI ] = "FI" ,
  3419. # endif
  3420. # if ENABLE_HUSH_LOOPS
  3421. [RES_FOR ] = "FOR" ,
  3422. [RES_WHILE] = "WHILE",
  3423. [RES_UNTIL] = "UNTIL",
  3424. [RES_DO ] = "DO" ,
  3425. [RES_DONE ] = "DONE" ,
  3426. # endif
  3427. # if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
  3428. [RES_IN ] = "IN" ,
  3429. # endif
  3430. # if ENABLE_HUSH_CASE
  3431. [RES_CASE ] = "CASE" ,
  3432. [RES_CASE_IN ] = "CASE_IN" ,
  3433. [RES_MATCH] = "MATCH",
  3434. [RES_CASE_BODY] = "CASE_BODY",
  3435. [RES_ESAC ] = "ESAC" ,
  3436. # endif
  3437. [RES_XXXX ] = "XXXX" ,
  3438. [RES_SNTX ] = "SNTX" ,
  3439. };
  3440. static const char *const CMDTYPE[] = {
  3441. "{}",
  3442. "()",
  3443. "[noglob]",
  3444. # if ENABLE_HUSH_FUNCTIONS
  3445. "func()",
  3446. # endif
  3447. };
  3448. int pin, prn;
  3449. pin = 0;
  3450. while (pi) {
  3451. fdprintf(2, "%*spipe %d #cmds:%d %sres_word=%s followup=%d %s\n",
  3452. lvl*2, "",
  3453. pin,
  3454. pi->num_cmds,
  3455. (IF_HAS_KEYWORDS(pi->pi_inverted ? "! " :) ""),
  3456. RES[pi->res_word],
  3457. pi->followup, PIPE[pi->followup]
  3458. );
  3459. prn = 0;
  3460. while (prn < pi->num_cmds) {
  3461. struct command *command = &pi->cmds[prn];
  3462. char **argv = command->argv;
  3463. fdprintf(2, "%*s cmd %d assignment_cnt:%d",
  3464. lvl*2, "", prn,
  3465. command->assignment_cnt);
  3466. # if ENABLE_HUSH_LINENO_VAR
  3467. fdprintf(2, " LINENO:%u", command->lineno);
  3468. # endif
  3469. if (command->group) {
  3470. fdprintf(2, " group %s: (argv=%p)%s%s\n",
  3471. CMDTYPE[command->cmd_type],
  3472. argv
  3473. # if !BB_MMU
  3474. , " group_as_string:", command->group_as_string
  3475. # else
  3476. , "", ""
  3477. # endif
  3478. );
  3479. debug_print_tree(command->group, lvl+1);
  3480. prn++;
  3481. continue;
  3482. }
  3483. if (argv) while (*argv) {
  3484. fdprintf(2, " '%s'", *argv);
  3485. argv++;
  3486. }
  3487. if (command->redirects)
  3488. fdprintf(2, " {redir}");
  3489. fdprintf(2, "\n");
  3490. prn++;
  3491. }
  3492. pi = pi->next;
  3493. pin++;
  3494. }
  3495. }
  3496. #endif /* debug_print_tree */
  3497. static struct pipe *new_pipe(void)
  3498. {
  3499. struct pipe *pi;
  3500. pi = xzalloc(sizeof(struct pipe));
  3501. /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
  3502. return pi;
  3503. }
  3504. /* Command (member of a pipe) is complete, or we start a new pipe
  3505. * if ctx->command is NULL.
  3506. * No errors possible here.
  3507. */
  3508. static int done_command(struct parse_context *ctx)
  3509. {
  3510. /* The command is really already in the pipe structure, so
  3511. * advance the pipe counter and make a new, null command. */
  3512. struct pipe *pi = ctx->pipe;
  3513. struct command *command = ctx->command;
  3514. #if 0 /* Instead we emit error message at run time */
  3515. if (ctx->pending_redirect) {
  3516. /* For example, "cmd >" (no filename to redirect to) */
  3517. syntax_error("invalid redirect");
  3518. ctx->pending_redirect = NULL;
  3519. }
  3520. #endif
  3521. if (command) {
  3522. if (IS_NULL_CMD(command)) {
  3523. debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
  3524. goto clear_and_ret;
  3525. }
  3526. pi->num_cmds++;
  3527. debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
  3528. //debug_print_tree(ctx->list_head, 20);
  3529. } else {
  3530. debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
  3531. }
  3532. /* Only real trickiness here is that the uncommitted
  3533. * command structure is not counted in pi->num_cmds. */
  3534. pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
  3535. ctx->command = command = &pi->cmds[pi->num_cmds];
  3536. clear_and_ret:
  3537. memset(command, 0, sizeof(*command));
  3538. #if ENABLE_HUSH_LINENO_VAR
  3539. command->lineno = G.parse_lineno;
  3540. debug_printf_parse("command->lineno = G.parse_lineno (%u)\n", G.parse_lineno);
  3541. #endif
  3542. return pi->num_cmds; /* used only for 0/nonzero check */
  3543. }
  3544. static void done_pipe(struct parse_context *ctx, pipe_style type)
  3545. {
  3546. int not_null;
  3547. debug_printf_parse("done_pipe entered, followup %d\n", type);
  3548. /* Close previous command */
  3549. not_null = done_command(ctx);
  3550. #if HAS_KEYWORDS
  3551. ctx->pipe->pi_inverted = ctx->ctx_inverted;
  3552. ctx->ctx_inverted = 0;
  3553. ctx->pipe->res_word = ctx->ctx_res_w;
  3554. #endif
  3555. if (type == PIPE_BG && ctx->list_head != ctx->pipe) {
  3556. /* Necessary since && and || have precedence over &:
  3557. * "cmd1 && cmd2 &" must spawn both cmds, not only cmd2,
  3558. * in a backgrounded subshell.
  3559. */
  3560. struct pipe *pi;
  3561. struct command *command;
  3562. /* Is this actually this construct, all pipes end with && or ||? */
  3563. pi = ctx->list_head;
  3564. while (pi != ctx->pipe) {
  3565. if (pi->followup != PIPE_AND && pi->followup != PIPE_OR)
  3566. goto no_conv;
  3567. pi = pi->next;
  3568. }
  3569. debug_printf_parse("BG with more than one pipe, converting to { p1 &&...pN; } &\n");
  3570. pi->followup = PIPE_SEQ; /* close pN _not_ with "&"! */
  3571. pi = xzalloc(sizeof(*pi));
  3572. pi->followup = PIPE_BG;
  3573. pi->num_cmds = 1;
  3574. pi->cmds = xzalloc(sizeof(pi->cmds[0]));
  3575. command = &pi->cmds[0];
  3576. if (CMD_NORMAL != 0) /* "if xzalloc didn't do that already" */
  3577. command->cmd_type = CMD_NORMAL;
  3578. command->group = ctx->list_head;
  3579. #if !BB_MMU
  3580. command->group_as_string = xstrndup(
  3581. ctx->as_string.data,
  3582. ctx->as_string.length - 1 /* do not copy last char, "&" */
  3583. );
  3584. #endif
  3585. /* Replace all pipes in ctx with one newly created */
  3586. ctx->list_head = ctx->pipe = pi;
  3587. /* for cases like "cmd && &", do not be tricked by last command
  3588. * being null - the entire {...} & is NOT null! */
  3589. not_null = 1;
  3590. } else {
  3591. no_conv:
  3592. ctx->pipe->followup = type;
  3593. }
  3594. /* Without this check, even just <enter> on command line generates
  3595. * tree of three NOPs (!). Which is harmless but annoying.
  3596. * IOW: it is safe to do it unconditionally. */
  3597. if (not_null
  3598. #if ENABLE_HUSH_IF
  3599. || ctx->ctx_res_w == RES_FI
  3600. #endif
  3601. #if ENABLE_HUSH_LOOPS
  3602. || ctx->ctx_res_w == RES_DONE
  3603. || ctx->ctx_res_w == RES_FOR
  3604. || ctx->ctx_res_w == RES_IN
  3605. #endif
  3606. #if ENABLE_HUSH_CASE
  3607. || ctx->ctx_res_w == RES_ESAC
  3608. #endif
  3609. ) {
  3610. struct pipe *new_p;
  3611. debug_printf_parse("done_pipe: adding new pipe: "
  3612. "not_null:%d ctx->ctx_res_w:%d\n",
  3613. not_null, ctx->ctx_res_w);
  3614. new_p = new_pipe();
  3615. ctx->pipe->next = new_p;
  3616. ctx->pipe = new_p;
  3617. /* RES_THEN, RES_DO etc are "sticky" -
  3618. * they remain set for pipes inside if/while.
  3619. * This is used to control execution.
  3620. * RES_FOR and RES_IN are NOT sticky (needed to support
  3621. * cases where variable or value happens to match a keyword):
  3622. */
  3623. #if ENABLE_HUSH_LOOPS
  3624. if (ctx->ctx_res_w == RES_FOR
  3625. || ctx->ctx_res_w == RES_IN)
  3626. ctx->ctx_res_w = RES_NONE;
  3627. #endif
  3628. #if ENABLE_HUSH_CASE
  3629. if (ctx->ctx_res_w == RES_MATCH)
  3630. ctx->ctx_res_w = RES_CASE_BODY;
  3631. if (ctx->ctx_res_w == RES_CASE)
  3632. ctx->ctx_res_w = RES_CASE_IN;
  3633. #endif
  3634. ctx->command = NULL; /* trick done_command below */
  3635. /* Create the memory for command, roughly:
  3636. * ctx->pipe->cmds = new struct command;
  3637. * ctx->command = &ctx->pipe->cmds[0];
  3638. */
  3639. done_command(ctx);
  3640. //debug_print_tree(ctx->list_head, 10);
  3641. }
  3642. debug_printf_parse("done_pipe return\n");
  3643. }
  3644. static void initialize_context(struct parse_context *ctx)
  3645. {
  3646. memset(ctx, 0, sizeof(*ctx));
  3647. if (MAYBE_ASSIGNMENT != 0)
  3648. ctx->is_assignment = MAYBE_ASSIGNMENT;
  3649. ctx->pipe = ctx->list_head = new_pipe();
  3650. /* Create the memory for command, roughly:
  3651. * ctx->pipe->cmds = new struct command;
  3652. * ctx->command = &ctx->pipe->cmds[0];
  3653. */
  3654. done_command(ctx);
  3655. }
  3656. /* If a reserved word is found and processed, parse context is modified
  3657. * and 1 is returned.
  3658. */
  3659. #if HAS_KEYWORDS
  3660. struct reserved_combo {
  3661. char literal[6];
  3662. unsigned char res;
  3663. unsigned char assignment_flag;
  3664. uint32_t flag;
  3665. };
  3666. enum {
  3667. FLAG_END = (1 << RES_NONE ),
  3668. # if ENABLE_HUSH_IF
  3669. FLAG_IF = (1 << RES_IF ),
  3670. FLAG_THEN = (1 << RES_THEN ),
  3671. FLAG_ELIF = (1 << RES_ELIF ),
  3672. FLAG_ELSE = (1 << RES_ELSE ),
  3673. FLAG_FI = (1 << RES_FI ),
  3674. # endif
  3675. # if ENABLE_HUSH_LOOPS
  3676. FLAG_FOR = (1 << RES_FOR ),
  3677. FLAG_WHILE = (1 << RES_WHILE),
  3678. FLAG_UNTIL = (1 << RES_UNTIL),
  3679. FLAG_DO = (1 << RES_DO ),
  3680. FLAG_DONE = (1 << RES_DONE ),
  3681. FLAG_IN = (1 << RES_IN ),
  3682. # endif
  3683. # if ENABLE_HUSH_CASE
  3684. FLAG_MATCH = (1 << RES_MATCH),
  3685. FLAG_ESAC = (1 << RES_ESAC ),
  3686. # endif
  3687. FLAG_START = (1 << RES_XXXX ),
  3688. };
  3689. static const struct reserved_combo* match_reserved_word(o_string *word)
  3690. {
  3691. /* Mostly a list of accepted follow-up reserved words.
  3692. * FLAG_END means we are done with the sequence, and are ready
  3693. * to turn the compound list into a command.
  3694. * FLAG_START means the word must start a new compound list.
  3695. */
  3696. static const struct reserved_combo reserved_list[] ALIGN4 = {
  3697. # if ENABLE_HUSH_IF
  3698. { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
  3699. { "if", RES_IF, MAYBE_ASSIGNMENT, FLAG_THEN | FLAG_START },
  3700. { "then", RES_THEN, MAYBE_ASSIGNMENT, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
  3701. { "elif", RES_ELIF, MAYBE_ASSIGNMENT, FLAG_THEN },
  3702. { "else", RES_ELSE, MAYBE_ASSIGNMENT, FLAG_FI },
  3703. { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
  3704. # endif
  3705. # if ENABLE_HUSH_LOOPS
  3706. { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
  3707. { "while", RES_WHILE, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
  3708. { "until", RES_UNTIL, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
  3709. { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
  3710. { "do", RES_DO, MAYBE_ASSIGNMENT, FLAG_DONE },
  3711. { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
  3712. # endif
  3713. # if ENABLE_HUSH_CASE
  3714. { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
  3715. { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
  3716. # endif
  3717. };
  3718. const struct reserved_combo *r;
  3719. for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
  3720. if (strcmp(word->data, r->literal) == 0)
  3721. return r;
  3722. }
  3723. return NULL;
  3724. }
  3725. /* Return NULL: not a keyword, else: keyword
  3726. */
  3727. static const struct reserved_combo* reserved_word(struct parse_context *ctx)
  3728. {
  3729. # if ENABLE_HUSH_CASE
  3730. static const struct reserved_combo reserved_match = {
  3731. "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
  3732. };
  3733. # endif
  3734. const struct reserved_combo *r;
  3735. if (ctx->word.has_quoted_part)
  3736. return 0;
  3737. r = match_reserved_word(&ctx->word);
  3738. if (!r)
  3739. return r; /* NULL */
  3740. debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
  3741. # if ENABLE_HUSH_CASE
  3742. if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
  3743. /* "case word IN ..." - IN part starts first MATCH part */
  3744. r = &reserved_match;
  3745. } else
  3746. # endif
  3747. if (r->flag == 0) { /* '!' */
  3748. if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
  3749. syntax_error("! ! command");
  3750. ctx->ctx_res_w = RES_SNTX;
  3751. }
  3752. ctx->ctx_inverted = 1;
  3753. return r;
  3754. }
  3755. if (r->flag & FLAG_START) {
  3756. struct parse_context *old;
  3757. old = xmemdup(ctx, sizeof(*ctx));
  3758. debug_printf_parse("push stack %p\n", old);
  3759. initialize_context(ctx);
  3760. ctx->stack = old;
  3761. } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
  3762. syntax_error_at(ctx->word.data);
  3763. ctx->ctx_res_w = RES_SNTX;
  3764. return r;
  3765. } else {
  3766. /* "{...} fi" is ok. "{...} if" is not
  3767. * Example:
  3768. * if { echo foo; } then { echo bar; } fi */
  3769. if (ctx->command->group)
  3770. done_pipe(ctx, PIPE_SEQ);
  3771. }
  3772. ctx->ctx_res_w = r->res;
  3773. ctx->old_flag = r->flag;
  3774. ctx->is_assignment = r->assignment_flag;
  3775. debug_printf_parse("ctx->is_assignment='%s'\n", assignment_flag[ctx->is_assignment]);
  3776. if (ctx->old_flag & FLAG_END) {
  3777. struct parse_context *old;
  3778. done_pipe(ctx, PIPE_SEQ);
  3779. debug_printf_parse("pop stack %p\n", ctx->stack);
  3780. old = ctx->stack;
  3781. old->command->group = ctx->list_head;
  3782. old->command->cmd_type = CMD_NORMAL;
  3783. # if !BB_MMU
  3784. /* At this point, the compound command's string is in
  3785. * ctx->as_string... except for the leading keyword!
  3786. * Consider this example: "echo a | if true; then echo a; fi"
  3787. * ctx->as_string will contain "true; then echo a; fi",
  3788. * with "if " remaining in old->as_string!
  3789. */
  3790. {
  3791. char *str;
  3792. int len = old->as_string.length;
  3793. /* Concatenate halves */
  3794. o_addstr(&old->as_string, ctx->as_string.data);
  3795. o_free(&ctx->as_string);
  3796. /* Find where leading keyword starts in first half */
  3797. str = old->as_string.data + len;
  3798. if (str > old->as_string.data)
  3799. str--; /* skip whitespace after keyword */
  3800. while (str > old->as_string.data && isalpha(str[-1]))
  3801. str--;
  3802. /* Ugh, we're done with this horrid hack */
  3803. old->command->group_as_string = xstrdup(str);
  3804. debug_printf_parse("pop, remembering as:'%s'\n",
  3805. old->command->group_as_string);
  3806. }
  3807. # endif
  3808. *ctx = *old; /* physical copy */
  3809. free(old);
  3810. }
  3811. return r;
  3812. }
  3813. #endif /* HAS_KEYWORDS */
  3814. /* Word is complete, look at it and update parsing context.
  3815. * Normal return is 0. Syntax errors return 1.
  3816. * Note: on return, word is reset, but not o_free'd!
  3817. */
  3818. static int done_word(struct parse_context *ctx)
  3819. {
  3820. struct command *command = ctx->command;
  3821. debug_printf_parse("done_word entered: '%s' %p\n", ctx->word.data, command);
  3822. if (ctx->word.length == 0 && !ctx->word.has_quoted_part) {
  3823. debug_printf_parse("done_word return 0: true null, ignored\n");
  3824. return 0;
  3825. }
  3826. if (ctx->pending_redirect) {
  3827. /* We do not glob in e.g. >*.tmp case. bash seems to glob here
  3828. * only if run as "bash", not "sh" */
  3829. /* http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
  3830. * "2.7 Redirection
  3831. * If the redirection operator is "<<" or "<<-", the word
  3832. * that follows the redirection operator shall be
  3833. * subjected to quote removal; it is unspecified whether
  3834. * any of the other expansions occur. For the other
  3835. * redirection operators, the word that follows the
  3836. * redirection operator shall be subjected to tilde
  3837. * expansion, parameter expansion, command substitution,
  3838. * arithmetic expansion, and quote removal.
  3839. * Pathname expansion shall not be performed
  3840. * on the word by a non-interactive shell; an interactive
  3841. * shell may perform it, but shall do so only when
  3842. * the expansion would result in one word."
  3843. */
  3844. //bash does not do parameter/command substitution or arithmetic expansion
  3845. //for _heredoc_ redirection word: these constructs look for exact eof marker
  3846. // as written:
  3847. // <<EOF$t
  3848. // <<EOF$((1))
  3849. // <<EOF`true` [this case also makes heredoc "quoted", a-la <<"EOF". Probably bash-4.3.43 bug]
  3850. ctx->pending_redirect->rd_filename = xstrdup(ctx->word.data);
  3851. /* Cater for >\file case:
  3852. * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
  3853. * Same with heredocs:
  3854. * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
  3855. */
  3856. if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
  3857. unbackslash(ctx->pending_redirect->rd_filename);
  3858. /* Is it <<"HEREDOC"? */
  3859. if (ctx->word.has_quoted_part) {
  3860. ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
  3861. }
  3862. }
  3863. debug_printf_parse("word stored in rd_filename: '%s'\n", ctx->word.data);
  3864. ctx->pending_redirect = NULL;
  3865. } else {
  3866. #if HAS_KEYWORDS
  3867. # if ENABLE_HUSH_CASE
  3868. if (ctx->ctx_dsemicolon
  3869. && strcmp(ctx->word.data, "esac") != 0 /* not "... pattern) cmd;; esac" */
  3870. ) {
  3871. /* already done when ctx_dsemicolon was set to 1: */
  3872. /* ctx->ctx_res_w = RES_MATCH; */
  3873. ctx->ctx_dsemicolon = 0;
  3874. } else
  3875. # endif
  3876. # if defined(CMD_TEST2_SINGLEWORD_NOGLOB)
  3877. if (command->cmd_type == CMD_TEST2_SINGLEWORD_NOGLOB
  3878. && strcmp(ctx->word.data, "]]") == 0
  3879. ) {
  3880. /* allow "[[ ]] >file" etc */
  3881. command->cmd_type = CMD_SINGLEWORD_NOGLOB;
  3882. } else
  3883. # endif
  3884. if (!command->argv /* if it's the first word... */
  3885. # if ENABLE_HUSH_LOOPS
  3886. && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
  3887. && ctx->ctx_res_w != RES_IN
  3888. # endif
  3889. # if ENABLE_HUSH_CASE
  3890. && ctx->ctx_res_w != RES_CASE
  3891. # endif
  3892. ) {
  3893. const struct reserved_combo *reserved;
  3894. reserved = reserved_word(ctx);
  3895. debug_printf_parse("checking for reserved-ness: %d\n", !!reserved);
  3896. if (reserved) {
  3897. # if ENABLE_HUSH_LINENO_VAR
  3898. /* Case:
  3899. * "while ...; do
  3900. * cmd ..."
  3901. * If we don't close the pipe _now_, immediately after "do", lineno logic
  3902. * sees "cmd" as starting at "do" - i.e., at the previous line.
  3903. */
  3904. if (0
  3905. IF_HUSH_IF(|| reserved->res == RES_THEN)
  3906. IF_HUSH_IF(|| reserved->res == RES_ELIF)
  3907. IF_HUSH_IF(|| reserved->res == RES_ELSE)
  3908. IF_HUSH_LOOPS(|| reserved->res == RES_DO)
  3909. ) {
  3910. done_pipe(ctx, PIPE_SEQ);
  3911. }
  3912. # endif
  3913. o_reset_to_empty_unquoted(&ctx->word);
  3914. debug_printf_parse("done_word return %d\n",
  3915. (ctx->ctx_res_w == RES_SNTX));
  3916. return (ctx->ctx_res_w == RES_SNTX);
  3917. }
  3918. # if defined(CMD_TEST2_SINGLEWORD_NOGLOB)
  3919. if (strcmp(ctx->word.data, "[[") == 0) {
  3920. command->cmd_type = CMD_TEST2_SINGLEWORD_NOGLOB;
  3921. } else
  3922. # endif
  3923. # if defined(CMD_SINGLEWORD_NOGLOB)
  3924. if (0
  3925. /* In bash, local/export/readonly are special, args
  3926. * are assignments and therefore expansion of them
  3927. * should be "one-word" expansion:
  3928. * $ export i=`echo 'a b'` # one arg: "i=a b"
  3929. * compare with:
  3930. * $ ls i=`echo 'a b'` # two args: "i=a" and "b"
  3931. * ls: cannot access i=a: No such file or directory
  3932. * ls: cannot access b: No such file or directory
  3933. * Note: bash 3.2.33(1) does this only if export word
  3934. * itself is not quoted:
  3935. * $ export i=`echo 'aaa bbb'`; echo "$i"
  3936. * aaa bbb
  3937. * $ "export" i=`echo 'aaa bbb'`; echo "$i"
  3938. * aaa
  3939. */
  3940. IF_HUSH_LOCAL( || strcmp(ctx->word.data, "local") == 0)
  3941. IF_HUSH_EXPORT( || strcmp(ctx->word.data, "export") == 0)
  3942. IF_HUSH_READONLY(|| strcmp(ctx->word.data, "readonly") == 0)
  3943. ) {
  3944. command->cmd_type = CMD_SINGLEWORD_NOGLOB;
  3945. }
  3946. # else
  3947. { /* empty block to pair "if ... else" */ }
  3948. # endif
  3949. }
  3950. #endif /* HAS_KEYWORDS */
  3951. if (command->group) {
  3952. /* "{ echo foo; } echo bar" - bad */
  3953. syntax_error_at(ctx->word.data);
  3954. debug_printf_parse("done_word return 1: syntax error, "
  3955. "groups and arglists don't mix\n");
  3956. return 1;
  3957. }
  3958. /* If this word wasn't an assignment, next ones definitely
  3959. * can't be assignments. Even if they look like ones. */
  3960. if (ctx->is_assignment != DEFINITELY_ASSIGNMENT
  3961. && ctx->is_assignment != WORD_IS_KEYWORD
  3962. ) {
  3963. ctx->is_assignment = NOT_ASSIGNMENT;
  3964. } else {
  3965. if (ctx->is_assignment == DEFINITELY_ASSIGNMENT) {
  3966. command->assignment_cnt++;
  3967. debug_printf_parse("++assignment_cnt=%d\n", command->assignment_cnt);
  3968. }
  3969. debug_printf_parse("ctx->is_assignment was:'%s'\n", assignment_flag[ctx->is_assignment]);
  3970. ctx->is_assignment = MAYBE_ASSIGNMENT;
  3971. }
  3972. debug_printf_parse("ctx->is_assignment='%s'\n", assignment_flag[ctx->is_assignment]);
  3973. command->argv = add_string_to_strings(command->argv, xstrdup(ctx->word.data));
  3974. debug_print_strings("word appended to argv", command->argv);
  3975. }
  3976. #if ENABLE_HUSH_LOOPS
  3977. if (ctx->ctx_res_w == RES_FOR) {
  3978. if (ctx->word.has_quoted_part
  3979. || endofname(command->argv[0])[0] != '\0'
  3980. ) {
  3981. /* bash says just "not a valid identifier" */
  3982. syntax_error("bad variable name in for");
  3983. return 1;
  3984. }
  3985. /* Force FOR to have just one word (variable name) */
  3986. /* NB: basically, this makes hush see "for v in ..."
  3987. * syntax as if it is "for v; in ...". FOR and IN become
  3988. * two pipe structs in parse tree. */
  3989. done_pipe(ctx, PIPE_SEQ);
  3990. }
  3991. #endif
  3992. #if ENABLE_HUSH_CASE
  3993. /* Force CASE to have just one word */
  3994. if (ctx->ctx_res_w == RES_CASE) {
  3995. done_pipe(ctx, PIPE_SEQ);
  3996. }
  3997. #endif
  3998. o_reset_to_empty_unquoted(&ctx->word);
  3999. debug_printf_parse("done_word return 0\n");
  4000. return 0;
  4001. }
  4002. /* Peek ahead in the input to find out if we have a "&n" construct,
  4003. * as in "2>&1", that represents duplicating a file descriptor.
  4004. * Return:
  4005. * REDIRFD_CLOSE if >&- "close fd" construct is seen,
  4006. * REDIRFD_SYNTAX_ERR if syntax error,
  4007. * REDIRFD_TO_FILE if no & was seen,
  4008. * or the number found.
  4009. */
  4010. #if BB_MMU
  4011. #define parse_redir_right_fd(as_string, input) \
  4012. parse_redir_right_fd(input)
  4013. #endif
  4014. static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
  4015. {
  4016. int ch, d, ok;
  4017. ch = i_peek(input);
  4018. if (ch != '&')
  4019. return REDIRFD_TO_FILE;
  4020. ch = i_getch(input); /* get the & */
  4021. nommu_addchr(as_string, ch);
  4022. ch = i_peek(input);
  4023. if (ch == '-') {
  4024. ch = i_getch(input);
  4025. nommu_addchr(as_string, ch);
  4026. return REDIRFD_CLOSE;
  4027. }
  4028. d = 0;
  4029. ok = 0;
  4030. while (ch != EOF && isdigit(ch)) {
  4031. d = d*10 + (ch-'0');
  4032. ok = 1;
  4033. ch = i_getch(input);
  4034. nommu_addchr(as_string, ch);
  4035. ch = i_peek(input);
  4036. }
  4037. if (ok) return d;
  4038. //TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
  4039. bb_simple_error_msg("ambiguous redirect");
  4040. return REDIRFD_SYNTAX_ERR;
  4041. }
  4042. /* Return code is 0 normal, 1 if a syntax error is detected
  4043. */
  4044. static int parse_redirect(struct parse_context *ctx,
  4045. int fd,
  4046. redir_type style,
  4047. struct in_str *input)
  4048. {
  4049. struct command *command = ctx->command;
  4050. struct redir_struct *redir;
  4051. struct redir_struct **redirp;
  4052. int dup_num;
  4053. dup_num = REDIRFD_TO_FILE;
  4054. if (style != REDIRECT_HEREDOC) {
  4055. /* Check for a '>&1' type redirect */
  4056. dup_num = parse_redir_right_fd(&ctx->as_string, input);
  4057. if (dup_num == REDIRFD_SYNTAX_ERR)
  4058. return 1;
  4059. } else {
  4060. int ch = i_peek_and_eat_bkslash_nl(input);
  4061. dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
  4062. if (dup_num) { /* <<-... */
  4063. ch = i_getch(input);
  4064. nommu_addchr(&ctx->as_string, ch);
  4065. ch = i_peek(input);
  4066. }
  4067. }
  4068. if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
  4069. int ch = i_peek_and_eat_bkslash_nl(input);
  4070. if (ch == '|') {
  4071. /* >|FILE redirect ("clobbering" >).
  4072. * Since we do not support "set -o noclobber" yet,
  4073. * >| and > are the same for now. Just eat |.
  4074. */
  4075. ch = i_getch(input);
  4076. nommu_addchr(&ctx->as_string, ch);
  4077. }
  4078. }
  4079. /* Create a new redir_struct and append it to the linked list */
  4080. redirp = &command->redirects;
  4081. while ((redir = *redirp) != NULL) {
  4082. redirp = &(redir->next);
  4083. }
  4084. *redirp = redir = xzalloc(sizeof(*redir));
  4085. /* redir->next = NULL; */
  4086. /* redir->rd_filename = NULL; */
  4087. redir->rd_type = style;
  4088. redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
  4089. debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
  4090. redir_table[style].descrip);
  4091. redir->rd_dup = dup_num;
  4092. if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
  4093. /* Erik had a check here that the file descriptor in question
  4094. * is legit; I postpone that to "run time"
  4095. * A "-" representation of "close me" shows up as a -3 here */
  4096. debug_printf_parse("duplicating redirect '%d>&%d'\n",
  4097. redir->rd_fd, redir->rd_dup);
  4098. } else {
  4099. #if 0 /* Instead we emit error message at run time */
  4100. if (ctx->pending_redirect) {
  4101. /* For example, "cmd > <file" */
  4102. syntax_error("invalid redirect");
  4103. }
  4104. #endif
  4105. /* Set ctx->pending_redirect, so we know what to do at the
  4106. * end of the next parsed word. */
  4107. ctx->pending_redirect = redir;
  4108. }
  4109. return 0;
  4110. }
  4111. /* If a redirect is immediately preceded by a number, that number is
  4112. * supposed to tell which file descriptor to redirect. This routine
  4113. * looks for such preceding numbers. In an ideal world this routine
  4114. * needs to handle all the following classes of redirects...
  4115. * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
  4116. * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
  4117. * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
  4118. * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
  4119. *
  4120. * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
  4121. * "2.7 Redirection
  4122. * ... If n is quoted, the number shall not be recognized as part of
  4123. * the redirection expression. For example:
  4124. * echo \2>a
  4125. * writes the character 2 into file a"
  4126. * We are getting it right by setting ->has_quoted_part on any \<char>
  4127. *
  4128. * A -1 return means no valid number was found,
  4129. * the caller should use the appropriate default for this redirection.
  4130. */
  4131. static int redirect_opt_num(o_string *o)
  4132. {
  4133. int num;
  4134. if (o->data == NULL)
  4135. return -1;
  4136. num = bb_strtou(o->data, NULL, 10);
  4137. if (errno || num < 0)
  4138. return -1;
  4139. o_reset_to_empty_unquoted(o);
  4140. return num;
  4141. }
  4142. #if BB_MMU
  4143. #define fetch_till_str(as_string, input, word, skip_tabs) \
  4144. fetch_till_str(input, word, skip_tabs)
  4145. #endif
  4146. static char *fetch_till_str(o_string *as_string,
  4147. struct in_str *input,
  4148. const char *word,
  4149. int heredoc_flags)
  4150. {
  4151. o_string heredoc = NULL_O_STRING;
  4152. unsigned past_EOL;
  4153. int prev = 0; /* not \ */
  4154. int ch;
  4155. /* Starting with "" is necessary for this case:
  4156. * cat <<EOF
  4157. *
  4158. * xxx
  4159. * EOF
  4160. */
  4161. heredoc.data = xzalloc(1); /* start as "", not as NULL */
  4162. goto jump_in;
  4163. while (1) {
  4164. ch = i_getch(input);
  4165. if (ch != EOF)
  4166. nommu_addchr(as_string, ch);
  4167. if (ch == '\n' || ch == EOF) {
  4168. check_heredoc_end:
  4169. if ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\') {
  4170. /* End-of-line, and not a line continuation */
  4171. if (strcmp(heredoc.data + past_EOL, word) == 0) {
  4172. heredoc.data[past_EOL] = '\0';
  4173. debug_printf_heredoc("parsed '%s' heredoc '%s'\n", word, heredoc.data);
  4174. return heredoc.data;
  4175. }
  4176. if (ch == '\n') {
  4177. /* This is a new line.
  4178. * Remember position and backslash-escaping status.
  4179. */
  4180. o_addchr(&heredoc, ch);
  4181. prev = ch;
  4182. jump_in:
  4183. past_EOL = heredoc.length;
  4184. /* Get 1st char of next line, possibly skipping leading tabs */
  4185. do {
  4186. ch = i_getch(input);
  4187. if (ch != EOF)
  4188. nommu_addchr(as_string, ch);
  4189. } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
  4190. /* If this immediately ended the line,
  4191. * go back to end-of-line checks.
  4192. */
  4193. if (ch == '\n')
  4194. goto check_heredoc_end;
  4195. }
  4196. } else {
  4197. /* Backslash-line continuation in an unquoted
  4198. * heredoc. This does not need special handling
  4199. * for heredoc body (unquoted heredocs are
  4200. * expanded on "execution" and that would take
  4201. * care of this case too), but not the case
  4202. * of line continuation *in terminator*:
  4203. * cat <<EOF
  4204. * Ok1
  4205. * EO\
  4206. * F
  4207. */
  4208. heredoc.data[--heredoc.length] = '\0';
  4209. prev = 0; /* not '\' */
  4210. continue;
  4211. }
  4212. }
  4213. if (ch == EOF) {
  4214. o_free(&heredoc);
  4215. return NULL; /* error */
  4216. }
  4217. o_addchr(&heredoc, ch);
  4218. nommu_addchr(as_string, ch);
  4219. if (prev == '\\' && ch == '\\')
  4220. /* Correctly handle foo\\<eol> (not a line cont.) */
  4221. prev = 0; /* not '\' */
  4222. else
  4223. prev = ch;
  4224. }
  4225. }
  4226. /* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
  4227. * and load them all. There should be exactly heredoc_cnt of them.
  4228. */
  4229. #if BB_MMU
  4230. #define fetch_heredocs(as_string, pi, heredoc_cnt, input) \
  4231. fetch_heredocs(pi, heredoc_cnt, input)
  4232. #endif
  4233. static int fetch_heredocs(o_string *as_string, struct pipe *pi, int heredoc_cnt, struct in_str *input)
  4234. {
  4235. while (pi && heredoc_cnt) {
  4236. int i;
  4237. struct command *cmd = pi->cmds;
  4238. debug_printf_heredoc("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
  4239. pi->num_cmds,
  4240. cmd->argv ? cmd->argv[0] : "NONE"
  4241. );
  4242. for (i = 0; i < pi->num_cmds; i++) {
  4243. struct redir_struct *redir = cmd->redirects;
  4244. debug_printf_heredoc("fetch_heredocs: %d cmd argv0:'%s'\n",
  4245. i, cmd->argv ? cmd->argv[0] : "NONE");
  4246. while (redir) {
  4247. if (redir->rd_type == REDIRECT_HEREDOC) {
  4248. char *p;
  4249. redir->rd_type = REDIRECT_HEREDOC2;
  4250. /* redir->rd_dup is (ab)used to indicate <<- */
  4251. p = fetch_till_str(as_string, input,
  4252. redir->rd_filename, redir->rd_dup);
  4253. if (!p) {
  4254. syntax_error("unexpected EOF in here document");
  4255. return -1;
  4256. }
  4257. free(redir->rd_filename);
  4258. redir->rd_filename = p;
  4259. heredoc_cnt--;
  4260. }
  4261. redir = redir->next;
  4262. }
  4263. if (cmd->group) {
  4264. //bb_error_msg("%s:%u heredoc_cnt:%d", __func__, __LINE__, heredoc_cnt);
  4265. heredoc_cnt = fetch_heredocs(as_string, cmd->group, heredoc_cnt, input);
  4266. //bb_error_msg("%s:%u heredoc_cnt:%d", __func__, __LINE__, heredoc_cnt);
  4267. if (heredoc_cnt < 0)
  4268. return heredoc_cnt; /* error */
  4269. }
  4270. cmd++;
  4271. }
  4272. pi = pi->next;
  4273. }
  4274. return heredoc_cnt;
  4275. }
  4276. static int run_list(struct pipe *pi);
  4277. #if BB_MMU
  4278. #define parse_stream(pstring, heredoc_cnt_ptr, input, end_trigger) \
  4279. parse_stream(heredoc_cnt_ptr, input, end_trigger)
  4280. #endif
  4281. static struct pipe *parse_stream(char **pstring,
  4282. int *heredoc_cnt_ptr,
  4283. struct in_str *input,
  4284. int end_trigger);
  4285. /* Returns number of heredocs not yet consumed,
  4286. * or -1 on error.
  4287. */
  4288. static int parse_group(struct parse_context *ctx,
  4289. struct in_str *input, int ch)
  4290. {
  4291. /* ctx->word contains characters seen prior to ( or {.
  4292. * Typically it's empty, but for function defs,
  4293. * it contains function name (without '()'). */
  4294. #if BB_MMU
  4295. # define as_string NULL
  4296. #else
  4297. char *as_string = NULL;
  4298. #endif
  4299. struct pipe *pipe_list;
  4300. int heredoc_cnt = 0;
  4301. int endch;
  4302. struct command *command = ctx->command;
  4303. debug_printf_parse("parse_group entered\n");
  4304. #if ENABLE_HUSH_FUNCTIONS
  4305. if (ch == '(' && !ctx->word.has_quoted_part) {
  4306. if (ctx->word.length)
  4307. if (done_word(ctx))
  4308. return -1;
  4309. if (!command->argv)
  4310. goto skip; /* (... */
  4311. if (command->argv[1]) { /* word word ... (... */
  4312. syntax_error_unexpected_ch('(');
  4313. return -1;
  4314. }
  4315. /* it is "word(..." or "word (..." */
  4316. do
  4317. ch = i_getch(input);
  4318. while (ch == ' ' || ch == '\t');
  4319. if (ch != ')') {
  4320. syntax_error_unexpected_ch(ch);
  4321. return -1;
  4322. }
  4323. nommu_addchr(&ctx->as_string, ch);
  4324. do
  4325. ch = i_getch(input);
  4326. while (ch == ' ' || ch == '\t' || ch == '\n');
  4327. if (ch != '{' && ch != '(') {
  4328. syntax_error_unexpected_ch(ch);
  4329. return -1;
  4330. }
  4331. nommu_addchr(&ctx->as_string, ch);
  4332. command->cmd_type = CMD_FUNCDEF;
  4333. goto skip;
  4334. }
  4335. #endif
  4336. #if 0 /* Prevented by caller */
  4337. if (command->argv /* word [word]{... */
  4338. || ctx->word.length /* word{... */
  4339. || ctx->word.has_quoted_part /* ""{... */
  4340. ) {
  4341. syntax_error(NULL);
  4342. debug_printf_parse("parse_group return -1: "
  4343. "syntax error, groups and arglists don't mix\n");
  4344. return -1;
  4345. }
  4346. #endif
  4347. IF_HUSH_FUNCTIONS(skip:)
  4348. endch = '}';
  4349. if (ch == '(') {
  4350. endch = ')';
  4351. IF_HUSH_FUNCTIONS(if (command->cmd_type != CMD_FUNCDEF))
  4352. command->cmd_type = CMD_SUBSHELL;
  4353. } else {
  4354. /* bash does not allow "{echo...", requires whitespace */
  4355. ch = i_peek(input);
  4356. if (ch != ' ' && ch != '\t' && ch != '\n'
  4357. && ch != '(' /* but "{(..." is allowed (without whitespace) */
  4358. ) {
  4359. syntax_error_unexpected_ch(ch);
  4360. return -1;
  4361. }
  4362. if (ch != '(') {
  4363. ch = i_getch(input);
  4364. nommu_addchr(&ctx->as_string, ch);
  4365. }
  4366. }
  4367. debug_printf_heredoc("calling parse_stream, heredoc_cnt:%d\n", heredoc_cnt);
  4368. pipe_list = parse_stream(&as_string, &heredoc_cnt, input, endch);
  4369. debug_printf_heredoc("parse_stream returned: heredoc_cnt:%d\n", heredoc_cnt);
  4370. #if !BB_MMU
  4371. if (as_string)
  4372. o_addstr(&ctx->as_string, as_string);
  4373. #endif
  4374. /* empty ()/{} or parse error? */
  4375. if (!pipe_list || pipe_list == ERR_PTR) {
  4376. /* parse_stream already emitted error msg */
  4377. if (!BB_MMU)
  4378. free(as_string);
  4379. debug_printf_parse("parse_group return -1: "
  4380. "parse_stream returned %p\n", pipe_list);
  4381. return -1;
  4382. }
  4383. #if !BB_MMU
  4384. as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
  4385. command->group_as_string = as_string;
  4386. debug_printf_parse("end of group, remembering as:'%s'\n",
  4387. command->group_as_string);
  4388. #endif
  4389. #if ENABLE_HUSH_FUNCTIONS
  4390. /* Convert "f() (cmds)" to "f() {(cmds)}" */
  4391. if (command->cmd_type == CMD_FUNCDEF && endch == ')') {
  4392. struct command *cmd2;
  4393. cmd2 = xzalloc(sizeof(*cmd2));
  4394. cmd2->cmd_type = CMD_SUBSHELL;
  4395. cmd2->group = pipe_list;
  4396. # if !BB_MMU
  4397. //UNTESTED!
  4398. cmd2->group_as_string = command->group_as_string;
  4399. command->group_as_string = xasprintf("(%s)", command->group_as_string);
  4400. # endif
  4401. pipe_list = new_pipe();
  4402. pipe_list->cmds = cmd2;
  4403. pipe_list->num_cmds = 1;
  4404. }
  4405. #endif
  4406. command->group = pipe_list;
  4407. debug_printf_parse("parse_group return %d\n", heredoc_cnt);
  4408. return heredoc_cnt;
  4409. /* command remains "open", available for possible redirects */
  4410. #undef as_string
  4411. }
  4412. #if ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS
  4413. /* Subroutines for copying $(...) and `...` things */
  4414. /* '...' */
  4415. static int add_till_single_quote(o_string *dest, struct in_str *input)
  4416. {
  4417. while (1) {
  4418. int ch = i_getch(input);
  4419. if (ch == EOF) {
  4420. syntax_error_unterm_ch('\'');
  4421. return 0;
  4422. }
  4423. if (ch == '\'')
  4424. return 1;
  4425. o_addchr(dest, ch);
  4426. }
  4427. }
  4428. static int add_till_single_quote_dquoted(o_string *dest, struct in_str *input)
  4429. {
  4430. while (1) {
  4431. int ch = i_getch(input);
  4432. if (ch == EOF) {
  4433. syntax_error_unterm_ch('\'');
  4434. return 0;
  4435. }
  4436. if (ch == '\'')
  4437. return 1;
  4438. o_addqchr(dest, ch);
  4439. }
  4440. }
  4441. /* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
  4442. static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote);
  4443. static int add_till_double_quote(o_string *dest, struct in_str *input)
  4444. {
  4445. while (1) {
  4446. int ch = i_getch(input);
  4447. if (ch == EOF) {
  4448. syntax_error_unterm_ch('"');
  4449. return 0;
  4450. }
  4451. if (ch == '"')
  4452. return 1;
  4453. if (ch == '\\') { /* \x. Copy both chars. */
  4454. o_addchr(dest, ch);
  4455. ch = i_getch(input);
  4456. }
  4457. o_addchr(dest, ch);
  4458. if (ch == '`') {
  4459. if (!add_till_backquote(dest, input, /*in_dquote:*/ 1))
  4460. return 0;
  4461. o_addchr(dest, ch);
  4462. continue;
  4463. }
  4464. //if (ch == '$') ...
  4465. }
  4466. }
  4467. /* Process `cmd` - copy contents until "`" is seen. Complicated by
  4468. * \` quoting.
  4469. * "Within the backquoted style of command substitution, backslash
  4470. * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
  4471. * The search for the matching backquote shall be satisfied by the first
  4472. * backquote found without a preceding backslash; during this search,
  4473. * if a non-escaped backquote is encountered within a shell comment,
  4474. * a here-document, an embedded command substitution of the $(command)
  4475. * form, or a quoted string, undefined results occur. A single-quoted
  4476. * or double-quoted string that begins, but does not end, within the
  4477. * "`...`" sequence produces undefined results."
  4478. * Example Output
  4479. * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
  4480. */
  4481. static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote)
  4482. {
  4483. while (1) {
  4484. int ch = i_getch(input);
  4485. if (ch == '`')
  4486. return 1;
  4487. if (ch == '\\') {
  4488. /* \x. Copy both unless it is \`, \$, \\ and maybe \" */
  4489. ch = i_getch(input);
  4490. if (ch != '`'
  4491. && ch != '$'
  4492. && ch != '\\'
  4493. && (!in_dquote || ch != '"')
  4494. ) {
  4495. o_addchr(dest, '\\');
  4496. }
  4497. }
  4498. if (ch == EOF) {
  4499. syntax_error_unterm_ch('`');
  4500. return 0;
  4501. }
  4502. o_addchr(dest, ch);
  4503. }
  4504. }
  4505. /* Process $(cmd) - copy contents until ")" is seen. Complicated by
  4506. * quoting and nested ()s.
  4507. * "With the $(command) style of command substitution, all characters
  4508. * following the open parenthesis to the matching closing parenthesis
  4509. * constitute the command. Any valid shell script can be used for command,
  4510. * except a script consisting solely of redirections which produces
  4511. * unspecified results."
  4512. * Example Output
  4513. * echo $(echo '(TEST)' BEST) (TEST) BEST
  4514. * echo $(echo 'TEST)' BEST) TEST) BEST
  4515. * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
  4516. *
  4517. * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
  4518. * can contain arbitrary constructs, just like $(cmd).
  4519. * In bash compat mode, it needs to also be able to stop on ':' or '/'
  4520. * for ${var:N[:M]} and ${var/P[/R]} parsing.
  4521. */
  4522. #define DOUBLE_CLOSE_CHAR_FLAG 0x80
  4523. static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
  4524. {
  4525. int ch;
  4526. char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
  4527. # if BASH_SUBSTR || BASH_PATTERN_SUBST
  4528. char end_char2 = end_ch >> 8;
  4529. # endif
  4530. end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
  4531. # if ENABLE_HUSH_INTERACTIVE
  4532. G.promptmode = 1; /* PS2 */
  4533. # endif
  4534. debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
  4535. while (1) {
  4536. ch = i_getch(input);
  4537. if (ch == EOF) {
  4538. syntax_error_unterm_ch(end_ch);
  4539. return 0;
  4540. }
  4541. if (ch == end_ch
  4542. # if BASH_SUBSTR || BASH_PATTERN_SUBST
  4543. || ch == end_char2
  4544. # endif
  4545. ) {
  4546. if (!dbl)
  4547. break;
  4548. /* we look for closing )) of $((EXPR)) */
  4549. if (i_peek_and_eat_bkslash_nl(input) == end_ch) {
  4550. i_getch(input); /* eat second ')' */
  4551. break;
  4552. }
  4553. }
  4554. o_addchr(dest, ch);
  4555. //bb_error_msg("%s:o_addchr('%c')", __func__, ch);
  4556. if (ch == '(' || ch == '{') {
  4557. ch = (ch == '(' ? ')' : '}');
  4558. if (!add_till_closing_bracket(dest, input, ch))
  4559. return 0;
  4560. o_addchr(dest, ch);
  4561. continue;
  4562. }
  4563. if (ch == '\'') {
  4564. if (!add_till_single_quote(dest, input))
  4565. return 0;
  4566. o_addchr(dest, ch);
  4567. continue;
  4568. }
  4569. if (ch == '"') {
  4570. if (!add_till_double_quote(dest, input))
  4571. return 0;
  4572. o_addchr(dest, ch);
  4573. continue;
  4574. }
  4575. if (ch == '`') {
  4576. if (!add_till_backquote(dest, input, /*in_dquote:*/ 0))
  4577. return 0;
  4578. o_addchr(dest, ch);
  4579. continue;
  4580. }
  4581. if (ch == '\\') {
  4582. /* \x. Copy verbatim. Important for \(, \) */
  4583. ch = i_getch(input);
  4584. if (ch == EOF) {
  4585. syntax_error_unterm_ch(end_ch);
  4586. return 0;
  4587. }
  4588. # if 0
  4589. if (ch == '\n') {
  4590. /* "backslash+newline", ignore both */
  4591. o_delchr(dest); /* undo insertion of '\' */
  4592. continue;
  4593. }
  4594. # endif
  4595. o_addchr(dest, ch);
  4596. //bb_error_msg("%s:o_addchr('%c') after '\\'", __func__, ch);
  4597. continue;
  4598. }
  4599. }
  4600. debug_printf_parse("%s return '%s' ch:'%c'\n", __func__, dest->data, ch);
  4601. return ch;
  4602. }
  4603. #endif /* ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS */
  4604. #if BASH_DOLLAR_SQUOTE
  4605. /* Return code: 1 for "found and parsed", 0 for "seen something else" */
  4606. # if BB_MMU
  4607. #define parse_dollar_squote(as_string, dest, input) \
  4608. parse_dollar_squote(dest, input)
  4609. #define as_string NULL
  4610. # endif
  4611. static int parse_dollar_squote(o_string *as_string, o_string *dest, struct in_str *input)
  4612. {
  4613. int start;
  4614. int ch = i_peek_and_eat_bkslash_nl(input); /* first character after the $ */
  4615. debug_printf_parse("parse_dollar_squote entered: ch='%c'\n", ch);
  4616. if (ch != '\'')
  4617. return 0;
  4618. dest->has_quoted_part = 1;
  4619. start = dest->length;
  4620. ch = i_getch(input); /* eat ' */
  4621. nommu_addchr(as_string, ch);
  4622. while (1) {
  4623. ch = i_getch(input);
  4624. nommu_addchr(as_string, ch);
  4625. if (ch == EOF) {
  4626. syntax_error_unterm_ch('\'');
  4627. return 0;
  4628. }
  4629. if (ch == '\'')
  4630. break;
  4631. if (ch == SPECIAL_VAR_SYMBOL) {
  4632. /* Convert raw ^C to corresponding special variable reference */
  4633. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4634. o_addchr(dest, SPECIAL_VAR_QUOTED_SVS);
  4635. /* will addchr() another SPECIAL_VAR_SYMBOL (see after the if() block) */
  4636. } else if (ch == '\\') {
  4637. static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
  4638. ch = i_getch(input);
  4639. nommu_addchr(as_string, ch);
  4640. if (strchr(C_escapes, ch)) {
  4641. char buf[4];
  4642. char *p = buf;
  4643. int cnt = 2;
  4644. buf[0] = ch;
  4645. if ((unsigned char)(ch - '0') <= 7) { /* \ooo */
  4646. do {
  4647. ch = i_peek(input);
  4648. if ((unsigned char)(ch - '0') > 7)
  4649. break;
  4650. *++p = ch = i_getch(input);
  4651. nommu_addchr(as_string, ch);
  4652. } while (--cnt != 0);
  4653. } else if (ch == 'x') { /* \xHH */
  4654. do {
  4655. ch = i_peek(input);
  4656. if (!isxdigit(ch))
  4657. break;
  4658. *++p = ch = i_getch(input);
  4659. nommu_addchr(as_string, ch);
  4660. } while (--cnt != 0);
  4661. if (cnt == 2) { /* \x but next char is "bad" */
  4662. ch = 'x';
  4663. goto unrecognized;
  4664. }
  4665. } /* else simple seq like \\ or \t */
  4666. *++p = '\0';
  4667. p = buf;
  4668. ch = bb_process_escape_sequence((void*)&p);
  4669. //bb_error_msg("buf:'%s' ch:%x", buf, ch);
  4670. if (ch == '\0')
  4671. continue; /* bash compat: $'...\0...' emits nothing */
  4672. } else { /* unrecognized "\z": encode both chars unless ' or " */
  4673. if (ch != '\'' && ch != '"') {
  4674. unrecognized:
  4675. o_addqchr(dest, '\\');
  4676. }
  4677. }
  4678. } /* if (\...) */
  4679. o_addqchr(dest, ch);
  4680. }
  4681. if (dest->length == start) {
  4682. /* $'', $'\0', $'\000\x00' and the like */
  4683. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4684. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4685. }
  4686. return 1;
  4687. # undef as_string
  4688. }
  4689. #else
  4690. # define parse_dollar_squote(as_string, dest, input) 0
  4691. #endif /* BASH_DOLLAR_SQUOTE */
  4692. /* Return code: 0 for OK, 1 for syntax error */
  4693. #if BB_MMU
  4694. #define parse_dollar(as_string, dest, input, quote_mask) \
  4695. parse_dollar(dest, input, quote_mask)
  4696. #define as_string NULL
  4697. #endif
  4698. static int parse_dollar(o_string *as_string,
  4699. o_string *dest,
  4700. struct in_str *input, unsigned char quote_mask)
  4701. {
  4702. int ch = i_peek_and_eat_bkslash_nl(input); /* first character after the $ */
  4703. debug_printf_parse("parse_dollar entered: ch='%c' quote_mask:0x%x\n", ch, quote_mask);
  4704. if (isalpha(ch)) {
  4705. make_var:
  4706. ch = i_getch(input);
  4707. nommu_addchr(as_string, ch);
  4708. /*make_var1:*/
  4709. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4710. while (1) {
  4711. debug_printf_parse(": '%c'\n", ch);
  4712. o_addchr(dest, ch | quote_mask);
  4713. quote_mask = 0;
  4714. ch = i_peek_and_eat_bkslash_nl(input);
  4715. if (!isalnum(ch) && ch != '_') {
  4716. /* End of variable name reached */
  4717. break;
  4718. }
  4719. ch = i_getch(input);
  4720. nommu_addchr(as_string, ch);
  4721. }
  4722. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4723. } else if (isdigit(ch)) {
  4724. make_one_char_var:
  4725. ch = i_getch(input);
  4726. nommu_addchr(as_string, ch);
  4727. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4728. debug_printf_parse(": '%c'\n", ch);
  4729. o_addchr(dest, ch | quote_mask);
  4730. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4731. } else switch (ch) {
  4732. case '$': /* pid */
  4733. case '!': /* last bg pid */
  4734. case '?': /* last exit code */
  4735. case '#': /* number of args */
  4736. case '*': /* args */
  4737. case '@': /* args */
  4738. case '-': /* $- option flags set by set builtin or shell options (-i etc) */
  4739. goto make_one_char_var;
  4740. case '{': {
  4741. char len_single_ch;
  4742. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4743. ch = i_getch(input); /* eat '{' */
  4744. nommu_addchr(as_string, ch);
  4745. ch = i_getch_and_eat_bkslash_nl(input); /* first char after '{' */
  4746. /* It should be ${?}, or ${#var},
  4747. * or even ${?+subst} - operator acting on a special variable,
  4748. * or the beginning of variable name.
  4749. */
  4750. if (ch == EOF
  4751. || (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) /* not one of those */
  4752. ) {
  4753. bad_dollar_syntax:
  4754. syntax_error_unterm_str("${name}");
  4755. debug_printf_parse("parse_dollar return 0: unterminated ${name}\n");
  4756. return 0;
  4757. }
  4758. nommu_addchr(as_string, ch);
  4759. len_single_ch = ch;
  4760. ch |= quote_mask;
  4761. /* It's possible to just call add_till_closing_bracket() at this point.
  4762. * However, this regresses some of our testsuite cases
  4763. * which check invalid constructs like ${%}.
  4764. * Oh well... let's check that the var name part is fine... */
  4765. if (isdigit(len_single_ch)
  4766. || (len_single_ch == '#' && isdigit(i_peek_and_eat_bkslash_nl(input)))
  4767. ) {
  4768. /* Execution engine uses plain xatoi_positive()
  4769. * to interpret ${NNN} and {#NNN},
  4770. * check syntax here in the parser.
  4771. * (bash does not support expressions in ${#NN},
  4772. * e.g. ${#$var} and {#1:+WORD} are not supported).
  4773. */
  4774. unsigned cnt = 9; /* max 9 digits for ${NN} and 8 for {#NN} */
  4775. while (1) {
  4776. o_addchr(dest, ch);
  4777. debug_printf_parse(": '%c'\n", ch);
  4778. ch = i_getch_and_eat_bkslash_nl(input);
  4779. nommu_addchr(as_string, ch);
  4780. if (ch == '}')
  4781. break;
  4782. if (--cnt == 0)
  4783. goto bad_dollar_syntax;
  4784. if (len_single_ch != '#' && strchr(VAR_SUBST_OPS, ch))
  4785. /* ${NN<op>...} is valid */
  4786. goto eat_until_closing;
  4787. if (!isdigit(ch))
  4788. goto bad_dollar_syntax;
  4789. }
  4790. } else
  4791. while (1) {
  4792. unsigned pos;
  4793. o_addchr(dest, ch);
  4794. debug_printf_parse(": '%c'\n", ch);
  4795. ch = i_getch(input);
  4796. nommu_addchr(as_string, ch);
  4797. if (ch == '}')
  4798. break;
  4799. if (!isalnum(ch) && ch != '_') {
  4800. unsigned end_ch;
  4801. unsigned char last_ch;
  4802. /* handle parameter expansions
  4803. * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
  4804. */
  4805. if (!strchr(VAR_SUBST_OPS, ch)) { /* ${var<bad_char>... */
  4806. if (len_single_ch != '#'
  4807. /*|| !strchr(SPECIAL_VARS_STR, ch) - disallow errors like ${#+} ? */
  4808. || i_peek(input) != '}'
  4809. ) {
  4810. goto bad_dollar_syntax;
  4811. }
  4812. /* else: it's "length of C" ${#C} op,
  4813. * where C is a single char
  4814. * special var name, e.g. ${#!}.
  4815. */
  4816. }
  4817. eat_until_closing:
  4818. /* Eat everything until closing '}' (or ':') */
  4819. end_ch = '}';
  4820. if (BASH_SUBSTR
  4821. && ch == ':'
  4822. && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
  4823. ) {
  4824. /* It's ${var:N[:M]} thing */
  4825. end_ch = '}' * 0x100 + ':';
  4826. }
  4827. if (BASH_PATTERN_SUBST
  4828. && ch == '/'
  4829. ) {
  4830. /* It's ${var/[/]pattern[/repl]} thing */
  4831. if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
  4832. i_getch(input);
  4833. nommu_addchr(as_string, '/');
  4834. ch = '\\';
  4835. }
  4836. end_ch = '}' * 0x100 + '/';
  4837. }
  4838. o_addchr(dest, ch);
  4839. /* The pattern can't be empty.
  4840. * IOW: if the first char after "${v//" is a slash,
  4841. * it does not terminate the pattern - it's the first char of the pattern:
  4842. * v=/dev/ram; echo ${v////-} prints -dev-ram (pattern is "/")
  4843. * v=/dev/ram; echo ${v///r/-} prints /dev-am (pattern is "/r")
  4844. */
  4845. if (i_peek(input) == '/') {
  4846. o_addchr(dest, i_getch(input));
  4847. }
  4848. again:
  4849. if (!BB_MMU)
  4850. pos = dest->length;
  4851. #if ENABLE_HUSH_DOLLAR_OPS
  4852. last_ch = add_till_closing_bracket(dest, input, end_ch);
  4853. if (last_ch == 0) /* error? */
  4854. return 0;
  4855. #else
  4856. # error Simple code to only allow ${var} is not implemented
  4857. #endif
  4858. if (as_string) {
  4859. o_addstr(as_string, dest->data + pos);
  4860. o_addchr(as_string, last_ch);
  4861. }
  4862. if ((BASH_SUBSTR || BASH_PATTERN_SUBST)
  4863. && (end_ch & 0xff00)
  4864. ) {
  4865. /* close the first block: */
  4866. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4867. /* while parsing N from ${var:N[:M]}
  4868. * or pattern from ${var/[/]pattern[/repl]} */
  4869. if ((end_ch & 0xff) == last_ch) {
  4870. /* got ':' or '/'- parse the rest */
  4871. end_ch = '}';
  4872. goto again;
  4873. }
  4874. /* got '}' */
  4875. if (BASH_SUBSTR && end_ch == '}' * 0x100 + ':') {
  4876. /* it's ${var:N} - emulate :999999999 */
  4877. o_addstr(dest, "999999999");
  4878. } /* else: it's ${var/[/]pattern} */
  4879. }
  4880. break;
  4881. }
  4882. len_single_ch = 0; /* it can't be ${#C} op */
  4883. }
  4884. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4885. break;
  4886. }
  4887. #if ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_TICK
  4888. case '(': {
  4889. unsigned pos;
  4890. ch = i_getch(input);
  4891. nommu_addchr(as_string, ch);
  4892. # if ENABLE_FEATURE_SH_MATH
  4893. if (i_peek_and_eat_bkslash_nl(input) == '(') {
  4894. ch = i_getch(input);
  4895. nommu_addchr(as_string, ch);
  4896. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4897. o_addchr(dest, quote_mask | '+');
  4898. if (!BB_MMU)
  4899. pos = dest->length;
  4900. if (!add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG))
  4901. return 0; /* error */
  4902. if (as_string) {
  4903. o_addstr(as_string, dest->data + pos);
  4904. o_addchr(as_string, ')');
  4905. o_addchr(as_string, ')');
  4906. }
  4907. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4908. break;
  4909. }
  4910. # endif
  4911. # if ENABLE_HUSH_TICK
  4912. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4913. o_addchr(dest, quote_mask | '`');
  4914. if (!BB_MMU)
  4915. pos = dest->length;
  4916. if (!add_till_closing_bracket(dest, input, ')'))
  4917. return 0; /* error */
  4918. if (as_string) {
  4919. o_addstr(as_string, dest->data + pos);
  4920. o_addchr(as_string, ')');
  4921. }
  4922. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4923. # endif
  4924. break;
  4925. }
  4926. #endif
  4927. case '_':
  4928. goto make_var;
  4929. #if 0
  4930. /* TODO: $_: */
  4931. /* $_ Shell or shell script name; or last argument of last command
  4932. * (if last command wasn't a pipe; if it was, bash sets $_ to "");
  4933. * but in command's env, set to full pathname used to invoke it */
  4934. ch = i_getch(input);
  4935. nommu_addchr(as_string, ch);
  4936. ch = i_peek_and_eat_bkslash_nl(input);
  4937. if (isalnum(ch)) { /* it's $_name or $_123 */
  4938. ch = '_';
  4939. goto make_var1;
  4940. }
  4941. /* else: it's $_ */
  4942. #endif
  4943. default:
  4944. o_addQchr(dest, '$');
  4945. }
  4946. debug_printf_parse("parse_dollar return 1 (ok)\n");
  4947. return 1;
  4948. #undef as_string
  4949. }
  4950. #if BB_MMU
  4951. #define encode_string(as_string, dest, input, dquote_end) \
  4952. encode_string(dest, input, dquote_end)
  4953. #define as_string NULL
  4954. #endif
  4955. static int encode_string(o_string *as_string,
  4956. o_string *dest,
  4957. struct in_str *input,
  4958. int dquote_end)
  4959. {
  4960. int ch;
  4961. int next;
  4962. again:
  4963. ch = i_getch(input);
  4964. if (ch != EOF)
  4965. nommu_addchr(as_string, ch);
  4966. if (ch == dquote_end) { /* may be only '"' or EOF */
  4967. debug_printf_parse("encode_string return 1 (ok)\n");
  4968. return 1;
  4969. }
  4970. /* note: can't move it above ch == dquote_end check! */
  4971. if (ch == EOF) {
  4972. syntax_error_unterm_ch('"');
  4973. return 0; /* error */
  4974. }
  4975. next = '\0';
  4976. if (ch != '\n') {
  4977. next = i_peek(input);
  4978. }
  4979. debug_printf_parse("\" ch=%c (%d) escape=%d\n",
  4980. ch, ch, !!(dest->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
  4981. if (ch == '\\') {
  4982. if (next == EOF) {
  4983. /* Testcase: in interactive shell a file with
  4984. * echo "unterminated string\<eof>
  4985. * is sourced.
  4986. */
  4987. syntax_error_unterm_ch('"');
  4988. return 0; /* error */
  4989. }
  4990. /* bash:
  4991. * "The backslash retains its special meaning [in "..."]
  4992. * only when followed by one of the following characters:
  4993. * $, `, ", \, or <newline>. A double quote may be quoted
  4994. * within double quotes by preceding it with a backslash."
  4995. * NB: in (unquoted) heredoc, above does not apply to ",
  4996. * therefore we check for it by "next == dquote_end" cond.
  4997. */
  4998. if (next == dquote_end || strchr("$`\\\n", next)) {
  4999. ch = i_getch(input); /* eat next */
  5000. if (ch == '\n')
  5001. goto again; /* skip \<newline> */
  5002. } /* else: ch remains == '\\', and we double it below: */
  5003. o_addqchr(dest, ch); /* \c if c is a glob char, else just c */
  5004. nommu_addchr(as_string, ch);
  5005. goto again;
  5006. }
  5007. if (ch == '$') {
  5008. //if (parse_dollar_squote(as_string, dest, input))
  5009. // goto again;
  5010. if (!parse_dollar(as_string, dest, input, /*quote_mask:*/ 0x80)) {
  5011. debug_printf_parse("encode_string return 0: "
  5012. "parse_dollar returned 0 (error)\n");
  5013. return 0;
  5014. }
  5015. goto again;
  5016. }
  5017. #if ENABLE_HUSH_TICK
  5018. if (ch == '`') {
  5019. //unsigned pos = dest->length;
  5020. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  5021. o_addchr(dest, 0x80 | '`');
  5022. if (!add_till_backquote(dest, input, /*in_dquote:*/ dquote_end == '"'))
  5023. return 0; /* error */
  5024. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  5025. //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
  5026. goto again;
  5027. }
  5028. #endif
  5029. o_addQchr(dest, ch);
  5030. if (ch == SPECIAL_VAR_SYMBOL) {
  5031. /* Convert "^C" to corresponding special variable reference */
  5032. o_addchr(dest, SPECIAL_VAR_QUOTED_SVS);
  5033. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  5034. }
  5035. goto again;
  5036. #undef as_string
  5037. }
  5038. /*
  5039. * Scan input until EOF or end_trigger char.
  5040. * Return a list of pipes to execute, or NULL on EOF
  5041. * or if end_trigger character is met.
  5042. * On syntax error, exit if shell is not interactive,
  5043. * reset parsing machinery and start parsing anew,
  5044. * or return ERR_PTR.
  5045. */
  5046. static struct pipe *parse_stream(char **pstring,
  5047. int *heredoc_cnt_ptr,
  5048. struct in_str *input,
  5049. int end_trigger)
  5050. {
  5051. struct parse_context ctx;
  5052. int heredoc_cnt;
  5053. /* Single-quote triggers a bypass of the main loop until its mate is
  5054. * found. When recursing, quote state is passed in via ctx.word.o_expflags.
  5055. */
  5056. debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
  5057. end_trigger ? end_trigger : 'X');
  5058. debug_enter();
  5059. initialize_context(&ctx);
  5060. /* If very first arg is "" or '', ctx.word.data may end up NULL.
  5061. * Preventing this:
  5062. */
  5063. ctx.word.data = xzalloc(1); /* start as "", not as NULL */
  5064. /* We used to separate words on $IFS here. This was wrong.
  5065. * $IFS is used only for word splitting when $var is expanded,
  5066. * here we should use blank chars as separators, not $IFS
  5067. */
  5068. heredoc_cnt = 0;
  5069. while (1) {
  5070. const char *is_blank;
  5071. const char *is_special;
  5072. int ch;
  5073. int next;
  5074. int redir_fd;
  5075. redir_type redir_style;
  5076. ch = i_getch(input);
  5077. debug_printf_parse(": ch=%c (%d) escape=%d\n",
  5078. ch, ch, !!(ctx.word.o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
  5079. if (ch == EOF) {
  5080. struct pipe *pi;
  5081. if (heredoc_cnt) {
  5082. syntax_error_unterm_str("here document");
  5083. goto parse_error_exitcode1;
  5084. }
  5085. if (end_trigger == ')') {
  5086. syntax_error_unterm_ch('(');
  5087. goto parse_error_exitcode1;
  5088. }
  5089. if (end_trigger == '}') {
  5090. syntax_error_unterm_ch('{');
  5091. goto parse_error_exitcode1;
  5092. }
  5093. if (done_word(&ctx)) {
  5094. goto parse_error_exitcode1;
  5095. }
  5096. o_free_and_set_NULL(&ctx.word);
  5097. done_pipe(&ctx, PIPE_SEQ);
  5098. pi = ctx.list_head;
  5099. /* If we got nothing... */
  5100. /* (this makes bare "&" cmd a no-op.
  5101. * bash says: "syntax error near unexpected token '&'") */
  5102. if (pi->num_cmds == 0
  5103. IF_HAS_KEYWORDS(&& pi->res_word == RES_NONE)
  5104. ) {
  5105. free_pipe_list(pi);
  5106. pi = NULL;
  5107. }
  5108. #if !BB_MMU
  5109. debug_printf_parse("as_string1 '%s'\n", ctx.as_string.data);
  5110. if (pstring)
  5111. *pstring = ctx.as_string.data;
  5112. else
  5113. o_free(&ctx.as_string);
  5114. #endif
  5115. // heredoc_cnt must be 0 here anyway
  5116. //if (heredoc_cnt_ptr)
  5117. // *heredoc_cnt_ptr = heredoc_cnt;
  5118. debug_leave();
  5119. debug_printf_heredoc("parse_stream return heredoc_cnt:%d\n", heredoc_cnt);
  5120. debug_printf_parse("parse_stream return %p\n", pi);
  5121. return pi;
  5122. }
  5123. /* Handle "'" and "\" first, as they won't play nice with
  5124. * i_peek_and_eat_bkslash_nl() anyway:
  5125. * echo z\\
  5126. * and
  5127. * echo '\
  5128. * '
  5129. * would break.
  5130. */
  5131. if (ch == '\\') {
  5132. ch = i_getch(input);
  5133. if (ch == '\n')
  5134. continue; /* drop \<newline>, get next char */
  5135. nommu_addchr(&ctx.as_string, '\\');
  5136. if (ch == SPECIAL_VAR_SYMBOL) {
  5137. nommu_addchr(&ctx.as_string, ch);
  5138. /* Convert \^C to corresponding special variable reference */
  5139. goto case_SPECIAL_VAR_SYMBOL;
  5140. }
  5141. o_addchr(&ctx.word, '\\');
  5142. if (ch == EOF) {
  5143. /* Testcase: eval 'echo Ok\' */
  5144. /* bash-4.3.43 was removing backslash,
  5145. * but 4.4.19 retains it, most other shells too
  5146. */
  5147. continue; /* get next char */
  5148. }
  5149. /* Example: echo Hello \2>file
  5150. * we need to know that word 2 is quoted
  5151. */
  5152. ctx.word.has_quoted_part = 1;
  5153. nommu_addchr(&ctx.as_string, ch);
  5154. o_addchr(&ctx.word, ch);
  5155. continue; /* get next char */
  5156. }
  5157. nommu_addchr(&ctx.as_string, ch);
  5158. if (ch == '\'') {
  5159. ctx.word.has_quoted_part = 1;
  5160. next = i_getch(input);
  5161. if (next == '\'' && !ctx.pending_redirect)
  5162. goto insert_empty_quoted_str_marker;
  5163. ch = next;
  5164. while (1) {
  5165. if (ch == EOF) {
  5166. syntax_error_unterm_ch('\'');
  5167. goto parse_error_exitcode1;
  5168. }
  5169. nommu_addchr(&ctx.as_string, ch);
  5170. if (ch == '\'')
  5171. break;
  5172. if (ch == SPECIAL_VAR_SYMBOL) {
  5173. /* Convert raw ^C to corresponding special variable reference */
  5174. o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
  5175. o_addchr(&ctx.word, SPECIAL_VAR_QUOTED_SVS);
  5176. }
  5177. o_addqchr(&ctx.word, ch);
  5178. ch = i_getch(input);
  5179. }
  5180. continue; /* get next char */
  5181. }
  5182. next = '\0';
  5183. if (ch != '\n')
  5184. next = i_peek_and_eat_bkslash_nl(input);
  5185. is_special = "{}<>&|();#" /* special outside of "str" */
  5186. "$\"" IF_HUSH_TICK("`") /* always special */
  5187. SPECIAL_VAR_SYMBOL_STR;
  5188. #if defined(CMD_TEST2_SINGLEWORD_NOGLOB)
  5189. if (ctx.command->cmd_type == CMD_TEST2_SINGLEWORD_NOGLOB) {
  5190. /* In [[ ]], {}<>&|() are not special */
  5191. is_special += 8;
  5192. } else
  5193. #endif
  5194. /* Are { and } special here? */
  5195. if (ctx.command->argv /* word [word]{... - non-special */
  5196. || ctx.word.length /* word{... - non-special */
  5197. || ctx.word.has_quoted_part /* ""{... - non-special */
  5198. || (next != ';' /* }; - special */
  5199. && next != ')' /* }) - special */
  5200. && next != '(' /* {( - special */
  5201. && next != '&' /* }& and }&& ... - special */
  5202. && next != '|' /* }|| ... - special */
  5203. && !strchr(defifs, next) /* {word - non-special */
  5204. )
  5205. ) {
  5206. /* They are not special, skip "{}" */
  5207. is_special += 2;
  5208. }
  5209. is_special = strchr(is_special, ch);
  5210. is_blank = strchr(defifs, ch);
  5211. if (!is_special && !is_blank) { /* ordinary char */
  5212. ordinary_char:
  5213. o_addQchr(&ctx.word, ch);
  5214. if ((ctx.is_assignment == MAYBE_ASSIGNMENT
  5215. || ctx.is_assignment == WORD_IS_KEYWORD)
  5216. && ch == '='
  5217. && endofname(ctx.word.data)[0] == '='
  5218. ) {
  5219. ctx.is_assignment = DEFINITELY_ASSIGNMENT;
  5220. debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
  5221. }
  5222. continue;
  5223. }
  5224. if (is_blank) {
  5225. #if ENABLE_HUSH_LINENO_VAR
  5226. /* Case:
  5227. * "while ...; do<whitespace><newline>
  5228. * cmd ..."
  5229. * would think that "cmd" starts in <whitespace> -
  5230. * i.e., at the previous line.
  5231. * We need to skip all whitespace before newlines.
  5232. */
  5233. while (ch != '\n') {
  5234. next = i_peek(input);
  5235. if (next != ' ' && next != '\t' && next != '\n')
  5236. break; /* next char is not ws */
  5237. ch = i_getch(input);
  5238. }
  5239. /* ch == last eaten whitespace char */
  5240. #endif
  5241. if (done_word(&ctx)) {
  5242. goto parse_error_exitcode1;
  5243. }
  5244. if (ch == '\n') {
  5245. /* Is this a case when newline is simply ignored?
  5246. * Some examples:
  5247. * "cmd | <newline> cmd ..."
  5248. * "case ... in <newline> word) ..."
  5249. */
  5250. if (IS_NULL_CMD(ctx.command)
  5251. && ctx.word.length == 0
  5252. && !ctx.word.has_quoted_part
  5253. && heredoc_cnt == 0
  5254. ) {
  5255. /* This newline can be ignored. But...
  5256. * Without check #1, interactive shell
  5257. * ignores even bare <newline>,
  5258. * and shows the continuation prompt:
  5259. * ps1_prompt$ <enter>
  5260. * ps2> _ <=== wrong, should be ps1
  5261. * Without check #2, "cmd & <newline>"
  5262. * is similarly mistreated.
  5263. * (BTW, this makes "cmd & cmd"
  5264. * and "cmd && cmd" non-orthogonal.
  5265. * Really, ask yourself, why
  5266. * "cmd && <newline>" doesn't start
  5267. * cmd but waits for more input?
  5268. * The only reason is that it might be
  5269. * a "cmd1 && <nl> cmd2 &" construct,
  5270. * cmd1 may need to run in BG).
  5271. */
  5272. struct pipe *pi = ctx.list_head;
  5273. if (pi->num_cmds != 0 /* check #1 */
  5274. && pi->followup != PIPE_BG /* check #2 */
  5275. ) {
  5276. continue;
  5277. }
  5278. }
  5279. /* Treat newline as a command separator. */
  5280. done_pipe(&ctx, PIPE_SEQ);
  5281. debug_printf_heredoc("heredoc_cnt:%d\n", heredoc_cnt);
  5282. if (heredoc_cnt) {
  5283. heredoc_cnt = fetch_heredocs(&ctx.as_string, ctx.list_head, heredoc_cnt, input);
  5284. if (heredoc_cnt != 0)
  5285. goto parse_error_exitcode1;
  5286. }
  5287. ctx.is_assignment = MAYBE_ASSIGNMENT;
  5288. debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
  5289. ch = ';';
  5290. /* note: if (is_blank) continue;
  5291. * will still trigger for us */
  5292. }
  5293. }
  5294. /* "cmd}" or "cmd }..." without semicolon or &:
  5295. * } is an ordinary char in this case, even inside { cmd; }
  5296. * Pathological example: { ""}; } should exec "}" cmd
  5297. */
  5298. if (ch == '}') {
  5299. if (ctx.word.length != 0 /* word} */
  5300. || ctx.word.has_quoted_part /* ""} */
  5301. ) {
  5302. goto ordinary_char;
  5303. }
  5304. if (!IS_NULL_CMD(ctx.command)) { /* cmd } */
  5305. /* Generally, there should be semicolon: "cmd; }"
  5306. * However, bash allows to omit it if "cmd" is
  5307. * a group. Examples:
  5308. * { { echo 1; } }
  5309. * {(echo 1)}
  5310. * { echo 0 >&2 | { echo 1; } }
  5311. * { while false; do :; done }
  5312. * { case a in b) ;; esac }
  5313. */
  5314. if (ctx.command->group)
  5315. goto term_group;
  5316. goto ordinary_char;
  5317. }
  5318. if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
  5319. /* Can't be an end of {cmd}, skip the check */
  5320. goto skip_end_trigger;
  5321. /* else: } does terminate a group */
  5322. }
  5323. term_group:
  5324. if (end_trigger && end_trigger == ch
  5325. && (ch != ';' || heredoc_cnt == 0)
  5326. #if ENABLE_HUSH_CASE
  5327. && (ch != ')'
  5328. || ctx.ctx_res_w != RES_MATCH
  5329. || (!ctx.word.has_quoted_part && strcmp(ctx.word.data, "esac") == 0)
  5330. )
  5331. #endif
  5332. ) {
  5333. if (done_word(&ctx)) {
  5334. goto parse_error_exitcode1;
  5335. }
  5336. done_pipe(&ctx, PIPE_SEQ);
  5337. ctx.is_assignment = MAYBE_ASSIGNMENT;
  5338. debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
  5339. /* Do we sit outside of any if's, loops or case's? */
  5340. if (!HAS_KEYWORDS
  5341. IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
  5342. ) {
  5343. o_free_and_set_NULL(&ctx.word);
  5344. #if !BB_MMU
  5345. debug_printf_parse("as_string2 '%s'\n", ctx.as_string.data);
  5346. if (pstring)
  5347. *pstring = ctx.as_string.data;
  5348. else
  5349. o_free(&ctx.as_string);
  5350. #endif
  5351. if (ch != ';' && IS_NULL_PIPE(ctx.list_head)) {
  5352. /* Example: bare "{ }", "()" */
  5353. G.last_exitcode = 2; /* bash compat */
  5354. syntax_error_unexpected_ch(ch);
  5355. goto parse_error;
  5356. }
  5357. if (heredoc_cnt_ptr)
  5358. *heredoc_cnt_ptr = heredoc_cnt;
  5359. debug_printf_heredoc("parse_stream return heredoc_cnt:%d\n", heredoc_cnt);
  5360. debug_printf_parse("parse_stream return %p: "
  5361. "end_trigger char found\n",
  5362. ctx.list_head);
  5363. debug_leave();
  5364. return ctx.list_head;
  5365. }
  5366. }
  5367. if (is_blank)
  5368. continue;
  5369. /* Catch <, > before deciding whether this word is
  5370. * an assignment. a=1 2>z b=2: b=2 is still assignment */
  5371. switch (ch) {
  5372. case '>':
  5373. redir_fd = redirect_opt_num(&ctx.word);
  5374. if (done_word(&ctx)) {
  5375. goto parse_error_exitcode1;
  5376. }
  5377. redir_style = REDIRECT_OVERWRITE;
  5378. if (next == '>') {
  5379. redir_style = REDIRECT_APPEND;
  5380. ch = i_getch(input);
  5381. nommu_addchr(&ctx.as_string, ch);
  5382. }
  5383. #if 0
  5384. else if (next == '(') {
  5385. syntax_error(">(process) not supported");
  5386. goto parse_error_exitcode1;
  5387. }
  5388. #endif
  5389. if (parse_redirect(&ctx, redir_fd, redir_style, input))
  5390. goto parse_error_exitcode1;
  5391. continue; /* get next char */
  5392. case '<':
  5393. redir_fd = redirect_opt_num(&ctx.word);
  5394. if (done_word(&ctx)) {
  5395. goto parse_error_exitcode1;
  5396. }
  5397. redir_style = REDIRECT_INPUT;
  5398. if (next == '<') {
  5399. redir_style = REDIRECT_HEREDOC;
  5400. heredoc_cnt++;
  5401. debug_printf_heredoc("++heredoc_cnt=%d\n", heredoc_cnt);
  5402. ch = i_getch(input);
  5403. nommu_addchr(&ctx.as_string, ch);
  5404. } else if (next == '>') {
  5405. redir_style = REDIRECT_IO;
  5406. ch = i_getch(input);
  5407. nommu_addchr(&ctx.as_string, ch);
  5408. }
  5409. #if 0
  5410. else if (next == '(') {
  5411. syntax_error("<(process) not supported");
  5412. goto parse_error_exitcode1;
  5413. }
  5414. #endif
  5415. if (parse_redirect(&ctx, redir_fd, redir_style, input))
  5416. goto parse_error_exitcode1;
  5417. continue; /* get next char */
  5418. case '#':
  5419. if (ctx.word.length == 0 && !ctx.word.has_quoted_part) {
  5420. /* skip "#comment" */
  5421. /* note: we do not add it to &ctx.as_string */
  5422. /* TODO: in bash:
  5423. * comment inside $() goes to the next \n, even inside quoted string (!):
  5424. * cmd "$(cmd2 #comment)" - syntax error
  5425. * cmd "`cmd2 #comment`" - ok
  5426. * We accept both (comment ends where command subst ends, in both cases).
  5427. */
  5428. while (1) {
  5429. ch = i_peek(input);
  5430. if (ch == '\n') {
  5431. nommu_addchr(&ctx.as_string, '\n');
  5432. break;
  5433. }
  5434. ch = i_getch(input);
  5435. if (ch == EOF)
  5436. break;
  5437. }
  5438. continue; /* get next char */
  5439. }
  5440. break;
  5441. }
  5442. skip_end_trigger:
  5443. if (ctx.is_assignment == MAYBE_ASSIGNMENT
  5444. /* check that we are not in word in "a=1 2>word b=1": */
  5445. && !ctx.pending_redirect
  5446. ) {
  5447. /* ch is a special char and thus this word
  5448. * cannot be an assignment */
  5449. ctx.is_assignment = NOT_ASSIGNMENT;
  5450. debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
  5451. }
  5452. /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
  5453. switch (ch) {
  5454. case_SPECIAL_VAR_SYMBOL:
  5455. case SPECIAL_VAR_SYMBOL:
  5456. /* Convert raw ^C to corresponding special variable reference */
  5457. o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
  5458. o_addchr(&ctx.word, SPECIAL_VAR_QUOTED_SVS);
  5459. /* fall through */
  5460. case '#':
  5461. /* non-comment #: "echo a#b" etc */
  5462. o_addchr(&ctx.word, ch);
  5463. continue; /* get next char */
  5464. case '$':
  5465. if (parse_dollar_squote(&ctx.as_string, &ctx.word, input))
  5466. continue; /* get next char */
  5467. if (!parse_dollar(&ctx.as_string, &ctx.word, input, /*quote_mask:*/ 0)) {
  5468. debug_printf_parse("parse_stream parse error: "
  5469. "parse_dollar returned 0 (error)\n");
  5470. goto parse_error_exitcode1;
  5471. }
  5472. continue; /* get next char */
  5473. case '"':
  5474. ctx.word.has_quoted_part = 1;
  5475. if (next == '"' && !ctx.pending_redirect) {
  5476. i_getch(input); /* eat second " */
  5477. insert_empty_quoted_str_marker:
  5478. nommu_addchr(&ctx.as_string, next);
  5479. o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
  5480. o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
  5481. continue; /* get next char */
  5482. }
  5483. if (ctx.is_assignment == NOT_ASSIGNMENT)
  5484. ctx.word.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
  5485. if (!encode_string(&ctx.as_string, &ctx.word, input, '"'))
  5486. goto parse_error_exitcode1;
  5487. ctx.word.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
  5488. continue; /* get next char */
  5489. #if ENABLE_HUSH_TICK
  5490. case '`': {
  5491. USE_FOR_NOMMU(unsigned pos;)
  5492. o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
  5493. o_addchr(&ctx.word, '`');
  5494. USE_FOR_NOMMU(pos = ctx.word.length;)
  5495. if (!add_till_backquote(&ctx.word, input, /*in_dquote:*/ 0))
  5496. goto parse_error_exitcode1;
  5497. # if !BB_MMU
  5498. o_addstr(&ctx.as_string, ctx.word.data + pos);
  5499. o_addchr(&ctx.as_string, '`');
  5500. # endif
  5501. o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
  5502. //debug_printf_subst("SUBST RES3 '%s'\n", ctx.word.data + pos);
  5503. continue; /* get next char */
  5504. }
  5505. #endif
  5506. case ';':
  5507. #if ENABLE_HUSH_CASE
  5508. case_semi:
  5509. #endif
  5510. if (done_word(&ctx)) {
  5511. goto parse_error_exitcode1;
  5512. }
  5513. done_pipe(&ctx, PIPE_SEQ);
  5514. #if ENABLE_HUSH_CASE
  5515. /* Eat multiple semicolons, detect
  5516. * whether it means something special */
  5517. while (1) {
  5518. ch = i_peek_and_eat_bkslash_nl(input);
  5519. if (ch != ';')
  5520. break;
  5521. ch = i_getch(input);
  5522. nommu_addchr(&ctx.as_string, ch);
  5523. if (ctx.ctx_res_w == RES_CASE_BODY) {
  5524. ctx.ctx_dsemicolon = 1;
  5525. ctx.ctx_res_w = RES_MATCH;
  5526. break;
  5527. }
  5528. }
  5529. #endif
  5530. new_cmd:
  5531. /* We just finished a cmd. New one may start
  5532. * with an assignment */
  5533. ctx.is_assignment = MAYBE_ASSIGNMENT;
  5534. debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
  5535. continue; /* get next char */
  5536. case '&':
  5537. if (done_word(&ctx)) {
  5538. goto parse_error_exitcode1;
  5539. }
  5540. if (next == '&') {
  5541. ch = i_getch(input);
  5542. nommu_addchr(&ctx.as_string, ch);
  5543. done_pipe(&ctx, PIPE_AND);
  5544. } else {
  5545. done_pipe(&ctx, PIPE_BG);
  5546. }
  5547. goto new_cmd;
  5548. case '|':
  5549. if (done_word(&ctx)) {
  5550. goto parse_error_exitcode1;
  5551. }
  5552. #if ENABLE_HUSH_CASE
  5553. if (ctx.ctx_res_w == RES_MATCH)
  5554. break; /* we are in case's "word | word)" */
  5555. #endif
  5556. if (next == '|') { /* || */
  5557. ch = i_getch(input);
  5558. nommu_addchr(&ctx.as_string, ch);
  5559. done_pipe(&ctx, PIPE_OR);
  5560. } else {
  5561. /* we could pick up a file descriptor choice here
  5562. * with redirect_opt_num(), but bash doesn't do it.
  5563. * "echo foo 2| cat" yields "foo 2". */
  5564. done_command(&ctx);
  5565. }
  5566. goto new_cmd;
  5567. case '(':
  5568. #if ENABLE_HUSH_CASE
  5569. /* "case... in [(]word)..." - skip '(' */
  5570. if (ctx.ctx_res_w == RES_MATCH
  5571. && ctx.command->argv == NULL /* not (word|(... */
  5572. && ctx.word.length == 0 /* not word(... */
  5573. && ctx.word.has_quoted_part == 0 /* not ""(... */
  5574. ) {
  5575. continue; /* get next char */
  5576. }
  5577. #endif
  5578. /* fall through */
  5579. case '{': {
  5580. int n = parse_group(&ctx, input, ch);
  5581. if (n < 0) {
  5582. goto parse_error_exitcode1;
  5583. }
  5584. debug_printf_heredoc("parse_group done, needs heredocs:%d\n", n);
  5585. heredoc_cnt += n;
  5586. goto new_cmd;
  5587. }
  5588. case ')':
  5589. #if ENABLE_HUSH_CASE
  5590. if (ctx.ctx_res_w == RES_MATCH)
  5591. goto case_semi;
  5592. #endif
  5593. case '}':
  5594. /* proper use of this character is caught by end_trigger:
  5595. * if we see {, we call parse_group(..., end_trigger='}')
  5596. * and it will match } earlier (not here). */
  5597. G.last_exitcode = 2;
  5598. syntax_error_unexpected_ch(ch);
  5599. goto parse_error;
  5600. default:
  5601. if (HUSH_DEBUG)
  5602. bb_error_msg_and_die("BUG: unexpected %c", ch);
  5603. }
  5604. } /* while (1) */
  5605. parse_error_exitcode1:
  5606. G.last_exitcode = 1;
  5607. parse_error:
  5608. {
  5609. struct parse_context *pctx;
  5610. IF_HAS_KEYWORDS(struct parse_context *p2;)
  5611. /* Clean up allocated tree.
  5612. * Sample for finding leaks on syntax error recovery path.
  5613. * Run it from interactive shell, watch pmap `pidof hush`.
  5614. * while if false; then false; fi; do break; fi
  5615. * Samples to catch leaks at execution:
  5616. * while if (true | { true;}); then echo ok; fi; do break; done
  5617. * while if (true | { true;}); then echo ok; fi; do (if echo ok; break; then :; fi) | cat; break; done
  5618. */
  5619. pctx = &ctx;
  5620. do {
  5621. /* Update pipe/command counts,
  5622. * otherwise freeing may miss some */
  5623. done_pipe(pctx, PIPE_SEQ);
  5624. debug_printf_clean("freeing list %p from ctx %p\n",
  5625. pctx->list_head, pctx);
  5626. debug_print_tree(pctx->list_head, 0);
  5627. free_pipe_list(pctx->list_head);
  5628. debug_printf_clean("freed list %p\n", pctx->list_head);
  5629. #if !BB_MMU
  5630. o_free(&pctx->as_string);
  5631. #endif
  5632. IF_HAS_KEYWORDS(p2 = pctx->stack;)
  5633. if (pctx != &ctx) {
  5634. free(pctx);
  5635. }
  5636. IF_HAS_KEYWORDS(pctx = p2;)
  5637. } while (HAS_KEYWORDS && pctx);
  5638. o_free(&ctx.word);
  5639. #if !BB_MMU
  5640. if (pstring)
  5641. *pstring = NULL;
  5642. #endif
  5643. debug_leave();
  5644. return ERR_PTR;
  5645. }
  5646. }
  5647. /*** Execution routines ***/
  5648. /* Expansion can recurse, need forward decls: */
  5649. #if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
  5650. #define expand_string_to_string(str, EXP_flags, do_unbackslash) \
  5651. expand_string_to_string(str)
  5652. #endif
  5653. static char *expand_string_to_string(const char *str, int EXP_flags, int do_unbackslash);
  5654. #if ENABLE_HUSH_TICK
  5655. static int process_command_subs(o_string *dest, const char *s);
  5656. #endif
  5657. static int expand_vars_to_list(o_string *output, int n, char *arg);
  5658. /* expand_strvec_to_strvec() takes a list of strings, expands
  5659. * all variable references within and returns a pointer to
  5660. * a list of expanded strings, possibly with larger number
  5661. * of strings. (Think VAR="a b"; echo $VAR).
  5662. * This new list is allocated as a single malloc block.
  5663. * NULL-terminated list of char* pointers is at the beginning of it,
  5664. * followed by strings themselves.
  5665. * Caller can deallocate entire list by single free(list). */
  5666. /* A horde of its helpers come first: */
  5667. static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
  5668. {
  5669. while (--len >= 0) {
  5670. char c = *str++;
  5671. #if ENABLE_HUSH_BRACE_EXPANSION
  5672. if (c == '{' || c == '}') {
  5673. /* { -> \{, } -> \} */
  5674. o_addchr(o, '\\');
  5675. /* And now we want to add { or } and continue:
  5676. * o_addchr(o, c);
  5677. * continue;
  5678. * luckily, just falling through achieves this.
  5679. */
  5680. }
  5681. #endif
  5682. o_addchr(o, c);
  5683. if (c == '\\') {
  5684. /* \z -> \\\z; \<eol> -> \\<eol> */
  5685. o_addchr(o, '\\');
  5686. if (len) {
  5687. len--;
  5688. o_addchr(o, '\\');
  5689. o_addchr(o, *str++);
  5690. }
  5691. }
  5692. }
  5693. }
  5694. /* Store given string, finalizing the word and starting new one whenever
  5695. * we encounter IFS char(s). This is used for expanding variable values.
  5696. * End-of-string does NOT finalize word: think about 'echo -$VAR-'.
  5697. * Return in output->ended_in_ifs:
  5698. * 1 - ended with IFS char, else 0 (this includes case of empty str).
  5699. */
  5700. static int expand_on_ifs(o_string *output, int n, const char *str)
  5701. {
  5702. int last_is_ifs = 0;
  5703. while (1) {
  5704. int word_len;
  5705. if (!*str) /* EOL - do not finalize word */
  5706. break;
  5707. word_len = strcspn(str, G.ifs);
  5708. if (word_len) {
  5709. /* We have WORD_LEN leading non-IFS chars */
  5710. if (!(output->o_expflags & EXP_FLAG_GLOB)) {
  5711. o_addblock(output, str, word_len);
  5712. } else {
  5713. /* Protect backslashes against globbing up :)
  5714. * Example: "v='\*'; echo b$v" prints "b\*"
  5715. * (and does not try to glob on "*")
  5716. */
  5717. o_addblock_duplicate_backslash(output, str, word_len);
  5718. /*/ Why can't we do it easier? */
  5719. /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
  5720. /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
  5721. }
  5722. last_is_ifs = 0;
  5723. str += word_len;
  5724. if (!*str) /* EOL - do not finalize word */
  5725. break;
  5726. }
  5727. /* We know str here points to at least one IFS char */
  5728. last_is_ifs = 1;
  5729. str += strspn(str, G.ifs_whitespace); /* skip IFS whitespace chars */
  5730. if (!*str) /* EOL - do not finalize word */
  5731. break;
  5732. if (G.ifs_whitespace != G.ifs /* usually false ($IFS is usually all whitespace), */
  5733. && strchr(G.ifs, *str) /* the second check would fail */
  5734. ) {
  5735. /* This is a non-whitespace $IFS char */
  5736. /* Skip it and IFS whitespace chars, start new word */
  5737. str++;
  5738. str += strspn(str, G.ifs_whitespace);
  5739. goto new_word;
  5740. }
  5741. /* Start new word... but not always! */
  5742. /* Case "v=' a'; echo ''$v": we do need to finalize empty word: */
  5743. if (output->has_quoted_part
  5744. /*
  5745. * Case "v=' a'; echo $v":
  5746. * here nothing precedes the space in $v expansion,
  5747. * therefore we should not finish the word
  5748. * (IOW: if there *is* word to finalize, only then do it):
  5749. * It's okay if this accesses the byte before first argv[]:
  5750. * past call to o_save_ptr() cleared it to zero byte
  5751. * (grep for -prev-ifs-check-).
  5752. */
  5753. || output->data[output->length - 1]
  5754. ) {
  5755. new_word:
  5756. o_addchr(output, '\0');
  5757. debug_print_list("expand_on_ifs", output, n);
  5758. n = o_save_ptr(output, n);
  5759. }
  5760. }
  5761. output->ended_in_ifs = last_is_ifs;
  5762. debug_print_list("expand_on_ifs[1]", output, n);
  5763. return n;
  5764. }
  5765. /* Helper to expand $((...)) and heredoc body. These act as if
  5766. * they are in double quotes, with the exception that they are not :).
  5767. * Just the rules are similar: "expand only $var and `cmd`"
  5768. *
  5769. * Returns malloced string.
  5770. * As an optimization, we return NULL if expansion is not needed.
  5771. */
  5772. static char *encode_then_expand_string(const char *str)
  5773. {
  5774. char *exp_str;
  5775. struct in_str input;
  5776. o_string dest = NULL_O_STRING;
  5777. const char *cp;
  5778. cp = str;
  5779. for (;;) {
  5780. if (!*cp) return NULL; /* string has no special chars */
  5781. if (*cp == '$') break;
  5782. if (*cp == '\\') break;
  5783. #if ENABLE_HUSH_TICK
  5784. if (*cp == '`') break;
  5785. #endif
  5786. cp++;
  5787. }
  5788. /* We need to expand. Example:
  5789. * echo $(($a + `echo 1`)) $((1 + $((2)) ))
  5790. */
  5791. setup_string_in_str(&input, str);
  5792. encode_string(NULL, &dest, &input, EOF);
  5793. //TODO: error check (encode_string returns 0 on error)?
  5794. //bb_error_msg("'%s' -> '%s'", str, dest.data);
  5795. exp_str = expand_string_to_string(dest.data,
  5796. EXP_FLAG_ESC_GLOB_CHARS,
  5797. /*unbackslash:*/ 1
  5798. );
  5799. //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
  5800. o_free(&dest);
  5801. return exp_str;
  5802. }
  5803. static const char *first_special_char_in_vararg(const char *cp)
  5804. {
  5805. for (;;) {
  5806. if (!*cp) return NULL; /* string has no special chars */
  5807. if (*cp == '$') return cp;
  5808. if (*cp == '\\') return cp;
  5809. if (*cp == '\'') return cp;
  5810. if (*cp == '"') return cp;
  5811. #if ENABLE_HUSH_TICK
  5812. if (*cp == '`') return cp;
  5813. #endif
  5814. /* dquoted "${x:+ARG}" should not glob, therefore
  5815. * '*' et al require some non-literal processing: */
  5816. if (*cp == '*') return cp;
  5817. if (*cp == '?') return cp;
  5818. if (*cp == '[') return cp;
  5819. cp++;
  5820. }
  5821. }
  5822. /* Expanding ARG in ${var#ARG}, ${var%ARG}, or ${var/ARG/ARG}.
  5823. * These can contain single- and double-quoted strings,
  5824. * and treated as if the ARG string is initially unquoted. IOW:
  5825. * ${var#ARG} and "${var#ARG}" treat ARG the same (ARG can even be
  5826. * a dquoted string: "${var#"zz"}"), the difference only comes later
  5827. * (word splitting and globbing of the ${var...} result).
  5828. */
  5829. #if !BASH_PATTERN_SUBST
  5830. #define encode_then_expand_vararg(str, handle_squotes, do_unbackslash) \
  5831. encode_then_expand_vararg(str, handle_squotes)
  5832. #endif
  5833. static char *encode_then_expand_vararg(const char *str, int handle_squotes, int do_unbackslash)
  5834. {
  5835. #if !BASH_PATTERN_SUBST && ENABLE_HUSH_CASE
  5836. const int do_unbackslash = 0;
  5837. #endif
  5838. char *exp_str;
  5839. struct in_str input;
  5840. o_string dest = NULL_O_STRING;
  5841. if (!first_special_char_in_vararg(str)) {
  5842. /* string has no special chars */
  5843. return NULL;
  5844. }
  5845. setup_string_in_str(&input, str);
  5846. dest.data = xzalloc(1); /* start as "", not as NULL */
  5847. exp_str = NULL;
  5848. for (;;) {
  5849. int ch;
  5850. ch = i_getch(&input);
  5851. debug_printf_parse("%s: ch=%c (%d) escape=%d\n",
  5852. __func__, ch, ch, !!dest.o_expflags);
  5853. if (!dest.o_expflags) {
  5854. if (ch == EOF)
  5855. break;
  5856. if (handle_squotes && ch == '\'') {
  5857. if (!add_till_single_quote_dquoted(&dest, &input))
  5858. goto ret; /* error */
  5859. continue;
  5860. }
  5861. }
  5862. if (ch == EOF) {
  5863. syntax_error_unterm_ch('"');
  5864. goto ret; /* error */
  5865. }
  5866. if (ch == '"') {
  5867. dest.o_expflags ^= EXP_FLAG_ESC_GLOB_CHARS;
  5868. continue;
  5869. }
  5870. if (ch == '\\') {
  5871. ch = i_getch(&input);
  5872. if (ch == EOF) {
  5873. //example? error message? syntax_error_unterm_ch('"');
  5874. debug_printf_parse("%s: error: \\<eof>\n", __func__);
  5875. goto ret;
  5876. }
  5877. o_addqchr(&dest, ch);
  5878. continue;
  5879. }
  5880. if (ch == '$') {
  5881. if (parse_dollar_squote(NULL, &dest, &input))
  5882. continue;
  5883. if (!parse_dollar(NULL, &dest, &input, /*quote_mask:*/ 0x80)) {
  5884. debug_printf_parse("%s: error: parse_dollar returned 0 (error)\n", __func__);
  5885. goto ret;
  5886. }
  5887. continue;
  5888. }
  5889. #if ENABLE_HUSH_TICK
  5890. if (ch == '`') {
  5891. //unsigned pos = dest->length;
  5892. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  5893. o_addchr(&dest, 0x80 | '`');
  5894. if (!add_till_backquote(&dest, &input,
  5895. /*in_dquote:*/ dest.o_expflags /* nonzero if EXP_FLAG_ESC_GLOB_CHARS set */
  5896. )
  5897. ) {
  5898. goto ret; /* error */
  5899. }
  5900. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  5901. //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
  5902. continue;
  5903. }
  5904. #endif
  5905. o_addQchr(&dest, ch);
  5906. } /* for (;;) */
  5907. debug_printf_parse("encode: '%s' -> '%s'\n", str, dest.data);
  5908. exp_str = expand_string_to_string(dest.data,
  5909. do_unbackslash ? EXP_FLAG_ESC_GLOB_CHARS : 0,
  5910. do_unbackslash
  5911. );
  5912. ret:
  5913. debug_printf_parse("expand: '%s' -> '%s'\n", dest.data, exp_str);
  5914. o_free(&dest);
  5915. return exp_str;
  5916. }
  5917. /* Expanding ARG in ${var+ARG}, ${var-ARG}
  5918. */
  5919. static int encode_then_append_var_plusminus(o_string *output, int n,
  5920. char *str, int dquoted)
  5921. {
  5922. struct in_str input;
  5923. o_string dest = NULL_O_STRING;
  5924. if (!first_special_char_in_vararg(str)
  5925. && '\0' == str[strcspn(str, G.ifs)]
  5926. ) {
  5927. /* string has no special chars
  5928. * && string has no $IFS chars
  5929. */
  5930. if (dquoted) {
  5931. /* Prints 1 (quoted expansion is a "" word, not nothing):
  5932. * set -- "${notexist-}"; echo $#
  5933. */
  5934. output->has_quoted_part = 1;
  5935. }
  5936. return expand_vars_to_list(output, n, str);
  5937. }
  5938. setup_string_in_str(&input, str);
  5939. for (;;) {
  5940. int ch;
  5941. ch = i_getch(&input);
  5942. debug_printf_parse("%s: ch=%c (%d) escape=%x\n",
  5943. __func__, ch, ch, dest.o_expflags);
  5944. if (!dest.o_expflags) {
  5945. if (ch == EOF)
  5946. break;
  5947. if (!dquoted && strchr(G.ifs, ch)) {
  5948. /* PREFIX${x:d${e}f ...} and we met space: expand "d${e}f" and start new word.
  5949. * do not assume we are at the start of the word (PREFIX above).
  5950. */
  5951. if (dest.data) {
  5952. n = expand_vars_to_list(output, n, dest.data);
  5953. o_free_and_set_NULL(&dest);
  5954. o_addchr(output, '\0');
  5955. n = o_save_ptr(output, n); /* create next word */
  5956. } else
  5957. if (output->length != o_get_last_ptr(output, n)
  5958. || output->has_quoted_part
  5959. ) {
  5960. /* For these cases:
  5961. * f() { for i; do echo "|$i|"; done; }; x=x
  5962. * f a${x:+ }b # 1st condition
  5963. * |a|
  5964. * |b|
  5965. * f ""${x:+ }b # 2nd condition
  5966. * ||
  5967. * |b|
  5968. */
  5969. o_addchr(output, '\0');
  5970. n = o_save_ptr(output, n); /* create next word */
  5971. }
  5972. continue;
  5973. }
  5974. if (!dquoted && ch == '\'') {
  5975. if (!add_till_single_quote_dquoted(&dest, &input))
  5976. goto ret; /* error */
  5977. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  5978. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  5979. continue;
  5980. }
  5981. }
  5982. if (ch == EOF) {
  5983. syntax_error_unterm_ch('"');
  5984. goto ret; /* error */
  5985. }
  5986. if (ch == '"') {
  5987. dest.o_expflags ^= EXP_FLAG_ESC_GLOB_CHARS;
  5988. if (dest.o_expflags) {
  5989. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  5990. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  5991. }
  5992. continue;
  5993. }
  5994. if (ch == '\\') {
  5995. ch = i_getch(&input);
  5996. if (ch == EOF) {
  5997. //example? error message? syntax_error_unterm_ch('"');
  5998. debug_printf_parse("%s: error: \\<eof>\n", __func__);
  5999. goto ret;
  6000. }
  6001. o_addqchr(&dest, ch);
  6002. continue;
  6003. }
  6004. if (ch == '$') {
  6005. if (!parse_dollar(NULL, &dest, &input, /*quote_mask:*/ (dest.o_expflags || dquoted) ? 0x80 : 0)) {
  6006. debug_printf_parse("%s: error: parse_dollar returned 0 (error)\n", __func__);
  6007. goto ret;
  6008. }
  6009. continue;
  6010. }
  6011. #if ENABLE_HUSH_TICK
  6012. if (ch == '`') {
  6013. //unsigned pos = dest->length;
  6014. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  6015. o_addchr(&dest, (dest.o_expflags || dquoted) ? 0x80 | '`' : '`');
  6016. if (!add_till_backquote(&dest, &input,
  6017. /*in_dquote:*/ dest.o_expflags /* nonzero if EXP_FLAG_ESC_GLOB_CHARS set */
  6018. )
  6019. ) {
  6020. goto ret; /* error */
  6021. }
  6022. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  6023. //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
  6024. continue;
  6025. }
  6026. #endif
  6027. if (dquoted) {
  6028. /* Always glob-protect if in dquotes:
  6029. * x=x; echo "${x:+/bin/c*}" - prints: /bin/c*
  6030. * x=x; echo "${x:+"/bin/c*"}" - prints: /bin/c*
  6031. */
  6032. o_addqchr(&dest, ch);
  6033. } else {
  6034. /* Glob-protect only if char is quoted:
  6035. * x=x; echo ${x:+/bin/c*} - prints many filenames
  6036. * x=x; echo ${x:+"/bin/c*"} - prints: /bin/c*
  6037. */
  6038. o_addQchr(&dest, ch);
  6039. }
  6040. } /* for (;;) */
  6041. if (dest.data) {
  6042. n = expand_vars_to_list(output, n, dest.data);
  6043. }
  6044. ret:
  6045. o_free(&dest);
  6046. return n;
  6047. }
  6048. #if ENABLE_FEATURE_SH_MATH
  6049. static arith_t expand_and_evaluate_arith(const char *arg, const char **errmsg_p)
  6050. {
  6051. arith_state_t math_state;
  6052. arith_t res;
  6053. char *exp_str;
  6054. math_state.lookupvar = get_local_var_value;
  6055. math_state.setvar = set_local_var_from_halves;
  6056. //math_state.endofname = endofname;
  6057. exp_str = encode_then_expand_string(arg);
  6058. res = arith(&math_state, exp_str ? exp_str : arg);
  6059. free(exp_str);
  6060. if (errmsg_p)
  6061. *errmsg_p = math_state.errmsg;
  6062. if (math_state.errmsg)
  6063. msg_and_die_if_script(math_state.errmsg);
  6064. return res;
  6065. }
  6066. #endif
  6067. #if BASH_PATTERN_SUBST
  6068. /* ${var/[/]pattern[/repl]} helpers */
  6069. static char *strstr_pattern(char *val, const char *pattern, int *size)
  6070. {
  6071. int sz = strcspn(pattern, "*?[\\");
  6072. if (pattern[sz] == '\0') {
  6073. /* Optimization for trivial patterns.
  6074. * Testcase for very slow replace (performs about 22k replaces):
  6075. * x=::::::::::::::::::::::
  6076. * x=$x$x;x=$x$x;x=$x$x;x=$x$x;x=$x$x;x=$x$x;x=$x$x;x=$x$x;x=$x$x;x=$x$x;echo ${#x}
  6077. * echo "${x//:/|}"
  6078. */
  6079. *size = sz;
  6080. return strstr(val, pattern);
  6081. }
  6082. while (1) {
  6083. char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
  6084. debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
  6085. if (end) {
  6086. *size = end - val;
  6087. return val;
  6088. }
  6089. if (*val == '\0')
  6090. return NULL;
  6091. /* Optimization: if "*pat" did not match the start of "string",
  6092. * we know that "tring", "ring" etc will not match too:
  6093. */
  6094. if (pattern[0] == '*')
  6095. return NULL;
  6096. val++;
  6097. }
  6098. }
  6099. static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
  6100. {
  6101. char *result = NULL;
  6102. unsigned res_len = 0;
  6103. unsigned repl_len = strlen(repl);
  6104. /* Null pattern never matches, including if "var" is empty */
  6105. if (!pattern[0])
  6106. return result; /* NULL, no replaces happened */
  6107. while (1) {
  6108. int size;
  6109. char *s = strstr_pattern(val, pattern, &size);
  6110. if (!s)
  6111. break;
  6112. result = xrealloc(result, res_len + (s - val) + repl_len + 1);
  6113. strcpy(mempcpy(result + res_len, val, s - val), repl);
  6114. res_len += (s - val) + repl_len;
  6115. debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
  6116. val = s + size;
  6117. if (exp_op == '/')
  6118. break;
  6119. }
  6120. if (*val && result) {
  6121. result = xrealloc(result, res_len + strlen(val) + 1);
  6122. strcpy(result + res_len, val);
  6123. debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
  6124. }
  6125. debug_printf_varexp("result:'%s'\n", result);
  6126. return result;
  6127. }
  6128. #endif /* BASH_PATTERN_SUBST */
  6129. static int append_str_maybe_ifs_split(o_string *output, int n,
  6130. int first_ch, const char *val)
  6131. {
  6132. if (!(first_ch & 0x80)) { /* unquoted $VAR */
  6133. debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val,
  6134. !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
  6135. if (val && val[0])
  6136. n = expand_on_ifs(output, n, val);
  6137. } else { /* quoted "$VAR" */
  6138. output->has_quoted_part = 1;
  6139. debug_printf_expand("quoted '%s', output->o_escape:%d\n", val,
  6140. !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
  6141. if (val && val[0])
  6142. o_addQstr(output, val);
  6143. }
  6144. return n;
  6145. }
  6146. /* Handle <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
  6147. */
  6148. static NOINLINE int expand_one_var(o_string *output, int n,
  6149. int first_ch, char *arg, char **pp)
  6150. {
  6151. const char *val;
  6152. char *to_be_freed;
  6153. char *p;
  6154. char *var;
  6155. char exp_op;
  6156. char exp_save = exp_save; /* for compiler */
  6157. char *exp_saveptr; /* points to expansion operator */
  6158. char *exp_word = exp_word; /* for compiler */
  6159. char arg0;
  6160. val = NULL;
  6161. to_be_freed = NULL;
  6162. p = *pp;
  6163. *p = '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
  6164. var = arg;
  6165. exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
  6166. arg0 = arg[0];
  6167. arg[0] = (arg0 & 0x7f);
  6168. exp_op = 0;
  6169. if (arg[0] == '#' && arg[1] /* ${#...} but not ${#} */
  6170. && (!exp_saveptr /* and ( not(${#<op_char>...}) */
  6171. || (arg[2] == '\0' && strchr(SPECIAL_VARS_STR, arg[1])) /* or ${#C} "len of $C" ) */
  6172. ) /* NB: skipping ^^^specvar check mishandles ${#::2} */
  6173. ) {
  6174. /* It must be length operator: ${#var} */
  6175. var++;
  6176. exp_op = 'L';
  6177. } else {
  6178. /* Maybe handle parameter expansion */
  6179. if (exp_saveptr /* if 2nd char is one of expansion operators */
  6180. && strchr(NUMERIC_SPECVARS_STR, arg[0]) /* 1st char is special variable */
  6181. ) {
  6182. /* ${?:0}, ${#[:]%0} etc */
  6183. exp_saveptr = var + 1;
  6184. } else {
  6185. /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
  6186. exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
  6187. }
  6188. exp_op = exp_save = *exp_saveptr;
  6189. if (exp_op) {
  6190. exp_word = exp_saveptr + 1;
  6191. if (exp_op == ':') {
  6192. exp_op = *exp_word++;
  6193. //TODO: try ${var:} and ${var:bogus} in non-bash config
  6194. if (BASH_SUBSTR
  6195. && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
  6196. ) {
  6197. /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
  6198. exp_op = ':';
  6199. exp_word--;
  6200. }
  6201. }
  6202. *exp_saveptr = '\0';
  6203. } /* else: it's not an expansion op, but bare ${var} */
  6204. }
  6205. /* Look up the variable in question */
  6206. if (isdigit(var[0])) {
  6207. /* parse_dollar should have vetted var for us */
  6208. int nn = xatoi_positive(var);
  6209. if (nn < G.global_argc)
  6210. val = G.global_argv[nn];
  6211. /* else val remains NULL: $N with too big N */
  6212. } else {
  6213. switch (var[0]) {
  6214. case '$': /* pid */
  6215. val = utoa(G.root_pid);
  6216. break;
  6217. case '!': /* bg pid */
  6218. val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
  6219. break;
  6220. case '?': /* exitcode */
  6221. val = utoa(G.last_exitcode);
  6222. break;
  6223. case '#': /* argc */
  6224. val = utoa(G.global_argc ? G.global_argc-1 : 0);
  6225. break;
  6226. case '-': { /* active options */
  6227. /* Check set_mode() to see what option chars we support */
  6228. char *cp;
  6229. val = cp = G.optstring_buf;
  6230. if (G.o_opt[OPT_O_ERREXIT])
  6231. *cp++ = 'e';
  6232. if (G_interactive_fd)
  6233. *cp++ = 'i';
  6234. if (G_x_mode)
  6235. *cp++ = 'x';
  6236. /* If G.o_opt[OPT_O_NOEXEC] is true,
  6237. * commands read but are not executed,
  6238. * so $- can not execute too, 'n' is never seen in $-.
  6239. */
  6240. if (G.opt_c)
  6241. *cp++ = 'c';
  6242. if (G.opt_s)
  6243. *cp++ = 's';
  6244. *cp = '\0';
  6245. break;
  6246. }
  6247. default:
  6248. val = get_local_var_value(var);
  6249. }
  6250. }
  6251. /* Handle any expansions */
  6252. if (exp_op == 'L') {
  6253. reinit_unicode_for_hush();
  6254. debug_printf_expand("expand: length(%s)=", val);
  6255. val = utoa(val ? unicode_strlen(val) : 0);
  6256. debug_printf_expand("%s\n", val);
  6257. } else if (exp_op) {
  6258. if (exp_op == '%' || exp_op == '#') {
  6259. /* Standard-mandated substring removal ops:
  6260. * ${parameter%word} - remove smallest suffix pattern
  6261. * ${parameter%%word} - remove largest suffix pattern
  6262. * ${parameter#word} - remove smallest prefix pattern
  6263. * ${parameter##word} - remove largest prefix pattern
  6264. *
  6265. * Word is expanded to produce a glob pattern.
  6266. * Then var's value is matched to it and matching part removed.
  6267. */
  6268. /* bash compat: if x is "" and no shrinking of it is possible,
  6269. * inner ${...} is not evaluated. Example:
  6270. * unset b; : ${a%${b=B}}; echo $b
  6271. * assignment b=B only happens if $a is not "".
  6272. */
  6273. if (val && val[0]) {
  6274. char *t;
  6275. char *exp_exp_word;
  6276. char *loc;
  6277. unsigned scan_flags = pick_scan(exp_op, *exp_word);
  6278. if (exp_op == *exp_word) /* ## or %% */
  6279. exp_word++;
  6280. debug_printf_expand("expand: exp_word:'%s'\n", exp_word);
  6281. exp_exp_word = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 0);
  6282. if (exp_exp_word)
  6283. exp_word = exp_exp_word;
  6284. debug_printf_expand("expand: exp_word:'%s'\n", exp_word);
  6285. /*
  6286. * HACK ALERT. We depend here on the fact that
  6287. * G.global_argv and results of utoa and get_local_var_value
  6288. * are actually in writable memory:
  6289. * scan_and_match momentarily stores NULs there.
  6290. */
  6291. t = (char*)val;
  6292. loc = scan_and_match(t, exp_word, scan_flags);
  6293. debug_printf_expand("op:%c str:'%s' pat:'%s' res:'%s'\n", exp_op, t, exp_word, loc);
  6294. free(exp_exp_word);
  6295. if (loc) { /* match was found */
  6296. if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
  6297. val = loc; /* take right part */
  6298. else /* %[%] */
  6299. val = to_be_freed = xstrndup(val, loc - val); /* left */
  6300. }
  6301. }
  6302. }
  6303. #if BASH_PATTERN_SUBST
  6304. else if (exp_op == '/' || exp_op == '\\') {
  6305. /* It's ${var/[/]pattern[/repl]} thing.
  6306. * Note that in encoded form it has TWO parts:
  6307. * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
  6308. * and if // is used, it is encoded as \:
  6309. * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
  6310. */
  6311. /* bash compat: if var is "", both pattern and repl
  6312. * are still evaluated, if it is unset, then not:
  6313. * unset b; a=; : ${a/z/${b=3}}; echo $b # b=3
  6314. * unset b; unset a; : ${a/z/${b=3}}; echo $b # b not set
  6315. */
  6316. if (val /*&& val[0]*/) {
  6317. /* pattern uses non-standard expansion.
  6318. * repl should be unbackslashed and globbed
  6319. * by the usual expansion rules:
  6320. * >az >bz
  6321. * v='a bz'; echo "${v/a*z/a*z}" #prints "a*z"
  6322. * v='a bz'; echo "${v/a*z/\z}" #prints "z"
  6323. * v='a bz'; echo ${v/a*z/a*z} #prints "az"
  6324. * v='a bz'; echo ${v/a*z/\z} #prints "z"
  6325. * (note that a*z _pattern_ is never globbed!)
  6326. */
  6327. char *pattern, *repl, *t;
  6328. pattern = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 0);
  6329. if (!pattern)
  6330. pattern = xstrdup(exp_word);
  6331. debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
  6332. *p++ = SPECIAL_VAR_SYMBOL;
  6333. exp_word = p;
  6334. p = strchr(p, SPECIAL_VAR_SYMBOL);
  6335. *p = '\0';
  6336. repl = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 1);
  6337. debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
  6338. /* HACK ALERT. We depend here on the fact that
  6339. * G.global_argv and results of utoa and get_local_var_value
  6340. * are actually in writable memory:
  6341. * replace_pattern momentarily stores NULs there. */
  6342. t = (char*)val;
  6343. to_be_freed = replace_pattern(t,
  6344. pattern,
  6345. (repl ? repl : exp_word),
  6346. exp_op);
  6347. if (to_be_freed) /* at least one replace happened */
  6348. val = to_be_freed;
  6349. free(pattern);
  6350. free(repl);
  6351. } else {
  6352. /* Unset variable always gives nothing */
  6353. // a=; echo ${a/*/w} # "w"
  6354. // unset a; echo ${a/*/w} # ""
  6355. /* Just skip "replace" part */
  6356. *p++ = SPECIAL_VAR_SYMBOL;
  6357. p = strchr(p, SPECIAL_VAR_SYMBOL);
  6358. *p = '\0';
  6359. }
  6360. }
  6361. #endif /* BASH_PATTERN_SUBST */
  6362. else if (exp_op == ':') {
  6363. #if BASH_SUBSTR && ENABLE_FEATURE_SH_MATH
  6364. /* It's ${var:N[:M]} bashism.
  6365. * Note that in encoded form it has TWO parts:
  6366. * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
  6367. */
  6368. arith_t beg, len;
  6369. unsigned vallen;
  6370. const char *errmsg;
  6371. beg = expand_and_evaluate_arith(exp_word, &errmsg);
  6372. if (errmsg)
  6373. goto empty_result;
  6374. debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
  6375. *p++ = SPECIAL_VAR_SYMBOL;
  6376. exp_word = p;
  6377. p = strchr(p, SPECIAL_VAR_SYMBOL);
  6378. *p = '\0';
  6379. vallen = val ? strlen(val) : 0;
  6380. if (beg < 0) {
  6381. /* negative beg counts from the end */
  6382. beg = (arith_t)vallen + beg;
  6383. }
  6384. /* If expansion will be empty, do not even evaluate len */
  6385. if (!val || beg < 0 || beg > vallen) {
  6386. /* Why > vallen, not >=? bash:
  6387. * unset b; a=ab; : ${a:2:${b=3}}; echo $b # "", b=3 (!!!)
  6388. * unset b; a=a; : ${a:2:${b=3}}; echo $b # "", b not set
  6389. */
  6390. goto empty_result;
  6391. }
  6392. len = expand_and_evaluate_arith(exp_word, &errmsg);
  6393. if (errmsg)
  6394. goto empty_result;
  6395. debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
  6396. debug_printf_varexp("from val:'%s'\n", val);
  6397. if (len < 0) {
  6398. /* in bash, len=-n means strlen()-n */
  6399. len = (arith_t)vallen - beg + len;
  6400. if (len < 0) /* bash compat */
  6401. msg_and_die_if_script("%s: substring expression < 0", var);
  6402. }
  6403. if (len <= 0 || !val /*|| beg >= vallen*/) {
  6404. empty_result:
  6405. val = NULL;
  6406. } else {
  6407. /* Paranoia. What if user entered 9999999999999
  6408. * which fits in arith_t but not int? */
  6409. if (len > INT_MAX)
  6410. len = INT_MAX;
  6411. val = to_be_freed = xstrndup(val + beg, len);
  6412. }
  6413. debug_printf_varexp("val:'%s'\n", val);
  6414. #else /* not (HUSH_SUBSTR_EXPANSION && FEATURE_SH_MATH) */
  6415. msg_and_die_if_script("malformed ${%s:...}", var);
  6416. val = NULL;
  6417. #endif
  6418. } else { /* one of "-=+?" */
  6419. /* Standard-mandated substitution ops:
  6420. * ${var?word} - indicate error if unset
  6421. * If var is unset, word (or a message indicating it is unset
  6422. * if word is null) is written to standard error
  6423. * and the shell exits with a non-zero exit status.
  6424. * Otherwise, the value of var is substituted.
  6425. * ${var-word} - use default value
  6426. * If var is unset, word is substituted.
  6427. * ${var=word} - assign and use default value
  6428. * If var is unset, word is assigned to var.
  6429. * In all cases, final value of var is substituted.
  6430. * ${var+word} - use alternative value
  6431. * If var is unset, null is substituted.
  6432. * Otherwise, word is substituted.
  6433. *
  6434. * Word is subjected to tilde expansion, parameter expansion,
  6435. * command substitution, and arithmetic expansion.
  6436. * If word is not needed, it is not expanded.
  6437. *
  6438. * Colon forms (${var:-word}, ${var:=word} etc) do the same,
  6439. * but also treat null var as if it is unset.
  6440. *
  6441. * Word-splitting and single quote behavior:
  6442. *
  6443. * $ f() { for i; do echo "|$i|"; done; }
  6444. *
  6445. * $ x=; f ${x:?'x y' z}; echo $?
  6446. * bash: x: x y z # neither f nor "echo $?" executes
  6447. * (if interactive, bash does not exit, but merely aborts to prompt. $? is set to 1)
  6448. * $ x=; f "${x:?'x y' z}"
  6449. * bash: x: x y z # dash prints: dash: x: 'x y' z
  6450. *
  6451. * $ x=; f ${x:='x y' z}
  6452. * |x|
  6453. * |y|
  6454. * |z|
  6455. * $ x=; f "${x:='x y' z}"
  6456. * |'x y' z|
  6457. *
  6458. * $ x=x; f ${x:+'x y' z}
  6459. * |x y|
  6460. * |z|
  6461. * $ x=x; f "${x:+'x y' z}"
  6462. * |'x y' z|
  6463. *
  6464. * $ x=; f ${x:-'x y' z}
  6465. * |x y|
  6466. * |z|
  6467. * $ x=; f "${x:-'x y' z}"
  6468. * |'x y' z|
  6469. */
  6470. int use_word = (!val || ((exp_save == ':') && !val[0]));
  6471. if (exp_op == '+')
  6472. use_word = !use_word;
  6473. debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
  6474. (exp_save == ':') ? "true" : "false", use_word);
  6475. if (use_word) {
  6476. if (exp_op == '+' || exp_op == '-') {
  6477. /* ${var+word} - use alternative value */
  6478. /* ${var-word} - use default value */
  6479. n = encode_then_append_var_plusminus(output, n, exp_word,
  6480. /*dquoted:*/ (arg0 & 0x80)
  6481. );
  6482. val = NULL;
  6483. } else {
  6484. /* ${var?word} - indicate error if unset */
  6485. /* ${var=word} - assign and use default value */
  6486. to_be_freed = encode_then_expand_vararg(exp_word,
  6487. /*handle_squotes:*/ !(arg0 & 0x80),
  6488. /*unbackslash:*/ 0
  6489. );
  6490. if (to_be_freed)
  6491. exp_word = to_be_freed;
  6492. if (exp_op == '?') {
  6493. /* mimic bash message */
  6494. msg_and_die_if_script("%s: %s",
  6495. var,
  6496. exp_word[0]
  6497. ? exp_word
  6498. : "parameter null or not set"
  6499. /* ash has more specific messages, a-la: */
  6500. /*: (exp_save == ':' ? "parameter null or not set" : "parameter not set")*/
  6501. );
  6502. //TODO: how interactive bash aborts expansion mid-command?
  6503. //It aborts the entire line, returns to prompt:
  6504. // $ f() { for i; do echo "|$i|"; done; }; x=; f "${x:?'x y' z}"; echo YO
  6505. // bash: x: x y z
  6506. // $
  6507. // ("echo YO" is not executed, neither the f function call)
  6508. } else {
  6509. val = exp_word;
  6510. }
  6511. if (exp_op == '=') {
  6512. /* ${var=[word]} or ${var:=[word]} */
  6513. if (isdigit(var[0]) || var[0] == '#') {
  6514. /* mimic bash message */
  6515. msg_and_die_if_script("$%s: cannot assign in this way", var);
  6516. val = NULL;
  6517. } else {
  6518. char *new_var = xasprintf("%s=%s", var, val);
  6519. set_local_var(new_var, /*flag:*/ 0);
  6520. }
  6521. }
  6522. }
  6523. }
  6524. } /* one of "-=+?" */
  6525. *exp_saveptr = exp_save;
  6526. } /* if (exp_op) */
  6527. arg[0] = arg0;
  6528. *pp = p;
  6529. n = append_str_maybe_ifs_split(output, n, first_ch, val);
  6530. free(to_be_freed);
  6531. return n;
  6532. }
  6533. /* Expand all variable references in given string, adding words to list[]
  6534. * at n, n+1,... positions. Return updated n (so that list[n] is next one
  6535. * to be filled). This routine is extremely tricky: has to deal with
  6536. * variables/parameters with whitespace, $* and $@, and constructs like
  6537. * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
  6538. static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
  6539. {
  6540. /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
  6541. * expansion of right-hand side of assignment == 1-element expand.
  6542. */
  6543. char cant_be_null = 0; /* only bit 0x80 matters */
  6544. char *p;
  6545. debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
  6546. !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
  6547. debug_print_list("expand_vars_to_list[0]", output, n);
  6548. while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
  6549. char first_ch;
  6550. #if ENABLE_FEATURE_SH_MATH
  6551. char arith_buf[sizeof(arith_t)*3 + 2];
  6552. #endif
  6553. if (output->ended_in_ifs) {
  6554. o_addchr(output, '\0');
  6555. n = o_save_ptr(output, n);
  6556. output->ended_in_ifs = 0;
  6557. }
  6558. o_addblock(output, arg, p - arg);
  6559. debug_print_list("expand_vars_to_list[1]", output, n);
  6560. arg = ++p;
  6561. p = strchr(p, SPECIAL_VAR_SYMBOL);
  6562. /* Fetch special var name (if it is indeed one of them)
  6563. * and quote bit, force the bit on if singleword expansion -
  6564. * important for not getting v=$@ expand to many words. */
  6565. first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
  6566. /* Is this variable quoted and thus expansion can't be null?
  6567. * "$@" is special. Even if quoted, it can still
  6568. * expand to nothing (not even an empty string),
  6569. * thus it is excluded. */
  6570. if ((first_ch & 0x7f) != '@')
  6571. cant_be_null |= first_ch;
  6572. switch (first_ch & 0x7f) {
  6573. /* Highest bit in first_ch indicates that var is double-quoted */
  6574. case '*':
  6575. case '@': {
  6576. int i;
  6577. if (!G.global_argv[1])
  6578. break;
  6579. i = 1;
  6580. cant_be_null |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
  6581. if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
  6582. while (G.global_argv[i]) {
  6583. n = expand_on_ifs(output, n, G.global_argv[i]);
  6584. debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
  6585. if (G.global_argv[i++][0] && G.global_argv[i]) {
  6586. /* this argv[] is not empty and not last:
  6587. * put terminating NUL, start new word */
  6588. o_addchr(output, '\0');
  6589. debug_print_list("expand_vars_to_list[2]", output, n);
  6590. n = o_save_ptr(output, n);
  6591. debug_print_list("expand_vars_to_list[3]", output, n);
  6592. }
  6593. }
  6594. } else
  6595. /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
  6596. * and in this case should treat it like '$*' - see 'else...' below */
  6597. if (first_ch == (char)('@'|0x80) /* quoted $@ */
  6598. && !(output->o_expflags & EXP_FLAG_SINGLEWORD) /* not v="$@" case */
  6599. ) {
  6600. while (1) {
  6601. o_addQstr(output, G.global_argv[i]);
  6602. if (++i >= G.global_argc)
  6603. break;
  6604. o_addchr(output, '\0');
  6605. debug_print_list("expand_vars_to_list[4]", output, n);
  6606. n = o_save_ptr(output, n);
  6607. }
  6608. } else { /* quoted $* (or v="$@" case): add as one word */
  6609. while (1) {
  6610. o_addQstr(output, G.global_argv[i]);
  6611. if (!G.global_argv[++i])
  6612. break;
  6613. if (G.ifs[0])
  6614. o_addchr(output, G.ifs[0]);
  6615. }
  6616. output->has_quoted_part = 1;
  6617. }
  6618. break;
  6619. }
  6620. case SPECIAL_VAR_SYMBOL: {
  6621. /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
  6622. /* "Empty variable", used to make "" etc to not disappear */
  6623. output->has_quoted_part = 1;
  6624. cant_be_null = 0x80;
  6625. arg++;
  6626. break;
  6627. }
  6628. case SPECIAL_VAR_QUOTED_SVS:
  6629. /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_QUOTED_SVS><SPECIAL_VAR_SYMBOL> */
  6630. /* "^C variable", represents literal ^C char (possible in scripts) */
  6631. o_addchr(output, SPECIAL_VAR_SYMBOL);
  6632. arg++;
  6633. break;
  6634. #if ENABLE_HUSH_TICK
  6635. case '`': {
  6636. /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
  6637. o_string subst_result = NULL_O_STRING;
  6638. *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
  6639. arg++;
  6640. /* Can't just stuff it into output o_string,
  6641. * expanded result may need to be globbed
  6642. * and $IFS-split */
  6643. debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
  6644. G.last_exitcode = process_command_subs(&subst_result, arg);
  6645. G.expand_exitcode = G.last_exitcode;
  6646. debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
  6647. n = append_str_maybe_ifs_split(output, n, first_ch, subst_result.data);
  6648. o_free(&subst_result);
  6649. break;
  6650. }
  6651. #endif
  6652. #if ENABLE_FEATURE_SH_MATH
  6653. case '+': {
  6654. /* <SPECIAL_VAR_SYMBOL>+arith<SPECIAL_VAR_SYMBOL> */
  6655. arith_t res;
  6656. arg++; /* skip '+' */
  6657. *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
  6658. debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
  6659. res = expand_and_evaluate_arith(arg, NULL);
  6660. debug_printf_subst("ARITH RES '"ARITH_FMT"'\n", res);
  6661. sprintf(arith_buf, ARITH_FMT, res);
  6662. if (res < 0
  6663. && first_ch == (char)('+'|0x80)
  6664. /* && (output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS) */
  6665. ) {
  6666. /* Quoted negative ariths, like filename[0"$((-9))"],
  6667. * should not be interpreted as glob ranges.
  6668. * Convert leading '-' to '\-':
  6669. */
  6670. o_grow_by(output, 1);
  6671. output->data[output->length++] = '\\';
  6672. }
  6673. o_addstr(output, arith_buf);
  6674. break;
  6675. }
  6676. #endif
  6677. default:
  6678. /* <SPECIAL_VAR_SYMBOL>varname[ops]<SPECIAL_VAR_SYMBOL> */
  6679. n = expand_one_var(output, n, first_ch, arg, &p);
  6680. break;
  6681. } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
  6682. /* Restore NULL'ed SPECIAL_VAR_SYMBOL.
  6683. * Do the check to avoid writing to a const string. */
  6684. if (*p != SPECIAL_VAR_SYMBOL)
  6685. *p = SPECIAL_VAR_SYMBOL;
  6686. arg = ++p;
  6687. } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
  6688. if (*arg) {
  6689. /* handle trailing string */
  6690. if (output->ended_in_ifs) {
  6691. o_addchr(output, '\0');
  6692. n = o_save_ptr(output, n);
  6693. }
  6694. debug_print_list("expand_vars_to_list[a]", output, n);
  6695. /* this part is literal, and it was already pre-quoted
  6696. * if needed (much earlier), do not use o_addQstr here!
  6697. */
  6698. o_addstr(output, arg);
  6699. debug_print_list("expand_vars_to_list[b]", output, n);
  6700. } else
  6701. if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
  6702. && !(cant_be_null & 0x80) /* and all vars were not quoted */
  6703. && !output->has_quoted_part
  6704. ) {
  6705. n--;
  6706. /* allow to reuse list[n] later without re-growth */
  6707. output->has_empty_slot = 1;
  6708. }
  6709. return n;
  6710. }
  6711. static char **expand_variables(char **argv, unsigned expflags)
  6712. {
  6713. int n;
  6714. char **list;
  6715. o_string output = NULL_O_STRING;
  6716. output.o_expflags = expflags;
  6717. n = 0;
  6718. for (;;) {
  6719. /* go to next list[n] */
  6720. output.ended_in_ifs = 0;
  6721. n = o_save_ptr(&output, n);
  6722. if (!*argv)
  6723. break;
  6724. /* expand argv[i] */
  6725. n = expand_vars_to_list(&output, n, *argv++);
  6726. /* if (!output->has_empty_slot) -- need this?? */
  6727. o_addchr(&output, '\0');
  6728. }
  6729. debug_print_list("expand_variables", &output, n);
  6730. /* output.data (malloced in one block) gets returned in "list" */
  6731. list = o_finalize_list(&output, n);
  6732. debug_print_strings("expand_variables[1]", list);
  6733. return list;
  6734. }
  6735. static char **expand_strvec_to_strvec(char **argv)
  6736. {
  6737. return expand_variables(argv, EXP_FLAG_GLOB | EXP_FLAG_ESC_GLOB_CHARS);
  6738. }
  6739. #if defined(CMD_SINGLEWORD_NOGLOB) || defined(CMD_TEST2_SINGLEWORD_NOGLOB)
  6740. static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
  6741. {
  6742. return expand_variables(argv, EXP_FLAG_SINGLEWORD);
  6743. }
  6744. #endif
  6745. /* Used for expansion of right hand of assignments,
  6746. * $((...)), heredocs, variable expansion parts.
  6747. *
  6748. * NB: should NOT do globbing!
  6749. * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*"
  6750. */
  6751. static char *expand_string_to_string(const char *str, int EXP_flags, int do_unbackslash)
  6752. {
  6753. #if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
  6754. const int do_unbackslash = 1;
  6755. const int EXP_flags = EXP_FLAG_ESC_GLOB_CHARS;
  6756. #endif
  6757. char *argv[2], **list;
  6758. debug_printf_expand("string_to_string<='%s'\n", str);
  6759. /* This is generally an optimization, but it also
  6760. * handles "", which otherwise trips over !list[0] check below.
  6761. * (is this ever happens that we actually get str="" here?)
  6762. */
  6763. if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
  6764. //TODO: Can use on strings with \ too, just unbackslash() them?
  6765. debug_printf_expand("string_to_string(fast)=>'%s'\n", str);
  6766. return xstrdup(str);
  6767. }
  6768. argv[0] = (char*)str;
  6769. argv[1] = NULL;
  6770. list = expand_variables(argv, EXP_flags | EXP_FLAG_SINGLEWORD);
  6771. if (!list[0]) {
  6772. /* Example where it happens:
  6773. * x=; echo ${x:-"$@"}
  6774. */
  6775. ((char*)list)[0] = '\0';
  6776. } else {
  6777. if (HUSH_DEBUG)
  6778. if (list[1])
  6779. bb_simple_error_msg_and_die("BUG in varexp2");
  6780. /* actually, just move string 2*sizeof(char*) bytes back */
  6781. overlapping_strcpy((char*)list, list[0]);
  6782. if (do_unbackslash)
  6783. unbackslash((char*)list);
  6784. }
  6785. debug_printf_expand("string_to_string=>'%s'\n", (char*)list);
  6786. return (char*)list;
  6787. }
  6788. #if 0
  6789. static char* expand_strvec_to_string(char **argv)
  6790. {
  6791. char **list;
  6792. list = expand_variables(argv, EXP_FLAG_SINGLEWORD);
  6793. /* Convert all NULs to spaces */
  6794. if (list[0]) {
  6795. int n = 1;
  6796. while (list[n]) {
  6797. if (HUSH_DEBUG)
  6798. if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
  6799. bb_error_msg_and_die("BUG in varexp3");
  6800. /* bash uses ' ' regardless of $IFS contents */
  6801. list[n][-1] = ' ';
  6802. n++;
  6803. }
  6804. }
  6805. overlapping_strcpy((char*)list, list[0] ? list[0] : "");
  6806. debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
  6807. return (char*)list;
  6808. }
  6809. #endif
  6810. static char **expand_assignments(char **argv, int count)
  6811. {
  6812. int i;
  6813. char **p;
  6814. G.expanded_assignments = p = NULL;
  6815. /* Expand assignments into one string each */
  6816. for (i = 0; i < count; i++) {
  6817. p = add_string_to_strings(p,
  6818. expand_string_to_string(argv[i],
  6819. EXP_FLAG_ESC_GLOB_CHARS,
  6820. /*unbackslash:*/ 1
  6821. )
  6822. );
  6823. G.expanded_assignments = p;
  6824. }
  6825. G.expanded_assignments = NULL;
  6826. return p;
  6827. }
  6828. static void switch_off_special_sigs(unsigned mask)
  6829. {
  6830. unsigned sig = 0;
  6831. while ((mask >>= 1) != 0) {
  6832. sig++;
  6833. if (!(mask & 1))
  6834. continue;
  6835. #if ENABLE_HUSH_TRAP
  6836. if (G_traps) {
  6837. if (G_traps[sig] && !G_traps[sig][0])
  6838. /* trap is '', has to remain SIG_IGN */
  6839. continue;
  6840. free(G_traps[sig]);
  6841. G_traps[sig] = NULL;
  6842. }
  6843. #endif
  6844. /* We are here only if no trap or trap was not '' */
  6845. install_sighandler(sig, SIG_DFL);
  6846. }
  6847. }
  6848. #if BB_MMU
  6849. /* never called */
  6850. void re_execute_shell(char ***to_free, const char *s,
  6851. char *g_argv0, char **g_argv,
  6852. char **builtin_argv) NORETURN;
  6853. static void reset_traps_to_defaults(void)
  6854. {
  6855. /* This function is always called in a child shell
  6856. * after fork (not vfork, NOMMU doesn't use this function).
  6857. */
  6858. IF_HUSH_TRAP(unsigned sig;)
  6859. unsigned mask;
  6860. /* Child shells are not interactive.
  6861. * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
  6862. * Testcase: (while :; do :; done) + ^Z should background.
  6863. * Same goes for SIGTERM, SIGHUP, SIGINT.
  6864. */
  6865. mask = (G.special_sig_mask & SPECIAL_INTERACTIVE_SIGS) | G_fatal_sig_mask;
  6866. if (!G_traps && !mask)
  6867. return; /* already no traps and no special sigs */
  6868. /* Switch off special sigs */
  6869. switch_off_special_sigs(mask);
  6870. # if ENABLE_HUSH_JOB
  6871. G_fatal_sig_mask = 0;
  6872. # endif
  6873. G.special_sig_mask &= ~SPECIAL_INTERACTIVE_SIGS;
  6874. /* SIGQUIT,SIGCHLD and maybe SPECIAL_JOBSTOP_SIGS
  6875. * remain set in G.special_sig_mask */
  6876. # if ENABLE_HUSH_TRAP
  6877. if (!G_traps)
  6878. return;
  6879. /* Reset all sigs to default except ones with empty traps */
  6880. for (sig = 0; sig < NSIG; sig++) {
  6881. if (!G_traps[sig])
  6882. continue; /* no trap: nothing to do */
  6883. if (!G_traps[sig][0])
  6884. continue; /* empty trap: has to remain SIG_IGN */
  6885. /* sig has non-empty trap, reset it: */
  6886. free(G_traps[sig]);
  6887. G_traps[sig] = NULL;
  6888. /* There is no signal for trap 0 (EXIT) */
  6889. if (sig == 0)
  6890. continue;
  6891. install_sighandler(sig, pick_sighandler(sig));
  6892. }
  6893. # endif
  6894. }
  6895. #else /* !BB_MMU */
  6896. static void re_execute_shell(char ***to_free, const char *s,
  6897. char *g_argv0, char **g_argv,
  6898. char **builtin_argv) NORETURN;
  6899. static void re_execute_shell(char ***to_free, const char *s,
  6900. char *g_argv0, char **g_argv,
  6901. char **builtin_argv)
  6902. {
  6903. # define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
  6904. /* delims + 2 * (number of bytes in printed hex numbers) */
  6905. char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
  6906. char *heredoc_argv[4];
  6907. struct variable *cur;
  6908. # if ENABLE_HUSH_FUNCTIONS
  6909. struct function *funcp;
  6910. # endif
  6911. char **argv, **pp;
  6912. unsigned cnt;
  6913. unsigned long long empty_trap_mask;
  6914. if (!g_argv0) { /* heredoc */
  6915. argv = heredoc_argv;
  6916. argv[0] = (char *) G.argv0_for_re_execing;
  6917. argv[1] = (char *) "-<";
  6918. argv[2] = (char *) s;
  6919. argv[3] = NULL;
  6920. pp = &argv[3]; /* used as pointer to empty environment */
  6921. goto do_exec;
  6922. }
  6923. cnt = 0;
  6924. pp = builtin_argv;
  6925. if (pp) while (*pp++)
  6926. cnt++;
  6927. empty_trap_mask = 0;
  6928. if (G_traps) {
  6929. int sig;
  6930. for (sig = 1; sig < NSIG; sig++) {
  6931. if (G_traps[sig] && !G_traps[sig][0])
  6932. empty_trap_mask |= 1LL << sig;
  6933. }
  6934. }
  6935. sprintf(param_buf, NOMMU_HACK_FMT
  6936. , (unsigned) G.root_pid
  6937. , (unsigned) G.root_ppid
  6938. , (unsigned) G.last_bg_pid
  6939. , (unsigned) G.last_exitcode
  6940. , cnt
  6941. , empty_trap_mask
  6942. IF_HUSH_LOOPS(, G.depth_of_loop)
  6943. );
  6944. # undef NOMMU_HACK_FMT
  6945. /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
  6946. * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
  6947. */
  6948. cnt += 6;
  6949. for (cur = G.top_var; cur; cur = cur->next) {
  6950. if (!cur->flg_export || cur->flg_read_only)
  6951. cnt += 2;
  6952. }
  6953. # if ENABLE_HUSH_FUNCTIONS
  6954. for (funcp = G.top_func; funcp; funcp = funcp->next)
  6955. cnt += 3;
  6956. # endif
  6957. pp = g_argv;
  6958. while (*pp++)
  6959. cnt++;
  6960. *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
  6961. *pp++ = (char *) G.argv0_for_re_execing;
  6962. *pp++ = param_buf;
  6963. for (cur = G.top_var; cur; cur = cur->next) {
  6964. if (strcmp(cur->varstr, hush_version_str) == 0)
  6965. continue;
  6966. if (cur->flg_read_only) {
  6967. *pp++ = (char *) "-R";
  6968. *pp++ = cur->varstr;
  6969. } else if (!cur->flg_export) {
  6970. *pp++ = (char *) "-V";
  6971. *pp++ = cur->varstr;
  6972. }
  6973. }
  6974. # if ENABLE_HUSH_FUNCTIONS
  6975. for (funcp = G.top_func; funcp; funcp = funcp->next) {
  6976. *pp++ = (char *) "-F";
  6977. *pp++ = funcp->name;
  6978. *pp++ = funcp->body_as_string;
  6979. }
  6980. # endif
  6981. /* We can pass activated traps here. Say, -Tnn:trap_string
  6982. *
  6983. * However, POSIX says that subshells reset signals with traps
  6984. * to SIG_DFL.
  6985. * I tested bash-3.2 and it not only does that with true subshells
  6986. * of the form ( list ), but with any forked children shells.
  6987. * I set trap "echo W" WINCH; and then tried:
  6988. *
  6989. * { echo 1; sleep 20; echo 2; } &
  6990. * while true; do echo 1; sleep 20; echo 2; break; done &
  6991. * true | { echo 1; sleep 20; echo 2; } | cat
  6992. *
  6993. * In all these cases sending SIGWINCH to the child shell
  6994. * did not run the trap. If I add trap "echo V" WINCH;
  6995. * _inside_ group (just before echo 1), it works.
  6996. *
  6997. * I conclude it means we don't need to pass active traps here.
  6998. */
  6999. *pp++ = (char *) "-c";
  7000. *pp++ = (char *) s;
  7001. if (builtin_argv) {
  7002. while (*++builtin_argv)
  7003. *pp++ = *builtin_argv;
  7004. *pp++ = (char *) "";
  7005. }
  7006. *pp++ = g_argv0;
  7007. while (*g_argv)
  7008. *pp++ = *g_argv++;
  7009. /* *pp = NULL; - is already there */
  7010. pp = environ;
  7011. do_exec:
  7012. debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
  7013. /* Don't propagate SIG_IGN to the child */
  7014. if (SPECIAL_JOBSTOP_SIGS != 0)
  7015. switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
  7016. execve(bb_busybox_exec_path, argv, pp);
  7017. /* Fallback. Useful for init=/bin/hush usage etc */
  7018. if (argv[0][0] == '/')
  7019. execve(argv[0], argv, pp);
  7020. xfunc_error_retval = 127;
  7021. bb_simple_error_msg_and_die("can't re-execute the shell");
  7022. }
  7023. #endif /* !BB_MMU */
  7024. static int run_and_free_list(struct pipe *pi);
  7025. /* Executing from string: eval, sh -c '...'
  7026. * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
  7027. * end_trigger controls how often we stop parsing
  7028. * NUL: parse all, execute, return
  7029. * ';': parse till ';' or newline, execute, repeat till EOF
  7030. */
  7031. static void parse_and_run_stream(struct in_str *inp, int end_trigger)
  7032. {
  7033. /* Why we need empty flag?
  7034. * An obscure corner case "false; ``; echo $?":
  7035. * empty command in `` should still set $? to 0.
  7036. * But we can't just set $? to 0 at the start,
  7037. * this breaks "false; echo `echo $?`" case.
  7038. */
  7039. bool empty = 1;
  7040. while (1) {
  7041. struct pipe *pipe_list;
  7042. #if ENABLE_HUSH_INTERACTIVE
  7043. if (end_trigger == ';') {
  7044. G.promptmode = 0; /* PS1 */
  7045. debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
  7046. }
  7047. #endif
  7048. pipe_list = parse_stream(NULL, NULL, inp, end_trigger);
  7049. if (!pipe_list || pipe_list == ERR_PTR) { /* EOF/error */
  7050. /* If we are in "big" script
  7051. * (not in `cmd` or something similar)...
  7052. */
  7053. if (pipe_list == ERR_PTR && end_trigger == ';') {
  7054. /* Discard cached input (rest of line) */
  7055. int ch = inp->last_char;
  7056. while (ch != EOF && ch != '\n') {
  7057. //bb_error_msg("Discarded:'%c'", ch);
  7058. ch = i_getch(inp);
  7059. }
  7060. /* Force prompt */
  7061. inp->p = NULL;
  7062. /* This stream isn't empty */
  7063. empty = 0;
  7064. continue;
  7065. }
  7066. if (!pipe_list && empty)
  7067. G.last_exitcode = 0;
  7068. break;
  7069. }
  7070. debug_print_tree(pipe_list, 0);
  7071. debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
  7072. run_and_free_list(pipe_list);
  7073. empty = 0;
  7074. if (G_flag_return_in_progress == 1)
  7075. break;
  7076. }
  7077. }
  7078. static void parse_and_run_string(const char *s)
  7079. {
  7080. struct in_str input;
  7081. //IF_HUSH_LINENO_VAR(unsigned sv = G.parse_lineno;)
  7082. setup_string_in_str(&input, s);
  7083. parse_and_run_stream(&input, '\0');
  7084. //IF_HUSH_LINENO_VAR(G.parse_lineno = sv;)
  7085. }
  7086. static void parse_and_run_file(HFILE *fp)
  7087. {
  7088. struct in_str input;
  7089. IF_HUSH_LINENO_VAR(unsigned sv = G.parse_lineno;)
  7090. IF_HUSH_LINENO_VAR(G.parse_lineno = 1;)
  7091. setup_file_in_str(&input, fp);
  7092. parse_and_run_stream(&input, ';');
  7093. IF_HUSH_LINENO_VAR(G.parse_lineno = sv;)
  7094. }
  7095. #if ENABLE_HUSH_TICK
  7096. static int generate_stream_from_string(const char *s, pid_t *pid_p)
  7097. {
  7098. pid_t pid;
  7099. int channel[2];
  7100. # if !BB_MMU
  7101. char **to_free = NULL;
  7102. # endif
  7103. xpipe(channel);
  7104. pid = BB_MMU ? xfork() : xvfork();
  7105. if (pid == 0) { /* child */
  7106. disable_restore_tty_pgrp_on_exit();
  7107. /* Process substitution is not considered to be usual
  7108. * 'command execution'.
  7109. * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
  7110. */
  7111. bb_signals(0
  7112. + (1 << SIGTSTP)
  7113. + (1 << SIGTTIN)
  7114. + (1 << SIGTTOU)
  7115. , SIG_IGN);
  7116. close(channel[0]); /* NB: close _first_, then move fd! */
  7117. xmove_fd(channel[1], 1);
  7118. # if ENABLE_HUSH_TRAP
  7119. /* Awful hack for `trap` or $(trap).
  7120. *
  7121. * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
  7122. * contains an example where "trap" is executed in a subshell:
  7123. *
  7124. * save_traps=$(trap)
  7125. * ...
  7126. * eval "$save_traps"
  7127. *
  7128. * Standard does not say that "trap" in subshell shall print
  7129. * parent shell's traps. It only says that its output
  7130. * must have suitable form, but then, in the above example
  7131. * (which is not supposed to be normative), it implies that.
  7132. *
  7133. * bash (and probably other shell) does implement it
  7134. * (traps are reset to defaults, but "trap" still shows them),
  7135. * but as a result, "trap" logic is hopelessly messed up:
  7136. *
  7137. * # trap
  7138. * trap -- 'echo Ho' SIGWINCH <--- we have a handler
  7139. * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
  7140. * # true | trap <--- trap is in subshell - no output (ditto)
  7141. * # echo `true | trap` <--- in subshell - output (but traps are reset!)
  7142. * trap -- 'echo Ho' SIGWINCH
  7143. * # echo `(trap)` <--- in subshell in subshell - output
  7144. * trap -- 'echo Ho' SIGWINCH
  7145. * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
  7146. * trap -- 'echo Ho' SIGWINCH
  7147. *
  7148. * The rules when to forget and when to not forget traps
  7149. * get really complex and nonsensical.
  7150. *
  7151. * Our solution: ONLY bare $(trap) or `trap` is special.
  7152. */
  7153. s = skip_whitespace(s);
  7154. if (is_prefixed_with(s, "trap")
  7155. && skip_whitespace(s + 4)[0] == '\0'
  7156. ) {
  7157. static const char *const argv[] = { NULL, NULL };
  7158. builtin_trap((char**)argv);
  7159. fflush_all(); /* important */
  7160. _exit(0);
  7161. }
  7162. # endif
  7163. # if BB_MMU
  7164. /* Prevent it from trying to handle ctrl-z etc */
  7165. IF_HUSH_JOB(G.run_list_level = 1;)
  7166. CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
  7167. reset_traps_to_defaults();
  7168. IF_HUSH_MODE_X(G.x_mode_depth++;)
  7169. //bb_error_msg("%s: ++x_mode_depth=%d", __func__, G.x_mode_depth);
  7170. parse_and_run_string(s);
  7171. _exit(G.last_exitcode);
  7172. # else
  7173. /* We re-execute after vfork on NOMMU. This makes this script safe:
  7174. * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
  7175. * huge=`cat BIG` # was blocking here forever
  7176. * echo OK
  7177. */
  7178. re_execute_shell(&to_free,
  7179. s,
  7180. G.global_argv[0],
  7181. G.global_argv + 1,
  7182. NULL);
  7183. # endif
  7184. }
  7185. /* parent */
  7186. *pid_p = pid;
  7187. # if ENABLE_HUSH_FAST
  7188. G.count_SIGCHLD++;
  7189. //bb_error_msg("[%d] fork in generate_stream_from_string:"
  7190. // " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
  7191. // getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
  7192. # endif
  7193. enable_restore_tty_pgrp_on_exit();
  7194. # if !BB_MMU
  7195. free(to_free);
  7196. # endif
  7197. close(channel[1]);
  7198. return channel[0];
  7199. }
  7200. /* Return code is exit status of the process that is run. */
  7201. static int process_command_subs(o_string *dest, const char *s)
  7202. {
  7203. FILE *fp;
  7204. pid_t pid;
  7205. int status, ch, eol_cnt;
  7206. fp = xfdopen_for_read(generate_stream_from_string(s, &pid));
  7207. /* Now send results of command back into original context */
  7208. eol_cnt = 0;
  7209. while ((ch = getc(fp)) != EOF) {
  7210. if (ch == '\0')
  7211. continue;
  7212. if (ch == '\n') {
  7213. eol_cnt++;
  7214. continue;
  7215. }
  7216. while (eol_cnt) {
  7217. o_addchr(dest, '\n');
  7218. eol_cnt--;
  7219. }
  7220. o_addQchr(dest, ch);
  7221. }
  7222. debug_printf("done reading from `cmd` pipe, closing it\n");
  7223. fclose(fp);
  7224. /* We need to extract exitcode. Test case
  7225. * "true; echo `sleep 1; false` $?"
  7226. * should print 1 */
  7227. safe_waitpid(pid, &status, 0);
  7228. debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
  7229. return WEXITSTATUS(status);
  7230. }
  7231. #endif /* ENABLE_HUSH_TICK */
  7232. static void setup_heredoc(struct redir_struct *redir)
  7233. {
  7234. struct fd_pair pair;
  7235. pid_t pid;
  7236. int len, written;
  7237. /* the _body_ of heredoc (misleading field name) */
  7238. const char *heredoc = redir->rd_filename;
  7239. char *expanded;
  7240. #if !BB_MMU
  7241. char **to_free;
  7242. #endif
  7243. expanded = NULL;
  7244. if (!(redir->rd_dup & HEREDOC_QUOTED)) {
  7245. expanded = encode_then_expand_string(heredoc);
  7246. if (expanded)
  7247. heredoc = expanded;
  7248. }
  7249. len = strlen(heredoc);
  7250. close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
  7251. xpiped_pair(pair);
  7252. xmove_fd(pair.rd, redir->rd_fd);
  7253. /* Try writing without forking. Newer kernels have
  7254. * dynamically growing pipes. Must use non-blocking write! */
  7255. ndelay_on(pair.wr);
  7256. while (1) {
  7257. written = write(pair.wr, heredoc, len);
  7258. if (written <= 0)
  7259. break;
  7260. len -= written;
  7261. if (len == 0) {
  7262. close(pair.wr);
  7263. free(expanded);
  7264. return;
  7265. }
  7266. heredoc += written;
  7267. }
  7268. ndelay_off(pair.wr);
  7269. /* Okay, pipe buffer was not big enough */
  7270. /* Note: we must not create a stray child (bastard? :)
  7271. * for the unsuspecting parent process. Child creates a grandchild
  7272. * and exits before parent execs the process which consumes heredoc
  7273. * (that exec happens after we return from this function) */
  7274. #if !BB_MMU
  7275. to_free = NULL;
  7276. #endif
  7277. pid = xvfork();
  7278. if (pid == 0) {
  7279. /* child */
  7280. disable_restore_tty_pgrp_on_exit();
  7281. pid = BB_MMU ? xfork() : xvfork();
  7282. if (pid != 0)
  7283. _exit(0);
  7284. /* grandchild */
  7285. close(redir->rd_fd); /* read side of the pipe */
  7286. #if BB_MMU
  7287. full_write(pair.wr, heredoc, len); /* may loop or block */
  7288. _exit(0);
  7289. #else
  7290. /* Delegate blocking writes to another process */
  7291. xmove_fd(pair.wr, STDOUT_FILENO);
  7292. re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
  7293. #endif
  7294. }
  7295. /* parent */
  7296. #if ENABLE_HUSH_FAST
  7297. G.count_SIGCHLD++;
  7298. //bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
  7299. #endif
  7300. enable_restore_tty_pgrp_on_exit();
  7301. #if !BB_MMU
  7302. free(to_free);
  7303. #endif
  7304. close(pair.wr);
  7305. free(expanded);
  7306. wait(NULL); /* wait till child has died */
  7307. }
  7308. struct squirrel {
  7309. int orig_fd;
  7310. int moved_to;
  7311. /* moved_to = n: fd was moved to n; restore back to orig_fd after redir */
  7312. /* moved_to = -1: fd was opened by redirect; close orig_fd after redir */
  7313. };
  7314. static struct squirrel *append_squirrel(struct squirrel *sq, int i, int orig, int moved)
  7315. {
  7316. sq = xrealloc(sq, (i + 2) * sizeof(sq[0]));
  7317. sq[i].orig_fd = orig;
  7318. sq[i].moved_to = moved;
  7319. sq[i+1].orig_fd = -1; /* end marker */
  7320. return sq;
  7321. }
  7322. static struct squirrel *add_squirrel(struct squirrel *sq, int fd, int avoid_fd)
  7323. {
  7324. int moved_to;
  7325. int i;
  7326. i = 0;
  7327. if (sq) for (; sq[i].orig_fd >= 0; i++) {
  7328. /* If we collide with an already moved fd... */
  7329. if (fd == sq[i].moved_to) {
  7330. sq[i].moved_to = dup_CLOEXEC(sq[i].moved_to, avoid_fd);
  7331. debug_printf_redir("redirect_fd %d: already busy, moving to %d\n", fd, sq[i].moved_to);
  7332. if (sq[i].moved_to < 0) /* what? */
  7333. xfunc_die();
  7334. return sq;
  7335. }
  7336. if (fd == sq[i].orig_fd) {
  7337. /* Example: echo Hello >/dev/null 1>&2 */
  7338. debug_printf_redir("redirect_fd %d: already moved\n", fd);
  7339. return sq;
  7340. }
  7341. }
  7342. /* If this fd is open, we move and remember it; if it's closed, moved_to = -1 */
  7343. moved_to = dup_CLOEXEC(fd, avoid_fd);
  7344. debug_printf_redir("redirect_fd %d: previous fd is moved to %d (-1 if it was closed)\n", fd, moved_to);
  7345. if (moved_to < 0 && errno != EBADF)
  7346. xfunc_die();
  7347. return append_squirrel(sq, i, fd, moved_to);
  7348. }
  7349. static struct squirrel *add_squirrel_closed(struct squirrel *sq, int fd)
  7350. {
  7351. int i;
  7352. i = 0;
  7353. if (sq) for (; sq[i].orig_fd >= 0; i++) {
  7354. /* If we collide with an already moved fd... */
  7355. if (fd == sq[i].orig_fd) {
  7356. /* Examples:
  7357. * "echo 3>FILE 3>&- 3>FILE"
  7358. * "echo 3>&- 3>FILE"
  7359. * No need for last redirect to insert
  7360. * another "need to close 3" indicator.
  7361. */
  7362. debug_printf_redir("redirect_fd %d: already moved or closed\n", fd);
  7363. return sq;
  7364. }
  7365. }
  7366. debug_printf_redir("redirect_fd %d: previous fd was closed\n", fd);
  7367. return append_squirrel(sq, i, fd, -1);
  7368. }
  7369. /* fd: redirect wants this fd to be used (e.g. 3>file).
  7370. * Move all conflicting internally used fds,
  7371. * and remember them so that we can restore them later.
  7372. */
  7373. static int save_fd_on_redirect(int fd, int avoid_fd, struct squirrel **sqp)
  7374. {
  7375. if (avoid_fd < 9) /* the important case here is that it can be -1 */
  7376. avoid_fd = 9;
  7377. #if ENABLE_HUSH_INTERACTIVE
  7378. if (fd != 0 /* don't trigger for G_interactive_fd == 0 (that's "not interactive" flag) */
  7379. && fd == G_interactive_fd
  7380. ) {
  7381. /* Testcase: "ls -l /proc/$$/fd 255>&-" should work */
  7382. G_interactive_fd = xdup_CLOEXEC_and_close(G_interactive_fd, avoid_fd);
  7383. debug_printf_redir("redirect_fd %d: matches interactive_fd, moving it to %d\n", fd, G_interactive_fd);
  7384. return 1; /* "we closed fd" */
  7385. }
  7386. #endif
  7387. /* Are we called from setup_redirects(squirrel==NULL)
  7388. * in redirect in a [v]forked child?
  7389. */
  7390. if (sqp == NULL) {
  7391. /* No need to move script fds.
  7392. * For NOMMU case, it's actively wrong: we'd change ->fd
  7393. * fields in memory for the parent, but parent's fds
  7394. * aren't moved, it would use wrong fd!
  7395. * Reproducer: "cmd 3>FILE" in script.
  7396. * If we would call move_HFILEs_on_redirect(), child would:
  7397. * fcntl64(3, F_DUPFD_CLOEXEC, 10) = 10
  7398. * close(3) = 0
  7399. * and change ->fd to 10 if fd#3 is a script fd. WRONG.
  7400. */
  7401. //bb_error_msg("sqp == NULL: [v]forked child");
  7402. return 0;
  7403. }
  7404. /* If this one of script's fds? */
  7405. if (move_HFILEs_on_redirect(fd, avoid_fd))
  7406. return 1; /* yes. "we closed fd" (actually moved it) */
  7407. /* Are we called for "exec 3>FILE"? Came through
  7408. * redirect_and_varexp_helper(squirrel=ERR_PTR) -> setup_redirects(ERR_PTR)
  7409. * This case used to fail for this script:
  7410. * exec 3>FILE
  7411. * echo Ok
  7412. * ...100000 more lines...
  7413. * echo Ok
  7414. * as follows:
  7415. * read(3, "exec 3>FILE\necho Ok\necho Ok"..., 1024) = 1024
  7416. * open("FILE", O_WRONLY|O_CREAT|O_TRUNC|O_LARGEFILE, 0666) = 4
  7417. * dup2(4, 3) = 3
  7418. * ^^^^^^^^ oops, we lost fd#3 opened to our script!
  7419. * close(4) = 0
  7420. * write(1, "Ok\n", 3) = 3
  7421. * ... = 3
  7422. * write(1, "Ok\n", 3) = 3
  7423. * read(3, 0x94fbc08, 1024) = -1 EBADF (Bad file descriptor)
  7424. * ^^^^^^^^ oops, wrong fd!!!
  7425. * With this case separate from sqp == NULL and *after* move_HFILEs,
  7426. * it now works:
  7427. */
  7428. if (sqp == ERR_PTR) {
  7429. /* Don't preserve redirected fds: exec is _meant_ to change these */
  7430. //bb_error_msg("sqp == ERR_PTR: exec >FILE");
  7431. return 0;
  7432. }
  7433. /* Check whether it collides with any open fds (e.g. stdio), save fds as needed */
  7434. *sqp = add_squirrel(*sqp, fd, avoid_fd);
  7435. return 0; /* "we did not close fd" */
  7436. }
  7437. static void restore_redirects(struct squirrel *sq)
  7438. {
  7439. if (sq) {
  7440. int i;
  7441. for (i = 0; sq[i].orig_fd >= 0; i++) {
  7442. if (sq[i].moved_to >= 0) {
  7443. /* We simply die on error */
  7444. debug_printf_redir("restoring redirected fd from %d to %d\n", sq[i].moved_to, sq[i].orig_fd);
  7445. xmove_fd(sq[i].moved_to, sq[i].orig_fd);
  7446. } else {
  7447. /* cmd1 9>FILE; cmd2_should_see_fd9_closed */
  7448. debug_printf_redir("restoring redirected fd %d: closing it\n", sq[i].orig_fd);
  7449. close(sq[i].orig_fd);
  7450. }
  7451. }
  7452. free(sq);
  7453. }
  7454. if (G.HFILE_stdin
  7455. && G.HFILE_stdin->fd > STDIN_FILENO
  7456. /* we compare > STDIN, not == STDIN, since hfgetc()
  7457. * closes fd and sets ->fd to -1 if EOF is reached.
  7458. * Testcase: echo 'pwd' | hush
  7459. */
  7460. ) {
  7461. /* Testcase: interactive "read r <FILE; echo $r; read r; echo $r".
  7462. * Redirect moves ->fd to e.g. 10,
  7463. * and it is not restored above (we do not restore script fds
  7464. * after redirects, we just use new, "moved" fds).
  7465. * However for stdin, get_user_input() -> read_line_input(),
  7466. * and read builtin, depend on fd == STDIN_FILENO.
  7467. */
  7468. debug_printf_redir("restoring %d to stdin\n", G.HFILE_stdin->fd);
  7469. xmove_fd(G.HFILE_stdin->fd, STDIN_FILENO);
  7470. G.HFILE_stdin->fd = STDIN_FILENO;
  7471. }
  7472. /* If moved, G_interactive_fd stays on new fd, not restoring it */
  7473. }
  7474. #if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
  7475. static void close_saved_fds_and_FILE_fds(void)
  7476. {
  7477. if (G_interactive_fd)
  7478. close(G_interactive_fd);
  7479. close_all_HFILE_list();
  7480. }
  7481. #endif
  7482. static int internally_opened_fd(int fd, struct squirrel *sq)
  7483. {
  7484. int i;
  7485. #if ENABLE_HUSH_INTERACTIVE
  7486. if (fd == G_interactive_fd)
  7487. return 1;
  7488. #endif
  7489. /* If this one of script's fds? */
  7490. if (fd_in_HFILEs(fd))
  7491. return 1;
  7492. if (sq) for (i = 0; sq[i].orig_fd >= 0; i++) {
  7493. if (fd == sq[i].moved_to)
  7494. return 1;
  7495. }
  7496. return 0;
  7497. }
  7498. /* squirrel != NULL means we squirrel away copies of stdin, stdout,
  7499. * and stderr if they are redirected. */
  7500. static int setup_redirects(struct command *prog, struct squirrel **sqp)
  7501. {
  7502. struct redir_struct *redir;
  7503. for (redir = prog->redirects; redir; redir = redir->next) {
  7504. int newfd;
  7505. int closed;
  7506. if (redir->rd_type == REDIRECT_HEREDOC2) {
  7507. /* "rd_fd<<HERE" case */
  7508. save_fd_on_redirect(redir->rd_fd, /*avoid:*/ 0, sqp);
  7509. /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
  7510. * of the heredoc */
  7511. debug_printf_redir("set heredoc '%s'\n",
  7512. redir->rd_filename);
  7513. setup_heredoc(redir);
  7514. continue;
  7515. }
  7516. if (redir->rd_dup == REDIRFD_TO_FILE) {
  7517. /* "rd_fd<*>file" case (<*> is <,>,>>,<>) */
  7518. char *p;
  7519. int mode;
  7520. if (redir->rd_filename == NULL) {
  7521. /* Examples:
  7522. * "cmd >" (no filename)
  7523. * "cmd > <file" (2nd redirect starts too early)
  7524. */
  7525. syntax_error("invalid redirect");
  7526. continue;
  7527. }
  7528. mode = redir_table[redir->rd_type].mode;
  7529. p = expand_string_to_string(redir->rd_filename,
  7530. EXP_FLAG_ESC_GLOB_CHARS, /*unbackslash:*/ 1);
  7531. newfd = open_or_warn(p, mode);
  7532. free(p);
  7533. if (newfd < 0) {
  7534. /* Error message from open_or_warn can be lost
  7535. * if stderr has been redirected, but bash
  7536. * and ash both lose it as well
  7537. * (though zsh doesn't!)
  7538. */
  7539. return 1;
  7540. }
  7541. if (newfd == redir->rd_fd && sqp) {
  7542. /* open() gave us precisely the fd we wanted.
  7543. * This means that this fd was not busy
  7544. * (not opened to anywhere).
  7545. * Remember to close it on restore:
  7546. */
  7547. *sqp = add_squirrel_closed(*sqp, newfd);
  7548. debug_printf_redir("redir to previously closed fd %d\n", newfd);
  7549. }
  7550. } else {
  7551. /* "rd_fd>&rd_dup" or "rd_fd>&-" case */
  7552. newfd = redir->rd_dup;
  7553. }
  7554. if (newfd == redir->rd_fd)
  7555. continue;
  7556. /* if "N>FILE": move newfd to redir->rd_fd */
  7557. /* if "N>&M": dup newfd to redir->rd_fd */
  7558. /* if "N>&-": close redir->rd_fd (newfd is REDIRFD_CLOSE) */
  7559. closed = save_fd_on_redirect(redir->rd_fd, /*avoid:*/ newfd, sqp);
  7560. if (newfd == REDIRFD_CLOSE) {
  7561. /* "N>&-" means "close me" */
  7562. if (!closed) {
  7563. /* ^^^ optimization: saving may already
  7564. * have closed it. If not... */
  7565. close(redir->rd_fd);
  7566. }
  7567. /* Sometimes we do another close on restore, getting EBADF.
  7568. * Consider "echo 3>FILE 3>&-"
  7569. * first redirect remembers "need to close 3",
  7570. * and second redirect closes 3! Restore code then closes 3 again.
  7571. */
  7572. } else {
  7573. /* if newfd is a script fd or saved fd, simulate EBADF */
  7574. if (internally_opened_fd(newfd, sqp && sqp != ERR_PTR ? *sqp : NULL)) {
  7575. //errno = EBADF;
  7576. //bb_perror_msg_and_die("can't duplicate file descriptor");
  7577. newfd = -1; /* same effect as code above */
  7578. }
  7579. xdup2(newfd, redir->rd_fd);
  7580. if (redir->rd_dup == REDIRFD_TO_FILE)
  7581. /* "rd_fd > FILE" */
  7582. close(newfd);
  7583. /* else: "rd_fd > rd_dup" */
  7584. }
  7585. }
  7586. return 0;
  7587. }
  7588. static char *find_in_path(const char *arg)
  7589. {
  7590. char *ret = NULL;
  7591. const char *PATH = get_local_var_value("PATH");
  7592. if (!PATH)
  7593. return NULL;
  7594. while (1) {
  7595. const char *end = strchrnul(PATH, ':');
  7596. int sz = end - PATH; /* must be int! */
  7597. free(ret);
  7598. if (sz != 0) {
  7599. ret = xasprintf("%.*s/%s", sz, PATH, arg);
  7600. } else {
  7601. /* We have xxx::yyyy in $PATH,
  7602. * it means "use current dir" */
  7603. ret = xstrdup(arg);
  7604. }
  7605. if (access(ret, F_OK) == 0)
  7606. break;
  7607. if (*end == '\0') {
  7608. free(ret);
  7609. return NULL;
  7610. }
  7611. PATH = end + 1;
  7612. }
  7613. return ret;
  7614. }
  7615. static const struct built_in_command *find_builtin_helper(const char *name,
  7616. const struct built_in_command *x,
  7617. const struct built_in_command *end)
  7618. {
  7619. while (x != end) {
  7620. if (strcmp(name, x->b_cmd) != 0) {
  7621. x++;
  7622. continue;
  7623. }
  7624. debug_printf_exec("found builtin '%s'\n", name);
  7625. return x;
  7626. }
  7627. return NULL;
  7628. }
  7629. static const struct built_in_command *find_builtin1(const char *name)
  7630. {
  7631. return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
  7632. }
  7633. static const struct built_in_command *find_builtin(const char *name)
  7634. {
  7635. const struct built_in_command *x = find_builtin1(name);
  7636. if (x)
  7637. return x;
  7638. return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
  7639. }
  7640. #if ENABLE_HUSH_JOB && EDITING_HAS_get_exe_name
  7641. static const char * FAST_FUNC get_builtin_name(int i)
  7642. {
  7643. if (/*i >= 0 && */ i < ARRAY_SIZE(bltins1)) {
  7644. return bltins1[i].b_cmd;
  7645. }
  7646. i -= ARRAY_SIZE(bltins1);
  7647. if (i < ARRAY_SIZE(bltins2)) {
  7648. return bltins2[i].b_cmd;
  7649. }
  7650. return NULL;
  7651. }
  7652. #endif
  7653. static void remove_nested_vars(void)
  7654. {
  7655. struct variable *cur;
  7656. struct variable **cur_pp;
  7657. cur_pp = &G.top_var;
  7658. while ((cur = *cur_pp) != NULL) {
  7659. if (cur->var_nest_level <= G.var_nest_level) {
  7660. cur_pp = &cur->next;
  7661. continue;
  7662. }
  7663. /* Unexport */
  7664. if (cur->flg_export) {
  7665. debug_printf_env("unexporting nested '%s'/%u\n", cur->varstr, cur->var_nest_level);
  7666. bb_unsetenv(cur->varstr);
  7667. }
  7668. /* Remove from global list */
  7669. *cur_pp = cur->next;
  7670. /* Free */
  7671. if (!cur->max_len) {
  7672. debug_printf_env("freeing nested '%s'/%u\n", cur->varstr, cur->var_nest_level);
  7673. free(cur->varstr);
  7674. }
  7675. free(cur);
  7676. }
  7677. }
  7678. static void enter_var_nest_level(void)
  7679. {
  7680. G.var_nest_level++;
  7681. debug_printf_env("var_nest_level++ %u\n", G.var_nest_level);
  7682. /* Try: f() { echo -n .; f; }; f
  7683. * struct variable::var_nest_level is uint16_t,
  7684. * thus limiting recursion to < 2^16.
  7685. * In any case, with 8 Mbyte stack SEGV happens
  7686. * not too long after 2^16 recursions anyway.
  7687. */
  7688. if (G.var_nest_level > 0xff00)
  7689. bb_error_msg_and_die("fatal recursion (depth %u)", G.var_nest_level);
  7690. }
  7691. static void leave_var_nest_level(void)
  7692. {
  7693. G.var_nest_level--;
  7694. debug_printf_env("var_nest_level-- %u\n", G.var_nest_level);
  7695. if (HUSH_DEBUG && (int)G.var_nest_level < 0)
  7696. bb_simple_error_msg_and_die("BUG: nesting underflow");
  7697. remove_nested_vars();
  7698. }
  7699. #if ENABLE_HUSH_FUNCTIONS
  7700. static struct function **find_function_slot(const char *name)
  7701. {
  7702. struct function *funcp;
  7703. struct function **funcpp = &G.top_func;
  7704. while ((funcp = *funcpp) != NULL) {
  7705. if (strcmp(name, funcp->name) == 0) {
  7706. debug_printf_exec("found function '%s'\n", name);
  7707. break;
  7708. }
  7709. funcpp = &funcp->next;
  7710. }
  7711. return funcpp;
  7712. }
  7713. static ALWAYS_INLINE const struct function *find_function(const char *name)
  7714. {
  7715. const struct function *funcp = *find_function_slot(name);
  7716. return funcp;
  7717. }
  7718. /* Note: takes ownership on name ptr */
  7719. static struct function *new_function(char *name)
  7720. {
  7721. struct function **funcpp = find_function_slot(name);
  7722. struct function *funcp = *funcpp;
  7723. if (funcp != NULL) {
  7724. struct command *cmd = funcp->parent_cmd;
  7725. debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
  7726. if (!cmd) {
  7727. debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
  7728. free(funcp->name);
  7729. /* Note: if !funcp->body, do not free body_as_string!
  7730. * This is a special case of "-F name body" function:
  7731. * body_as_string was not malloced! */
  7732. if (funcp->body) {
  7733. free_pipe_list(funcp->body);
  7734. # if !BB_MMU
  7735. free(funcp->body_as_string);
  7736. # endif
  7737. }
  7738. } else {
  7739. debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
  7740. cmd->argv[0] = funcp->name;
  7741. cmd->group = funcp->body;
  7742. # if !BB_MMU
  7743. cmd->group_as_string = funcp->body_as_string;
  7744. # endif
  7745. }
  7746. } else {
  7747. debug_printf_exec("remembering new function '%s'\n", name);
  7748. funcp = *funcpp = xzalloc(sizeof(*funcp));
  7749. /*funcp->next = NULL;*/
  7750. }
  7751. funcp->name = name;
  7752. return funcp;
  7753. }
  7754. # if ENABLE_HUSH_UNSET
  7755. static void unset_func(const char *name)
  7756. {
  7757. struct function **funcpp = find_function_slot(name);
  7758. struct function *funcp = *funcpp;
  7759. if (funcp != NULL) {
  7760. debug_printf_exec("freeing function '%s'\n", funcp->name);
  7761. *funcpp = funcp->next;
  7762. /* funcp is unlinked now, deleting it.
  7763. * Note: if !funcp->body, the function was created by
  7764. * "-F name body", do not free ->body_as_string
  7765. * and ->name as they were not malloced. */
  7766. if (funcp->body) {
  7767. free_pipe_list(funcp->body);
  7768. free(funcp->name);
  7769. # if !BB_MMU
  7770. free(funcp->body_as_string);
  7771. # endif
  7772. }
  7773. free(funcp);
  7774. }
  7775. }
  7776. # endif
  7777. # if BB_MMU
  7778. #define exec_function(to_free, funcp, argv) \
  7779. exec_function(funcp, argv)
  7780. # endif
  7781. static void exec_function(char ***to_free,
  7782. const struct function *funcp,
  7783. char **argv) NORETURN;
  7784. static void exec_function(char ***to_free,
  7785. const struct function *funcp,
  7786. char **argv)
  7787. {
  7788. # if BB_MMU
  7789. int n;
  7790. argv[0] = G.global_argv[0];
  7791. G.global_argv = argv;
  7792. G.global_argc = n = 1 + string_array_len(argv + 1);
  7793. // Example when we are here: "cmd | func"
  7794. // func will run with saved-redirect fds open.
  7795. // $ f() { echo /proc/self/fd/*; }
  7796. // $ true | f
  7797. // /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3
  7798. // stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ DIR fd for glob
  7799. // Same in script:
  7800. // $ . ./SCRIPT
  7801. // /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3 /proc/self/fd/4
  7802. // stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ opened ./SCRIPT DIR fd for glob
  7803. // They are CLOEXEC so external programs won't see them, but
  7804. // for "more correctness" we might want to close those extra fds here:
  7805. //? close_saved_fds_and_FILE_fds();
  7806. /* "we are in a function, ok to use return" */
  7807. G_flag_return_in_progress = -1;
  7808. enter_var_nest_level();
  7809. IF_HUSH_LOCAL(G.func_nest_level++;)
  7810. /* On MMU, funcp->body is always non-NULL */
  7811. n = run_list(funcp->body);
  7812. _exit(n);
  7813. # else
  7814. //? close_saved_fds_and_FILE_fds();
  7815. //TODO: check whether "true | func_with_return" works
  7816. re_execute_shell(to_free,
  7817. funcp->body_as_string,
  7818. G.global_argv[0],
  7819. argv + 1,
  7820. NULL);
  7821. # endif
  7822. }
  7823. static int run_function(const struct function *funcp, char **argv)
  7824. {
  7825. int rc;
  7826. save_arg_t sv;
  7827. smallint sv_flg;
  7828. save_and_replace_G_args(&sv, argv);
  7829. /* "We are in function, ok to use return" */
  7830. sv_flg = G_flag_return_in_progress;
  7831. G_flag_return_in_progress = -1;
  7832. /* Make "local" variables properly shadow previous ones */
  7833. IF_HUSH_LOCAL(enter_var_nest_level();)
  7834. IF_HUSH_LOCAL(G.func_nest_level++;)
  7835. /* On MMU, funcp->body is always non-NULL */
  7836. # if !BB_MMU
  7837. if (!funcp->body) {
  7838. /* Function defined by -F */
  7839. parse_and_run_string(funcp->body_as_string);
  7840. rc = G.last_exitcode;
  7841. } else
  7842. # endif
  7843. {
  7844. rc = run_list(funcp->body);
  7845. }
  7846. IF_HUSH_LOCAL(G.func_nest_level--;)
  7847. IF_HUSH_LOCAL(leave_var_nest_level();)
  7848. G_flag_return_in_progress = sv_flg;
  7849. # if ENABLE_HUSH_TRAP
  7850. debug_printf_exec("G.return_exitcode=-1\n");
  7851. G.return_exitcode = -1; /* invalidate stashed return value */
  7852. # endif
  7853. restore_G_args(&sv, argv);
  7854. return rc;
  7855. }
  7856. #endif /* ENABLE_HUSH_FUNCTIONS */
  7857. #if BB_MMU
  7858. #define exec_builtin(to_free, x, argv) \
  7859. exec_builtin(x, argv)
  7860. #else
  7861. #define exec_builtin(to_free, x, argv) \
  7862. exec_builtin(to_free, argv)
  7863. #endif
  7864. static void exec_builtin(char ***to_free,
  7865. const struct built_in_command *x,
  7866. char **argv) NORETURN;
  7867. static void exec_builtin(char ***to_free,
  7868. const struct built_in_command *x,
  7869. char **argv)
  7870. {
  7871. #if BB_MMU
  7872. int rcode;
  7873. //? close_saved_fds_and_FILE_fds();
  7874. rcode = x->b_function(argv);
  7875. fflush_all();
  7876. _exit(rcode);
  7877. #else
  7878. fflush_all();
  7879. /* On NOMMU, we must never block!
  7880. * Example: { sleep 99 | read line; } & echo Ok
  7881. */
  7882. re_execute_shell(to_free,
  7883. argv[0],
  7884. G.global_argv[0],
  7885. G.global_argv + 1,
  7886. argv);
  7887. #endif
  7888. }
  7889. static void execvp_or_die(char **argv) NORETURN;
  7890. static void execvp_or_die(char **argv)
  7891. {
  7892. int e;
  7893. debug_printf_exec("execing '%s'\n", argv[0]);
  7894. /* Don't propagate SIG_IGN to the child */
  7895. if (SPECIAL_JOBSTOP_SIGS != 0)
  7896. switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
  7897. execvp(argv[0], argv);
  7898. e = 2;
  7899. if (errno == EACCES) e = 126;
  7900. if (errno == ENOENT) e = 127;
  7901. bb_perror_msg("can't execute '%s'", argv[0]);
  7902. _exit(e);
  7903. }
  7904. #if ENABLE_HUSH_MODE_X
  7905. static void x_mode_print_optionally_squoted(const char *str)
  7906. {
  7907. unsigned len;
  7908. const char *cp;
  7909. cp = str;
  7910. /* the set of chars which-cause-string-to-be-squoted mimics bash */
  7911. /* test a char with: bash -c 'set -x; echo "CH"' */
  7912. if (str[strcspn(str, "\\\"'`$(){}[]<>;#&|~*?!^"
  7913. " " "\001\002\003\004\005\006\007"
  7914. "\010\011\012\013\014\015\016\017"
  7915. "\020\021\022\023\024\025\026\027"
  7916. "\030\031\032\033\034\035\036\037"
  7917. )
  7918. ] == '\0'
  7919. ) {
  7920. /* string has no special chars */
  7921. x_mode_addstr(str);
  7922. return;
  7923. }
  7924. cp = str;
  7925. for (;;) {
  7926. /* print '....' up to EOL or first squote */
  7927. len = (int)(strchrnul(cp, '\'') - cp);
  7928. if (len != 0) {
  7929. x_mode_addchr('\'');
  7930. x_mode_addblock(cp, len);
  7931. x_mode_addchr('\'');
  7932. cp += len;
  7933. }
  7934. if (*cp == '\0')
  7935. break;
  7936. /* string contains squote(s), print them as \' */
  7937. x_mode_addchr('\\');
  7938. x_mode_addchr('\'');
  7939. cp++;
  7940. }
  7941. }
  7942. static void dump_cmd_in_x_mode(char **argv)
  7943. {
  7944. if (G_x_mode && argv) {
  7945. unsigned n;
  7946. /* "+[+++...][ cmd...]\n\0" */
  7947. x_mode_prefix();
  7948. n = 0;
  7949. while (argv[n]) {
  7950. x_mode_addchr(' ');
  7951. if (argv[n][0] == '\0') {
  7952. x_mode_addchr('\'');
  7953. x_mode_addchr('\'');
  7954. } else {
  7955. x_mode_print_optionally_squoted(argv[n]);
  7956. }
  7957. n++;
  7958. }
  7959. x_mode_flush();
  7960. }
  7961. }
  7962. #else
  7963. # define dump_cmd_in_x_mode(argv) ((void)0)
  7964. #endif
  7965. #if ENABLE_HUSH_COMMAND
  7966. static void if_command_vV_print_and_exit(char opt_vV, char *cmd, const char *explanation)
  7967. {
  7968. char *to_free;
  7969. if (!opt_vV)
  7970. return;
  7971. to_free = NULL;
  7972. if (!explanation) {
  7973. char *path = getenv("PATH");
  7974. explanation = to_free = find_executable(cmd, &path); /* path == NULL is ok */
  7975. if (!explanation)
  7976. _exit(1); /* PROG was not found */
  7977. if (opt_vV != 'V')
  7978. cmd = to_free; /* -v PROG prints "/path/to/PROG" */
  7979. }
  7980. printf((opt_vV == 'V') ? "%s is %s\n" : "%s\n", cmd, explanation);
  7981. free(to_free);
  7982. fflush_all();
  7983. _exit(0);
  7984. }
  7985. #else
  7986. # define if_command_vV_print_and_exit(a,b,c) ((void)0)
  7987. #endif
  7988. #if BB_MMU
  7989. #define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
  7990. pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
  7991. #define pseudo_exec(nommu_save, command, argv_expanded) \
  7992. pseudo_exec(command, argv_expanded)
  7993. #endif
  7994. /* Called after [v]fork() in run_pipe, or from builtin_exec.
  7995. * Never returns.
  7996. * Don't exit() here. If you don't exec, use _exit instead.
  7997. * The at_exit handlers apparently confuse the calling process,
  7998. * in particular stdin handling. Not sure why? -- because of vfork! (vda)
  7999. */
  8000. static void pseudo_exec_argv(nommu_save_t *nommu_save,
  8001. char **argv, int assignment_cnt,
  8002. char **argv_expanded) NORETURN;
  8003. static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
  8004. char **argv, int assignment_cnt,
  8005. char **argv_expanded)
  8006. {
  8007. const struct built_in_command *x;
  8008. struct variable **sv_shadowed;
  8009. char **new_env;
  8010. IF_HUSH_COMMAND(char opt_vV = 0;)
  8011. IF_HUSH_FUNCTIONS(const struct function *funcp;)
  8012. new_env = expand_assignments(argv, assignment_cnt);
  8013. dump_cmd_in_x_mode(new_env);
  8014. if (!argv[assignment_cnt]) {
  8015. /* Case when we are here: ... | var=val | ...
  8016. * (note that we do not exit early, i.e., do not optimize out
  8017. * expand_assignments(): think about ... | var=`sleep 1` | ...
  8018. */
  8019. free_strings(new_env);
  8020. _exit(EXIT_SUCCESS);
  8021. }
  8022. sv_shadowed = G.shadowed_vars_pp;
  8023. #if BB_MMU
  8024. G.shadowed_vars_pp = NULL; /* "don't save, free them instead" */
  8025. #else
  8026. G.shadowed_vars_pp = &nommu_save->old_vars;
  8027. G.var_nest_level++;
  8028. #endif
  8029. set_vars_and_save_old(new_env);
  8030. G.shadowed_vars_pp = sv_shadowed;
  8031. if (argv_expanded) {
  8032. argv = argv_expanded;
  8033. } else {
  8034. argv = expand_strvec_to_strvec(argv + assignment_cnt);
  8035. #if !BB_MMU
  8036. nommu_save->argv = argv;
  8037. #endif
  8038. }
  8039. dump_cmd_in_x_mode(argv);
  8040. #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
  8041. if (strchr(argv[0], '/') != NULL)
  8042. goto skip;
  8043. #endif
  8044. #if ENABLE_HUSH_FUNCTIONS
  8045. /* Check if the command matches any functions (this goes before bltins) */
  8046. funcp = find_function(argv[0]);
  8047. if (funcp)
  8048. exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
  8049. #endif
  8050. #if ENABLE_HUSH_COMMAND
  8051. /* "command BAR": run BAR without looking it up among functions
  8052. * "command -v BAR": print "BAR" or "/path/to/BAR"; or exit 1
  8053. * "command -V BAR": print "BAR is {a function,a shell builtin,/path/to/BAR}"
  8054. */
  8055. while (strcmp(argv[0], "command") == 0 && argv[1]) {
  8056. char *p;
  8057. argv++;
  8058. p = *argv;
  8059. if (p[0] != '-' || !p[1])
  8060. continue; /* bash allows "command command command [-OPT] BAR" */
  8061. for (;;) {
  8062. p++;
  8063. switch (*p) {
  8064. case '\0':
  8065. argv++;
  8066. p = *argv;
  8067. if (p[0] != '-' || !p[1])
  8068. goto after_opts;
  8069. continue; /* next arg is also -opts, process it too */
  8070. case 'v':
  8071. case 'V':
  8072. opt_vV = *p;
  8073. continue;
  8074. default:
  8075. bb_error_msg_and_die("%s: %s: invalid option", "command", argv[0]);
  8076. }
  8077. }
  8078. }
  8079. after_opts:
  8080. # if ENABLE_HUSH_FUNCTIONS
  8081. if (opt_vV && find_function(argv[0]))
  8082. if_command_vV_print_and_exit(opt_vV, argv[0], "a function");
  8083. # endif
  8084. #endif
  8085. /* Check if the command matches any of the builtins.
  8086. * Depending on context, this might be redundant. But it's
  8087. * easier to waste a few CPU cycles than it is to figure out
  8088. * if this is one of those cases.
  8089. */
  8090. /* Why "BB_MMU ? :" difference in logic? -
  8091. * On NOMMU, it is more expensive to re-execute shell
  8092. * just in order to run echo or test builtin.
  8093. * It's better to skip it here and run corresponding
  8094. * non-builtin later. */
  8095. x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
  8096. if (x) {
  8097. if_command_vV_print_and_exit(opt_vV, argv[0], "a shell builtin");
  8098. exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
  8099. }
  8100. #if ENABLE_FEATURE_SH_STANDALONE
  8101. /* Check if the command matches any busybox applets */
  8102. {
  8103. int a = find_applet_by_name(argv[0]);
  8104. if (a >= 0) {
  8105. if_command_vV_print_and_exit(opt_vV, argv[0], "an applet");
  8106. # if BB_MMU /* see above why on NOMMU it is not allowed */
  8107. if (APPLET_IS_NOEXEC(a)) {
  8108. /* Do not leak open fds from opened script files etc.
  8109. * Testcase: interactive "ls -l /proc/self/fd"
  8110. * should not show tty fd open.
  8111. */
  8112. close_saved_fds_and_FILE_fds();
  8113. //FIXME: should also close saved redir fds
  8114. //This casuses test failures in
  8115. //redir_children_should_not_see_saved_fd_2.tests
  8116. //redir_children_should_not_see_saved_fd_3.tests
  8117. //if you replace "busybox find" with just "find" in them
  8118. /* Without this, "rm -i FILE" can't be ^C'ed: */
  8119. switch_off_special_sigs(G.special_sig_mask);
  8120. debug_printf_exec("running applet '%s'\n", argv[0]);
  8121. run_noexec_applet_and_exit(a, argv[0], argv);
  8122. }
  8123. # endif
  8124. /* Re-exec ourselves */
  8125. debug_printf_exec("re-execing applet '%s'\n", argv[0]);
  8126. /* Don't propagate SIG_IGN to the child */
  8127. if (SPECIAL_JOBSTOP_SIGS != 0)
  8128. switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
  8129. execv(bb_busybox_exec_path, argv);
  8130. /* If they called chroot or otherwise made the binary no longer
  8131. * executable, fall through */
  8132. }
  8133. }
  8134. #endif
  8135. #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
  8136. skip:
  8137. #endif
  8138. if_command_vV_print_and_exit(opt_vV, argv[0], NULL);
  8139. execvp_or_die(argv);
  8140. }
  8141. /* Called after [v]fork() in run_pipe
  8142. */
  8143. static void pseudo_exec(nommu_save_t *nommu_save,
  8144. struct command *command,
  8145. char **argv_expanded) NORETURN;
  8146. static void pseudo_exec(nommu_save_t *nommu_save,
  8147. struct command *command,
  8148. char **argv_expanded)
  8149. {
  8150. #if ENABLE_HUSH_FUNCTIONS
  8151. if (command->cmd_type == CMD_FUNCDEF) {
  8152. /* Ignore funcdefs in pipes:
  8153. * true | f() { cmd }
  8154. */
  8155. _exit(0);
  8156. }
  8157. #endif
  8158. if (command->argv) {
  8159. pseudo_exec_argv(nommu_save, command->argv,
  8160. command->assignment_cnt, argv_expanded);
  8161. }
  8162. if (command->group) {
  8163. /* Cases when we are here:
  8164. * ( list )
  8165. * { list } &
  8166. * ... | ( list ) | ...
  8167. * ... | { list } | ...
  8168. */
  8169. #if BB_MMU
  8170. int rcode;
  8171. debug_printf_exec("pseudo_exec: run_list\n");
  8172. reset_traps_to_defaults();
  8173. rcode = run_list(command->group);
  8174. /* OK to leak memory by not calling free_pipe_list,
  8175. * since this process is about to exit */
  8176. _exit(rcode);
  8177. #else
  8178. re_execute_shell(&nommu_save->argv_from_re_execing,
  8179. command->group_as_string,
  8180. G.global_argv[0],
  8181. G.global_argv + 1,
  8182. NULL);
  8183. #endif
  8184. }
  8185. /* Case when we are here: ... | >file */
  8186. debug_printf_exec("pseudo_exec'ed null command\n");
  8187. _exit(EXIT_SUCCESS);
  8188. }
  8189. #if ENABLE_HUSH_JOB
  8190. static const char *get_cmdtext(struct pipe *pi)
  8191. {
  8192. char **argv;
  8193. char *p;
  8194. int len;
  8195. /* This is subtle. ->cmdtext is created only on first backgrounding.
  8196. * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
  8197. * On subsequent bg argv is trashed, but we won't use it */
  8198. if (pi->cmdtext)
  8199. return pi->cmdtext;
  8200. argv = pi->cmds[0].argv;
  8201. if (!argv) {
  8202. pi->cmdtext = xzalloc(1);
  8203. return pi->cmdtext;
  8204. }
  8205. len = 0;
  8206. do {
  8207. len += strlen(*argv) + 1;
  8208. } while (*++argv);
  8209. p = xmalloc(len);
  8210. pi->cmdtext = p;
  8211. argv = pi->cmds[0].argv;
  8212. do {
  8213. p = stpcpy(p, *argv);
  8214. *p++ = ' ';
  8215. } while (*++argv);
  8216. p[-1] = '\0';
  8217. return pi->cmdtext;
  8218. }
  8219. static void remove_job_from_table(struct pipe *pi)
  8220. {
  8221. struct pipe *prev_pipe;
  8222. if (pi == G.job_list) {
  8223. G.job_list = pi->next;
  8224. } else {
  8225. prev_pipe = G.job_list;
  8226. while (prev_pipe->next != pi)
  8227. prev_pipe = prev_pipe->next;
  8228. prev_pipe->next = pi->next;
  8229. }
  8230. G.last_jobid = 0;
  8231. if (G.job_list)
  8232. G.last_jobid = G.job_list->jobid;
  8233. }
  8234. static void delete_finished_job(struct pipe *pi)
  8235. {
  8236. remove_job_from_table(pi);
  8237. free_pipe(pi);
  8238. }
  8239. static void clean_up_last_dead_job(void)
  8240. {
  8241. if (G.job_list && !G.job_list->alive_cmds)
  8242. delete_finished_job(G.job_list);
  8243. }
  8244. static void insert_job_into_table(struct pipe *pi)
  8245. {
  8246. struct pipe *job, **jobp;
  8247. int i;
  8248. clean_up_last_dead_job();
  8249. /* Find the end of the list, and find next job ID to use */
  8250. i = 0;
  8251. jobp = &G.job_list;
  8252. while ((job = *jobp) != NULL) {
  8253. if (job->jobid > i)
  8254. i = job->jobid;
  8255. jobp = &job->next;
  8256. }
  8257. pi->jobid = i + 1;
  8258. /* Create a new job struct at the end */
  8259. job = *jobp = xmemdup(pi, sizeof(*pi));
  8260. job->next = NULL;
  8261. job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
  8262. /* Cannot copy entire pi->cmds[] vector! This causes double frees */
  8263. for (i = 0; i < pi->num_cmds; i++) {
  8264. job->cmds[i].pid = pi->cmds[i].pid;
  8265. /* all other fields are not used and stay zero */
  8266. }
  8267. job->cmdtext = xstrdup(get_cmdtext(pi));
  8268. if (G_interactive_fd)
  8269. printf("[%u] %u %s\n", job->jobid, (unsigned)job->cmds[0].pid, job->cmdtext);
  8270. G.last_jobid = job->jobid;
  8271. }
  8272. #endif /* JOB */
  8273. static int job_exited_or_stopped(struct pipe *pi)
  8274. {
  8275. int rcode, i;
  8276. if (pi->alive_cmds != pi->stopped_cmds)
  8277. return -1;
  8278. /* All processes in fg pipe have exited or stopped */
  8279. rcode = 0;
  8280. i = pi->num_cmds;
  8281. while (--i >= 0) {
  8282. rcode = pi->cmds[i].cmd_exitcode;
  8283. /* usually last process gives overall exitstatus,
  8284. * but with "set -o pipefail", last *failed* process does */
  8285. if (G.o_opt[OPT_O_PIPEFAIL] == 0 || rcode != 0)
  8286. break;
  8287. }
  8288. IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
  8289. return rcode;
  8290. }
  8291. static int process_wait_result(struct pipe *fg_pipe, pid_t childpid, int status)
  8292. {
  8293. #if ENABLE_HUSH_JOB
  8294. struct pipe *pi;
  8295. #endif
  8296. int i, dead;
  8297. dead = WIFEXITED(status) || WIFSIGNALED(status);
  8298. #if DEBUG_JOBS
  8299. if (WIFSTOPPED(status))
  8300. debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
  8301. childpid, WSTOPSIG(status), WEXITSTATUS(status));
  8302. if (WIFSIGNALED(status))
  8303. debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
  8304. childpid, WTERMSIG(status), WEXITSTATUS(status));
  8305. if (WIFEXITED(status))
  8306. debug_printf_jobs("pid %d exited, exitcode %d\n",
  8307. childpid, WEXITSTATUS(status));
  8308. #endif
  8309. /* Were we asked to wait for a fg pipe? */
  8310. if (fg_pipe) {
  8311. i = fg_pipe->num_cmds;
  8312. while (--i >= 0) {
  8313. int rcode;
  8314. debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
  8315. if (fg_pipe->cmds[i].pid != childpid)
  8316. continue;
  8317. if (dead) {
  8318. int ex;
  8319. fg_pipe->cmds[i].pid = 0;
  8320. fg_pipe->alive_cmds--;
  8321. ex = WEXITSTATUS(status);
  8322. /* bash prints killer signal's name for *last*
  8323. * process in pipe (prints just newline for SIGINT/SIGPIPE).
  8324. * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
  8325. */
  8326. if (WIFSIGNALED(status)) {
  8327. int sig = WTERMSIG(status);
  8328. #if ENABLE_HUSH_JOB
  8329. if (G.run_list_level == 1
  8330. /* ^^^^^ Do not print in nested contexts, example:
  8331. * echo `sleep 1; sh -c 'kill -9 $$'` - prints "137", NOT "Killed 137"
  8332. */
  8333. && i == fg_pipe->num_cmds-1
  8334. ) {
  8335. /* strsignal() is for bash compat. ~600 bloat versus bbox's get_signame() */
  8336. puts(sig == SIGINT || sig == SIGPIPE ? "" : strsignal(sig));
  8337. }
  8338. #endif
  8339. /* TODO: if (WCOREDUMP(status)) + " (core dumped)"; */
  8340. /* MIPS has 128 sigs (1..128), if sig==128,
  8341. * 128 + sig would result in exitcode 256 -> 0!
  8342. */
  8343. ex = 128 | sig;
  8344. }
  8345. fg_pipe->cmds[i].cmd_exitcode = ex;
  8346. } else {
  8347. fg_pipe->stopped_cmds++;
  8348. }
  8349. debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
  8350. fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
  8351. rcode = job_exited_or_stopped(fg_pipe);
  8352. if (rcode >= 0) {
  8353. /* Note: *non-interactive* bash does not continue if all processes in fg pipe
  8354. * are stopped. Testcase: "cat | cat" in a script (not on command line!)
  8355. * and "killall -STOP cat" */
  8356. if (G_interactive_fd) {
  8357. #if ENABLE_HUSH_JOB
  8358. if (fg_pipe->alive_cmds != 0)
  8359. insert_job_into_table(fg_pipe);
  8360. #endif
  8361. return rcode;
  8362. }
  8363. if (fg_pipe->alive_cmds == 0)
  8364. return rcode;
  8365. }
  8366. /* There are still running processes in the fg_pipe */
  8367. return -1;
  8368. }
  8369. /* It wasn't in fg_pipe, look for process in bg pipes */
  8370. }
  8371. #if ENABLE_HUSH_JOB
  8372. /* We were asked to wait for bg or orphaned children */
  8373. /* No need to remember exitcode in this case */
  8374. for (pi = G.job_list; pi; pi = pi->next) {
  8375. for (i = 0; i < pi->num_cmds; i++) {
  8376. if (pi->cmds[i].pid == childpid)
  8377. goto found_pi_and_prognum;
  8378. }
  8379. }
  8380. /* Happens when shell is used as init process (init=/bin/sh) */
  8381. debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
  8382. return -1; /* this wasn't a process from fg_pipe */
  8383. found_pi_and_prognum:
  8384. if (dead) {
  8385. /* child exited */
  8386. int rcode = WEXITSTATUS(status);
  8387. if (WIFSIGNALED(status))
  8388. /* NB: not 128 + sig, MIPS has sig 128 */
  8389. rcode = 128 | WTERMSIG(status);
  8390. pi->cmds[i].cmd_exitcode = rcode;
  8391. if (G.last_bg_pid == pi->cmds[i].pid)
  8392. G.last_bg_pid_exitcode = rcode;
  8393. pi->cmds[i].pid = 0;
  8394. pi->alive_cmds--;
  8395. if (!pi->alive_cmds) {
  8396. # if ENABLE_HUSH_BASH_COMPAT
  8397. G.dead_job_exitcode = job_exited_or_stopped(pi);
  8398. # endif
  8399. if (G_interactive_fd) {
  8400. printf(JOB_STATUS_FORMAT, pi->jobid,
  8401. "Done", pi->cmdtext);
  8402. delete_finished_job(pi);
  8403. } else {
  8404. /*
  8405. * bash deletes finished jobs from job table only in interactive mode,
  8406. * after "jobs" cmd, or if pid of a new process matches one of the old ones
  8407. * (see cleanup_dead_jobs(), delete_old_job(), J_NOTIFIED in bash source).
  8408. * Testcase script: "(exit 3) & sleep 1; wait %1; echo $?" prints 3 in bash.
  8409. * We only retain one "dead" job, if it's the single job on the list.
  8410. * This covers most of real-world scenarios where this is useful.
  8411. */
  8412. if (pi != G.job_list)
  8413. delete_finished_job(pi);
  8414. }
  8415. }
  8416. } else {
  8417. /* child stopped */
  8418. pi->stopped_cmds++;
  8419. }
  8420. #endif
  8421. return -1; /* this wasn't a process from fg_pipe */
  8422. }
  8423. /* Check to see if any processes have exited -- if they have,
  8424. * figure out why and see if a job has completed.
  8425. *
  8426. * If non-NULL fg_pipe: wait for its completion or stop.
  8427. * Return its exitcode or zero if stopped.
  8428. *
  8429. * Alternatively (fg_pipe == NULL, waitfor_pid != 0):
  8430. * waitpid(WNOHANG), if waitfor_pid exits or stops, return exitcode+1,
  8431. * else return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
  8432. * or 0 if no children changed status.
  8433. *
  8434. * Alternatively (fg_pipe == NULL, waitfor_pid == 0),
  8435. * return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
  8436. * or 0 if no children changed status.
  8437. */
  8438. static int checkjobs(struct pipe *fg_pipe, pid_t waitfor_pid)
  8439. {
  8440. int attributes;
  8441. int status;
  8442. int rcode = 0;
  8443. debug_printf_jobs("checkjobs %p\n", fg_pipe);
  8444. attributes = WUNTRACED;
  8445. if (fg_pipe == NULL)
  8446. attributes |= WNOHANG;
  8447. errno = 0;
  8448. #if ENABLE_HUSH_FAST
  8449. if (G.handled_SIGCHLD == G.count_SIGCHLD) {
  8450. //bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
  8451. //getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
  8452. /* There was neither fork nor SIGCHLD since last waitpid */
  8453. /* Avoid doing waitpid syscall if possible */
  8454. if (!G.we_have_children) {
  8455. errno = ECHILD;
  8456. return -1;
  8457. }
  8458. if (fg_pipe == NULL) { /* is WNOHANG set? */
  8459. /* We have children, but they did not exit
  8460. * or stop yet (we saw no SIGCHLD) */
  8461. return 0;
  8462. }
  8463. /* else: !WNOHANG, waitpid will block, can't short-circuit */
  8464. }
  8465. #endif
  8466. /* Do we do this right?
  8467. * bash-3.00# sleep 20 | false
  8468. * <ctrl-Z pressed>
  8469. * [3]+ Stopped sleep 20 | false
  8470. * bash-3.00# echo $?
  8471. * 1 <========== bg pipe is not fully done, but exitcode is already known!
  8472. * [hush 1.14.0: yes we do it right]
  8473. */
  8474. while (1) {
  8475. pid_t childpid;
  8476. #if ENABLE_HUSH_FAST
  8477. int i;
  8478. i = G.count_SIGCHLD;
  8479. #endif
  8480. childpid = waitpid(-1, &status, attributes);
  8481. if (childpid <= 0) {
  8482. if (childpid && errno != ECHILD)
  8483. bb_simple_perror_msg("waitpid");
  8484. #if ENABLE_HUSH_FAST
  8485. else { /* Until next SIGCHLD, waitpid's are useless */
  8486. G.we_have_children = (childpid == 0);
  8487. G.handled_SIGCHLD = i;
  8488. //bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
  8489. }
  8490. #endif
  8491. /* ECHILD (no children), or 0 (no change in children status) */
  8492. rcode = childpid;
  8493. break;
  8494. }
  8495. rcode = process_wait_result(fg_pipe, childpid, status);
  8496. if (rcode >= 0) {
  8497. /* fg_pipe exited or stopped */
  8498. break;
  8499. }
  8500. if (childpid == waitfor_pid) { /* "wait PID" */
  8501. debug_printf_exec("childpid==waitfor_pid:%d status:0x%08x\n", childpid, status);
  8502. rcode = WEXITSTATUS(status);
  8503. if (WIFSIGNALED(status))
  8504. rcode = 128 | WTERMSIG(status);
  8505. if (WIFSTOPPED(status))
  8506. /* bash: "cmd & wait $!" and cmd stops: $? = 128 | stopsig */
  8507. rcode = 128 | WSTOPSIG(status);
  8508. rcode++;
  8509. break; /* "wait PID" called us, give it exitcode+1 */
  8510. }
  8511. #if ENABLE_HUSH_BASH_COMPAT
  8512. if (-1 == waitfor_pid /* "wait -n" (wait for any one job) */
  8513. && G.dead_job_exitcode >= 0 /* some job did finish */
  8514. ) {
  8515. debug_printf_exec("waitfor_pid:-1\n");
  8516. rcode = G.dead_job_exitcode + 1;
  8517. break;
  8518. }
  8519. #endif
  8520. /* This wasn't one of our processes, or */
  8521. /* fg_pipe still has running processes, do waitpid again */
  8522. } /* while (waitpid succeeds)... */
  8523. return rcode;
  8524. }
  8525. #if ENABLE_HUSH_JOB
  8526. static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
  8527. {
  8528. pid_t p;
  8529. int rcode = checkjobs(fg_pipe, 0 /*(no pid to wait for)*/);
  8530. if (G_saved_tty_pgrp) {
  8531. /* Job finished, move the shell to the foreground */
  8532. p = getpgrp(); /* our process group id */
  8533. debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
  8534. tcsetpgrp(G_interactive_fd, p);
  8535. }
  8536. return rcode;
  8537. }
  8538. #endif
  8539. /* Start all the jobs, but don't wait for anything to finish.
  8540. * See checkjobs().
  8541. *
  8542. * Return code is normally -1, when the caller has to wait for children
  8543. * to finish to determine the exit status of the pipe. If the pipe
  8544. * is a simple builtin command, however, the action is done by the
  8545. * time run_pipe returns, and the exit code is provided as the
  8546. * return value.
  8547. *
  8548. * Returns -1 only if started some children. IOW: we have to
  8549. * mask out retvals of builtins etc with 0xff!
  8550. *
  8551. * The only case when we do not need to [v]fork is when the pipe
  8552. * is single, non-backgrounded, non-subshell command. Examples:
  8553. * cmd ; ... { list } ; ...
  8554. * cmd && ... { list } && ...
  8555. * cmd || ... { list } || ...
  8556. * If it is, then we can run cmd as a builtin, NOFORK,
  8557. * or (if SH_STANDALONE) an applet, and we can run the { list }
  8558. * with run_list. If it isn't one of these, we fork and exec cmd.
  8559. *
  8560. * Cases when we must fork:
  8561. * non-single: cmd | cmd
  8562. * backgrounded: cmd & { list } &
  8563. * subshell: ( list ) [&]
  8564. */
  8565. #if !ENABLE_HUSH_MODE_X
  8566. #define redirect_and_varexp_helper(command, sqp, argv_expanded) \
  8567. redirect_and_varexp_helper(command, sqp)
  8568. #endif
  8569. static int redirect_and_varexp_helper(
  8570. struct command *command,
  8571. struct squirrel **sqp,
  8572. char **argv_expanded)
  8573. {
  8574. /* Assignments occur before redirects. Try:
  8575. * a=`sleep 1` sleep 2 3>/qwe/rty
  8576. */
  8577. char **new_env = expand_assignments(command->argv, command->assignment_cnt);
  8578. dump_cmd_in_x_mode(new_env);
  8579. dump_cmd_in_x_mode(argv_expanded);
  8580. /* this takes ownership of new_env[i] elements, and frees new_env: */
  8581. set_vars_and_save_old(new_env);
  8582. return setup_redirects(command, sqp);
  8583. }
  8584. static NOINLINE int run_pipe(struct pipe *pi)
  8585. {
  8586. static const char *const null_ptr = NULL;
  8587. int cmd_no;
  8588. int next_infd;
  8589. struct command *command;
  8590. char **argv_expanded;
  8591. char **argv;
  8592. struct squirrel *squirrel = NULL;
  8593. int rcode;
  8594. debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
  8595. debug_enter();
  8596. /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
  8597. * Result should be 3 lines: q w e, qwe, q w e
  8598. */
  8599. if (G.ifs_whitespace != G.ifs)
  8600. free(G.ifs_whitespace);
  8601. G.ifs = get_local_var_value("IFS");
  8602. if (G.ifs) {
  8603. char *p;
  8604. G.ifs_whitespace = (char*)G.ifs;
  8605. p = skip_whitespace(G.ifs);
  8606. if (*p) {
  8607. /* Not all $IFS is whitespace */
  8608. char *d;
  8609. int len = p - G.ifs;
  8610. p = skip_non_whitespace(p);
  8611. G.ifs_whitespace = xmalloc(len + strlen(p) + 1); /* can overestimate */
  8612. d = mempcpy(G.ifs_whitespace, G.ifs, len);
  8613. while (*p) {
  8614. if (isspace(*p))
  8615. *d++ = *p;
  8616. p++;
  8617. }
  8618. *d = '\0';
  8619. }
  8620. } else {
  8621. G.ifs = defifs;
  8622. G.ifs_whitespace = (char*)G.ifs;
  8623. }
  8624. IF_HUSH_JOB(pi->pgrp = -1;)
  8625. pi->stopped_cmds = 0;
  8626. command = &pi->cmds[0];
  8627. argv_expanded = NULL;
  8628. if (pi->num_cmds != 1
  8629. || pi->followup == PIPE_BG
  8630. || command->cmd_type == CMD_SUBSHELL
  8631. ) {
  8632. goto must_fork;
  8633. }
  8634. pi->alive_cmds = 1;
  8635. debug_printf_exec(": group:%p argv:'%s'\n",
  8636. command->group, command->argv ? command->argv[0] : "NONE");
  8637. if (command->group) {
  8638. #if ENABLE_HUSH_FUNCTIONS
  8639. if (command->cmd_type == CMD_FUNCDEF) {
  8640. /* "executing" func () { list } */
  8641. struct function *funcp;
  8642. funcp = new_function(command->argv[0]);
  8643. /* funcp->name is already set to argv[0] */
  8644. funcp->body = command->group;
  8645. # if !BB_MMU
  8646. funcp->body_as_string = command->group_as_string;
  8647. command->group_as_string = NULL;
  8648. # endif
  8649. command->group = NULL;
  8650. command->argv[0] = NULL;
  8651. debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
  8652. funcp->parent_cmd = command;
  8653. command->child_func = funcp;
  8654. debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
  8655. debug_leave();
  8656. return EXIT_SUCCESS;
  8657. }
  8658. #endif
  8659. /* { list } */
  8660. debug_printf_exec("non-subshell group\n");
  8661. rcode = 1; /* exitcode if redir failed */
  8662. if (setup_redirects(command, &squirrel) == 0) {
  8663. debug_printf_exec(": run_list\n");
  8664. //FIXME: we need to pass squirrel down into run_list()
  8665. //for SH_STANDALONE case, or else this construct:
  8666. // { find /proc/self/fd; true; } >FILE; cmd2
  8667. //has no way of closing saved fd#1 for "find",
  8668. //and in SH_STANDALONE mode, "find" is not execed,
  8669. //therefore CLOEXEC on saved fd does not help.
  8670. rcode = run_list(command->group) & 0xff;
  8671. }
  8672. restore_redirects(squirrel);
  8673. IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
  8674. debug_leave();
  8675. debug_printf_exec("run_pipe: return %d\n", rcode);
  8676. return rcode;
  8677. }
  8678. argv = command->argv ? command->argv : (char **) &null_ptr;
  8679. {
  8680. const struct built_in_command *x;
  8681. IF_HUSH_FUNCTIONS(const struct function *funcp;)
  8682. IF_NOT_HUSH_FUNCTIONS(enum { funcp = 0 };)
  8683. struct variable **sv_shadowed;
  8684. struct variable *old_vars;
  8685. #if ENABLE_HUSH_LINENO_VAR
  8686. G.execute_lineno = command->lineno;
  8687. #endif
  8688. if (argv[command->assignment_cnt] == NULL) {
  8689. /* Assignments, but no command.
  8690. * Ensure redirects take effect (that is, create files).
  8691. * Try "a=t >file"
  8692. */
  8693. unsigned i;
  8694. G.expand_exitcode = 0;
  8695. only_assignments:
  8696. rcode = setup_redirects(command, &squirrel);
  8697. restore_redirects(squirrel);
  8698. /* Set shell variables */
  8699. i = 0;
  8700. while (i < command->assignment_cnt) {
  8701. char *p = expand_string_to_string(argv[i],
  8702. EXP_FLAG_ESC_GLOB_CHARS,
  8703. /*unbackslash:*/ 1
  8704. );
  8705. #if ENABLE_HUSH_MODE_X
  8706. if (G_x_mode) {
  8707. char *eq;
  8708. if (i == 0)
  8709. x_mode_prefix();
  8710. x_mode_addchr(' ');
  8711. eq = strchrnul(p, '=');
  8712. if (*eq) eq++;
  8713. x_mode_addblock(p, (eq - p));
  8714. x_mode_print_optionally_squoted(eq);
  8715. x_mode_flush();
  8716. }
  8717. #endif
  8718. debug_printf_env("set shell var:'%s'->'%s'\n", *argv, p);
  8719. if (set_local_var(p, /*flag:*/ 0)) {
  8720. /* assignment to readonly var / putenv error? */
  8721. rcode = 1;
  8722. }
  8723. i++;
  8724. }
  8725. /* Redirect error sets $? to 1. Otherwise,
  8726. * if evaluating assignment value set $?, retain it.
  8727. * Else, clear $?:
  8728. * false; q=`exit 2`; echo $? - should print 2
  8729. * false; x=1; echo $? - should print 0
  8730. * Because of the 2nd case, we can't just use G.last_exitcode.
  8731. */
  8732. if (rcode == 0)
  8733. rcode = G.expand_exitcode;
  8734. IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
  8735. debug_leave();
  8736. debug_printf_exec("run_pipe: return %d\n", rcode);
  8737. return rcode;
  8738. }
  8739. /* Expand the rest into (possibly) many strings each */
  8740. #if defined(CMD_TEST2_SINGLEWORD_NOGLOB)
  8741. if (command->cmd_type == CMD_TEST2_SINGLEWORD_NOGLOB)
  8742. argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
  8743. else
  8744. #endif
  8745. #if defined(CMD_SINGLEWORD_NOGLOB)
  8746. if (command->cmd_type == CMD_SINGLEWORD_NOGLOB)
  8747. argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
  8748. else
  8749. #endif
  8750. argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
  8751. /* If someone gives us an empty string: `cmd with empty output` */
  8752. if (!argv_expanded[0]) {
  8753. free(argv_expanded);
  8754. /* `false` still has to set exitcode 1 */
  8755. G.expand_exitcode = G.last_exitcode;
  8756. goto only_assignments;
  8757. }
  8758. old_vars = NULL;
  8759. sv_shadowed = G.shadowed_vars_pp;
  8760. /* Check if argv[0] matches any functions (this goes before bltins) */
  8761. IF_HUSH_FUNCTIONS(funcp = find_function(argv_expanded[0]);)
  8762. IF_HUSH_FUNCTIONS(x = NULL;)
  8763. IF_HUSH_FUNCTIONS(if (!funcp))
  8764. x = find_builtin(argv_expanded[0]);
  8765. if (x || funcp) {
  8766. if (x && x->b_function == builtin_exec && argv_expanded[1] == NULL) {
  8767. debug_printf("exec with redirects only\n");
  8768. /*
  8769. * Variable assignments are executed, but then "forgotten":
  8770. * a=`sleep 1;echo A` exec 3>&-; echo $a
  8771. * sleeps, but prints nothing.
  8772. */
  8773. enter_var_nest_level();
  8774. G.shadowed_vars_pp = &old_vars;
  8775. rcode = redirect_and_varexp_helper(command,
  8776. /*squirrel:*/ ERR_PTR,
  8777. argv_expanded
  8778. );
  8779. G.shadowed_vars_pp = sv_shadowed;
  8780. /* rcode=1 can be if redir file can't be opened */
  8781. goto clean_up_and_ret1;
  8782. }
  8783. /* Bump var nesting, or this will leak exported $a:
  8784. * a=b true; env | grep ^a=
  8785. */
  8786. enter_var_nest_level();
  8787. /* Collect all variables "shadowed" by helper
  8788. * (IOW: old vars overridden by "var1=val1 var2=val2 cmd..." syntax)
  8789. * into old_vars list:
  8790. */
  8791. G.shadowed_vars_pp = &old_vars;
  8792. rcode = redirect_and_varexp_helper(command, &squirrel, argv_expanded);
  8793. if (rcode == 0) {
  8794. if (!funcp) {
  8795. /* Do not collect *to old_vars list* vars shadowed
  8796. * by e.g. "local VAR" builtin (collect them
  8797. * in the previously nested list instead):
  8798. * don't want them to be restored immediately
  8799. * after "local" completes.
  8800. */
  8801. G.shadowed_vars_pp = sv_shadowed;
  8802. debug_printf_exec(": builtin '%s' '%s'...\n",
  8803. x->b_cmd, argv_expanded[1]);
  8804. fflush_all();
  8805. rcode = x->b_function(argv_expanded) & 0xff;
  8806. fflush_all();
  8807. }
  8808. #if ENABLE_HUSH_FUNCTIONS
  8809. else {
  8810. debug_printf_exec(": function '%s' '%s'...\n",
  8811. funcp->name, argv_expanded[1]);
  8812. rcode = run_function(funcp, argv_expanded) & 0xff;
  8813. /*
  8814. * But do collect *to old_vars list* vars shadowed
  8815. * within function execution. To that end, restore
  8816. * this pointer _after_ function run:
  8817. */
  8818. G.shadowed_vars_pp = sv_shadowed;
  8819. }
  8820. #endif
  8821. }
  8822. } else
  8823. if (ENABLE_FEATURE_SH_NOFORK && NUM_APPLETS > 1) {
  8824. int n = find_applet_by_name(argv_expanded[0]);
  8825. if (n < 0 || !APPLET_IS_NOFORK(n))
  8826. goto must_fork;
  8827. enter_var_nest_level();
  8828. /* Collect all variables "shadowed" by helper into old_vars list */
  8829. G.shadowed_vars_pp = &old_vars;
  8830. rcode = redirect_and_varexp_helper(command, &squirrel, argv_expanded);
  8831. G.shadowed_vars_pp = sv_shadowed;
  8832. if (rcode == 0) {
  8833. debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
  8834. argv_expanded[0], argv_expanded[1]);
  8835. /*
  8836. * Note: signals (^C) can't interrupt here.
  8837. * We remember them and they will be acted upon
  8838. * after applet returns.
  8839. * This makes applets which can run for a long time
  8840. * and/or wait for user input ineligible for NOFORK:
  8841. * for example, "yes" or "rm" (rm -i waits for input).
  8842. */
  8843. rcode = run_nofork_applet(n, argv_expanded);
  8844. }
  8845. } else
  8846. goto must_fork;
  8847. restore_redirects(squirrel);
  8848. clean_up_and_ret1:
  8849. leave_var_nest_level();
  8850. add_vars(old_vars);
  8851. /*
  8852. * Try "usleep 99999999" + ^C + "echo $?"
  8853. * with FEATURE_SH_NOFORK=y.
  8854. */
  8855. if (!funcp) {
  8856. /* It was builtin or nofork.
  8857. * if this would be a real fork/execed program,
  8858. * it should have died if a fatal sig was received.
  8859. * But OTOH, there was no separate process,
  8860. * the sig was sent to _shell_, not to non-existing
  8861. * child.
  8862. * Let's just handle ^C only, this one is obvious:
  8863. * we aren't ok with exitcode 0 when ^C was pressed
  8864. * during builtin/nofork.
  8865. */
  8866. if (sigismember(&G.pending_set, SIGINT))
  8867. rcode = 128 | SIGINT;
  8868. }
  8869. free(argv_expanded);
  8870. IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
  8871. debug_leave();
  8872. debug_printf_exec("run_pipe return %d\n", rcode);
  8873. return rcode;
  8874. }
  8875. must_fork:
  8876. /* NB: argv_expanded may already be created, and that
  8877. * might include `cmd` runs! Do not rerun it! We *must*
  8878. * use argv_expanded if it's non-NULL */
  8879. /* Going to fork a child per each pipe member */
  8880. pi->alive_cmds = 0;
  8881. next_infd = 0;
  8882. cmd_no = 0;
  8883. while (cmd_no < pi->num_cmds) {
  8884. struct fd_pair pipefds;
  8885. #if !BB_MMU
  8886. int sv_var_nest_level = G.var_nest_level;
  8887. volatile nommu_save_t nommu_save;
  8888. nommu_save.old_vars = NULL;
  8889. nommu_save.argv = NULL;
  8890. nommu_save.argv_from_re_execing = NULL;
  8891. #endif
  8892. command = &pi->cmds[cmd_no];
  8893. cmd_no++;
  8894. if (command->argv) {
  8895. debug_printf_exec(": pipe member '%s' '%s'...\n",
  8896. command->argv[0], command->argv[1]);
  8897. } else {
  8898. debug_printf_exec(": pipe member with no argv\n");
  8899. }
  8900. /* pipes are inserted between pairs of commands */
  8901. pipefds.rd = 0;
  8902. pipefds.wr = 1;
  8903. if (cmd_no < pi->num_cmds)
  8904. xpiped_pair(pipefds);
  8905. #if ENABLE_HUSH_LINENO_VAR
  8906. G.execute_lineno = command->lineno;
  8907. #endif
  8908. command->pid = BB_MMU ? fork() : vfork();
  8909. if (!command->pid) { /* child */
  8910. #if ENABLE_HUSH_JOB
  8911. disable_restore_tty_pgrp_on_exit();
  8912. CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
  8913. /* Every child adds itself to new process group
  8914. * with pgid == pid_of_first_child_in_pipe */
  8915. if (G.run_list_level == 1 && G_interactive_fd) {
  8916. pid_t pgrp;
  8917. pgrp = pi->pgrp;
  8918. if (pgrp < 0) /* true for 1st process only */
  8919. pgrp = getpid();
  8920. if (setpgid(0, pgrp) == 0
  8921. && pi->followup != PIPE_BG
  8922. && G_saved_tty_pgrp /* we have ctty */
  8923. ) {
  8924. /* We do it in *every* child, not just first,
  8925. * to avoid races */
  8926. tcsetpgrp(G_interactive_fd, pgrp);
  8927. }
  8928. }
  8929. #endif
  8930. if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
  8931. /* 1st cmd in backgrounded pipe
  8932. * should have its stdin /dev/null'ed */
  8933. close(0);
  8934. if (open(bb_dev_null, O_RDONLY))
  8935. xopen("/", O_RDONLY);
  8936. } else {
  8937. xmove_fd(next_infd, 0);
  8938. }
  8939. xmove_fd(pipefds.wr, 1);
  8940. if (pipefds.rd > 1)
  8941. close(pipefds.rd);
  8942. /* Like bash, explicit redirects override pipes,
  8943. * and the pipe fd (fd#1) is available for dup'ing:
  8944. * "cmd1 2>&1 | cmd2": fd#1 is duped to fd#2, thus stderr
  8945. * of cmd1 goes into pipe.
  8946. */
  8947. if (setup_redirects(command, NULL)) {
  8948. /* Happens when redir file can't be opened:
  8949. * $ hush -c 'echo FOO >&2 | echo BAR 3>/qwe/rty; echo BAZ'
  8950. * FOO
  8951. * hush: can't open '/qwe/rty': No such file or directory
  8952. * BAZ
  8953. * (echo BAR is not executed, it hits _exit(1) below)
  8954. */
  8955. _exit(1);
  8956. }
  8957. /* Stores to nommu_save list of env vars putenv'ed
  8958. * (NOMMU, on MMU we don't need that) */
  8959. /* cast away volatility... */
  8960. pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
  8961. /* pseudo_exec() does not return */
  8962. }
  8963. /* parent or error */
  8964. #if ENABLE_HUSH_FAST
  8965. G.count_SIGCHLD++;
  8966. //bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
  8967. #endif
  8968. enable_restore_tty_pgrp_on_exit();
  8969. #if !BB_MMU
  8970. /* Clean up after vforked child */
  8971. free(nommu_save.argv);
  8972. free(nommu_save.argv_from_re_execing);
  8973. G.var_nest_level = sv_var_nest_level;
  8974. remove_nested_vars();
  8975. add_vars(nommu_save.old_vars);
  8976. #endif
  8977. free(argv_expanded);
  8978. argv_expanded = NULL;
  8979. if (command->pid < 0) { /* [v]fork failed */
  8980. /* Clearly indicate, was it fork or vfork */
  8981. bb_simple_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
  8982. } else {
  8983. pi->alive_cmds++;
  8984. #if ENABLE_HUSH_JOB
  8985. /* Second and next children need to know pid of first one */
  8986. if (pi->pgrp < 0)
  8987. pi->pgrp = command->pid;
  8988. #endif
  8989. }
  8990. if (cmd_no > 1)
  8991. close(next_infd);
  8992. if (cmd_no < pi->num_cmds)
  8993. close(pipefds.wr);
  8994. /* Pass read (output) pipe end to next iteration */
  8995. next_infd = pipefds.rd;
  8996. }
  8997. if (!pi->alive_cmds) {
  8998. debug_leave();
  8999. debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
  9000. return 1;
  9001. }
  9002. debug_leave();
  9003. debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
  9004. return -1;
  9005. }
  9006. /* NB: called by pseudo_exec, and therefore must not modify any
  9007. * global data until exec/_exit (we can be a child after vfork!) */
  9008. static int run_list(struct pipe *pi)
  9009. {
  9010. #if ENABLE_HUSH_CASE
  9011. char *case_word = NULL;
  9012. #endif
  9013. #if ENABLE_HUSH_LOOPS
  9014. struct pipe *loop_top = NULL;
  9015. char **for_lcur = NULL;
  9016. char **for_list = NULL;
  9017. #endif
  9018. smallint last_followup;
  9019. smalluint rcode;
  9020. #if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
  9021. smalluint cond_code = 0;
  9022. #else
  9023. enum { cond_code = 0 };
  9024. #endif
  9025. #if HAS_KEYWORDS
  9026. smallint rword; /* RES_foo */
  9027. smallint last_rword; /* ditto */
  9028. #endif
  9029. debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
  9030. debug_enter();
  9031. #if ENABLE_HUSH_LOOPS
  9032. /* Check syntax for "for" */
  9033. {
  9034. struct pipe *cpipe;
  9035. for (cpipe = pi; cpipe; cpipe = cpipe->next) {
  9036. if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
  9037. continue;
  9038. /* current word is FOR or IN (BOLD in comments below) */
  9039. if (cpipe->next == NULL) {
  9040. syntax_error("malformed for");
  9041. debug_leave();
  9042. debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
  9043. return 1;
  9044. }
  9045. /* "FOR v; do ..." and "for v IN a b; do..." are ok */
  9046. if (cpipe->next->res_word == RES_DO)
  9047. continue;
  9048. /* next word is not "do". It must be "in" then ("FOR v in ...") */
  9049. if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
  9050. || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
  9051. ) {
  9052. syntax_error("malformed for");
  9053. debug_leave();
  9054. debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
  9055. return 1;
  9056. }
  9057. }
  9058. }
  9059. #endif
  9060. /* Past this point, all code paths should jump to ret: label
  9061. * in order to return, no direct "return" statements please.
  9062. * This helps to ensure that no memory is leaked. */
  9063. #if ENABLE_HUSH_JOB
  9064. G.run_list_level++;
  9065. #endif
  9066. #if HAS_KEYWORDS
  9067. rword = RES_NONE;
  9068. last_rword = RES_XXXX;
  9069. #endif
  9070. last_followup = PIPE_SEQ;
  9071. rcode = G.last_exitcode;
  9072. /* Go through list of pipes, (maybe) executing them. */
  9073. for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
  9074. int r;
  9075. int sv_errexit_depth;
  9076. if (G.flag_SIGINT)
  9077. break;
  9078. if (G_flag_return_in_progress == 1)
  9079. break;
  9080. IF_HAS_KEYWORDS(rword = pi->res_word;)
  9081. debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
  9082. rword, cond_code, last_rword);
  9083. sv_errexit_depth = G.errexit_depth;
  9084. if (
  9085. #if ENABLE_HUSH_IF
  9086. rword == RES_IF || rword == RES_ELIF ||
  9087. #endif
  9088. pi->followup != PIPE_SEQ
  9089. ) {
  9090. G.errexit_depth++;
  9091. }
  9092. #if ENABLE_HUSH_LOOPS
  9093. if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
  9094. && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
  9095. ) {
  9096. /* start of a loop: remember where loop starts */
  9097. loop_top = pi;
  9098. G.depth_of_loop++;
  9099. }
  9100. #endif
  9101. /* Still in the same "if...", "then..." or "do..." branch? */
  9102. if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
  9103. if ((rcode == 0 && last_followup == PIPE_OR)
  9104. || (rcode != 0 && last_followup == PIPE_AND)
  9105. ) {
  9106. /* It is "<true> || CMD" or "<false> && CMD"
  9107. * and we should not execute CMD */
  9108. debug_printf_exec("skipped cmd because of || or &&\n");
  9109. last_followup = pi->followup;
  9110. goto dont_check_jobs_but_continue;
  9111. }
  9112. }
  9113. last_followup = pi->followup;
  9114. IF_HAS_KEYWORDS(last_rword = rword;)
  9115. #if ENABLE_HUSH_IF
  9116. if (cond_code) {
  9117. if (rword == RES_THEN) {
  9118. /* if false; then ... fi has exitcode 0! */
  9119. G.last_exitcode = rcode = EXIT_SUCCESS;
  9120. /* "if <false> THEN cmd": skip cmd */
  9121. continue;
  9122. }
  9123. } else {
  9124. if (rword == RES_ELSE || rword == RES_ELIF) {
  9125. /* "if <true> then ... ELSE/ELIF cmd":
  9126. * skip cmd and all following ones */
  9127. break;
  9128. }
  9129. }
  9130. #endif
  9131. #if ENABLE_HUSH_LOOPS
  9132. if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
  9133. if (!for_lcur) {
  9134. /* first loop through for */
  9135. static const char encoded_dollar_at[] ALIGN1 = {
  9136. SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
  9137. }; /* encoded representation of "$@" */
  9138. static const char *const encoded_dollar_at_argv[] = {
  9139. encoded_dollar_at, NULL
  9140. }; /* argv list with one element: "$@" */
  9141. char **vals;
  9142. G.last_exitcode = rcode = EXIT_SUCCESS;
  9143. vals = (char**)encoded_dollar_at_argv;
  9144. if (pi->next->res_word == RES_IN) {
  9145. /* if no variable values after "in" we skip "for" */
  9146. if (!pi->next->cmds[0].argv) {
  9147. debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
  9148. break;
  9149. }
  9150. vals = pi->next->cmds[0].argv;
  9151. } /* else: "for var; do..." -> assume "$@" list */
  9152. /* create list of variable values */
  9153. debug_print_strings("for_list made from", vals);
  9154. for_list = expand_strvec_to_strvec(vals);
  9155. for_lcur = for_list;
  9156. debug_print_strings("for_list", for_list);
  9157. }
  9158. if (!*for_lcur) {
  9159. /* "for" loop is over, clean up */
  9160. free(for_list);
  9161. for_list = NULL;
  9162. for_lcur = NULL;
  9163. break;
  9164. }
  9165. /* Insert next value from for_lcur */
  9166. /* note: *for_lcur already has quotes removed, $var expanded, etc */
  9167. set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*flag:*/ 0);
  9168. continue;
  9169. }
  9170. if (rword == RES_IN) {
  9171. continue; /* "for v IN list;..." - "in" has no cmds anyway */
  9172. }
  9173. if (rword == RES_DONE) {
  9174. continue; /* "done" has no cmds too */
  9175. }
  9176. #endif
  9177. #if ENABLE_HUSH_CASE
  9178. if (rword == RES_CASE) {
  9179. debug_printf_exec("CASE cond_code:%d\n", cond_code);
  9180. case_word = expand_string_to_string(pi->cmds->argv[0],
  9181. EXP_FLAG_ESC_GLOB_CHARS, /*unbackslash:*/ 1);
  9182. debug_printf_exec("CASE word1:'%s'\n", case_word);
  9183. //unbackslash(case_word);
  9184. //debug_printf_exec("CASE word2:'%s'\n", case_word);
  9185. continue;
  9186. }
  9187. if (rword == RES_MATCH) {
  9188. char **argv;
  9189. debug_printf_exec("MATCH cond_code:%d\n", cond_code);
  9190. if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
  9191. break;
  9192. /* all prev words didn't match, does this one match? */
  9193. argv = pi->cmds->argv;
  9194. while (*argv) {
  9195. char *pattern;
  9196. debug_printf_exec("expand_string_to_string('%s')\n", *argv);
  9197. pattern = expand_string_to_string(*argv,
  9198. EXP_FLAG_ESC_GLOB_CHARS,
  9199. /*unbackslash:*/ 0
  9200. );
  9201. /* TODO: which FNM_xxx flags to use? */
  9202. cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
  9203. debug_printf_exec("fnmatch(pattern:'%s',str:'%s'):%d\n",
  9204. pattern, case_word, cond_code);
  9205. free(pattern);
  9206. if (cond_code == 0) {
  9207. /* match! we will execute this branch */
  9208. free(case_word);
  9209. case_word = NULL; /* make future "word)" stop */
  9210. break;
  9211. }
  9212. argv++;
  9213. }
  9214. continue;
  9215. }
  9216. if (rword == RES_CASE_BODY) { /* inside of a case branch */
  9217. debug_printf_exec("CASE_BODY cond_code:%d\n", cond_code);
  9218. if (cond_code != 0)
  9219. continue; /* not matched yet, skip this pipe */
  9220. }
  9221. if (rword == RES_ESAC) {
  9222. debug_printf_exec("ESAC cond_code:%d\n", cond_code);
  9223. if (case_word) {
  9224. /* "case" did not match anything: still set $? (to 0) */
  9225. G.last_exitcode = rcode = EXIT_SUCCESS;
  9226. }
  9227. }
  9228. #endif
  9229. /* Just pressing <enter> in shell should check for jobs.
  9230. * OTOH, in non-interactive shell this is useless
  9231. * and only leads to extra job checks */
  9232. if (pi->num_cmds == 0) {
  9233. if (G_interactive_fd)
  9234. goto check_jobs_and_continue;
  9235. continue;
  9236. }
  9237. /* After analyzing all keywords and conditions, we decided
  9238. * to execute this pipe. NB: have to do checkjobs(NULL)
  9239. * after run_pipe to collect any background children,
  9240. * even if list execution is to be stopped. */
  9241. debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
  9242. #if ENABLE_HUSH_LOOPS
  9243. G.flag_break_continue = 0;
  9244. #endif
  9245. rcode = r = run_pipe(pi); /* NB: rcode is a smalluint, r is int */
  9246. if (r != -1) {
  9247. /* We ran a builtin, function, or group.
  9248. * rcode is already known
  9249. * and we don't need to wait for anything. */
  9250. debug_printf_exec(": builtin/func exitcode %d\n", rcode);
  9251. G.last_exitcode = rcode;
  9252. check_and_run_traps();
  9253. #if ENABLE_HUSH_TRAP && ENABLE_HUSH_FUNCTIONS
  9254. rcode = G.last_exitcode; /* "return" in trap can change it, read back */
  9255. #endif
  9256. #if ENABLE_HUSH_LOOPS
  9257. /* Was it "break" or "continue"? */
  9258. if (G.flag_break_continue) {
  9259. smallint fbc = G.flag_break_continue;
  9260. /* We might fall into outer *loop*,
  9261. * don't want to break it too */
  9262. if (loop_top) {
  9263. G.depth_break_continue--;
  9264. if (G.depth_break_continue == 0)
  9265. G.flag_break_continue = 0;
  9266. /* else: e.g. "continue 2" should *break* once, *then* continue */
  9267. } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
  9268. if (G.depth_break_continue != 0 || fbc == BC_BREAK) {
  9269. checkjobs(NULL, 0 /*(no pid to wait for)*/);
  9270. break;
  9271. }
  9272. /* "continue": simulate end of loop */
  9273. rword = RES_DONE;
  9274. continue;
  9275. }
  9276. #endif
  9277. if (G_flag_return_in_progress == 1) {
  9278. checkjobs(NULL, 0 /*(no pid to wait for)*/);
  9279. break;
  9280. }
  9281. } else if (pi->followup == PIPE_BG) {
  9282. /* What does bash do with attempts to background builtins? */
  9283. /* even bash 3.2 doesn't do that well with nested bg:
  9284. * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
  9285. * I'm NOT treating inner &'s as jobs */
  9286. #if ENABLE_HUSH_JOB
  9287. if (G.run_list_level == 1)
  9288. insert_job_into_table(pi);
  9289. #endif
  9290. /* Last command's pid goes to $! */
  9291. G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
  9292. G.last_bg_pid_exitcode = 0;
  9293. debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
  9294. /* Check pi->pi_inverted? "! sleep 1 & echo $?": bash says 1. dash and ash say 0 */
  9295. rcode = EXIT_SUCCESS;
  9296. goto check_traps;
  9297. } else {
  9298. #if ENABLE_HUSH_JOB
  9299. if (G.run_list_level == 1 && G_interactive_fd) {
  9300. /* Waits for completion, then fg's main shell */
  9301. rcode = checkjobs_and_fg_shell(pi);
  9302. debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
  9303. goto check_traps;
  9304. }
  9305. #endif
  9306. /* This one just waits for completion */
  9307. rcode = checkjobs(pi, 0 /*(no pid to wait for)*/);
  9308. debug_printf_exec(": checkjobs exitcode %d\n", rcode);
  9309. check_traps:
  9310. G.last_exitcode = rcode;
  9311. check_and_run_traps();
  9312. #if ENABLE_HUSH_TRAP && ENABLE_HUSH_FUNCTIONS
  9313. rcode = G.last_exitcode; /* "return" in trap can change it, read back */
  9314. #endif
  9315. }
  9316. /* Handle "set -e" */
  9317. if (rcode != 0 && G.o_opt[OPT_O_ERREXIT]) {
  9318. debug_printf_exec("ERREXIT:1 errexit_depth:%d\n", G.errexit_depth);
  9319. if (G.errexit_depth == 0)
  9320. hush_exit(rcode);
  9321. }
  9322. G.errexit_depth = sv_errexit_depth;
  9323. /* Analyze how result affects subsequent commands */
  9324. #if ENABLE_HUSH_IF
  9325. if (rword == RES_IF || rword == RES_ELIF)
  9326. cond_code = rcode;
  9327. #endif
  9328. check_jobs_and_continue:
  9329. checkjobs(NULL, 0 /*(no pid to wait for)*/);
  9330. dont_check_jobs_but_continue: ;
  9331. #if ENABLE_HUSH_LOOPS
  9332. /* Beware of "while false; true; do ..."! */
  9333. if (pi->next
  9334. && (pi->next->res_word == RES_DO || pi->next->res_word == RES_DONE)
  9335. /* check for RES_DONE is needed for "while ...; do \n done" case */
  9336. ) {
  9337. if (rword == RES_WHILE) {
  9338. if (rcode) {
  9339. /* "while false; do...done" - exitcode 0 */
  9340. G.last_exitcode = rcode = EXIT_SUCCESS;
  9341. debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
  9342. break;
  9343. }
  9344. }
  9345. if (rword == RES_UNTIL) {
  9346. if (!rcode) {
  9347. debug_printf_exec(": until expr is true: breaking\n");
  9348. break;
  9349. }
  9350. }
  9351. }
  9352. #endif
  9353. } /* for (pi) */
  9354. #if ENABLE_HUSH_JOB
  9355. G.run_list_level--;
  9356. #endif
  9357. #if ENABLE_HUSH_LOOPS
  9358. if (loop_top)
  9359. G.depth_of_loop--;
  9360. free(for_list);
  9361. #endif
  9362. #if ENABLE_HUSH_CASE
  9363. free(case_word);
  9364. #endif
  9365. debug_leave();
  9366. debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
  9367. return rcode;
  9368. }
  9369. /* Select which version we will use */
  9370. static int run_and_free_list(struct pipe *pi)
  9371. {
  9372. int rcode = 0;
  9373. debug_printf_exec("run_and_free_list entered\n");
  9374. if (!G.o_opt[OPT_O_NOEXEC]) {
  9375. debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
  9376. rcode = run_list(pi);
  9377. }
  9378. /* free_pipe_list has the side effect of clearing memory.
  9379. * In the long run that function can be merged with run_list,
  9380. * but doing that now would hobble the debugging effort. */
  9381. free_pipe_list(pi);
  9382. debug_printf_exec("run_and_free_list return %d\n", rcode);
  9383. return rcode;
  9384. }
  9385. static void install_sighandlers(unsigned mask)
  9386. {
  9387. sighandler_t old_handler;
  9388. unsigned sig = 0;
  9389. while ((mask >>= 1) != 0) {
  9390. sig++;
  9391. if (!(mask & 1))
  9392. continue;
  9393. old_handler = install_sighandler(sig, pick_sighandler(sig));
  9394. /* POSIX allows shell to re-enable SIGCHLD
  9395. * even if it was SIG_IGN on entry.
  9396. * Therefore we skip IGN check for it:
  9397. */
  9398. if (sig == SIGCHLD)
  9399. continue;
  9400. /* Interactive bash re-enables SIGHUP which is SIG_IGNed on entry.
  9401. * Try:
  9402. * trap '' hup; bash; echo RET # type "kill -hup $$", see SIGHUP having effect
  9403. * trap '' hup; bash -c 'kill -hup $$; echo ALIVE' # here SIGHUP is SIG_IGNed
  9404. */
  9405. if (sig == SIGHUP && G_interactive_fd)
  9406. continue;
  9407. /* Unless one of the above signals, is it SIG_IGN? */
  9408. if (old_handler == SIG_IGN) {
  9409. /* oops... restore back to IGN, and record this fact */
  9410. install_sighandler(sig, old_handler);
  9411. #if ENABLE_HUSH_TRAP
  9412. if (!G_traps)
  9413. G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
  9414. free(G_traps[sig]);
  9415. G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
  9416. #endif
  9417. }
  9418. }
  9419. }
  9420. /* Called a few times only (or even once if "sh -c") */
  9421. static void install_special_sighandlers(void)
  9422. {
  9423. unsigned mask;
  9424. /* Which signals are shell-special? */
  9425. mask = (1 << SIGQUIT) | (1 << SIGCHLD);
  9426. if (G_interactive_fd) {
  9427. mask |= SPECIAL_INTERACTIVE_SIGS;
  9428. if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
  9429. mask |= SPECIAL_JOBSTOP_SIGS;
  9430. }
  9431. /* Careful, do not re-install handlers we already installed */
  9432. if (G.special_sig_mask != mask) {
  9433. unsigned diff = mask & ~G.special_sig_mask;
  9434. G.special_sig_mask = mask;
  9435. install_sighandlers(diff);
  9436. }
  9437. }
  9438. #if ENABLE_HUSH_JOB
  9439. /* helper */
  9440. /* Set handlers to restore tty pgrp and exit */
  9441. static void install_fatal_sighandlers(void)
  9442. {
  9443. unsigned mask;
  9444. /* We will restore tty pgrp on these signals */
  9445. mask = 0
  9446. /*+ (1 << SIGILL ) * HUSH_DEBUG*/
  9447. /*+ (1 << SIGFPE ) * HUSH_DEBUG*/
  9448. + (1 << SIGBUS ) * HUSH_DEBUG
  9449. + (1 << SIGSEGV) * HUSH_DEBUG
  9450. /*+ (1 << SIGTRAP) * HUSH_DEBUG*/
  9451. + (1 << SIGABRT)
  9452. /* bash 3.2 seems to handle these just like 'fatal' ones */
  9453. + (1 << SIGPIPE)
  9454. + (1 << SIGALRM)
  9455. /* if we are interactive, SIGHUP, SIGTERM and SIGINT are special sigs.
  9456. * if we aren't interactive... but in this case
  9457. * we never want to restore pgrp on exit, and this fn is not called
  9458. */
  9459. /*+ (1 << SIGHUP )*/
  9460. /*+ (1 << SIGTERM)*/
  9461. /*+ (1 << SIGINT )*/
  9462. ;
  9463. G_fatal_sig_mask = mask;
  9464. install_sighandlers(mask);
  9465. }
  9466. #endif
  9467. static int set_mode(int state, char mode, const char *o_opt)
  9468. {
  9469. int idx;
  9470. switch (mode) {
  9471. case 'n':
  9472. G.o_opt[OPT_O_NOEXEC] = state;
  9473. break;
  9474. case 'x':
  9475. IF_HUSH_MODE_X(G_x_mode = state;)
  9476. IF_HUSH_MODE_X(if (G.x_mode_fd <= 0) G.x_mode_fd = dup_CLOEXEC(2, 10);)
  9477. break;
  9478. case 'e':
  9479. G.o_opt[OPT_O_ERREXIT] = state;
  9480. break;
  9481. case 'o':
  9482. if (!o_opt) {
  9483. /* "set -o" or "set +o" without parameter.
  9484. * in bash, set -o produces this output:
  9485. * pipefail off
  9486. * and set +o:
  9487. * set +o pipefail
  9488. * We always use the second form.
  9489. */
  9490. const char *p = o_opt_strings;
  9491. idx = 0;
  9492. while (*p) {
  9493. printf("set %co %s\n", (G.o_opt[idx] ? '-' : '+'), p);
  9494. idx++;
  9495. p += strlen(p) + 1;
  9496. }
  9497. break;
  9498. }
  9499. idx = index_in_strings(o_opt_strings, o_opt);
  9500. if (idx >= 0) {
  9501. G.o_opt[idx] = state;
  9502. break;
  9503. }
  9504. /* fall through to error */
  9505. default:
  9506. return EXIT_FAILURE;
  9507. }
  9508. return EXIT_SUCCESS;
  9509. }
  9510. int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  9511. int hush_main(int argc, char **argv)
  9512. {
  9513. pid_t cached_getpid;
  9514. enum {
  9515. OPT_login = (1 << 0),
  9516. };
  9517. unsigned flags;
  9518. #if !BB_MMU
  9519. unsigned builtin_argc = 0;
  9520. #endif
  9521. char **e;
  9522. struct variable *cur_var;
  9523. struct variable *shell_ver;
  9524. INIT_G();
  9525. if (EXIT_SUCCESS != 0) /* if EXIT_SUCCESS == 0, it is already done */
  9526. G.last_exitcode = EXIT_SUCCESS;
  9527. #if ENABLE_HUSH_TRAP
  9528. # if ENABLE_HUSH_FUNCTIONS
  9529. G.return_exitcode = -1;
  9530. # endif
  9531. G.pre_trap_exitcode = -1;
  9532. #endif
  9533. #if ENABLE_HUSH_FAST
  9534. G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
  9535. #endif
  9536. #if !BB_MMU
  9537. G.argv0_for_re_execing = argv[0];
  9538. #endif
  9539. cached_getpid = getpid(); /* for tcsetpgrp() during init */
  9540. G.root_pid = cached_getpid; /* for $PID (NOMMU can override via -$HEXPID:HEXPPID:...) */
  9541. G.root_ppid = getppid(); /* for $PPID (NOMMU can override) */
  9542. /* Deal with HUSH_VERSION */
  9543. debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
  9544. unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
  9545. shell_ver = xzalloc(sizeof(*shell_ver));
  9546. shell_ver->flg_export = 1;
  9547. shell_ver->flg_read_only = 1;
  9548. /* Code which handles ${var<op>...} needs writable values for all variables,
  9549. * therefore we xstrdup: */
  9550. shell_ver->varstr = xstrdup(hush_version_str);
  9551. /* Create shell local variables from the values
  9552. * currently living in the environment */
  9553. G.top_var = shell_ver;
  9554. cur_var = G.top_var;
  9555. e = environ;
  9556. if (e) while (*e) {
  9557. char *value = strchr(*e, '=');
  9558. if (value) { /* paranoia */
  9559. cur_var->next = xzalloc(sizeof(*cur_var));
  9560. cur_var = cur_var->next;
  9561. cur_var->varstr = *e;
  9562. cur_var->max_len = strlen(*e);
  9563. cur_var->flg_export = 1;
  9564. }
  9565. e++;
  9566. }
  9567. /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
  9568. debug_printf_env("putenv '%s'\n", shell_ver->varstr);
  9569. putenv(shell_ver->varstr);
  9570. /* Export PWD */
  9571. set_pwd_var(SETFLAG_EXPORT);
  9572. #if BASH_HOSTNAME_VAR
  9573. /* Set (but not export) HOSTNAME unless already set */
  9574. if (!get_local_var_value("HOSTNAME")) {
  9575. struct utsname uts;
  9576. uname(&uts);
  9577. set_local_var_from_halves("HOSTNAME", uts.nodename);
  9578. }
  9579. #endif
  9580. /* IFS is not inherited from the parent environment */
  9581. set_local_var_from_halves("IFS", defifs);
  9582. if (!get_local_var_value("PATH"))
  9583. set_local_var_from_halves("PATH", bb_default_root_path);
  9584. /* PS1/PS2 are set later, if we determine that we are interactive */
  9585. /* bash also exports SHLVL and _,
  9586. * and sets (but doesn't export) the following variables:
  9587. * BASH=/bin/bash
  9588. * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
  9589. * BASH_VERSION='3.2.0(1)-release'
  9590. * HOSTTYPE=i386
  9591. * MACHTYPE=i386-pc-linux-gnu
  9592. * OSTYPE=linux-gnu
  9593. * PPID=<NNNNN> - we also do it elsewhere
  9594. * EUID=<NNNNN>
  9595. * UID=<NNNNN>
  9596. * GROUPS=()
  9597. * LINES=<NNN>
  9598. * COLUMNS=<NNN>
  9599. * BASH_ARGC=()
  9600. * BASH_ARGV=()
  9601. * BASH_LINENO=()
  9602. * BASH_SOURCE=()
  9603. * DIRSTACK=()
  9604. * PIPESTATUS=([0]="0")
  9605. * HISTFILE=/<xxx>/.bash_history
  9606. * HISTFILESIZE=500
  9607. * HISTSIZE=500
  9608. * MAILCHECK=60
  9609. * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
  9610. * SHELL=/bin/bash
  9611. * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
  9612. * TERM=dumb
  9613. * OPTERR=1
  9614. * OPTIND=1
  9615. * PS4='+ '
  9616. */
  9617. #if NUM_SCRIPTS > 0
  9618. if (argc < 0) {
  9619. char *script = get_script_content(-argc - 1);
  9620. G.global_argv = argv;
  9621. G.global_argc = string_array_len(argv);
  9622. //install_special_sighandlers(); - needed?
  9623. parse_and_run_string(script);
  9624. goto final_return;
  9625. }
  9626. #endif
  9627. /* Initialize some more globals to non-zero values */
  9628. die_func = restore_ttypgrp_and__exit;
  9629. /* Shell is non-interactive at first. We need to call
  9630. * install_special_sighandlers() if we are going to execute "sh <script>",
  9631. * "sh -c <cmds>" or login shell's /etc/profile and friends.
  9632. * If we later decide that we are interactive, we run install_special_sighandlers()
  9633. * in order to intercept (more) signals.
  9634. */
  9635. /* Parse options */
  9636. /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
  9637. flags = (argv[0] && argv[0][0] == '-') ? OPT_login : 0;
  9638. while (1) {
  9639. int opt = getopt(argc, argv, "+" /* stop at 1st non-option */
  9640. "cexinsl"
  9641. #if !BB_MMU
  9642. "<:$:R:V:"
  9643. # if ENABLE_HUSH_FUNCTIONS
  9644. "F:"
  9645. # endif
  9646. #endif
  9647. );
  9648. if (opt <= 0)
  9649. break;
  9650. switch (opt) {
  9651. case 'c':
  9652. /* Note: -c is not an option with param!
  9653. * "hush -c -l SCRIPT" is valid. "hush -cSCRIPT" is not.
  9654. */
  9655. G.opt_c = 1;
  9656. break;
  9657. case 'i':
  9658. /* Well, we cannot just declare interactiveness,
  9659. * we have to have some stuff (ctty, etc) */
  9660. /* G_interactive_fd++; */
  9661. break;
  9662. case 's':
  9663. G.opt_s = 1;
  9664. break;
  9665. case 'l':
  9666. flags |= OPT_login;
  9667. break;
  9668. #if !BB_MMU
  9669. case '<': /* "big heredoc" support */
  9670. full_write1_str(optarg);
  9671. _exit(0);
  9672. case '$': {
  9673. unsigned long long empty_trap_mask;
  9674. G.root_pid = bb_strtou(optarg, &optarg, 16);
  9675. optarg++;
  9676. G.root_ppid = bb_strtou(optarg, &optarg, 16);
  9677. optarg++;
  9678. G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
  9679. optarg++;
  9680. G.last_exitcode = bb_strtou(optarg, &optarg, 16);
  9681. optarg++;
  9682. builtin_argc = bb_strtou(optarg, &optarg, 16);
  9683. optarg++;
  9684. empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
  9685. if (empty_trap_mask != 0) {
  9686. IF_HUSH_TRAP(int sig;)
  9687. install_special_sighandlers();
  9688. # if ENABLE_HUSH_TRAP
  9689. G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
  9690. for (sig = 1; sig < NSIG; sig++) {
  9691. if (empty_trap_mask & (1LL << sig)) {
  9692. G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
  9693. install_sighandler(sig, SIG_IGN);
  9694. }
  9695. }
  9696. # endif
  9697. }
  9698. # if ENABLE_HUSH_LOOPS
  9699. optarg++;
  9700. G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
  9701. # endif
  9702. /* Suppress "killed by signal" message, -$ hack is used
  9703. * for subshells: echo `sh -c 'kill -9 $$'`
  9704. * should be silent.
  9705. */
  9706. IF_HUSH_JOB(G.run_list_level = 1;)
  9707. # if ENABLE_HUSH_FUNCTIONS
  9708. /* nommu uses re-exec trick for "... | func | ...",
  9709. * should allow "return".
  9710. * This accidentally allows returns in subshells.
  9711. */
  9712. G_flag_return_in_progress = -1;
  9713. # endif
  9714. break;
  9715. }
  9716. case 'R':
  9717. case 'V':
  9718. set_local_var(xstrdup(optarg), opt == 'R' ? SETFLAG_MAKE_RO : 0);
  9719. break;
  9720. # if ENABLE_HUSH_FUNCTIONS
  9721. case 'F': {
  9722. struct function *funcp = new_function(optarg);
  9723. /* funcp->name is already set to optarg */
  9724. /* funcp->body is set to NULL. It's a special case. */
  9725. funcp->body_as_string = argv[optind];
  9726. optind++;
  9727. break;
  9728. }
  9729. # endif
  9730. #endif
  9731. /*case '?': invalid option encountered (set_mode('?') will fail) */
  9732. /*case 'n':*/
  9733. /*case 'x':*/
  9734. /*case 'e':*/
  9735. default:
  9736. if (set_mode(1, opt, NULL) == 0) /* no error */
  9737. break;
  9738. bb_show_usage();
  9739. }
  9740. } /* option parsing loop */
  9741. /* Skip options. Try "hush -l": $1 should not be "-l"! */
  9742. G.global_argc = argc - (optind - 1);
  9743. G.global_argv = argv + (optind - 1);
  9744. G.global_argv[0] = argv[0];
  9745. /* If we are login shell... */
  9746. if (flags & OPT_login) {
  9747. const char *hp = NULL;
  9748. HFILE *input;
  9749. debug_printf("sourcing /etc/profile\n");
  9750. input = hfopen("/etc/profile");
  9751. run_profile:
  9752. if (input != NULL) {
  9753. install_special_sighandlers();
  9754. parse_and_run_file(input);
  9755. hfclose(input);
  9756. }
  9757. /* bash: after sourcing /etc/profile,
  9758. * tries to source (in the given order):
  9759. * ~/.bash_profile, ~/.bash_login, ~/.profile,
  9760. * stopping on first found. --noprofile turns this off.
  9761. * bash also sources ~/.bash_logout on exit.
  9762. * If called as sh, skips .bash_XXX files.
  9763. */
  9764. if (!hp) { /* unless we looped on the "goto" already */
  9765. hp = get_local_var_value("HOME");
  9766. if (hp && hp[0]) {
  9767. debug_printf("sourcing ~/.profile\n");
  9768. hp = concat_path_file(hp, ".profile");
  9769. input = hfopen(hp);
  9770. free((char*)hp);
  9771. goto run_profile;
  9772. }
  9773. }
  9774. }
  9775. /* -c takes effect *after* -l */
  9776. if (G.opt_c) {
  9777. /* Possibilities:
  9778. * sh ... -c 'script'
  9779. * sh ... -c 'script' ARG0 [ARG1...]
  9780. * On NOMMU, if builtin_argc != 0,
  9781. * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
  9782. * "" needs to be replaced with NULL
  9783. * and BARGV vector fed to builtin function.
  9784. * Note: the form without ARG0 never happens:
  9785. * sh ... -c 'builtin' BARGV... ""
  9786. */
  9787. char *script;
  9788. install_special_sighandlers();
  9789. G.global_argc--;
  9790. G.global_argv++;
  9791. #if !BB_MMU
  9792. if (builtin_argc) {
  9793. /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
  9794. const struct built_in_command *x;
  9795. x = find_builtin(G.global_argv[0]);
  9796. if (x) { /* paranoia */
  9797. argv = G.global_argv;
  9798. G.global_argc -= builtin_argc + 1; /* skip [BARGV...] "" */
  9799. G.global_argv += builtin_argc + 1;
  9800. G.global_argv[-1] = NULL; /* replace "" */
  9801. G.last_exitcode = x->b_function(argv);
  9802. }
  9803. goto final_return;
  9804. }
  9805. #endif
  9806. script = G.global_argv[0];
  9807. if (!script)
  9808. bb_error_msg_and_die(bb_msg_requires_arg, "-c");
  9809. if (!G.global_argv[1]) {
  9810. /* -c 'script' (no params): prevent empty $0 */
  9811. G.global_argv[0] = argv[0];
  9812. } else { /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
  9813. G.global_argc--;
  9814. G.global_argv++;
  9815. }
  9816. parse_and_run_string(script);
  9817. goto final_return;
  9818. }
  9819. /* -s is: hush -s ARGV1 ARGV2 (no SCRIPT) */
  9820. if (!G.opt_s && G.global_argv[1]) {
  9821. HFILE *input;
  9822. /*
  9823. * "bash <script>" (which is never interactive (unless -i?))
  9824. * sources $BASH_ENV here (without scanning $PATH).
  9825. * If called as sh, does the same but with $ENV.
  9826. * Also NB, per POSIX, $ENV should undergo parameter expansion.
  9827. */
  9828. G.global_argc--;
  9829. G.global_argv++;
  9830. debug_printf("running script '%s'\n", G.global_argv[0]);
  9831. xfunc_error_retval = 127; /* for "hush /does/not/exist" case */
  9832. input = hfopen(G.global_argv[0]);
  9833. if (!input) {
  9834. bb_simple_perror_msg_and_die(G.global_argv[0]);
  9835. }
  9836. xfunc_error_retval = 1;
  9837. install_special_sighandlers();
  9838. parse_and_run_file(input);
  9839. #if ENABLE_FEATURE_CLEAN_UP
  9840. hfclose(input);
  9841. #endif
  9842. goto final_return;
  9843. }
  9844. /* "implicit" -s: bare interactive hush shows 's' in $- */
  9845. G.opt_s = 1;
  9846. /* Up to here, shell was non-interactive. Now it may become one.
  9847. * NB: don't forget to (re)run install_special_sighandlers() as needed.
  9848. */
  9849. /* A shell is interactive if the '-i' flag was given,
  9850. * or if all of the following conditions are met:
  9851. * no -c command
  9852. * no arguments remaining or the -s flag given
  9853. * standard input is a terminal
  9854. * standard output is a terminal
  9855. * Refer to Posix.2, the description of the 'sh' utility.
  9856. */
  9857. #if ENABLE_HUSH_JOB
  9858. if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
  9859. G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
  9860. debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
  9861. if (G_saved_tty_pgrp < 0)
  9862. G_saved_tty_pgrp = 0;
  9863. /* try to dup stdin to high fd#, >= 255 */
  9864. G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, 254);
  9865. if (G_interactive_fd < 0) {
  9866. /* try to dup to any fd */
  9867. G_interactive_fd = dup(STDIN_FILENO);
  9868. if (G_interactive_fd < 0) {
  9869. /* give up */
  9870. G_interactive_fd = 0;
  9871. G_saved_tty_pgrp = 0;
  9872. }
  9873. }
  9874. }
  9875. debug_printf("interactive_fd:%d\n", G_interactive_fd);
  9876. if (G_interactive_fd) {
  9877. close_on_exec_on(G_interactive_fd);
  9878. if (G_saved_tty_pgrp) {
  9879. /* If we were run as 'hush &', sleep until we are
  9880. * in the foreground (tty pgrp == our pgrp).
  9881. * If we get started under a job aware app (like bash),
  9882. * make sure we are now in charge so we don't fight over
  9883. * who gets the foreground */
  9884. while (1) {
  9885. pid_t shell_pgrp = getpgrp();
  9886. G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
  9887. if (G_saved_tty_pgrp == shell_pgrp)
  9888. break;
  9889. /* send TTIN to ourself (should stop us) */
  9890. kill(- shell_pgrp, SIGTTIN);
  9891. }
  9892. }
  9893. /* Install more signal handlers */
  9894. install_special_sighandlers();
  9895. if (G_saved_tty_pgrp) {
  9896. /* Set other signals to restore saved_tty_pgrp */
  9897. install_fatal_sighandlers();
  9898. /* Put ourselves in our own process group
  9899. * (bash, too, does this only if ctty is available) */
  9900. bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
  9901. /* Grab control of the terminal */
  9902. tcsetpgrp(G_interactive_fd, cached_getpid);
  9903. }
  9904. enable_restore_tty_pgrp_on_exit();
  9905. # if ENABLE_FEATURE_EDITING
  9906. G.line_input_state = new_line_input_t(FOR_SHELL);
  9907. # if EDITING_HAS_get_exe_name
  9908. G.line_input_state->get_exe_name = get_builtin_name;
  9909. # endif
  9910. # endif
  9911. # if ENABLE_HUSH_SAVEHISTORY && MAX_HISTORY > 0
  9912. {
  9913. const char *hp = get_local_var_value("HISTFILE");
  9914. if (!hp) {
  9915. hp = get_local_var_value("HOME");
  9916. if (hp)
  9917. hp = concat_path_file(hp, ".hush_history");
  9918. } else {
  9919. hp = xstrdup(hp);
  9920. }
  9921. if (hp) {
  9922. G.line_input_state->hist_file = hp;
  9923. //set_local_var(xasprintf("HISTFILE=%s", ...));
  9924. }
  9925. # if ENABLE_FEATURE_SH_HISTFILESIZE
  9926. hp = get_local_var_value("HISTFILESIZE");
  9927. G.line_input_state->max_history = size_from_HISTFILESIZE(hp);
  9928. # endif
  9929. }
  9930. # endif
  9931. } else {
  9932. install_special_sighandlers();
  9933. }
  9934. #elif ENABLE_HUSH_INTERACTIVE
  9935. /* No job control compiled in, only prompt/line editing */
  9936. if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
  9937. G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, 254);
  9938. if (G_interactive_fd < 0) {
  9939. /* try to dup to any fd */
  9940. G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, -1);
  9941. if (G_interactive_fd < 0)
  9942. /* give up */
  9943. G_interactive_fd = 0;
  9944. }
  9945. }
  9946. if (G_interactive_fd) {
  9947. close_on_exec_on(G_interactive_fd);
  9948. }
  9949. install_special_sighandlers();
  9950. #else
  9951. /* We have interactiveness code disabled */
  9952. install_special_sighandlers();
  9953. #endif
  9954. /* bash:
  9955. * if interactive but not a login shell, sources ~/.bashrc
  9956. * (--norc turns this off, --rcfile <file> overrides)
  9957. */
  9958. if (G_interactive_fd) {
  9959. #if ENABLE_HUSH_INTERACTIVE && ENABLE_FEATURE_EDITING_FANCY_PROMPT
  9960. /* Set (but not export) PS1/2 unless already set */
  9961. if (!get_local_var_value("PS1"))
  9962. set_local_var_from_halves("PS1", "\\w \\$ ");
  9963. if (!get_local_var_value("PS2"))
  9964. set_local_var_from_halves("PS2", "> ");
  9965. #endif
  9966. if (!ENABLE_FEATURE_SH_EXTRA_QUIET) {
  9967. /* note: ash and hush share this string */
  9968. printf("\n\n%s %s\n"
  9969. IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
  9970. "\n",
  9971. bb_banner,
  9972. "hush - the humble shell"
  9973. );
  9974. }
  9975. }
  9976. parse_and_run_file(hfopen(NULL)); /* stdin */
  9977. final_return:
  9978. hush_exit(G.last_exitcode);
  9979. }
  9980. /*
  9981. * Built-ins
  9982. */
  9983. static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
  9984. {
  9985. return 0;
  9986. }
  9987. #if ENABLE_HUSH_TEST || ENABLE_HUSH_ECHO || ENABLE_HUSH_PRINTF || ENABLE_HUSH_KILL
  9988. static NOINLINE int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
  9989. {
  9990. int argc = string_array_len(argv);
  9991. return applet_main_func(argc, argv);
  9992. }
  9993. #endif
  9994. #if ENABLE_HUSH_TEST || BASH_TEST2
  9995. static int FAST_FUNC builtin_test(char **argv)
  9996. {
  9997. return run_applet_main(argv, test_main);
  9998. }
  9999. #endif
  10000. #if ENABLE_HUSH_ECHO
  10001. static int FAST_FUNC builtin_echo(char **argv)
  10002. {
  10003. return run_applet_main(argv, echo_main);
  10004. }
  10005. #endif
  10006. #if ENABLE_HUSH_PRINTF
  10007. static int FAST_FUNC builtin_printf(char **argv)
  10008. {
  10009. return run_applet_main(argv, printf_main);
  10010. }
  10011. #endif
  10012. #if ENABLE_HUSH_HELP
  10013. static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
  10014. {
  10015. const struct built_in_command *x;
  10016. printf(
  10017. "Built-in commands:\n"
  10018. "------------------\n");
  10019. for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
  10020. if (x->b_descr)
  10021. printf("%-10s%s\n", x->b_cmd, x->b_descr);
  10022. }
  10023. return EXIT_SUCCESS;
  10024. }
  10025. #endif
  10026. #if MAX_HISTORY && ENABLE_FEATURE_EDITING
  10027. static int FAST_FUNC builtin_history(char **argv UNUSED_PARAM)
  10028. {
  10029. show_history(G.line_input_state);
  10030. return EXIT_SUCCESS;
  10031. }
  10032. #endif
  10033. static char **skip_dash_dash(char **argv)
  10034. {
  10035. argv++;
  10036. if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
  10037. argv++;
  10038. return argv;
  10039. }
  10040. static int FAST_FUNC builtin_cd(char **argv)
  10041. {
  10042. const char *newdir;
  10043. argv = skip_dash_dash(argv);
  10044. newdir = argv[0];
  10045. if (newdir == NULL) {
  10046. /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
  10047. * bash says "bash: cd: HOME not set" and does nothing
  10048. * (exitcode 1)
  10049. */
  10050. const char *home = get_local_var_value("HOME");
  10051. newdir = home ? home : "/";
  10052. }
  10053. if (chdir(newdir)) {
  10054. /* Mimic bash message exactly */
  10055. bb_perror_msg("cd: %s", newdir);
  10056. return EXIT_FAILURE;
  10057. }
  10058. /* Read current dir (get_cwd(1) is inside) and set PWD.
  10059. * Note: do not enforce exporting. If PWD was unset or unexported,
  10060. * set it again, but do not export. bash does the same.
  10061. */
  10062. set_pwd_var(/*flag:*/ 0);
  10063. return EXIT_SUCCESS;
  10064. }
  10065. static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
  10066. {
  10067. puts(get_cwd(0));
  10068. return EXIT_SUCCESS;
  10069. }
  10070. static int FAST_FUNC builtin_eval(char **argv)
  10071. {
  10072. argv = skip_dash_dash(argv);
  10073. if (!argv[0])
  10074. return EXIT_SUCCESS;
  10075. IF_HUSH_MODE_X(G.x_mode_depth++;)
  10076. //bb_error_msg("%s: ++x_mode_depth=%d", __func__, G.x_mode_depth);
  10077. if (!argv[1]) {
  10078. /* bash:
  10079. * eval "echo Hi; done" ("done" is syntax error):
  10080. * "echo Hi" will not execute too.
  10081. */
  10082. parse_and_run_string(argv[0]);
  10083. } else {
  10084. /* "The eval utility shall construct a command by
  10085. * concatenating arguments together, separating
  10086. * each with a <space> character."
  10087. */
  10088. char *str, *p;
  10089. unsigned len = 0;
  10090. char **pp = argv;
  10091. do
  10092. len += strlen(*pp) + 1;
  10093. while (*++pp);
  10094. str = p = xmalloc(len);
  10095. pp = argv;
  10096. for (;;) {
  10097. p = stpcpy(p, *pp);
  10098. pp++;
  10099. if (!*pp)
  10100. break;
  10101. *p++ = ' ';
  10102. }
  10103. parse_and_run_string(str);
  10104. free(str);
  10105. }
  10106. IF_HUSH_MODE_X(G.x_mode_depth--;)
  10107. //bb_error_msg("%s: --x_mode_depth=%d", __func__, G.x_mode_depth);
  10108. return G.last_exitcode;
  10109. }
  10110. static int FAST_FUNC builtin_exec(char **argv)
  10111. {
  10112. argv = skip_dash_dash(argv);
  10113. if (argv[0] == NULL)
  10114. return EXIT_SUCCESS; /* bash does this */
  10115. /* Careful: we can end up here after [v]fork. Do not restore
  10116. * tty pgrp then, only top-level shell process does that */
  10117. if (G_saved_tty_pgrp && getpid() == G.root_pid)
  10118. tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
  10119. /* Saved-redirect fds, script fds and G_interactive_fd are still
  10120. * open here. However, they are all CLOEXEC, and execv below
  10121. * closes them. Try interactive "exec ls -l /proc/self/fd",
  10122. * it should show no extra open fds in the "ls" process.
  10123. * If we'd try to run builtins/NOEXECs, this would need improving.
  10124. */
  10125. //close_saved_fds_and_FILE_fds();
  10126. /* TODO: if exec fails, bash does NOT exit! We do.
  10127. * We'll need to undo trap cleanup (it's inside execvp_or_die)
  10128. * and tcsetpgrp, and this is inherently racy.
  10129. */
  10130. execvp_or_die(argv);
  10131. }
  10132. static int FAST_FUNC builtin_exit(char **argv)
  10133. {
  10134. debug_printf_exec("%s()\n", __func__);
  10135. /* interactive bash:
  10136. * # trap "echo EEE" EXIT
  10137. * # exit
  10138. * exit
  10139. * There are stopped jobs.
  10140. * (if there are _stopped_ jobs, running ones don't count)
  10141. * # exit
  10142. * exit
  10143. * EEE (then bash exits)
  10144. *
  10145. * TODO: we can use G.exiting = -1 as indicator "last cmd was exit"
  10146. */
  10147. /* note: EXIT trap is run by hush_exit */
  10148. argv = skip_dash_dash(argv);
  10149. if (argv[0] == NULL) {
  10150. #if ENABLE_HUSH_TRAP
  10151. if (G.pre_trap_exitcode >= 0) /* "exit" in trap uses $? from before the trap */
  10152. hush_exit(G.pre_trap_exitcode);
  10153. #endif
  10154. hush_exit(G.last_exitcode);
  10155. }
  10156. /* mimic bash: exit 123abc == exit 255 + error msg */
  10157. xfunc_error_retval = 255;
  10158. /* bash: exit -2 == exit 254, no error msg */
  10159. hush_exit(xatoi(argv[0]) & 0xff);
  10160. }
  10161. #if ENABLE_HUSH_TYPE
  10162. /* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
  10163. static int FAST_FUNC builtin_type(char **argv)
  10164. {
  10165. int ret = EXIT_SUCCESS;
  10166. while (*++argv) {
  10167. const char *type;
  10168. char *path = NULL;
  10169. if (0) {} /* make conditional compile easier below */
  10170. /*else if (find_alias(*argv))
  10171. type = "an alias";*/
  10172. # if ENABLE_HUSH_FUNCTIONS
  10173. else if (find_function(*argv))
  10174. type = "a function";
  10175. # endif
  10176. else if (find_builtin(*argv))
  10177. type = "a shell builtin";
  10178. else if ((path = find_in_path(*argv)) != NULL)
  10179. type = path;
  10180. else {
  10181. bb_error_msg("type: %s: not found", *argv);
  10182. ret = EXIT_FAILURE;
  10183. continue;
  10184. }
  10185. printf("%s is %s\n", *argv, type);
  10186. free(path);
  10187. }
  10188. return ret;
  10189. }
  10190. #endif
  10191. #if ENABLE_HUSH_READ
  10192. /* Interruptibility of read builtin in bash
  10193. * (tested on bash-4.2.8 by sending signals (not by ^C)):
  10194. *
  10195. * Empty trap makes read ignore corresponding signal, for any signal.
  10196. *
  10197. * SIGINT:
  10198. * - terminates non-interactive shell;
  10199. * - interrupts read in interactive shell;
  10200. * if it has non-empty trap:
  10201. * - executes trap and returns to command prompt in interactive shell;
  10202. * - executes trap and returns to read in non-interactive shell;
  10203. * SIGTERM:
  10204. * - is ignored (does not interrupt) read in interactive shell;
  10205. * - terminates non-interactive shell;
  10206. * if it has non-empty trap:
  10207. * - executes trap and returns to read;
  10208. * SIGHUP:
  10209. * - terminates shell (regardless of interactivity);
  10210. * if it has non-empty trap:
  10211. * - executes trap and returns to read;
  10212. * SIGCHLD from children:
  10213. * - does not interrupt read regardless of interactivity:
  10214. * try: sleep 1 & read x; echo $x
  10215. */
  10216. static int FAST_FUNC builtin_read(char **argv)
  10217. {
  10218. const char *r;
  10219. struct builtin_read_params params;
  10220. memset(&params, 0, sizeof(params));
  10221. /* "!": do not abort on errors.
  10222. * Option string must start with "sr" to match BUILTIN_READ_xxx
  10223. */
  10224. params.read_flags = getopt32(argv,
  10225. # if BASH_READ_D
  10226. IF_NOT_HUSH_BASH_COMPAT("^")
  10227. "!srn:p:t:u:d:" IF_NOT_HUSH_BASH_COMPAT("\0" "-1"/*min 1 arg*/),
  10228. &params.opt_n, &params.opt_p, &params.opt_t, &params.opt_u, &params.opt_d
  10229. # else
  10230. IF_NOT_HUSH_BASH_COMPAT("^")
  10231. "!srn:p:t:u:" IF_NOT_HUSH_BASH_COMPAT("\0" "-1"/*min 1 arg*/),
  10232. &params.opt_n, &params.opt_p, &params.opt_t, &params.opt_u
  10233. # endif
  10234. //TODO: print "read: need variable name"
  10235. //for the case of !BASH "read" with no args (now it fails silently)
  10236. //(or maybe extend getopt32() to emit a message if "-1" fails)
  10237. );
  10238. if ((uint32_t)params.read_flags == (uint32_t)-1)
  10239. return EXIT_FAILURE;
  10240. argv += optind;
  10241. params.argv = argv;
  10242. params.setvar = set_local_var_from_halves;
  10243. params.ifs = get_local_var_value("IFS"); /* can be NULL */
  10244. again:
  10245. r = shell_builtin_read(&params);
  10246. if ((uintptr_t)r == 1 && errno == EINTR) {
  10247. unsigned sig = check_and_run_traps();
  10248. if (sig != SIGINT)
  10249. goto again;
  10250. }
  10251. if ((uintptr_t)r > 1) {
  10252. bb_simple_error_msg(r);
  10253. r = (char*)(uintptr_t)1;
  10254. }
  10255. return (uintptr_t)r;
  10256. }
  10257. #endif
  10258. #if ENABLE_HUSH_UMASK
  10259. static int FAST_FUNC builtin_umask(char **argv)
  10260. {
  10261. int rc;
  10262. mode_t mask;
  10263. rc = 1;
  10264. mask = umask(0);
  10265. argv = skip_dash_dash(argv);
  10266. if (argv[0]) {
  10267. mode_t old_mask = mask;
  10268. /* numeric umasks are taken as-is */
  10269. /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
  10270. if (!isdigit(argv[0][0]))
  10271. mask ^= 0777;
  10272. mask = bb_parse_mode(argv[0], mask);
  10273. if (!isdigit(argv[0][0]))
  10274. mask ^= 0777;
  10275. if ((unsigned)mask > 0777) {
  10276. mask = old_mask;
  10277. /* bash messages:
  10278. * bash: umask: 'q': invalid symbolic mode operator
  10279. * bash: umask: 999: octal number out of range
  10280. */
  10281. bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
  10282. rc = 0;
  10283. }
  10284. } else {
  10285. /* Mimic bash */
  10286. printf("%04o\n", (unsigned) mask);
  10287. /* fall through and restore mask which we set to 0 */
  10288. }
  10289. umask(mask);
  10290. return !rc; /* rc != 0 - success */
  10291. }
  10292. #endif
  10293. #if ENABLE_HUSH_EXPORT || ENABLE_HUSH_TRAP
  10294. static void print_escaped(const char *s)
  10295. {
  10296. if (*s == '\'')
  10297. goto squote;
  10298. do {
  10299. const char *p = strchrnul(s, '\'');
  10300. /* print 'xxxx', possibly just '' */
  10301. printf("'%.*s'", (int)(p - s), s);
  10302. if (*p == '\0')
  10303. break;
  10304. s = p;
  10305. squote:
  10306. /* s points to '; print "'''...'''" */
  10307. putchar('"');
  10308. do putchar('\''); while (*++s == '\'');
  10309. putchar('"');
  10310. } while (*s);
  10311. }
  10312. #endif
  10313. #if ENABLE_HUSH_EXPORT || ENABLE_HUSH_LOCAL || ENABLE_HUSH_READONLY
  10314. static int helper_export_local(char **argv, unsigned flags)
  10315. {
  10316. do {
  10317. char *name = *argv;
  10318. const char *name_end = endofname(name);
  10319. if (*name_end == '\0') {
  10320. struct variable *var, **vpp;
  10321. vpp = get_ptr_to_local_var(name, name_end - name);
  10322. var = vpp ? *vpp : NULL;
  10323. if (flags & SETFLAG_UNEXPORT) {
  10324. /* export -n NAME (without =VALUE) */
  10325. if (var) {
  10326. var->flg_export = 0;
  10327. debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
  10328. unsetenv(name);
  10329. } /* else: export -n NOT_EXISTING_VAR: no-op */
  10330. continue;
  10331. }
  10332. if (flags & SETFLAG_EXPORT) {
  10333. /* export NAME (without =VALUE) */
  10334. if (var) {
  10335. var->flg_export = 1;
  10336. debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
  10337. putenv(var->varstr);
  10338. continue;
  10339. }
  10340. }
  10341. if (flags & SETFLAG_MAKE_RO) {
  10342. /* readonly NAME (without =VALUE) */
  10343. if (var) {
  10344. var->flg_read_only = 1;
  10345. continue;
  10346. }
  10347. }
  10348. # if ENABLE_HUSH_LOCAL
  10349. /* Is this "local" bltin? */
  10350. if (!(flags & (SETFLAG_EXPORT|SETFLAG_UNEXPORT|SETFLAG_MAKE_RO))) {
  10351. unsigned lvl = flags >> SETFLAG_VARLVL_SHIFT;
  10352. if (var && var->var_nest_level == lvl) {
  10353. /* "local x=abc; ...; local x" - ignore second local decl */
  10354. continue;
  10355. }
  10356. }
  10357. # endif
  10358. /* Exporting non-existing variable.
  10359. * bash does not put it in environment,
  10360. * but remembers that it is exported,
  10361. * and does put it in env when it is set later.
  10362. * We just set it to "" and export.
  10363. */
  10364. /* Or, it's "local NAME" (without =VALUE).
  10365. * bash sets the value to "".
  10366. */
  10367. /* Or, it's "readonly NAME" (without =VALUE).
  10368. * bash remembers NAME and disallows its creation
  10369. * in the future.
  10370. */
  10371. name = xasprintf("%s=", name);
  10372. } else {
  10373. if (*name_end != '=') {
  10374. bb_error_msg("'%s': bad variable name", name);
  10375. /* do not parse following argv[]s: */
  10376. return 1;
  10377. }
  10378. /* (Un)exporting/making local NAME=VALUE */
  10379. name = xstrdup(name);
  10380. /* Testcase: export PS1='\w \$ ' */
  10381. unbackslash(name);
  10382. }
  10383. debug_printf_env("%s: set_local_var('%s')\n", __func__, name);
  10384. if (set_local_var(name, flags))
  10385. return EXIT_FAILURE;
  10386. } while (*++argv);
  10387. return EXIT_SUCCESS;
  10388. }
  10389. #endif
  10390. #if ENABLE_HUSH_EXPORT
  10391. static int FAST_FUNC builtin_export(char **argv)
  10392. {
  10393. unsigned opt_unexport;
  10394. # if ENABLE_HUSH_EXPORT_N
  10395. /* "!": do not abort on errors */
  10396. opt_unexport = getopt32(argv, "!n");
  10397. if (opt_unexport == (uint32_t)-1)
  10398. return EXIT_FAILURE;
  10399. argv += optind;
  10400. # else
  10401. opt_unexport = 0;
  10402. argv++;
  10403. # endif
  10404. if (argv[0] == NULL) {
  10405. char **e = environ;
  10406. if (e) {
  10407. while (*e) {
  10408. # if 0
  10409. puts(*e++);
  10410. # else
  10411. /* ash emits: export VAR='VAL'
  10412. * bash: declare -x VAR="VAL"
  10413. * we follow ash example */
  10414. const char *s = *e++;
  10415. const char *p = strchr(s, '=');
  10416. if (!p) /* wtf? take next variable */
  10417. continue;
  10418. /* export var= */
  10419. printf("export %.*s", (int)(p - s) + 1, s);
  10420. print_escaped(p + 1);
  10421. putchar('\n');
  10422. # endif
  10423. }
  10424. /*fflush_all(); - done after each builtin anyway */
  10425. }
  10426. return EXIT_SUCCESS;
  10427. }
  10428. return helper_export_local(argv, opt_unexport ? SETFLAG_UNEXPORT : SETFLAG_EXPORT);
  10429. }
  10430. #endif
  10431. #if ENABLE_HUSH_LOCAL
  10432. static int FAST_FUNC builtin_local(char **argv)
  10433. {
  10434. if (G.func_nest_level == 0) {
  10435. bb_error_msg("%s: not in a function", argv[0]);
  10436. return EXIT_FAILURE; /* bash compat */
  10437. }
  10438. argv++;
  10439. /* Since all builtins run in a nested variable level,
  10440. * need to use level - 1 here. Or else the variable will be removed at once
  10441. * after builtin returns.
  10442. */
  10443. return helper_export_local(argv, (G.var_nest_level - 1) << SETFLAG_VARLVL_SHIFT);
  10444. }
  10445. #endif
  10446. #if ENABLE_HUSH_READONLY
  10447. static int FAST_FUNC builtin_readonly(char **argv)
  10448. {
  10449. argv++;
  10450. if (*argv == NULL) {
  10451. /* bash: readonly [-p]: list all readonly VARs
  10452. * (-p has no effect in bash)
  10453. */
  10454. struct variable *e;
  10455. for (e = G.top_var; e; e = e->next) {
  10456. if (e->flg_read_only) {
  10457. //TODO: quote value: readonly VAR='VAL'
  10458. printf("readonly %s\n", e->varstr);
  10459. }
  10460. }
  10461. return EXIT_SUCCESS;
  10462. }
  10463. return helper_export_local(argv, SETFLAG_MAKE_RO);
  10464. }
  10465. #endif
  10466. #if ENABLE_HUSH_UNSET
  10467. /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
  10468. static int FAST_FUNC builtin_unset(char **argv)
  10469. {
  10470. int ret;
  10471. unsigned opts;
  10472. /* "!": do not abort on errors */
  10473. /* "+": stop at 1st non-option */
  10474. opts = getopt32(argv, "!+vf");
  10475. if (opts == (unsigned)-1)
  10476. return EXIT_FAILURE;
  10477. if (opts == 3) {
  10478. bb_simple_error_msg("unset: -v and -f are exclusive");
  10479. return EXIT_FAILURE;
  10480. }
  10481. argv += optind;
  10482. ret = EXIT_SUCCESS;
  10483. while (*argv) {
  10484. if (!(opts & 2)) { /* not -f */
  10485. if (unset_local_var(*argv)) {
  10486. /* unset <nonexistent_var> doesn't fail.
  10487. * Error is when one tries to unset RO var.
  10488. * Message was printed by unset_local_var. */
  10489. ret = EXIT_FAILURE;
  10490. }
  10491. }
  10492. # if ENABLE_HUSH_FUNCTIONS
  10493. else {
  10494. unset_func(*argv);
  10495. }
  10496. # endif
  10497. argv++;
  10498. }
  10499. return ret;
  10500. }
  10501. #endif
  10502. #if ENABLE_HUSH_SET
  10503. /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
  10504. * built-in 'set' handler
  10505. * SUSv3 says:
  10506. * set [-abCefhmnuvx] [-o option] [argument...]
  10507. * set [+abCefhmnuvx] [+o option] [argument...]
  10508. * set -- [argument...]
  10509. * set -o
  10510. * set +o
  10511. * Implementations shall support the options in both their hyphen and
  10512. * plus-sign forms. These options can also be specified as options to sh.
  10513. * Examples:
  10514. * Write out all variables and their values: set
  10515. * Set $1, $2, and $3 and set "$#" to 3: set c a b
  10516. * Turn on the -x and -v options: set -xv
  10517. * Unset all positional parameters: set --
  10518. * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
  10519. * Set the positional parameters to the expansion of x, even if x expands
  10520. * with a leading '-' or '+': set -- $x
  10521. *
  10522. * So far, we only support "set -- [argument...]" and some of the short names.
  10523. */
  10524. static int FAST_FUNC builtin_set(char **argv)
  10525. {
  10526. int n;
  10527. char **pp, **g_argv;
  10528. char *arg = *++argv;
  10529. if (arg == NULL) {
  10530. struct variable *e;
  10531. for (e = G.top_var; e; e = e->next)
  10532. puts(e->varstr);
  10533. return EXIT_SUCCESS;
  10534. }
  10535. do {
  10536. if (strcmp(arg, "--") == 0) {
  10537. ++argv;
  10538. goto set_argv;
  10539. }
  10540. if (arg[0] != '+' && arg[0] != '-')
  10541. break;
  10542. for (n = 1; arg[n]; ++n) {
  10543. if (set_mode((arg[0] == '-'), arg[n], argv[1])) {
  10544. bb_error_msg("%s: %s: invalid option", "set", arg);
  10545. return EXIT_FAILURE;
  10546. }
  10547. if (arg[n] == 'o' && argv[1])
  10548. argv++;
  10549. }
  10550. } while ((arg = *++argv) != NULL);
  10551. /* Now argv[0] is 1st argument */
  10552. if (arg == NULL)
  10553. return EXIT_SUCCESS;
  10554. set_argv:
  10555. /* NB: G.global_argv[0] ($0) is never freed/changed */
  10556. g_argv = G.global_argv;
  10557. if (G.global_args_malloced) {
  10558. pp = g_argv;
  10559. while (*++pp)
  10560. free(*pp);
  10561. g_argv[1] = NULL;
  10562. } else {
  10563. G.global_args_malloced = 1;
  10564. pp = xzalloc(sizeof(pp[0]) * 2);
  10565. pp[0] = g_argv[0]; /* retain $0 */
  10566. g_argv = pp;
  10567. }
  10568. /* This realloc's G.global_argv */
  10569. G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
  10570. G.global_argc = 1 + string_array_len(pp + 1);
  10571. return EXIT_SUCCESS;
  10572. }
  10573. #endif
  10574. static int FAST_FUNC builtin_shift(char **argv)
  10575. {
  10576. int n = 1;
  10577. argv = skip_dash_dash(argv);
  10578. if (argv[0]) {
  10579. n = bb_strtou(argv[0], NULL, 10);
  10580. if (errno || n < 0) {
  10581. /* shared string with ash.c */
  10582. bb_error_msg("Illegal number: %s", argv[0]);
  10583. /*
  10584. * ash aborts in this case.
  10585. * bash prints error message and set $? to 1.
  10586. * Interestingly, for "shift 99999" bash does not
  10587. * print error message, but does set $? to 1
  10588. * (and does no shifting at all).
  10589. */
  10590. }
  10591. }
  10592. if (n >= 0 && n < G.global_argc) {
  10593. if (G_global_args_malloced) {
  10594. int m = 1;
  10595. while (m <= n)
  10596. free(G.global_argv[m++]);
  10597. }
  10598. G.global_argc -= n;
  10599. memmove(&G.global_argv[1], &G.global_argv[n+1],
  10600. G.global_argc * sizeof(G.global_argv[0]));
  10601. return EXIT_SUCCESS;
  10602. }
  10603. return EXIT_FAILURE;
  10604. }
  10605. #if ENABLE_HUSH_GETOPTS
  10606. static int FAST_FUNC builtin_getopts(char **argv)
  10607. {
  10608. /* http://pubs.opengroup.org/onlinepubs/9699919799/utilities/getopts.html
  10609. TODO:
  10610. If a required argument is not found, and getopts is not silent,
  10611. a question mark (?) is placed in VAR, OPTARG is unset, and a
  10612. diagnostic message is printed. If getopts is silent, then a
  10613. colon (:) is placed in VAR and OPTARG is set to the option
  10614. character found.
  10615. Test that VAR is a valid variable name?
  10616. "Whenever the shell is invoked, OPTIND shall be initialized to 1"
  10617. */
  10618. char cbuf[2];
  10619. const char *cp, *optstring, *var;
  10620. int c, n, exitcode, my_opterr;
  10621. unsigned count;
  10622. optstring = *++argv;
  10623. if (!optstring || !(var = *++argv)) {
  10624. bb_simple_error_msg("usage: getopts OPTSTRING VAR [ARGS]");
  10625. return EXIT_FAILURE;
  10626. }
  10627. if (argv[1])
  10628. argv[0] = G.global_argv[0]; /* for error messages in getopt() */
  10629. else
  10630. argv = G.global_argv;
  10631. cbuf[1] = '\0';
  10632. my_opterr = 0;
  10633. if (optstring[0] != ':') {
  10634. cp = get_local_var_value("OPTERR");
  10635. /* 0 if "OPTERR=0", 1 otherwise */
  10636. my_opterr = (!cp || NOT_LONE_CHAR(cp, '0'));
  10637. }
  10638. /* getopts stops on first non-option. Add "+" to force that */
  10639. /*if (optstring[0] != '+')*/ {
  10640. char *s = alloca(strlen(optstring) + 2);
  10641. sprintf(s, "+%s", optstring);
  10642. optstring = s;
  10643. }
  10644. /* Naively, now we should just
  10645. * cp = get_local_var_value("OPTIND");
  10646. * optind = cp ? atoi(cp) : 0;
  10647. * optarg = NULL;
  10648. * opterr = my_opterr;
  10649. * c = getopt(string_array_len(argv), argv, optstring);
  10650. * and be done? Not so fast...
  10651. * Unlike normal getopt() usage in C programs, here
  10652. * each successive call will (usually) have the same argv[] CONTENTS,
  10653. * but not the ADDRESSES. Worse yet, it's possible that between
  10654. * invocations of "getopts", there will be calls to shell builtins
  10655. * which use getopt() internally. Example:
  10656. * while getopts "abc" RES -a -bc -abc de; do
  10657. * unset -ff func
  10658. * done
  10659. * This would not work correctly: getopt() call inside "unset"
  10660. * modifies internal libc state which is tracking position in
  10661. * multi-option strings ("-abc"). At best, it can skip options
  10662. * or return the same option infinitely. With glibc implementation
  10663. * of getopt(), it would use outright invalid pointers and return
  10664. * garbage even _without_ "unset" mangling internal state.
  10665. *
  10666. * We resort to resetting getopt() state and calling it N times,
  10667. * until we get Nth result (or failure).
  10668. * (N == G.getopt_count is reset to 0 whenever OPTIND is [un]set).
  10669. */
  10670. GETOPT_RESET();
  10671. count = 0;
  10672. n = string_array_len(argv);
  10673. do {
  10674. optarg = NULL;
  10675. opterr = (count < G.getopt_count) ? 0 : my_opterr;
  10676. c = getopt(n, argv, optstring);
  10677. if (c < 0)
  10678. break;
  10679. count++;
  10680. } while (count <= G.getopt_count);
  10681. /* Set OPTIND. Prevent resetting of the magic counter! */
  10682. set_local_var_from_halves("OPTIND", utoa(optind));
  10683. G.getopt_count = count; /* "next time, give me N+1'th result" */
  10684. GETOPT_RESET(); /* just in case */
  10685. /* Set OPTARG */
  10686. /* Always set or unset, never left as-is, even on exit/error:
  10687. * "If no option was found, or if the option that was found
  10688. * does not have an option-argument, OPTARG shall be unset."
  10689. */
  10690. cp = optarg;
  10691. if (c == '?') {
  10692. /* If ":optstring" and unknown option is seen,
  10693. * it is stored to OPTARG.
  10694. */
  10695. if (optstring[1] == ':') {
  10696. cbuf[0] = optopt;
  10697. cp = cbuf;
  10698. }
  10699. }
  10700. if (cp)
  10701. set_local_var_from_halves("OPTARG", cp);
  10702. else
  10703. unset_local_var("OPTARG");
  10704. /* Convert -1 to "?" */
  10705. exitcode = EXIT_SUCCESS;
  10706. if (c < 0) { /* -1: end of options */
  10707. exitcode = EXIT_FAILURE;
  10708. c = '?';
  10709. }
  10710. /* Set VAR */
  10711. cbuf[0] = c;
  10712. set_local_var_from_halves(var, cbuf);
  10713. return exitcode;
  10714. }
  10715. #endif
  10716. static int FAST_FUNC builtin_source(char **argv)
  10717. {
  10718. char *arg_path, *filename;
  10719. HFILE *input;
  10720. save_arg_t sv;
  10721. char *args_need_save;
  10722. #if ENABLE_HUSH_FUNCTIONS
  10723. smallint sv_flg;
  10724. #endif
  10725. argv = skip_dash_dash(argv);
  10726. filename = argv[0];
  10727. if (!filename) {
  10728. /* bash says: "bash: .: filename argument required" */
  10729. return 2; /* bash compat */
  10730. }
  10731. arg_path = NULL;
  10732. if (!strchr(filename, '/')) {
  10733. arg_path = find_in_path(filename);
  10734. if (arg_path)
  10735. filename = arg_path;
  10736. else if (!ENABLE_HUSH_BASH_SOURCE_CURDIR) {
  10737. errno = ENOENT;
  10738. bb_simple_perror_msg(filename);
  10739. return EXIT_FAILURE;
  10740. }
  10741. }
  10742. input = hfopen(filename);
  10743. free(arg_path);
  10744. if (!input) {
  10745. bb_perror_msg("%s", filename);
  10746. /* POSIX: non-interactive shell should abort here,
  10747. * not merely fail. So far no one complained :)
  10748. */
  10749. return EXIT_FAILURE;
  10750. }
  10751. #if ENABLE_HUSH_FUNCTIONS
  10752. sv_flg = G_flag_return_in_progress;
  10753. /* "we are inside sourced file, ok to use return" */
  10754. G_flag_return_in_progress = -1;
  10755. #endif
  10756. args_need_save = argv[1]; /* used as a boolean variable */
  10757. if (args_need_save)
  10758. save_and_replace_G_args(&sv, argv);
  10759. /* "false; . ./empty_line; echo Zero:$?" should print 0 */
  10760. G.last_exitcode = 0;
  10761. parse_and_run_file(input);
  10762. hfclose(input);
  10763. if (args_need_save) /* can't use argv[1] instead: "shift" can mangle it */
  10764. restore_G_args(&sv, argv);
  10765. #if ENABLE_HUSH_FUNCTIONS
  10766. G_flag_return_in_progress = sv_flg;
  10767. #endif
  10768. return G.last_exitcode;
  10769. }
  10770. #if ENABLE_HUSH_TRAP
  10771. static int FAST_FUNC builtin_trap(char **argv)
  10772. {
  10773. int sig;
  10774. char *new_cmd;
  10775. if (!G_traps)
  10776. G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
  10777. argv++;
  10778. if (!*argv) {
  10779. int i;
  10780. /* No args: print all trapped */
  10781. for (i = 0; i < NSIG; ++i) {
  10782. if (G_traps[i]) {
  10783. printf("trap -- ");
  10784. print_escaped(G_traps[i]);
  10785. /* note: bash adds "SIG", but only if invoked
  10786. * as "bash". If called as "sh", or if set -o posix,
  10787. * then it prints short signal names.
  10788. * We are printing short names: */
  10789. printf(" %s\n", get_signame(i));
  10790. }
  10791. }
  10792. /*fflush_all(); - done after each builtin anyway */
  10793. return EXIT_SUCCESS;
  10794. }
  10795. new_cmd = NULL;
  10796. /* If first arg is a number: reset all specified signals */
  10797. sig = bb_strtou(*argv, NULL, 10);
  10798. if (errno == 0) {
  10799. int ret;
  10800. process_sig_list:
  10801. ret = EXIT_SUCCESS;
  10802. while (*argv) {
  10803. sighandler_t handler;
  10804. sig = get_signum(*argv++);
  10805. if (sig < 0) {
  10806. ret = EXIT_FAILURE;
  10807. /* Mimic bash message exactly */
  10808. bb_error_msg("trap: %s: invalid signal specification", argv[-1]);
  10809. continue;
  10810. }
  10811. free(G_traps[sig]);
  10812. G_traps[sig] = xstrdup(new_cmd);
  10813. debug_printf("trap: setting SIG%s (%i) to '%s'\n",
  10814. get_signame(sig), sig, G_traps[sig]);
  10815. /* There is no signal for 0 (EXIT) */
  10816. if (sig == 0)
  10817. continue;
  10818. if (new_cmd)
  10819. handler = (new_cmd[0] ? record_pending_signo : SIG_IGN);
  10820. else
  10821. /* We are removing trap handler */
  10822. handler = pick_sighandler(sig);
  10823. install_sighandler(sig, handler);
  10824. }
  10825. return ret;
  10826. }
  10827. if (!argv[1]) { /* no second arg */
  10828. bb_simple_error_msg("trap: invalid arguments");
  10829. return EXIT_FAILURE;
  10830. }
  10831. /* First arg is "-": reset all specified to default */
  10832. /* First arg is "--": skip it, the rest is "handler SIGs..." */
  10833. /* Everything else: set arg as signal handler
  10834. * (includes "" case, which ignores signal) */
  10835. if (argv[0][0] == '-') {
  10836. if (argv[0][1] == '\0') { /* "-" */
  10837. /* new_cmd remains NULL: "reset these sigs" */
  10838. goto reset_traps;
  10839. }
  10840. if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
  10841. argv++;
  10842. }
  10843. /* else: "-something", no special meaning */
  10844. }
  10845. new_cmd = *argv;
  10846. reset_traps:
  10847. argv++;
  10848. goto process_sig_list;
  10849. }
  10850. #endif
  10851. #if ENABLE_HUSH_JOB
  10852. static struct pipe *parse_jobspec(const char *str)
  10853. {
  10854. struct pipe *pi;
  10855. unsigned jobnum;
  10856. if (sscanf(str, "%%%u", &jobnum) != 1) {
  10857. if (str[0] != '%'
  10858. || (str[1] != '%' && str[1] != '+' && str[1] != '\0')
  10859. ) {
  10860. bb_error_msg("bad argument '%s'", str);
  10861. return NULL;
  10862. }
  10863. /* It is "%%", "%+" or "%" - current job */
  10864. jobnum = G.last_jobid;
  10865. if (jobnum == 0) {
  10866. bb_simple_error_msg("no current job");
  10867. return NULL;
  10868. }
  10869. }
  10870. for (pi = G.job_list; pi; pi = pi->next) {
  10871. if (pi->jobid == jobnum) {
  10872. return pi;
  10873. }
  10874. }
  10875. bb_error_msg("%u: no such job", jobnum);
  10876. return NULL;
  10877. }
  10878. static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
  10879. {
  10880. struct pipe *job;
  10881. const char *status_string;
  10882. checkjobs(NULL, 0 /*(no pid to wait for)*/);
  10883. for (job = G.job_list; job; job = job->next) {
  10884. if (job->alive_cmds == job->stopped_cmds)
  10885. status_string = "Stopped";
  10886. else
  10887. status_string = "Running";
  10888. printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
  10889. }
  10890. clean_up_last_dead_job();
  10891. return EXIT_SUCCESS;
  10892. }
  10893. /* built-in 'fg' and 'bg' handler */
  10894. static int FAST_FUNC builtin_fg_bg(char **argv)
  10895. {
  10896. int i;
  10897. struct pipe *pi;
  10898. if (!G_interactive_fd)
  10899. return EXIT_FAILURE;
  10900. /* If they gave us no args, assume they want the last backgrounded task */
  10901. if (!argv[1]) {
  10902. for (pi = G.job_list; pi; pi = pi->next) {
  10903. if (pi->jobid == G.last_jobid) {
  10904. goto found;
  10905. }
  10906. }
  10907. bb_error_msg("%s: no current job", argv[0]);
  10908. return EXIT_FAILURE;
  10909. }
  10910. pi = parse_jobspec(argv[1]);
  10911. if (!pi)
  10912. return EXIT_FAILURE;
  10913. found:
  10914. /* TODO: bash prints a string representation
  10915. * of job being foregrounded (like "sleep 1 | cat") */
  10916. if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
  10917. /* Put the job into the foreground. */
  10918. tcsetpgrp(G_interactive_fd, pi->pgrp);
  10919. }
  10920. /* Restart the processes in the job */
  10921. debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
  10922. for (i = 0; i < pi->num_cmds; i++) {
  10923. debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
  10924. }
  10925. pi->stopped_cmds = 0;
  10926. i = kill(- pi->pgrp, SIGCONT);
  10927. if (i < 0) {
  10928. if (errno == ESRCH) {
  10929. delete_finished_job(pi);
  10930. return EXIT_SUCCESS;
  10931. }
  10932. bb_simple_perror_msg("kill (SIGCONT)");
  10933. }
  10934. if (argv[0][0] == 'f') {
  10935. remove_job_from_table(pi); /* FG job shouldn't be in job table */
  10936. return checkjobs_and_fg_shell(pi);
  10937. }
  10938. return EXIT_SUCCESS;
  10939. }
  10940. #endif
  10941. #if ENABLE_HUSH_KILL
  10942. static int FAST_FUNC builtin_kill(char **argv)
  10943. {
  10944. int ret = 0;
  10945. # if ENABLE_HUSH_JOB
  10946. if (argv[1] && strcmp(argv[1], "-l") != 0) {
  10947. int i = 1;
  10948. do {
  10949. struct pipe *pi;
  10950. char *dst;
  10951. int j, n;
  10952. if (argv[i][0] != '%')
  10953. continue;
  10954. /*
  10955. * "kill %N" - job kill
  10956. * Converting to pgrp / pid kill
  10957. */
  10958. pi = parse_jobspec(argv[i]);
  10959. if (!pi) {
  10960. /* Eat bad jobspec */
  10961. j = i;
  10962. do {
  10963. j++;
  10964. argv[j - 1] = argv[j];
  10965. } while (argv[j]);
  10966. ret = 1;
  10967. i--;
  10968. continue;
  10969. }
  10970. /*
  10971. * In jobs started under job control, we signal
  10972. * entire process group by kill -PGRP_ID.
  10973. * This happens, f.e., in interactive shell.
  10974. *
  10975. * Otherwise, we signal each child via
  10976. * kill PID1 PID2 PID3.
  10977. * Testcases:
  10978. * sh -c 'sleep 1|sleep 1 & kill %1'
  10979. * sh -c 'true|sleep 2 & sleep 1; kill %1'
  10980. * sh -c 'true|sleep 1 & sleep 2; kill %1'
  10981. */
  10982. n = G_interactive_fd ? 1 : pi->num_cmds;
  10983. dst = alloca(n * sizeof(int)*4);
  10984. argv[i] = dst;
  10985. if (G_interactive_fd)
  10986. dst += sprintf(dst, " -%u", (int)pi->pgrp);
  10987. else for (j = 0; j < n; j++) {
  10988. struct command *cmd = &pi->cmds[j];
  10989. /* Skip exited members of the job */
  10990. if (cmd->pid == 0)
  10991. continue;
  10992. /*
  10993. * kill_main has matching code to expect
  10994. * leading space. Needed to not confuse
  10995. * negative pids with "kill -SIGNAL_NO" syntax
  10996. */
  10997. dst += sprintf(dst, " %u", (int)cmd->pid);
  10998. }
  10999. *dst = '\0';
  11000. } while (argv[++i]);
  11001. }
  11002. # endif
  11003. if (argv[1] || ret == 0) {
  11004. ret = run_applet_main(argv, kill_main);
  11005. }
  11006. /* else: ret = 1, "kill %bad_jobspec" case */
  11007. return ret;
  11008. }
  11009. #endif
  11010. #if ENABLE_HUSH_WAIT
  11011. /* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
  11012. # if !ENABLE_HUSH_JOB
  11013. # define wait_for_child_or_signal(pipe,pid) wait_for_child_or_signal(pid)
  11014. # endif
  11015. static int wait_for_child_or_signal(struct pipe *waitfor_pipe, pid_t waitfor_pid)
  11016. {
  11017. int ret = 0;
  11018. for (;;) {
  11019. int sig;
  11020. sigset_t oldset;
  11021. if (!sigisemptyset(&G.pending_set))
  11022. goto check_sig;
  11023. /* waitpid is not interruptible by SA_RESTARTed
  11024. * signals which we use. Thus, this ugly dance:
  11025. */
  11026. /* Make sure possible SIGCHLD is stored in kernel's
  11027. * pending signal mask before we call waitpid.
  11028. * Or else we may race with SIGCHLD, lose it,
  11029. * and get stuck in sigsuspend...
  11030. */
  11031. sigfillset(&oldset); /* block all signals, remember old set */
  11032. sigprocmask2(SIG_SETMASK, &oldset);
  11033. if (!sigisemptyset(&G.pending_set)) {
  11034. /* Crap! we raced with some signal! */
  11035. goto restore;
  11036. }
  11037. /*errno = 0; - checkjobs does this */
  11038. /* Can't pass waitfor_pipe into checkjobs(): it won't be interruptible */
  11039. ret = checkjobs(NULL, waitfor_pid); /* waitpid(WNOHANG) inside */
  11040. debug_printf_exec("checkjobs:%d\n", ret);
  11041. # if ENABLE_HUSH_JOB
  11042. if (waitfor_pipe) {
  11043. int rcode = job_exited_or_stopped(waitfor_pipe);
  11044. debug_printf_exec("job_exited_or_stopped:%d\n", rcode);
  11045. if (rcode >= 0) {
  11046. ret = rcode;
  11047. sigprocmask(SIG_SETMASK, &oldset, NULL);
  11048. break;
  11049. }
  11050. }
  11051. # endif
  11052. /* if ECHILD, there are no children (ret is -1 or 0) */
  11053. /* if ret == 0, no children changed state */
  11054. /* if ret != 0, it's exitcode+1 of exited waitfor_pid child */
  11055. if (errno == ECHILD || ret) {
  11056. ret--;
  11057. if (ret < 0) /* if ECHILD, may need to fix "ret" */
  11058. ret = 0;
  11059. # if ENABLE_HUSH_BASH_COMPAT
  11060. if (waitfor_pid == -1 && errno == ECHILD) {
  11061. /* exitcode of "wait -n" with no children is 127, not 0 */
  11062. ret = 127;
  11063. }
  11064. # endif
  11065. sigprocmask(SIG_SETMASK, &oldset, NULL);
  11066. break;
  11067. }
  11068. /* Wait for SIGCHLD or any other signal */
  11069. /* It is vitally important for sigsuspend that SIGCHLD has non-DFL handler! */
  11070. /* Note: sigsuspend invokes signal handler */
  11071. sigsuspend(&oldset);
  11072. /* ^^^ add "sigdelset(&oldset, SIGCHLD)" before sigsuspend
  11073. * to make sure SIGCHLD is not masked off?
  11074. * It was reported that this:
  11075. * fn() { : | return; }
  11076. * shopt -s lastpipe
  11077. * fn
  11078. * exec hush SCRIPT
  11079. * under bash 4.4.23 runs SCRIPT with SIGCHLD masked,
  11080. * making "wait" commands in SCRIPT block forever.
  11081. */
  11082. restore:
  11083. sigprocmask(SIG_SETMASK, &oldset, NULL);
  11084. check_sig:
  11085. /* So, did we get a signal? */
  11086. sig = check_and_run_traps();
  11087. if (sig /*&& sig != SIGCHLD - always true */) {
  11088. /* Do this for any (non-ignored) signal, not only for ^C */
  11089. ret = 128 | sig;
  11090. break;
  11091. }
  11092. /* SIGCHLD, or no signal, or ignored one, such as SIGQUIT. Repeat */
  11093. }
  11094. return ret;
  11095. }
  11096. static int FAST_FUNC builtin_wait(char **argv)
  11097. {
  11098. int ret;
  11099. int status;
  11100. argv = skip_dash_dash(argv);
  11101. # if ENABLE_HUSH_BASH_COMPAT
  11102. if (argv[0] && strcmp(argv[0], "-n") == 0) {
  11103. /* wait -n */
  11104. /* (bash accepts "wait -n PID" too and ignores PID) */
  11105. G.dead_job_exitcode = -1;
  11106. return wait_for_child_or_signal(NULL, -1 /*no job, wait for one job*/);
  11107. }
  11108. # endif
  11109. if (argv[0] == NULL) {
  11110. /* Don't care about wait results */
  11111. /* Note 1: must wait until there are no more children */
  11112. /* Note 2: must be interruptible */
  11113. /* Examples:
  11114. * $ sleep 3 & sleep 6 & wait
  11115. * [1] 30934 sleep 3
  11116. * [2] 30935 sleep 6
  11117. * [1] Done sleep 3
  11118. * [2] Done sleep 6
  11119. * $ sleep 3 & sleep 6 & wait
  11120. * [1] 30936 sleep 3
  11121. * [2] 30937 sleep 6
  11122. * [1] Done sleep 3
  11123. * ^C <-- after ~4 sec from keyboard
  11124. * $
  11125. */
  11126. return wait_for_child_or_signal(NULL, 0 /*no job and no pid to wait for*/);
  11127. }
  11128. do {
  11129. pid_t pid = bb_strtou(*argv, NULL, 10);
  11130. if (errno || pid <= 0) {
  11131. # if ENABLE_HUSH_JOB
  11132. if (argv[0][0] == '%') {
  11133. struct pipe *wait_pipe;
  11134. ret = 127; /* bash compat for bad jobspecs */
  11135. wait_pipe = parse_jobspec(*argv);
  11136. if (wait_pipe) {
  11137. ret = job_exited_or_stopped(wait_pipe);
  11138. if (ret < 0) {
  11139. ret = wait_for_child_or_signal(wait_pipe, 0);
  11140. } else {
  11141. /* waiting on "last dead job" removes it */
  11142. clean_up_last_dead_job();
  11143. }
  11144. }
  11145. /* else: parse_jobspec() already emitted error msg */
  11146. continue;
  11147. }
  11148. # endif
  11149. /* mimic bash message */
  11150. bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
  11151. ret = EXIT_FAILURE;
  11152. continue; /* bash checks all argv[] */
  11153. }
  11154. /* Do we have such child? */
  11155. ret = waitpid(pid, &status, WNOHANG);
  11156. if (ret < 0) {
  11157. /* No */
  11158. ret = 127;
  11159. if (errno == ECHILD) {
  11160. if (pid == G.last_bg_pid) {
  11161. /* "wait $!" but last bg task has already exited. Try:
  11162. * (sleep 1; exit 3) & sleep 2; echo $?; wait $!; echo $?
  11163. * In bash it prints exitcode 0, then 3.
  11164. * In dash, it is 127.
  11165. */
  11166. ret = G.last_bg_pid_exitcode;
  11167. } else {
  11168. /* Example: "wait 1". mimic bash message */
  11169. bb_error_msg("wait: pid %u is not a child of this shell", (unsigned)pid);
  11170. }
  11171. } else {
  11172. /* ??? */
  11173. bb_perror_msg("wait %s", *argv);
  11174. }
  11175. continue; /* bash checks all argv[] */
  11176. }
  11177. if (ret == 0) {
  11178. /* Yes, and it still runs */
  11179. ret = wait_for_child_or_signal(NULL, pid);
  11180. } else {
  11181. /* Yes, and it just exited */
  11182. process_wait_result(NULL, pid, status);
  11183. ret = WEXITSTATUS(status);
  11184. if (WIFSIGNALED(status))
  11185. ret = 128 | WTERMSIG(status);
  11186. }
  11187. } while (*++argv);
  11188. return ret;
  11189. }
  11190. #endif
  11191. #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
  11192. static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
  11193. {
  11194. if (argv[1]) {
  11195. def = bb_strtou(argv[1], NULL, 10);
  11196. if (errno || def < def_min || argv[2]) {
  11197. bb_error_msg("%s: bad arguments", argv[0]);
  11198. def = UINT_MAX;
  11199. }
  11200. }
  11201. return def;
  11202. }
  11203. #endif
  11204. #if ENABLE_HUSH_LOOPS
  11205. static int FAST_FUNC builtin_break(char **argv)
  11206. {
  11207. unsigned depth;
  11208. if (G.depth_of_loop == 0) {
  11209. bb_error_msg("%s: only meaningful in a loop", argv[0]);
  11210. /* if we came from builtin_continue(), need to undo "= 1" */
  11211. G.flag_break_continue = 0;
  11212. return EXIT_SUCCESS; /* bash compat */
  11213. }
  11214. G.flag_break_continue++; /* BC_BREAK = 1, or BC_CONTINUE = 2 */
  11215. G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
  11216. if (depth == UINT_MAX)
  11217. G.flag_break_continue = BC_BREAK;
  11218. if (G.depth_of_loop < depth)
  11219. G.depth_break_continue = G.depth_of_loop;
  11220. return EXIT_SUCCESS;
  11221. }
  11222. static int FAST_FUNC builtin_continue(char **argv)
  11223. {
  11224. G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
  11225. return builtin_break(argv);
  11226. }
  11227. #endif
  11228. #if ENABLE_HUSH_FUNCTIONS
  11229. static int FAST_FUNC builtin_return(char **argv)
  11230. {
  11231. int rc;
  11232. if (G_flag_return_in_progress != -1) {
  11233. bb_error_msg("%s: not in a function or sourced script", argv[0]);
  11234. return EXIT_FAILURE; /* bash compat */
  11235. }
  11236. G_flag_return_in_progress = 1;
  11237. /* bash:
  11238. * out of range: wraps around at 256, does not error out
  11239. * non-numeric param:
  11240. * f() { false; return qwe; }; f; echo $?
  11241. * bash: return: qwe: numeric argument required <== we do this
  11242. * 255 <== we also do this
  11243. */
  11244. rc = parse_numeric_argv1(argv, G.last_exitcode, 0);
  11245. # if ENABLE_HUSH_TRAP
  11246. if (argv[1]) { /* "return ARG" inside a running trap sets $? */
  11247. debug_printf_exec("G.return_exitcode=%d\n", rc);
  11248. G.return_exitcode = rc;
  11249. }
  11250. # endif
  11251. return rc;
  11252. }
  11253. #endif
  11254. #if ENABLE_HUSH_TIMES
  11255. static int FAST_FUNC builtin_times(char **argv UNUSED_PARAM)
  11256. {
  11257. static const uint8_t times_tbl[] ALIGN1 = {
  11258. ' ', offsetof(struct tms, tms_utime),
  11259. '\n', offsetof(struct tms, tms_stime),
  11260. ' ', offsetof(struct tms, tms_cutime),
  11261. '\n', offsetof(struct tms, tms_cstime),
  11262. 0
  11263. };
  11264. const uint8_t *p;
  11265. unsigned clk_tck;
  11266. struct tms buf;
  11267. clk_tck = bb_clk_tck();
  11268. times(&buf);
  11269. p = times_tbl;
  11270. do {
  11271. unsigned sec, frac;
  11272. unsigned long t;
  11273. t = *(clock_t *)(((char *) &buf) + p[1]);
  11274. sec = t / clk_tck;
  11275. frac = t % clk_tck;
  11276. printf("%um%u.%03us%c",
  11277. sec / 60, sec % 60,
  11278. (frac * 1000) / clk_tck,
  11279. p[0]);
  11280. p += 2;
  11281. } while (*p);
  11282. return EXIT_SUCCESS;
  11283. }
  11284. #endif
  11285. #if ENABLE_HUSH_MEMLEAK
  11286. static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
  11287. {
  11288. void *p;
  11289. unsigned long l;
  11290. # ifdef M_TRIM_THRESHOLD
  11291. /* Optional. Reduces probability of false positives */
  11292. malloc_trim(0);
  11293. # endif
  11294. /* Crude attempt to find where "free memory" starts,
  11295. * sans fragmentation. */
  11296. p = malloc(240);
  11297. l = (unsigned long)p;
  11298. free(p);
  11299. p = malloc(3400);
  11300. if (l < (unsigned long)p) l = (unsigned long)p;
  11301. free(p);
  11302. # if 0 /* debug */
  11303. {
  11304. struct mallinfo mi = mallinfo();
  11305. printf("top alloc:0x%lx malloced:%d+%d=%d\n", l,
  11306. mi.arena, mi.hblkhd, mi.arena + mi.hblkhd);
  11307. }
  11308. # endif
  11309. if (!G.memleak_value)
  11310. G.memleak_value = l;
  11311. l -= G.memleak_value;
  11312. if ((long)l < 0)
  11313. l = 0;
  11314. l /= 1024;
  11315. if (l > 127)
  11316. l = 127;
  11317. /* Exitcode is "how many kilobytes we leaked since 1st call" */
  11318. return l;
  11319. }
  11320. #endif