hush.c 327 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * A prototype Bourne shell grammar parser.
  4. * Intended to follow the original Thompson and Ritchie
  5. * "small and simple is beautiful" philosophy, which
  6. * incidentally is a good match to today's BusyBox.
  7. *
  8. * Copyright (C) 2000,2001 Larry Doolittle <larry@doolittle.boa.org>
  9. * Copyright (C) 2008,2009 Denys Vlasenko <vda.linux@googlemail.com>
  10. *
  11. * Licensed under GPLv2 or later, see file LICENSE in this source tree.
  12. *
  13. * Credits:
  14. * The parser routines proper are all original material, first
  15. * written Dec 2000 and Jan 2001 by Larry Doolittle. The
  16. * execution engine, the builtins, and much of the underlying
  17. * support has been adapted from busybox-0.49pre's lash, which is
  18. * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
  19. * written by Erik Andersen <andersen@codepoet.org>. That, in turn,
  20. * is based in part on ladsh.c, by Michael K. Johnson and Erik W.
  21. * Troan, which they placed in the public domain. I don't know
  22. * how much of the Johnson/Troan code has survived the repeated
  23. * rewrites.
  24. *
  25. * Other credits:
  26. * o_addchr derived from similar w_addchar function in glibc-2.2.
  27. * parse_redirect, redirect_opt_num, and big chunks of main
  28. * and many builtins derived from contributions by Erik Andersen.
  29. * Miscellaneous bugfixes from Matt Kraai.
  30. *
  31. * There are two big (and related) architecture differences between
  32. * this parser and the lash parser. One is that this version is
  33. * actually designed from the ground up to understand nearly all
  34. * of the Bourne grammar. The second, consequential change is that
  35. * the parser and input reader have been turned inside out. Now,
  36. * the parser is in control, and asks for input as needed. The old
  37. * way had the input reader in control, and it asked for parsing to
  38. * take place as needed. The new way makes it much easier to properly
  39. * handle the recursion implicit in the various substitutions, especially
  40. * across continuation lines.
  41. *
  42. * TODOs:
  43. * grep for "TODO" and fix (some of them are easy)
  44. * make complex ${var%...} constructs support optional
  45. * make here documents optional
  46. * special variables (done: PWD, PPID, RANDOM)
  47. * follow IFS rules more precisely, including update semantics
  48. * tilde expansion
  49. * aliases
  50. * "command" missing features:
  51. * command -p CMD: run CMD using default $PATH
  52. * (can use this to override standalone shell as well?)
  53. * command BLTIN: disables special-ness (e.g. errors do not abort)
  54. * command -V CMD1 CMD2 CMD3 (multiple args) (not in standard)
  55. * builtins mandated by standards we don't support:
  56. * [un]alias, fc:
  57. * fc -l[nr] [BEG] [END]: list range of commands in history
  58. * fc [-e EDITOR] [BEG] [END]: edit/rerun range of commands
  59. * fc -s [PAT=REP] [CMD]: rerun CMD, replacing PAT with REP
  60. *
  61. * Bash compat TODO:
  62. * redirection of stdout+stderr: &> and >&
  63. * reserved words: function select
  64. * advanced test: [[ ]]
  65. * process substitution: <(list) and >(list)
  66. * let EXPR [EXPR...]
  67. * Each EXPR is an arithmetic expression (ARITHMETIC EVALUATION)
  68. * If the last arg evaluates to 0, let returns 1; 0 otherwise.
  69. * NB: let `echo 'a=a + 1'` - error (IOW: multi-word expansion is used)
  70. * ((EXPR))
  71. * The EXPR is evaluated according to ARITHMETIC EVALUATION.
  72. * This is exactly equivalent to let "EXPR".
  73. * $[EXPR]: synonym for $((EXPR))
  74. * indirect expansion: ${!VAR}
  75. * substring op on @: ${@:n:m}
  76. *
  77. * Won't do:
  78. * Some builtins mandated by standards:
  79. * newgrp [GRP]: not a builtin in bash but a suid binary
  80. * which spawns a new shell with new group ID
  81. *
  82. * Status of [[ support:
  83. * [[ args ]] are CMD_SINGLEWORD_NOGLOB:
  84. * v='a b'; [[ $v = 'a b' ]]; echo 0:$?
  85. * [[ /bin/n* ]]; echo 0:$?
  86. * = is glob match operator, not equality operator: STR = GLOB
  87. * == same as =
  88. * =~ is regex match operator: STR =~ REGEX
  89. * TODO:
  90. * quoting needs to be considered (-f is an operator, "-f" and ""-f are not; etc)
  91. * in word = GLOB, quoting should be significant on char-by-char basis: a*cd"*"
  92. */
  93. //config:config HUSH
  94. //config: bool "hush (68 kb)"
  95. //config: default y
  96. //config: select SHELL_HUSH
  97. //config: help
  98. //config: hush is a small shell. It handles the normal flow control
  99. //config: constructs such as if/then/elif/else/fi, for/in/do/done, while loops,
  100. //config: case/esac. Redirections, here documents, $((arithmetic))
  101. //config: and functions are supported.
  102. //config:
  103. //config: It will compile and work on no-mmu systems.
  104. //config:
  105. //config: It does not handle select, aliases, tilde expansion,
  106. //config: &>file and >&file redirection of stdout+stderr.
  107. //config:
  108. // This option is visible (has a description) to make it possible to select
  109. // a "scripted" applet (such as NOLOGIN) but avoid selecting any shells:
  110. //config:config SHELL_HUSH
  111. //config: bool "Internal shell for embedded script support"
  112. //config: default n
  113. //config:
  114. //config:# hush options
  115. //config:# It's only needed to get "nice" menuconfig indenting.
  116. //config:if SHELL_HUSH || HUSH || SH_IS_HUSH || BASH_IS_HUSH
  117. //config:
  118. //config:config HUSH_BASH_COMPAT
  119. //config: bool "bash-compatible extensions"
  120. //config: default y
  121. //config: depends on SHELL_HUSH
  122. //config:
  123. //config:config HUSH_BRACE_EXPANSION
  124. //config: bool "Brace expansion"
  125. //config: default y
  126. //config: depends on HUSH_BASH_COMPAT
  127. //config: help
  128. //config: Enable {abc,def} extension.
  129. //config:
  130. //config:config HUSH_LINENO_VAR
  131. //config: bool "$LINENO variable"
  132. //config: default y
  133. //config: depends on HUSH_BASH_COMPAT
  134. //config:
  135. //config:config HUSH_BASH_SOURCE_CURDIR
  136. //config: bool "'source' and '.' builtins search current directory after $PATH"
  137. //config: default n # do not encourage non-standard behavior
  138. //config: depends on HUSH_BASH_COMPAT
  139. //config: help
  140. //config: This is not compliant with standards. Avoid if possible.
  141. //config:
  142. //config:config HUSH_INTERACTIVE
  143. //config: bool "Interactive mode"
  144. //config: default y
  145. //config: depends on SHELL_HUSH
  146. //config: help
  147. //config: Enable interactive mode (prompt and command editing).
  148. //config: Without this, hush simply reads and executes commands
  149. //config: from stdin just like a shell script from a file.
  150. //config: No prompt, no PS1/PS2 magic shell variables.
  151. //config:
  152. //config:config HUSH_SAVEHISTORY
  153. //config: bool "Save command history to .hush_history"
  154. //config: default y
  155. //config: depends on HUSH_INTERACTIVE && FEATURE_EDITING_SAVEHISTORY
  156. //config:
  157. //config:config HUSH_JOB
  158. //config: bool "Job control"
  159. //config: default y
  160. //config: depends on HUSH_INTERACTIVE
  161. //config: help
  162. //config: Enable job control: Ctrl-Z backgrounds, Ctrl-C interrupts current
  163. //config: command (not entire shell), fg/bg builtins work. Without this option,
  164. //config: "cmd &" still works by simply spawning a process and immediately
  165. //config: prompting for next command (or executing next command in a script),
  166. //config: but no separate process group is formed.
  167. //config:
  168. //config:config HUSH_TICK
  169. //config: bool "Support command substitution"
  170. //config: default y
  171. //config: depends on SHELL_HUSH
  172. //config: help
  173. //config: Enable `command` and $(command).
  174. //config:
  175. //config:config HUSH_IF
  176. //config: bool "Support if/then/elif/else/fi"
  177. //config: default y
  178. //config: depends on SHELL_HUSH
  179. //config:
  180. //config:config HUSH_LOOPS
  181. //config: bool "Support for, while and until loops"
  182. //config: default y
  183. //config: depends on SHELL_HUSH
  184. //config:
  185. //config:config HUSH_CASE
  186. //config: bool "Support case ... esac statement"
  187. //config: default y
  188. //config: depends on SHELL_HUSH
  189. //config: help
  190. //config: Enable case ... esac statement. +400 bytes.
  191. //config:
  192. //config:config HUSH_FUNCTIONS
  193. //config: bool "Support funcname() { commands; } syntax"
  194. //config: default y
  195. //config: depends on SHELL_HUSH
  196. //config: help
  197. //config: Enable support for shell functions. +800 bytes.
  198. //config:
  199. //config:config HUSH_LOCAL
  200. //config: bool "local builtin"
  201. //config: default y
  202. //config: depends on HUSH_FUNCTIONS
  203. //config: help
  204. //config: Enable support for local variables in functions.
  205. //config:
  206. //config:config HUSH_RANDOM_SUPPORT
  207. //config: bool "Pseudorandom generator and $RANDOM variable"
  208. //config: default y
  209. //config: depends on SHELL_HUSH
  210. //config: help
  211. //config: Enable pseudorandom generator and dynamic variable "$RANDOM".
  212. //config: Each read of "$RANDOM" will generate a new pseudorandom value.
  213. //config:
  214. //config:config HUSH_MODE_X
  215. //config: bool "Support 'hush -x' option and 'set -x' command"
  216. //config: default y
  217. //config: depends on SHELL_HUSH
  218. //config: help
  219. //config: This instructs hush to print commands before execution.
  220. //config: Adds ~300 bytes.
  221. //config:
  222. //config:config HUSH_ECHO
  223. //config: bool "echo builtin"
  224. //config: default y
  225. //config: depends on SHELL_HUSH
  226. //config:
  227. //config:config HUSH_PRINTF
  228. //config: bool "printf builtin"
  229. //config: default y
  230. //config: depends on SHELL_HUSH
  231. //config:
  232. //config:config HUSH_TEST
  233. //config: bool "test builtin"
  234. //config: default y
  235. //config: depends on SHELL_HUSH
  236. //config:
  237. //config:config HUSH_HELP
  238. //config: bool "help builtin"
  239. //config: default y
  240. //config: depends on SHELL_HUSH
  241. //config:
  242. //config:config HUSH_EXPORT
  243. //config: bool "export builtin"
  244. //config: default y
  245. //config: depends on SHELL_HUSH
  246. //config:
  247. //config:config HUSH_EXPORT_N
  248. //config: bool "Support 'export -n' option"
  249. //config: default y
  250. //config: depends on HUSH_EXPORT
  251. //config: help
  252. //config: export -n unexports variables. It is a bash extension.
  253. //config:
  254. //config:config HUSH_READONLY
  255. //config: bool "readonly builtin"
  256. //config: default y
  257. //config: depends on SHELL_HUSH
  258. //config: help
  259. //config: Enable support for read-only variables.
  260. //config:
  261. //config:config HUSH_KILL
  262. //config: bool "kill builtin (supports kill %jobspec)"
  263. //config: default y
  264. //config: depends on SHELL_HUSH
  265. //config:
  266. //config:config HUSH_WAIT
  267. //config: bool "wait builtin"
  268. //config: default y
  269. //config: depends on SHELL_HUSH
  270. //config:
  271. //config:config HUSH_COMMAND
  272. //config: bool "command builtin"
  273. //config: default y
  274. //config: depends on SHELL_HUSH
  275. //config:
  276. //config:config HUSH_TRAP
  277. //config: bool "trap builtin"
  278. //config: default y
  279. //config: depends on SHELL_HUSH
  280. //config:
  281. //config:config HUSH_TYPE
  282. //config: bool "type builtin"
  283. //config: default y
  284. //config: depends on SHELL_HUSH
  285. //config:
  286. //config:config HUSH_TIMES
  287. //config: bool "times builtin"
  288. //config: default y
  289. //config: depends on SHELL_HUSH
  290. //config:
  291. //config:config HUSH_READ
  292. //config: bool "read builtin"
  293. //config: default y
  294. //config: depends on SHELL_HUSH
  295. //config:
  296. //config:config HUSH_SET
  297. //config: bool "set builtin"
  298. //config: default y
  299. //config: depends on SHELL_HUSH
  300. //config:
  301. //config:config HUSH_UNSET
  302. //config: bool "unset builtin"
  303. //config: default y
  304. //config: depends on SHELL_HUSH
  305. //config:
  306. //config:config HUSH_ULIMIT
  307. //config: bool "ulimit builtin"
  308. //config: default y
  309. //config: depends on SHELL_HUSH
  310. //config:
  311. //config:config HUSH_UMASK
  312. //config: bool "umask builtin"
  313. //config: default y
  314. //config: depends on SHELL_HUSH
  315. //config:
  316. //config:config HUSH_GETOPTS
  317. //config: bool "getopts builtin"
  318. //config: default y
  319. //config: depends on SHELL_HUSH
  320. //config:
  321. //config:config HUSH_MEMLEAK
  322. //config: bool "memleak builtin (debugging)"
  323. //config: default n
  324. //config: depends on SHELL_HUSH
  325. //config:
  326. //config:endif # hush options
  327. //applet:IF_HUSH(APPLET(hush, BB_DIR_BIN, BB_SUID_DROP))
  328. // APPLET_ODDNAME:name main location suid_type help
  329. //applet:IF_SH_IS_HUSH( APPLET_ODDNAME(sh, hush, BB_DIR_BIN, BB_SUID_DROP, hush))
  330. //applet:IF_BASH_IS_HUSH(APPLET_ODDNAME(bash, hush, BB_DIR_BIN, BB_SUID_DROP, hush))
  331. //kbuild:lib-$(CONFIG_SHELL_HUSH) += hush.o match.o shell_common.o
  332. //kbuild:lib-$(CONFIG_HUSH_RANDOM_SUPPORT) += random.o
  333. /* -i (interactive) is also accepted,
  334. * but does nothing, therefore not shown in help.
  335. * NOMMU-specific options are not meant to be used by users,
  336. * therefore we don't show them either.
  337. */
  338. //usage:#define hush_trivial_usage
  339. //usage: "[-enxl] [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS] / -s [ARGS]]"
  340. //usage:#define hush_full_usage "\n\n"
  341. //usage: "Unix shell interpreter"
  342. #if !(defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) \
  343. || defined(__APPLE__) \
  344. )
  345. # include <malloc.h> /* for malloc_trim */
  346. #endif
  347. #include <glob.h>
  348. /* #include <dmalloc.h> */
  349. #if ENABLE_HUSH_CASE
  350. # include <fnmatch.h>
  351. #endif
  352. #include <sys/times.h>
  353. #include <sys/utsname.h> /* for setting $HOSTNAME */
  354. #include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
  355. #include "unicode.h"
  356. #include "shell_common.h"
  357. #include "math.h"
  358. #include "match.h"
  359. #if ENABLE_HUSH_RANDOM_SUPPORT
  360. # include "random.h"
  361. #else
  362. # define CLEAR_RANDOM_T(rnd) ((void)0)
  363. #endif
  364. #ifndef O_CLOEXEC
  365. # define O_CLOEXEC 0
  366. #endif
  367. #ifndef F_DUPFD_CLOEXEC
  368. # define F_DUPFD_CLOEXEC F_DUPFD
  369. #endif
  370. #if ENABLE_FEATURE_SH_EMBEDDED_SCRIPTS && !(ENABLE_ASH || ENABLE_SH_IS_ASH || ENABLE_BASH_IS_ASH)
  371. # include "embedded_scripts.h"
  372. #else
  373. # define NUM_SCRIPTS 0
  374. #endif
  375. /* So far, all bash compat is controlled by one config option */
  376. /* Separate defines document which part of code implements what */
  377. #define BASH_PATTERN_SUBST ENABLE_HUSH_BASH_COMPAT
  378. #define BASH_SUBSTR ENABLE_HUSH_BASH_COMPAT
  379. #define BASH_SOURCE ENABLE_HUSH_BASH_COMPAT
  380. #define BASH_HOSTNAME_VAR ENABLE_HUSH_BASH_COMPAT
  381. #define BASH_EPOCH_VARS ENABLE_HUSH_BASH_COMPAT
  382. #define BASH_TEST2 (ENABLE_HUSH_BASH_COMPAT && ENABLE_HUSH_TEST)
  383. #define BASH_READ_D ENABLE_HUSH_BASH_COMPAT
  384. /* Build knobs */
  385. #define LEAK_HUNTING 0
  386. #define BUILD_AS_NOMMU 0
  387. /* Enable/disable sanity checks. Ok to enable in production,
  388. * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
  389. * Keeping 1 for now even in released versions.
  390. */
  391. #define HUSH_DEBUG 1
  392. /* Slightly bigger (+200 bytes), but faster hush.
  393. * So far it only enables a trick with counting SIGCHLDs and forks,
  394. * which allows us to do fewer waitpid's.
  395. * (we can detect a case where neither forks were done nor SIGCHLDs happened
  396. * and therefore waitpid will return the same result as last time)
  397. */
  398. #define ENABLE_HUSH_FAST 0
  399. /* TODO: implement simplified code for users which do not need ${var%...} ops
  400. * So far ${var%...} ops are always enabled:
  401. */
  402. #define ENABLE_HUSH_DOLLAR_OPS 1
  403. #if BUILD_AS_NOMMU
  404. # undef BB_MMU
  405. # undef USE_FOR_NOMMU
  406. # undef USE_FOR_MMU
  407. # define BB_MMU 0
  408. # define USE_FOR_NOMMU(...) __VA_ARGS__
  409. # define USE_FOR_MMU(...)
  410. #endif
  411. #include "NUM_APPLETS.h"
  412. #if NUM_APPLETS == 1
  413. /* STANDALONE does not make sense, and won't compile */
  414. # undef CONFIG_FEATURE_SH_STANDALONE
  415. # undef ENABLE_FEATURE_SH_STANDALONE
  416. # undef IF_FEATURE_SH_STANDALONE
  417. # undef IF_NOT_FEATURE_SH_STANDALONE
  418. # define ENABLE_FEATURE_SH_STANDALONE 0
  419. # define IF_FEATURE_SH_STANDALONE(...)
  420. # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
  421. #endif
  422. #if !ENABLE_HUSH_INTERACTIVE
  423. # undef ENABLE_FEATURE_EDITING
  424. # define ENABLE_FEATURE_EDITING 0
  425. # undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
  426. # define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
  427. # undef ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
  428. # define ENABLE_FEATURE_EDITING_SAVE_ON_EXIT 0
  429. #endif
  430. /* Do we support ANY keywords? */
  431. #if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
  432. # define HAS_KEYWORDS 1
  433. # define IF_HAS_KEYWORDS(...) __VA_ARGS__
  434. # define IF_HAS_NO_KEYWORDS(...)
  435. #else
  436. # define HAS_KEYWORDS 0
  437. # define IF_HAS_KEYWORDS(...)
  438. # define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
  439. #endif
  440. /* If you comment out one of these below, it will be #defined later
  441. * to perform debug printfs to stderr: */
  442. #define debug_printf(...) do {} while (0)
  443. /* Finer-grained debug switches */
  444. #define debug_printf_parse(...) do {} while (0)
  445. #define debug_printf_heredoc(...) do {} while (0)
  446. #define debug_print_tree(a, b) do {} while (0)
  447. #define debug_printf_exec(...) do {} while (0)
  448. #define debug_printf_env(...) do {} while (0)
  449. #define debug_printf_jobs(...) do {} while (0)
  450. #define debug_printf_expand(...) do {} while (0)
  451. #define debug_printf_varexp(...) do {} while (0)
  452. #define debug_printf_glob(...) do {} while (0)
  453. #define debug_printf_redir(...) do {} while (0)
  454. #define debug_printf_list(...) do {} while (0)
  455. #define debug_printf_subst(...) do {} while (0)
  456. #define debug_printf_prompt(...) do {} while (0)
  457. #define debug_printf_clean(...) do {} while (0)
  458. #define ERR_PTR ((void*)(long)1)
  459. #define JOB_STATUS_FORMAT "[%u] %-22s %.40s\n"
  460. #define _SPECIAL_VARS_STR "_*@$!?#-"
  461. #define SPECIAL_VARS_STR ("_*@$!?#-" + 1)
  462. #define NUMERIC_SPECVARS_STR ("_*@$!?#-" + 3)
  463. #if BASH_PATTERN_SUBST
  464. /* Support / and // replace ops */
  465. /* Note that // is stored as \ in "encoded" string representation */
  466. # define VAR_ENCODED_SUBST_OPS "\\/%#:-=+?"
  467. # define VAR_SUBST_OPS ("\\/%#:-=+?" + 1)
  468. # define MINUS_PLUS_EQUAL_QUESTION ("\\/%#:-=+?" + 5)
  469. #else
  470. # define VAR_ENCODED_SUBST_OPS "%#:-=+?"
  471. # define VAR_SUBST_OPS "%#:-=+?"
  472. # define MINUS_PLUS_EQUAL_QUESTION ("%#:-=+?" + 3)
  473. #endif
  474. #define SPECIAL_VAR_SYMBOL_STR "\3"
  475. #define SPECIAL_VAR_SYMBOL 3
  476. /* The "variable" with name "\1" emits string "\3". Testcase: "echo ^C" */
  477. #define SPECIAL_VAR_QUOTED_SVS 1
  478. struct variable;
  479. static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
  480. /* This supports saving pointers malloced in vfork child,
  481. * to be freed in the parent.
  482. */
  483. #if !BB_MMU
  484. typedef struct nommu_save_t {
  485. struct variable *old_vars;
  486. char **argv;
  487. char **argv_from_re_execing;
  488. } nommu_save_t;
  489. #endif
  490. enum {
  491. RES_NONE = 0,
  492. #if ENABLE_HUSH_IF
  493. RES_IF ,
  494. RES_THEN ,
  495. RES_ELIF ,
  496. RES_ELSE ,
  497. RES_FI ,
  498. #endif
  499. #if ENABLE_HUSH_LOOPS
  500. RES_FOR ,
  501. RES_WHILE ,
  502. RES_UNTIL ,
  503. RES_DO ,
  504. RES_DONE ,
  505. #endif
  506. #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
  507. RES_IN ,
  508. #endif
  509. #if ENABLE_HUSH_CASE
  510. RES_CASE ,
  511. /* three pseudo-keywords support contrived "case" syntax: */
  512. RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
  513. RES_MATCH , /* "word)" */
  514. RES_CASE_BODY, /* "this command is inside CASE" */
  515. RES_ESAC ,
  516. #endif
  517. RES_XXXX ,
  518. RES_SNTX
  519. };
  520. typedef struct o_string {
  521. char *data;
  522. int length; /* position where data is appended */
  523. int maxlen;
  524. int o_expflags;
  525. /* At least some part of the string was inside '' or "",
  526. * possibly empty one: word"", wo''rd etc. */
  527. smallint has_quoted_part;
  528. smallint has_empty_slot;
  529. smallint ended_in_ifs;
  530. } o_string;
  531. enum {
  532. EXP_FLAG_SINGLEWORD = 0x80, /* must be 0x80 */
  533. EXP_FLAG_GLOB = 0x2,
  534. /* Protect newly added chars against globbing
  535. * by prepending \ to *, ?, [, \ */
  536. EXP_FLAG_ESC_GLOB_CHARS = 0x1,
  537. };
  538. /* Used for initialization: o_string foo = NULL_O_STRING; */
  539. #define NULL_O_STRING { NULL }
  540. #ifndef debug_printf_parse
  541. static const char *const assignment_flag[] = {
  542. "MAYBE_ASSIGNMENT",
  543. "DEFINITELY_ASSIGNMENT",
  544. "NOT_ASSIGNMENT",
  545. "WORD_IS_KEYWORD",
  546. };
  547. #endif
  548. /* We almost can use standard FILE api, but we need an ability to move
  549. * its fd when redirects coincide with it. No api exists for that
  550. * (RFE for it at https://sourceware.org/bugzilla/show_bug.cgi?id=21902).
  551. * HFILE is our internal alternative. Only supports reading.
  552. * Since we now can, we incorporate linked list of all opened HFILEs
  553. * into the struct (used to be a separate mini-list).
  554. */
  555. typedef struct HFILE {
  556. char *cur;
  557. char *end;
  558. struct HFILE *next_hfile;
  559. int fd;
  560. char buf[1024];
  561. } HFILE;
  562. typedef struct in_str {
  563. const char *p;
  564. int peek_buf[2];
  565. int last_char;
  566. HFILE *file;
  567. } in_str;
  568. /* The descrip member of this structure is only used to make
  569. * debugging output pretty */
  570. static const struct {
  571. int32_t mode;
  572. signed char default_fd;
  573. char descrip[3];
  574. } redir_table[] ALIGN4 = {
  575. { O_RDONLY, 0, "<" },
  576. { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
  577. { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
  578. { O_CREAT|O_RDWR, 1, "<>" },
  579. { O_RDONLY, 0, "<<" },
  580. /* Should not be needed. Bogus default_fd helps in debugging */
  581. /* { O_RDONLY, 77, "<<" }, */
  582. };
  583. struct redir_struct {
  584. struct redir_struct *next;
  585. char *rd_filename; /* filename */
  586. int rd_fd; /* fd to redirect */
  587. /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
  588. int rd_dup;
  589. smallint rd_type; /* (enum redir_type) */
  590. /* note: for heredocs, rd_filename contains heredoc delimiter,
  591. * and subsequently heredoc itself; and rd_dup is a bitmask:
  592. * bit 0: do we need to trim leading tabs?
  593. * bit 1: is heredoc quoted (<<'delim' syntax) ?
  594. */
  595. };
  596. typedef enum redir_type {
  597. REDIRECT_INPUT = 0,
  598. REDIRECT_OVERWRITE = 1,
  599. REDIRECT_APPEND = 2,
  600. REDIRECT_IO = 3,
  601. REDIRECT_HEREDOC = 4,
  602. REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
  603. REDIRFD_CLOSE = -3,
  604. REDIRFD_SYNTAX_ERR = -2,
  605. REDIRFD_TO_FILE = -1,
  606. /* otherwise, rd_fd is redirected to rd_dup */
  607. HEREDOC_SKIPTABS = 1,
  608. HEREDOC_QUOTED = 2,
  609. } redir_type;
  610. struct command {
  611. pid_t pid; /* 0 if exited */
  612. unsigned assignment_cnt; /* how many argv[i] are assignments? */
  613. #if ENABLE_HUSH_LINENO_VAR
  614. unsigned lineno;
  615. #endif
  616. smallint cmd_type; /* CMD_xxx */
  617. #define CMD_NORMAL 0
  618. #define CMD_SUBSHELL 1
  619. #if BASH_TEST2
  620. /* used for "[[ EXPR ]]" */
  621. # define CMD_TEST2_SINGLEWORD_NOGLOB 2
  622. #endif
  623. #if ENABLE_HUSH_LOCAL || ENABLE_HUSH_EXPORT || ENABLE_HUSH_READONLY
  624. /* used to prevent word splitting and globbing in "export v=t*" */
  625. # define CMD_SINGLEWORD_NOGLOB 3
  626. #endif
  627. #if ENABLE_HUSH_FUNCTIONS
  628. # define CMD_FUNCDEF 4
  629. #endif
  630. smalluint cmd_exitcode;
  631. /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
  632. struct pipe *group;
  633. #if !BB_MMU
  634. char *group_as_string;
  635. #endif
  636. #if ENABLE_HUSH_FUNCTIONS
  637. struct function *child_func;
  638. /* This field is used to prevent a bug here:
  639. * while...do f1() {a;}; f1; f1() {b;}; f1; done
  640. * When we execute "f1() {a;}" cmd, we create new function and clear
  641. * cmd->group, cmd->group_as_string, cmd->argv[0].
  642. * When we execute "f1() {b;}", we notice that f1 exists,
  643. * and that its "parent cmd" struct is still "alive",
  644. * we put those fields back into cmd->xxx
  645. * (struct function has ->parent_cmd ptr to facilitate that).
  646. * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
  647. * Without this trick, loop would execute a;b;b;b;...
  648. * instead of correct sequence a;b;a;b;...
  649. * When command is freed, it severs the link
  650. * (sets ->child_func->parent_cmd to NULL).
  651. */
  652. #endif
  653. char **argv; /* command name and arguments */
  654. /* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
  655. * and on execution these are substituted with their values.
  656. * Substitution can make _several_ words out of one argv[n]!
  657. * Example: argv[0]=='.^C*^C.' here: echo .$*.
  658. * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
  659. */
  660. struct redir_struct *redirects; /* I/O redirections */
  661. };
  662. /* Is there anything in this command at all? */
  663. #define IS_NULL_CMD(cmd) \
  664. (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
  665. struct pipe {
  666. struct pipe *next;
  667. int num_cmds; /* total number of commands in pipe */
  668. int alive_cmds; /* number of commands running (not exited) */
  669. int stopped_cmds; /* number of commands alive, but stopped */
  670. #if ENABLE_HUSH_JOB
  671. unsigned jobid; /* job number */
  672. pid_t pgrp; /* process group ID for the job */
  673. char *cmdtext; /* name of job */
  674. #endif
  675. struct command *cmds; /* array of commands in pipe */
  676. smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
  677. IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
  678. IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
  679. };
  680. typedef enum pipe_style {
  681. PIPE_SEQ = 0,
  682. PIPE_AND = 1,
  683. PIPE_OR = 2,
  684. PIPE_BG = 3,
  685. } pipe_style;
  686. /* Is there anything in this pipe at all? */
  687. #define IS_NULL_PIPE(pi) \
  688. ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
  689. /* This holds pointers to the various results of parsing */
  690. struct parse_context {
  691. /* linked list of pipes */
  692. struct pipe *list_head;
  693. /* last pipe (being constructed right now) */
  694. struct pipe *pipe;
  695. /* last command in pipe (being constructed right now) */
  696. struct command *command;
  697. /* last redirect in command->redirects list */
  698. struct redir_struct *pending_redirect;
  699. o_string word;
  700. #if !BB_MMU
  701. o_string as_string;
  702. #endif
  703. smallint is_assignment; /* 0:maybe, 1:yes, 2:no, 3:keyword */
  704. #if HAS_KEYWORDS
  705. smallint ctx_res_w;
  706. smallint ctx_inverted; /* "! cmd | cmd" */
  707. #if ENABLE_HUSH_CASE
  708. smallint ctx_dsemicolon; /* ";;" seen */
  709. #endif
  710. /* bitmask of FLAG_xxx, for figuring out valid reserved words */
  711. int old_flag;
  712. /* group we are enclosed in:
  713. * example: "if pipe1; pipe2; then pipe3; fi"
  714. * when we see "if" or "then", we malloc and copy current context,
  715. * and make ->stack point to it. then we parse pipeN.
  716. * when closing "then" / fi" / whatever is found,
  717. * we move list_head into ->stack->command->group,
  718. * copy ->stack into current context, and delete ->stack.
  719. * (parsing of { list } and ( list ) doesn't use this method)
  720. */
  721. struct parse_context *stack;
  722. #endif
  723. };
  724. enum {
  725. MAYBE_ASSIGNMENT = 0,
  726. DEFINITELY_ASSIGNMENT = 1,
  727. NOT_ASSIGNMENT = 2,
  728. /* Not an assignment, but next word may be: "if v=xyz cmd;" */
  729. WORD_IS_KEYWORD = 3,
  730. };
  731. /* On program start, environ points to initial environment.
  732. * putenv adds new pointers into it, unsetenv removes them.
  733. * Neither of these (de)allocates the strings.
  734. * setenv allocates new strings in malloc space and does putenv,
  735. * and thus setenv is unusable (leaky) for shell's purposes */
  736. #define setenv(...) setenv_is_leaky_dont_use()
  737. struct variable {
  738. struct variable *next;
  739. char *varstr; /* points to "name=" portion */
  740. int max_len; /* if > 0, name is part of initial env; else name is malloced */
  741. uint16_t var_nest_level;
  742. smallint flg_export; /* putenv should be done on this var */
  743. smallint flg_read_only;
  744. };
  745. enum {
  746. BC_BREAK = 1,
  747. BC_CONTINUE = 2,
  748. };
  749. #if ENABLE_HUSH_FUNCTIONS
  750. struct function {
  751. struct function *next;
  752. char *name;
  753. struct command *parent_cmd;
  754. struct pipe *body;
  755. # if !BB_MMU
  756. char *body_as_string;
  757. # endif
  758. };
  759. #endif
  760. /* set -/+o OPT support. (TODO: make it optional)
  761. * bash supports the following opts:
  762. * allexport off
  763. * braceexpand on
  764. * emacs on
  765. * errexit off
  766. * errtrace off
  767. * functrace off
  768. * hashall on
  769. * histexpand off
  770. * history on
  771. * ignoreeof off
  772. * interactive-comments on
  773. * keyword off
  774. * monitor on
  775. * noclobber off
  776. * noexec off
  777. * noglob off
  778. * nolog off
  779. * notify off
  780. * nounset off
  781. * onecmd off
  782. * physical off
  783. * pipefail off
  784. * posix off
  785. * privileged off
  786. * verbose off
  787. * vi off
  788. * xtrace off
  789. */
  790. static const char o_opt_strings[] ALIGN1 =
  791. "pipefail\0"
  792. "noexec\0"
  793. "errexit\0"
  794. #if ENABLE_HUSH_MODE_X
  795. "xtrace\0"
  796. #endif
  797. ;
  798. enum {
  799. OPT_O_PIPEFAIL,
  800. OPT_O_NOEXEC,
  801. OPT_O_ERREXIT,
  802. #if ENABLE_HUSH_MODE_X
  803. OPT_O_XTRACE,
  804. #endif
  805. NUM_OPT_O
  806. };
  807. /* "Globals" within this file */
  808. /* Sorted roughly by size (smaller offsets == smaller code) */
  809. struct globals {
  810. /* interactive_fd != 0 means we are an interactive shell.
  811. * If we are, then saved_tty_pgrp can also be != 0, meaning
  812. * that controlling tty is available. With saved_tty_pgrp == 0,
  813. * job control still works, but terminal signals
  814. * (^C, ^Z, ^Y, ^\) won't work at all, and background
  815. * process groups can only be created with "cmd &".
  816. * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
  817. * to give tty to the foreground process group,
  818. * and will take it back when the group is stopped (^Z)
  819. * or killed (^C).
  820. */
  821. #if ENABLE_HUSH_INTERACTIVE
  822. /* 'interactive_fd' is a fd# open to ctty, if we have one
  823. * _AND_ if we decided to act interactively */
  824. int interactive_fd;
  825. IF_NOT_FEATURE_EDITING_FANCY_PROMPT(char *PS1;)
  826. # define G_interactive_fd (G.interactive_fd)
  827. #else
  828. # define G_interactive_fd 0
  829. #endif
  830. #if ENABLE_FEATURE_EDITING
  831. line_input_t *line_input_state;
  832. #endif
  833. pid_t root_pid;
  834. pid_t root_ppid;
  835. pid_t last_bg_pid;
  836. #if ENABLE_HUSH_RANDOM_SUPPORT
  837. random_t random_gen;
  838. #endif
  839. #if ENABLE_HUSH_JOB
  840. int run_list_level;
  841. unsigned last_jobid;
  842. pid_t saved_tty_pgrp;
  843. struct pipe *job_list;
  844. # define G_saved_tty_pgrp (G.saved_tty_pgrp)
  845. #else
  846. # define G_saved_tty_pgrp 0
  847. #endif
  848. /* How deeply are we in context where "set -e" is ignored */
  849. int errexit_depth;
  850. /* "set -e" rules (do we follow them correctly?):
  851. * Exit if pipe, list, or compound command exits with a non-zero status.
  852. * Shell does not exit if failed command is part of condition in
  853. * if/while, part of && or || list except the last command, any command
  854. * in a pipe but the last, or if the command's return value is being
  855. * inverted with !. If a compound command other than a subshell returns a
  856. * non-zero status because a command failed while -e was being ignored, the
  857. * shell does not exit. A trap on ERR, if set, is executed before the shell
  858. * exits [ERR is a bashism].
  859. *
  860. * If a compound command or function executes in a context where -e is
  861. * ignored, none of the commands executed within are affected by the -e
  862. * setting. If a compound command or function sets -e while executing in a
  863. * context where -e is ignored, that setting does not have any effect until
  864. * the compound command or the command containing the function call completes.
  865. */
  866. char o_opt[NUM_OPT_O];
  867. #if ENABLE_HUSH_MODE_X
  868. # define G_x_mode (G.o_opt[OPT_O_XTRACE])
  869. #else
  870. # define G_x_mode 0
  871. #endif
  872. char opt_s;
  873. char opt_c;
  874. #if ENABLE_HUSH_INTERACTIVE
  875. smallint promptmode; /* 0: PS1, 1: PS2 */
  876. # if ENABLE_FEATURE_EDITING
  877. smallint flag_ctrlC; /* when set, suppresses syntax error messages */
  878. # endif
  879. #endif
  880. smallint flag_SIGINT;
  881. #if ENABLE_HUSH_LOOPS
  882. smallint flag_break_continue;
  883. #endif
  884. #if ENABLE_HUSH_FUNCTIONS
  885. /* 0: outside of a function (or sourced file)
  886. * -1: inside of a function, ok to use return builtin
  887. * 1: return is invoked, skip all till end of func
  888. */
  889. smallint flag_return_in_progress;
  890. # define G_flag_return_in_progress (G.flag_return_in_progress)
  891. #else
  892. # define G_flag_return_in_progress 0
  893. #endif
  894. smallint exiting; /* used to prevent EXIT trap recursion */
  895. /* These support $? */
  896. smalluint last_exitcode;
  897. smalluint expand_exitcode;
  898. smalluint last_bg_pid_exitcode;
  899. #if ENABLE_HUSH_SET
  900. /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
  901. smalluint global_args_malloced;
  902. # define G_global_args_malloced (G.global_args_malloced)
  903. #else
  904. # define G_global_args_malloced 0
  905. #endif
  906. #if ENABLE_HUSH_BASH_COMPAT
  907. int dead_job_exitcode; /* for "wait -n" */
  908. #endif
  909. /* how many non-NULL argv's we have. NB: $# + 1 */
  910. int global_argc;
  911. char **global_argv;
  912. #if !BB_MMU
  913. char *argv0_for_re_execing;
  914. #endif
  915. #if ENABLE_HUSH_LOOPS
  916. unsigned depth_break_continue;
  917. unsigned depth_of_loop;
  918. #endif
  919. #if ENABLE_HUSH_GETOPTS
  920. unsigned getopt_count;
  921. #endif
  922. const char *ifs;
  923. char *ifs_whitespace; /* = G.ifs or malloced */
  924. const char *cwd;
  925. struct variable *top_var;
  926. char **expanded_assignments;
  927. struct variable **shadowed_vars_pp;
  928. unsigned var_nest_level;
  929. #if ENABLE_HUSH_FUNCTIONS
  930. # if ENABLE_HUSH_LOCAL
  931. unsigned func_nest_level; /* solely to prevent "local v" in non-functions */
  932. # endif
  933. struct function *top_func;
  934. #endif
  935. /* Signal and trap handling */
  936. #if ENABLE_HUSH_FAST
  937. unsigned count_SIGCHLD;
  938. unsigned handled_SIGCHLD;
  939. smallint we_have_children;
  940. #endif
  941. #if ENABLE_HUSH_LINENO_VAR
  942. unsigned parse_lineno;
  943. unsigned execute_lineno;
  944. #endif
  945. HFILE *HFILE_list;
  946. HFILE *HFILE_stdin;
  947. /* Which signals have non-DFL handler (even with no traps set)?
  948. * Set at the start to:
  949. * (SIGQUIT + maybe SPECIAL_INTERACTIVE_SIGS + maybe SPECIAL_JOBSTOP_SIGS)
  950. * SPECIAL_INTERACTIVE_SIGS are cleared after fork.
  951. * The rest is cleared right before execv syscalls.
  952. * Other than these two times, never modified.
  953. */
  954. unsigned special_sig_mask;
  955. #if ENABLE_HUSH_JOB
  956. unsigned fatal_sig_mask;
  957. # define G_fatal_sig_mask (G.fatal_sig_mask)
  958. #else
  959. # define G_fatal_sig_mask 0
  960. #endif
  961. #if ENABLE_HUSH_TRAP
  962. int pre_trap_exitcode;
  963. # if ENABLE_HUSH_FUNCTIONS
  964. int return_exitcode;
  965. # endif
  966. char **traps; /* char *traps[NSIG] */
  967. # define G_traps G.traps
  968. #else
  969. # define G_traps ((char**)NULL)
  970. #endif
  971. sigset_t pending_set;
  972. #if ENABLE_HUSH_MEMLEAK
  973. unsigned long memleak_value;
  974. #endif
  975. #if ENABLE_HUSH_MODE_X
  976. unsigned x_mode_depth;
  977. /* "set -x" output should not be redirectable with subsequent 2>FILE.
  978. * We dup fd#2 to x_mode_fd when "set -x" is executed, and use it
  979. * for all subsequent output.
  980. */
  981. int x_mode_fd;
  982. o_string x_mode_buf;
  983. #endif
  984. #if HUSH_DEBUG >= 2
  985. int debug_indent;
  986. #endif
  987. struct sigaction sa;
  988. char optstring_buf[sizeof("eixcs")];
  989. #if BASH_EPOCH_VARS
  990. char epoch_buf[sizeof("%lu.nnnnnn") + sizeof(long)*3];
  991. #endif
  992. #if ENABLE_FEATURE_EDITING
  993. char user_input_buf[CONFIG_FEATURE_EDITING_MAX_LEN];
  994. #endif
  995. };
  996. #define G (*ptr_to_globals)
  997. /* Not #defining name to G.name - this quickly gets unwieldy
  998. * (too many defines). Also, I actually prefer to see when a variable
  999. * is global, thus "G." prefix is a useful hint */
  1000. #define INIT_G() do { \
  1001. SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
  1002. /* memset(&G.sa, 0, sizeof(G.sa)); */ \
  1003. sigfillset(&G.sa.sa_mask); \
  1004. G.sa.sa_flags = SA_RESTART; \
  1005. } while (0)
  1006. /* Function prototypes for builtins */
  1007. static int builtin_cd(char **argv) FAST_FUNC;
  1008. #if ENABLE_HUSH_ECHO
  1009. static int builtin_echo(char **argv) FAST_FUNC;
  1010. #endif
  1011. static int builtin_eval(char **argv) FAST_FUNC;
  1012. static int builtin_exec(char **argv) FAST_FUNC;
  1013. static int builtin_exit(char **argv) FAST_FUNC;
  1014. #if ENABLE_HUSH_EXPORT
  1015. static int builtin_export(char **argv) FAST_FUNC;
  1016. #endif
  1017. #if ENABLE_HUSH_READONLY
  1018. static int builtin_readonly(char **argv) FAST_FUNC;
  1019. #endif
  1020. #if ENABLE_HUSH_JOB
  1021. static int builtin_fg_bg(char **argv) FAST_FUNC;
  1022. static int builtin_jobs(char **argv) FAST_FUNC;
  1023. #endif
  1024. #if ENABLE_HUSH_GETOPTS
  1025. static int builtin_getopts(char **argv) FAST_FUNC;
  1026. #endif
  1027. #if ENABLE_HUSH_HELP
  1028. static int builtin_help(char **argv) FAST_FUNC;
  1029. #endif
  1030. #if MAX_HISTORY && ENABLE_FEATURE_EDITING
  1031. static int builtin_history(char **argv) FAST_FUNC;
  1032. #endif
  1033. #if ENABLE_HUSH_LOCAL
  1034. static int builtin_local(char **argv) FAST_FUNC;
  1035. #endif
  1036. #if ENABLE_HUSH_MEMLEAK
  1037. static int builtin_memleak(char **argv) FAST_FUNC;
  1038. #endif
  1039. #if ENABLE_HUSH_PRINTF
  1040. static int builtin_printf(char **argv) FAST_FUNC;
  1041. #endif
  1042. static int builtin_pwd(char **argv) FAST_FUNC;
  1043. #if ENABLE_HUSH_READ
  1044. static int builtin_read(char **argv) FAST_FUNC;
  1045. #endif
  1046. #if ENABLE_HUSH_SET
  1047. static int builtin_set(char **argv) FAST_FUNC;
  1048. #endif
  1049. static int builtin_shift(char **argv) FAST_FUNC;
  1050. static int builtin_source(char **argv) FAST_FUNC;
  1051. #if ENABLE_HUSH_TEST || BASH_TEST2
  1052. static int builtin_test(char **argv) FAST_FUNC;
  1053. #endif
  1054. #if ENABLE_HUSH_TRAP
  1055. static int builtin_trap(char **argv) FAST_FUNC;
  1056. #endif
  1057. #if ENABLE_HUSH_TYPE
  1058. static int builtin_type(char **argv) FAST_FUNC;
  1059. #endif
  1060. #if ENABLE_HUSH_TIMES
  1061. static int builtin_times(char **argv) FAST_FUNC;
  1062. #endif
  1063. static int builtin_true(char **argv) FAST_FUNC;
  1064. #if ENABLE_HUSH_UMASK
  1065. static int builtin_umask(char **argv) FAST_FUNC;
  1066. #endif
  1067. #if ENABLE_HUSH_UNSET
  1068. static int builtin_unset(char **argv) FAST_FUNC;
  1069. #endif
  1070. #if ENABLE_HUSH_KILL
  1071. static int builtin_kill(char **argv) FAST_FUNC;
  1072. #endif
  1073. #if ENABLE_HUSH_WAIT
  1074. static int builtin_wait(char **argv) FAST_FUNC;
  1075. #endif
  1076. #if ENABLE_HUSH_LOOPS
  1077. static int builtin_break(char **argv) FAST_FUNC;
  1078. static int builtin_continue(char **argv) FAST_FUNC;
  1079. #endif
  1080. #if ENABLE_HUSH_FUNCTIONS
  1081. static int builtin_return(char **argv) FAST_FUNC;
  1082. #endif
  1083. /* Table of built-in functions. They can be forked or not, depending on
  1084. * context: within pipes, they fork. As simple commands, they do not.
  1085. * When used in non-forking context, they can change global variables
  1086. * in the parent shell process. If forked, of course they cannot.
  1087. * For example, 'unset foo | whatever' will parse and run, but foo will
  1088. * still be set at the end. */
  1089. struct built_in_command {
  1090. const char *b_cmd;
  1091. int (*b_function)(char **argv) FAST_FUNC;
  1092. #if ENABLE_HUSH_HELP
  1093. const char *b_descr;
  1094. # define BLTIN(cmd, func, help) { cmd, func, help }
  1095. #else
  1096. # define BLTIN(cmd, func, help) { cmd, func }
  1097. #endif
  1098. };
  1099. static const struct built_in_command bltins1[] ALIGN_PTR = {
  1100. BLTIN("." , builtin_source , "Run commands in file"),
  1101. BLTIN(":" , builtin_true , NULL),
  1102. #if ENABLE_HUSH_JOB
  1103. BLTIN("bg" , builtin_fg_bg , "Resume job in background"),
  1104. #endif
  1105. #if ENABLE_HUSH_LOOPS
  1106. BLTIN("break" , builtin_break , "Exit loop"),
  1107. #endif
  1108. BLTIN("cd" , builtin_cd , "Change directory"),
  1109. #if ENABLE_HUSH_LOOPS
  1110. BLTIN("continue" , builtin_continue, "Start new loop iteration"),
  1111. #endif
  1112. BLTIN("eval" , builtin_eval , "Construct and run shell command"),
  1113. BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
  1114. BLTIN("exit" , builtin_exit , NULL),
  1115. #if ENABLE_HUSH_EXPORT
  1116. BLTIN("export" , builtin_export , "Set environment variables"),
  1117. #endif
  1118. #if ENABLE_HUSH_JOB
  1119. BLTIN("fg" , builtin_fg_bg , "Bring job to foreground"),
  1120. #endif
  1121. #if ENABLE_HUSH_GETOPTS
  1122. BLTIN("getopts" , builtin_getopts , NULL),
  1123. #endif
  1124. #if ENABLE_HUSH_HELP
  1125. BLTIN("help" , builtin_help , NULL),
  1126. #endif
  1127. #if MAX_HISTORY && ENABLE_FEATURE_EDITING
  1128. BLTIN("history" , builtin_history , "Show history"),
  1129. #endif
  1130. #if ENABLE_HUSH_JOB
  1131. BLTIN("jobs" , builtin_jobs , "List jobs"),
  1132. #endif
  1133. #if ENABLE_HUSH_KILL
  1134. BLTIN("kill" , builtin_kill , "Send signals to processes"),
  1135. #endif
  1136. #if ENABLE_HUSH_LOCAL
  1137. BLTIN("local" , builtin_local , "Set local variables"),
  1138. #endif
  1139. #if ENABLE_HUSH_MEMLEAK
  1140. BLTIN("memleak" , builtin_memleak , NULL),
  1141. #endif
  1142. #if ENABLE_HUSH_READ
  1143. BLTIN("read" , builtin_read , "Input into variable"),
  1144. #endif
  1145. #if ENABLE_HUSH_READONLY
  1146. BLTIN("readonly" , builtin_readonly, "Make variables read-only"),
  1147. #endif
  1148. #if ENABLE_HUSH_FUNCTIONS
  1149. BLTIN("return" , builtin_return , "Return from function"),
  1150. #endif
  1151. #if ENABLE_HUSH_SET
  1152. BLTIN("set" , builtin_set , "Set positional parameters"),
  1153. #endif
  1154. BLTIN("shift" , builtin_shift , "Shift positional parameters"),
  1155. #if BASH_SOURCE
  1156. BLTIN("source" , builtin_source , NULL),
  1157. #endif
  1158. #if ENABLE_HUSH_TIMES
  1159. BLTIN("times" , builtin_times , NULL),
  1160. #endif
  1161. #if ENABLE_HUSH_TRAP
  1162. BLTIN("trap" , builtin_trap , "Trap signals"),
  1163. #endif
  1164. BLTIN("true" , builtin_true , NULL),
  1165. #if ENABLE_HUSH_TYPE
  1166. BLTIN("type" , builtin_type , "Show command type"),
  1167. #endif
  1168. #if ENABLE_HUSH_ULIMIT
  1169. BLTIN("ulimit" , shell_builtin_ulimit, "Control resource limits"),
  1170. #endif
  1171. #if ENABLE_HUSH_UMASK
  1172. BLTIN("umask" , builtin_umask , "Set file creation mask"),
  1173. #endif
  1174. #if ENABLE_HUSH_UNSET
  1175. BLTIN("unset" , builtin_unset , "Unset variables"),
  1176. #endif
  1177. #if ENABLE_HUSH_WAIT
  1178. BLTIN("wait" , builtin_wait , "Wait for process to finish"),
  1179. #endif
  1180. };
  1181. /* These builtins won't be used if we are on NOMMU and need to re-exec
  1182. * (it's cheaper to run an external program in this case):
  1183. */
  1184. static const struct built_in_command bltins2[] ALIGN_PTR = {
  1185. #if ENABLE_HUSH_TEST
  1186. BLTIN("[" , builtin_test , NULL),
  1187. #endif
  1188. #if BASH_TEST2
  1189. BLTIN("[[" , builtin_test , NULL),
  1190. #endif
  1191. #if ENABLE_HUSH_ECHO
  1192. BLTIN("echo" , builtin_echo , NULL),
  1193. #endif
  1194. #if ENABLE_HUSH_PRINTF
  1195. BLTIN("printf" , builtin_printf , NULL),
  1196. #endif
  1197. BLTIN("pwd" , builtin_pwd , NULL),
  1198. #if ENABLE_HUSH_TEST
  1199. BLTIN("test" , builtin_test , NULL),
  1200. #endif
  1201. };
  1202. /* Debug printouts.
  1203. */
  1204. #if HUSH_DEBUG >= 2
  1205. /* prevent disasters with G.debug_indent < 0 */
  1206. # define indent() fdprintf(2, "%*s", (G.debug_indent * 2) & 0xff, "")
  1207. # define debug_enter() (G.debug_indent++)
  1208. # define debug_leave() (G.debug_indent--)
  1209. #else
  1210. # define indent() ((void)0)
  1211. # define debug_enter() ((void)0)
  1212. # define debug_leave() ((void)0)
  1213. #endif
  1214. #ifndef debug_printf
  1215. # define debug_printf(...) (indent(), fdprintf(2, __VA_ARGS__))
  1216. #endif
  1217. #ifndef debug_printf_parse
  1218. # define debug_printf_parse(...) (indent(), fdprintf(2, __VA_ARGS__))
  1219. #endif
  1220. #ifndef debug_printf_heredoc
  1221. # define debug_printf_heredoc(...) (indent(), fdprintf(2, __VA_ARGS__))
  1222. #endif
  1223. #ifndef debug_printf_exec
  1224. #define debug_printf_exec(...) (indent(), fdprintf(2, __VA_ARGS__))
  1225. #endif
  1226. #ifndef debug_printf_env
  1227. # define debug_printf_env(...) (indent(), fdprintf(2, __VA_ARGS__))
  1228. #endif
  1229. #ifndef debug_printf_jobs
  1230. # define debug_printf_jobs(...) (indent(), fdprintf(2, __VA_ARGS__))
  1231. # define DEBUG_JOBS 1
  1232. #else
  1233. # define DEBUG_JOBS 0
  1234. #endif
  1235. #ifndef debug_printf_expand
  1236. # define debug_printf_expand(...) (indent(), fdprintf(2, __VA_ARGS__))
  1237. # define DEBUG_EXPAND 1
  1238. #else
  1239. # define DEBUG_EXPAND 0
  1240. #endif
  1241. #ifndef debug_printf_varexp
  1242. # define debug_printf_varexp(...) (indent(), fdprintf(2, __VA_ARGS__))
  1243. #endif
  1244. #ifndef debug_printf_glob
  1245. # define debug_printf_glob(...) (indent(), fdprintf(2, __VA_ARGS__))
  1246. # define DEBUG_GLOB 1
  1247. #else
  1248. # define DEBUG_GLOB 0
  1249. #endif
  1250. #ifndef debug_printf_redir
  1251. # define debug_printf_redir(...) (indent(), fdprintf(2, __VA_ARGS__))
  1252. #endif
  1253. #ifndef debug_printf_list
  1254. # define debug_printf_list(...) (indent(), fdprintf(2, __VA_ARGS__))
  1255. #endif
  1256. #ifndef debug_printf_subst
  1257. # define debug_printf_subst(...) (indent(), fdprintf(2, __VA_ARGS__))
  1258. #endif
  1259. #ifndef debug_printf_prompt
  1260. # define debug_printf_prompt(...) (indent(), fdprintf(2, __VA_ARGS__))
  1261. #endif
  1262. #ifndef debug_printf_clean
  1263. # define debug_printf_clean(...) (indent(), fdprintf(2, __VA_ARGS__))
  1264. # define DEBUG_CLEAN 1
  1265. #else
  1266. # define DEBUG_CLEAN 0
  1267. #endif
  1268. #if DEBUG_EXPAND
  1269. static void debug_print_strings(const char *prefix, char **vv)
  1270. {
  1271. indent();
  1272. fdprintf(2, "%s:\n", prefix);
  1273. while (*vv)
  1274. fdprintf(2, " '%s'\n", *vv++);
  1275. }
  1276. #else
  1277. # define debug_print_strings(prefix, vv) ((void)0)
  1278. #endif
  1279. /* Leak hunting. Use hush_leaktool.sh for post-processing.
  1280. */
  1281. #if LEAK_HUNTING
  1282. static void *xxmalloc(int lineno, size_t size)
  1283. {
  1284. void *ptr = xmalloc((size + 0xff) & ~0xff);
  1285. fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
  1286. return ptr;
  1287. }
  1288. static void *xxrealloc(int lineno, void *ptr, size_t size)
  1289. {
  1290. ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
  1291. fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
  1292. return ptr;
  1293. }
  1294. static char *xxstrdup(int lineno, const char *str)
  1295. {
  1296. char *ptr = xstrdup(str);
  1297. fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
  1298. return ptr;
  1299. }
  1300. static void xxfree(void *ptr)
  1301. {
  1302. fdprintf(2, "free %p\n", ptr);
  1303. free(ptr);
  1304. }
  1305. # define xmalloc(s) xxmalloc(__LINE__, s)
  1306. # define xrealloc(p, s) xxrealloc(__LINE__, p, s)
  1307. # define xstrdup(s) xxstrdup(__LINE__, s)
  1308. # define free(p) xxfree(p)
  1309. #endif
  1310. /* Syntax and runtime errors. They always abort scripts.
  1311. * In interactive use they usually discard unparsed and/or unexecuted commands
  1312. * and return to the prompt.
  1313. * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
  1314. */
  1315. #if HUSH_DEBUG < 2
  1316. # define msg_and_die_if_script(lineno, ...) msg_and_die_if_script(__VA_ARGS__)
  1317. # define syntax_error(lineno, msg) syntax_error(msg)
  1318. # define syntax_error_at(lineno, msg) syntax_error_at(msg)
  1319. # define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
  1320. # define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
  1321. # define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
  1322. #endif
  1323. static void die_if_script(void)
  1324. {
  1325. if (!G_interactive_fd) {
  1326. if (G.last_exitcode) /* sometines it's 2, not 1 (bash compat) */
  1327. xfunc_error_retval = G.last_exitcode;
  1328. xfunc_die();
  1329. }
  1330. }
  1331. static void msg_and_die_if_script(unsigned lineno, const char *fmt, ...)
  1332. {
  1333. va_list p;
  1334. #if HUSH_DEBUG >= 2
  1335. bb_error_msg("hush.c:%u", lineno);
  1336. #endif
  1337. va_start(p, fmt);
  1338. bb_verror_msg(fmt, p, NULL);
  1339. va_end(p);
  1340. die_if_script();
  1341. }
  1342. static void syntax_error(unsigned lineno UNUSED_PARAM, const char *msg)
  1343. {
  1344. if (msg)
  1345. bb_error_msg("syntax error: %s", msg);
  1346. else
  1347. bb_simple_error_msg("syntax error");
  1348. die_if_script();
  1349. }
  1350. static void syntax_error_at(unsigned lineno UNUSED_PARAM, const char *msg)
  1351. {
  1352. bb_error_msg("syntax error at '%s'", msg);
  1353. die_if_script();
  1354. }
  1355. static void syntax_error_unterm_str(unsigned lineno UNUSED_PARAM, const char *s)
  1356. {
  1357. #if ENABLE_FEATURE_EDITING
  1358. if (!G.flag_ctrlC)
  1359. #endif
  1360. bb_error_msg("syntax error: unterminated %s", s);
  1361. //? source4.tests fails: in bash, echo ${^} in script does not terminate the script
  1362. // die_if_script();
  1363. }
  1364. static void syntax_error_unterm_ch(unsigned lineno, char ch)
  1365. {
  1366. char msg[2] = { ch, '\0' };
  1367. syntax_error_unterm_str(lineno, msg);
  1368. }
  1369. static void syntax_error_unexpected_ch(unsigned lineno UNUSED_PARAM, int ch)
  1370. {
  1371. char msg[2];
  1372. msg[0] = ch;
  1373. msg[1] = '\0';
  1374. #if HUSH_DEBUG >= 2
  1375. bb_error_msg("hush.c:%u", lineno);
  1376. #endif
  1377. bb_error_msg("syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
  1378. die_if_script();
  1379. }
  1380. #if HUSH_DEBUG < 2
  1381. # undef msg_and_die_if_script
  1382. # undef syntax_error
  1383. # undef syntax_error_at
  1384. # undef syntax_error_unterm_ch
  1385. # undef syntax_error_unterm_str
  1386. # undef syntax_error_unexpected_ch
  1387. #else
  1388. # define msg_and_die_if_script(...) msg_and_die_if_script(__LINE__, __VA_ARGS__)
  1389. # define syntax_error(msg) syntax_error(__LINE__, msg)
  1390. # define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
  1391. # define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
  1392. # define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
  1393. # define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
  1394. #endif
  1395. /* Utility functions
  1396. */
  1397. /* Replace each \x with x in place, return ptr past NUL. */
  1398. static char *unbackslash(char *src)
  1399. {
  1400. char *dst = src = strchrnul(src, '\\');
  1401. while (1) {
  1402. if (*src == '\\') {
  1403. src++;
  1404. if (*src != '\0') {
  1405. /* \x -> x */
  1406. *dst++ = *src++;
  1407. continue;
  1408. }
  1409. /* else: "\<nul>". Do not delete this backslash.
  1410. * Testcase: eval 'echo ok\'
  1411. */
  1412. *dst++ = '\\';
  1413. /* fallthrough */
  1414. }
  1415. if ((*dst++ = *src++) == '\0')
  1416. break;
  1417. }
  1418. return dst;
  1419. }
  1420. static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
  1421. {
  1422. int i;
  1423. unsigned count1;
  1424. unsigned count2;
  1425. char **v;
  1426. v = strings;
  1427. count1 = 0;
  1428. if (v) {
  1429. while (*v) {
  1430. count1++;
  1431. v++;
  1432. }
  1433. }
  1434. count2 = 0;
  1435. v = add;
  1436. while (*v) {
  1437. count2++;
  1438. v++;
  1439. }
  1440. v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
  1441. v[count1 + count2] = NULL;
  1442. i = count2;
  1443. while (--i >= 0)
  1444. v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
  1445. return v;
  1446. }
  1447. #if LEAK_HUNTING
  1448. static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
  1449. {
  1450. char **ptr = add_strings_to_strings(strings, add, need_to_dup);
  1451. fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
  1452. return ptr;
  1453. }
  1454. #define add_strings_to_strings(strings, add, need_to_dup) \
  1455. xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
  1456. #endif
  1457. /* Note: takes ownership of "add" ptr (it is not strdup'ed) */
  1458. static char **add_string_to_strings(char **strings, char *add)
  1459. {
  1460. char *v[2];
  1461. v[0] = add;
  1462. v[1] = NULL;
  1463. return add_strings_to_strings(strings, v, /*dup:*/ 0);
  1464. }
  1465. #if LEAK_HUNTING
  1466. static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
  1467. {
  1468. char **ptr = add_string_to_strings(strings, add);
  1469. fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
  1470. return ptr;
  1471. }
  1472. #define add_string_to_strings(strings, add) \
  1473. xx_add_string_to_strings(__LINE__, strings, add)
  1474. #endif
  1475. static void free_strings(char **strings)
  1476. {
  1477. char **v;
  1478. if (!strings)
  1479. return;
  1480. v = strings;
  1481. while (*v) {
  1482. free(*v);
  1483. v++;
  1484. }
  1485. free(strings);
  1486. }
  1487. static int dup_CLOEXEC(int fd, int avoid_fd)
  1488. {
  1489. int newfd;
  1490. repeat:
  1491. newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
  1492. if (newfd >= 0) {
  1493. if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
  1494. fcntl(newfd, F_SETFD, FD_CLOEXEC);
  1495. } else { /* newfd < 0 */
  1496. if (errno == EBUSY)
  1497. goto repeat;
  1498. if (errno == EINTR)
  1499. goto repeat;
  1500. }
  1501. return newfd;
  1502. }
  1503. static int xdup_CLOEXEC_and_close(int fd, int avoid_fd)
  1504. {
  1505. int newfd;
  1506. repeat:
  1507. newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
  1508. if (newfd < 0) {
  1509. if (errno == EBUSY)
  1510. goto repeat;
  1511. if (errno == EINTR)
  1512. goto repeat;
  1513. /* fd was not open? */
  1514. if (errno == EBADF)
  1515. return fd;
  1516. xfunc_die();
  1517. }
  1518. if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
  1519. fcntl(newfd, F_SETFD, FD_CLOEXEC);
  1520. close(fd);
  1521. return newfd;
  1522. }
  1523. /* Manipulating HFILEs */
  1524. static HFILE *hfopen(const char *name)
  1525. {
  1526. HFILE *fp;
  1527. int fd;
  1528. fd = STDIN_FILENO;
  1529. if (name) {
  1530. fd = open(name, O_RDONLY | O_CLOEXEC);
  1531. if (fd < 0)
  1532. return NULL;
  1533. if (O_CLOEXEC == 0) /* ancient libc */
  1534. close_on_exec_on(fd);
  1535. }
  1536. fp = xmalloc(sizeof(*fp));
  1537. if (name == NULL)
  1538. G.HFILE_stdin = fp;
  1539. fp->fd = fd;
  1540. fp->cur = fp->end = fp->buf;
  1541. fp->next_hfile = G.HFILE_list;
  1542. G.HFILE_list = fp;
  1543. return fp;
  1544. }
  1545. static void hfclose(HFILE *fp)
  1546. {
  1547. HFILE **pp = &G.HFILE_list;
  1548. while (*pp) {
  1549. HFILE *cur = *pp;
  1550. if (cur == fp) {
  1551. *pp = cur->next_hfile;
  1552. break;
  1553. }
  1554. pp = &cur->next_hfile;
  1555. }
  1556. if (fp->fd >= 0)
  1557. close(fp->fd);
  1558. free(fp);
  1559. }
  1560. static int refill_HFILE_and_getc(HFILE *fp)
  1561. {
  1562. int n;
  1563. if (fp->fd < 0) {
  1564. /* Already saw EOF */
  1565. return EOF;
  1566. }
  1567. /* Try to buffer more input */
  1568. fp->cur = fp->buf;
  1569. n = safe_read(fp->fd, fp->buf, sizeof(fp->buf));
  1570. if (n < 0) {
  1571. bb_simple_perror_msg("read error");
  1572. n = 0;
  1573. }
  1574. fp->end = fp->buf + n;
  1575. if (n == 0) {
  1576. /* EOF/error */
  1577. close(fp->fd);
  1578. fp->fd = -1;
  1579. return EOF;
  1580. }
  1581. return (unsigned char)(*fp->cur++);
  1582. }
  1583. /* Inlined for common case of non-empty buffer.
  1584. */
  1585. static ALWAYS_INLINE int hfgetc(HFILE *fp)
  1586. {
  1587. if (fp->cur < fp->end)
  1588. return (unsigned char)(*fp->cur++);
  1589. /* Buffer empty */
  1590. return refill_HFILE_and_getc(fp);
  1591. }
  1592. static int move_HFILEs_on_redirect(int fd, int avoid_fd)
  1593. {
  1594. HFILE *fl = G.HFILE_list;
  1595. while (fl) {
  1596. if (fd == fl->fd) {
  1597. /* We use it only on script files, they are all CLOEXEC */
  1598. fl->fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
  1599. debug_printf_redir("redirect_fd %d: matches a script fd, moving it to %d\n", fd, fl->fd);
  1600. return 1; /* "found and moved" */
  1601. }
  1602. fl = fl->next_hfile;
  1603. }
  1604. #if ENABLE_HUSH_MODE_X
  1605. if (G.x_mode_fd > 0 && fd == G.x_mode_fd) {
  1606. G.x_mode_fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
  1607. return 1; /* "found and moved" */
  1608. }
  1609. #endif
  1610. return 0; /* "not in the list" */
  1611. }
  1612. #if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
  1613. static void close_all_HFILE_list(void)
  1614. {
  1615. HFILE *fl = G.HFILE_list;
  1616. while (fl) {
  1617. /* hfclose would also free HFILE object.
  1618. * It is disastrous if we share memory with a vforked parent.
  1619. * I'm not sure we never come here after vfork.
  1620. * Therefore just close fd, nothing more.
  1621. *
  1622. * ">" instead of ">=": we don't close fd#0,
  1623. * interactive shell uses hfopen(NULL) as stdin input
  1624. * which has fl->fd == 0, but fd#0 gets redirected in pipes.
  1625. * If we'd close it here, then e.g. interactive "set | sort"
  1626. * with NOFORKed sort, would have sort's input fd closed.
  1627. */
  1628. if (fl->fd > 0)
  1629. /*hfclose(fl); - unsafe */
  1630. close(fl->fd);
  1631. fl = fl->next_hfile;
  1632. }
  1633. }
  1634. #endif
  1635. static int fd_in_HFILEs(int fd)
  1636. {
  1637. HFILE *fl = G.HFILE_list;
  1638. while (fl) {
  1639. if (fl->fd == fd)
  1640. return 1;
  1641. fl = fl->next_hfile;
  1642. }
  1643. return 0;
  1644. }
  1645. /* Helpers for setting new $n and restoring them back
  1646. */
  1647. typedef struct save_arg_t {
  1648. char *sv_argv0;
  1649. char **sv_g_argv;
  1650. int sv_g_argc;
  1651. IF_HUSH_SET(smallint sv_g_malloced;)
  1652. } save_arg_t;
  1653. static void save_and_replace_G_args(save_arg_t *sv, char **argv)
  1654. {
  1655. sv->sv_argv0 = argv[0];
  1656. sv->sv_g_argv = G.global_argv;
  1657. sv->sv_g_argc = G.global_argc;
  1658. IF_HUSH_SET(sv->sv_g_malloced = G.global_args_malloced;)
  1659. argv[0] = G.global_argv[0]; /* retain $0 */
  1660. G.global_argv = argv;
  1661. IF_HUSH_SET(G.global_args_malloced = 0;)
  1662. G.global_argc = 1 + string_array_len(argv + 1);
  1663. }
  1664. static void restore_G_args(save_arg_t *sv, char **argv)
  1665. {
  1666. #if ENABLE_HUSH_SET
  1667. if (G.global_args_malloced) {
  1668. /* someone ran "set -- arg1 arg2 ...", undo */
  1669. char **pp = G.global_argv;
  1670. while (*++pp) /* note: does not free $0 */
  1671. free(*pp);
  1672. free(G.global_argv);
  1673. }
  1674. #endif
  1675. argv[0] = sv->sv_argv0;
  1676. G.global_argv = sv->sv_g_argv;
  1677. G.global_argc = sv->sv_g_argc;
  1678. IF_HUSH_SET(G.global_args_malloced = sv->sv_g_malloced;)
  1679. }
  1680. /* Basic theory of signal handling in shell
  1681. * ========================================
  1682. * This does not describe what hush does, rather, it is current understanding
  1683. * what it _should_ do. If it doesn't, it's a bug.
  1684. * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
  1685. *
  1686. * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
  1687. * is finished or backgrounded. It is the same in interactive and
  1688. * non-interactive shells, and is the same regardless of whether
  1689. * a user trap handler is installed or a shell special one is in effect.
  1690. * ^C or ^Z from keyboard seems to execute "at once" because it usually
  1691. * backgrounds (i.e. stops) or kills all members of currently running
  1692. * pipe.
  1693. *
  1694. * Wait builtin is interruptible by signals for which user trap is set
  1695. * or by SIGINT in interactive shell.
  1696. *
  1697. * Trap handlers will execute even within trap handlers. (right?)
  1698. *
  1699. * User trap handlers are forgotten when subshell ("(cmd)") is entered,
  1700. * except for handlers set to '' (empty string).
  1701. *
  1702. * If job control is off, backgrounded commands ("cmd &")
  1703. * have SIGINT, SIGQUIT set to SIG_IGN.
  1704. *
  1705. * Commands which are run in command substitution ("`cmd`")
  1706. * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
  1707. *
  1708. * Ordinary commands have signals set to SIG_IGN/DFL as inherited
  1709. * by the shell from its parent.
  1710. *
  1711. * Signals which differ from SIG_DFL action
  1712. * (note: child (i.e., [v]forked) shell is not an interactive shell):
  1713. *
  1714. * SIGQUIT: ignore
  1715. * SIGTERM (interactive): ignore
  1716. * SIGHUP (interactive):
  1717. * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
  1718. * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
  1719. * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
  1720. * that all pipe members are stopped. Try this in bash:
  1721. * while :; do :; done - ^Z does not background it
  1722. * (while :; do :; done) - ^Z backgrounds it
  1723. * SIGINT (interactive): wait for last pipe, ignore the rest
  1724. * of the command line, show prompt. NB: ^C does not send SIGINT
  1725. * to interactive shell while shell is waiting for a pipe,
  1726. * since shell is bg'ed (is not in foreground process group).
  1727. * Example 1: this waits 5 sec, but does not execute ls:
  1728. * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
  1729. * Example 2: this does not wait and does not execute ls:
  1730. * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
  1731. * Example 3: this does not wait 5 sec, but executes ls:
  1732. * "sleep 5; ls -l" + press ^C
  1733. * Example 4: this does not wait and does not execute ls:
  1734. * "sleep 5 & wait; ls -l" + press ^C
  1735. *
  1736. * (What happens to signals which are IGN on shell start?)
  1737. * (What happens with signal mask on shell start?)
  1738. *
  1739. * Old implementation
  1740. * ==================
  1741. * We use in-kernel pending signal mask to determine which signals were sent.
  1742. * We block all signals which we don't want to take action immediately,
  1743. * i.e. we block all signals which need to have special handling as described
  1744. * above, and all signals which have traps set.
  1745. * After each pipe execution, we extract any pending signals via sigtimedwait()
  1746. * and act on them.
  1747. *
  1748. * unsigned special_sig_mask: a mask of such "special" signals
  1749. * sigset_t blocked_set: current blocked signal set
  1750. *
  1751. * "trap - SIGxxx":
  1752. * clear bit in blocked_set unless it is also in special_sig_mask
  1753. * "trap 'cmd' SIGxxx":
  1754. * set bit in blocked_set (even if 'cmd' is '')
  1755. * after [v]fork, if we plan to be a shell:
  1756. * unblock signals with special interactive handling
  1757. * (child shell is not interactive),
  1758. * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
  1759. * after [v]fork, if we plan to exec:
  1760. * POSIX says fork clears pending signal mask in child - no need to clear it.
  1761. * Restore blocked signal set to one inherited by shell just prior to exec.
  1762. *
  1763. * Note: as a result, we do not use signal handlers much. The only uses
  1764. * are to count SIGCHLDs
  1765. * and to restore tty pgrp on signal-induced exit.
  1766. *
  1767. * Note 2 (compat):
  1768. * Standard says "When a subshell is entered, traps that are not being ignored
  1769. * are set to the default actions". bash interprets it so that traps which
  1770. * are set to '' (ignore) are NOT reset to defaults. We do the same.
  1771. *
  1772. * Problem: the above approach makes it unwieldy to catch signals while
  1773. * we are in read builtin, or while we read commands from stdin:
  1774. * masked signals are not visible!
  1775. *
  1776. * New implementation
  1777. * ==================
  1778. * We record each signal we are interested in by installing signal handler
  1779. * for them - a bit like emulating kernel pending signal mask in userspace.
  1780. * We are interested in: signals which need to have special handling
  1781. * as described above, and all signals which have traps set.
  1782. * Signals are recorded in pending_set.
  1783. * After each pipe execution, we extract any pending signals
  1784. * and act on them.
  1785. *
  1786. * unsigned special_sig_mask: a mask of shell-special signals.
  1787. * unsigned fatal_sig_mask: a mask of signals on which we restore tty pgrp.
  1788. * char *traps[sig] if trap for sig is set (even if it's '').
  1789. * sigset_t pending_set: set of sigs we received.
  1790. *
  1791. * "trap - SIGxxx":
  1792. * if sig is in special_sig_mask, set handler back to:
  1793. * record_pending_signo, or to IGN if it's a tty stop signal
  1794. * if sig is in fatal_sig_mask, set handler back to sigexit.
  1795. * else: set handler back to SIG_DFL
  1796. * "trap 'cmd' SIGxxx":
  1797. * set handler to record_pending_signo.
  1798. * "trap '' SIGxxx":
  1799. * set handler to SIG_IGN.
  1800. * after [v]fork, if we plan to be a shell:
  1801. * set signals with special interactive handling to SIG_DFL
  1802. * (because child shell is not interactive),
  1803. * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
  1804. * after [v]fork, if we plan to exec:
  1805. * POSIX says fork clears pending signal mask in child - no need to clear it.
  1806. *
  1807. * To make wait builtin interruptible, we handle SIGCHLD as special signal,
  1808. * otherwise (if we leave it SIG_DFL) sigsuspend in wait builtin will not wake up on it.
  1809. *
  1810. * Note (compat):
  1811. * Standard says "When a subshell is entered, traps that are not being ignored
  1812. * are set to the default actions". bash interprets it so that traps which
  1813. * are set to '' (ignore) are NOT reset to defaults. We do the same.
  1814. */
  1815. enum {
  1816. SPECIAL_INTERACTIVE_SIGS = 0
  1817. | (1 << SIGTERM)
  1818. | (1 << SIGINT)
  1819. | (1 << SIGHUP)
  1820. ,
  1821. SPECIAL_JOBSTOP_SIGS = 0
  1822. #if ENABLE_HUSH_JOB
  1823. | (1 << SIGTTIN)
  1824. | (1 << SIGTTOU)
  1825. | (1 << SIGTSTP)
  1826. #endif
  1827. ,
  1828. };
  1829. static void record_pending_signo(int sig)
  1830. {
  1831. sigaddset(&G.pending_set, sig);
  1832. #if ENABLE_HUSH_FAST
  1833. if (sig == SIGCHLD) {
  1834. G.count_SIGCHLD++;
  1835. //bb_error_msg("[%d] SIGCHLD_handler: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
  1836. }
  1837. #endif
  1838. }
  1839. static sighandler_t install_sighandler(int sig, sighandler_t handler)
  1840. {
  1841. struct sigaction old_sa;
  1842. /* We could use signal() to install handlers... almost:
  1843. * except that we need to mask ALL signals while handlers run.
  1844. * I saw signal nesting in strace, race window isn't small.
  1845. * SA_RESTART is also needed, but in Linux, signal()
  1846. * sets SA_RESTART too.
  1847. */
  1848. /* memset(&G.sa, 0, sizeof(G.sa)); - already done */
  1849. /* sigfillset(&G.sa.sa_mask); - already done */
  1850. /* G.sa.sa_flags = SA_RESTART; - already done */
  1851. G.sa.sa_handler = handler;
  1852. sigaction(sig, &G.sa, &old_sa);
  1853. return old_sa.sa_handler;
  1854. }
  1855. static void hush_exit(int exitcode) NORETURN;
  1856. static void restore_ttypgrp_and__exit(void) NORETURN;
  1857. static void restore_ttypgrp_and__exit(void)
  1858. {
  1859. /* xfunc has failed! die die die */
  1860. /* no EXIT traps, this is an escape hatch! */
  1861. G.exiting = 1;
  1862. hush_exit(xfunc_error_retval);
  1863. }
  1864. #if ENABLE_HUSH_JOB
  1865. /* Needed only on some libc:
  1866. * It was observed that on exit(), fgetc'ed buffered data
  1867. * gets "unwound" via lseek(fd, -NUM, SEEK_CUR).
  1868. * With the net effect that even after fork(), not vfork(),
  1869. * exit() in NOEXECed applet in "sh SCRIPT":
  1870. * noexec_applet_here
  1871. * echo END_OF_SCRIPT
  1872. * lseeks fd in input FILE object from EOF to "e" in "echo END_OF_SCRIPT".
  1873. * This makes "echo END_OF_SCRIPT" executed twice.
  1874. * Similar problems can be seen with msg_and_die_if_script() -> xfunc_die()
  1875. * and in `cmd` handling.
  1876. * If set as die_func(), this makes xfunc_die() exit via _exit(), not exit():
  1877. */
  1878. static void fflush_and__exit(void) NORETURN;
  1879. static void fflush_and__exit(void)
  1880. {
  1881. fflush_all();
  1882. _exit(xfunc_error_retval);
  1883. }
  1884. /* After [v]fork, in child: do not restore tty pgrp on xfunc death */
  1885. # define disable_restore_tty_pgrp_on_exit() (die_func = fflush_and__exit)
  1886. /* After [v]fork, in parent: restore tty pgrp on xfunc death */
  1887. # define enable_restore_tty_pgrp_on_exit() (die_func = restore_ttypgrp_and__exit)
  1888. /* Restores tty foreground process group, and exits.
  1889. * May be called as signal handler for fatal signal
  1890. * (will resend signal to itself, producing correct exit state)
  1891. * or called directly with -EXITCODE.
  1892. * We also call it if xfunc is exiting.
  1893. */
  1894. static void sigexit(int sig) NORETURN;
  1895. static void sigexit(int sig)
  1896. {
  1897. /* Careful: we can end up here after [v]fork. Do not restore
  1898. * tty pgrp then, only top-level shell process does that */
  1899. if (G_saved_tty_pgrp && getpid() == G.root_pid) {
  1900. /* Disable all signals: job control, SIGPIPE, etc.
  1901. * Mostly paranoid measure, to prevent infinite SIGTTOU.
  1902. */
  1903. sigprocmask_allsigs(SIG_BLOCK);
  1904. tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
  1905. }
  1906. /* Not a signal, just exit */
  1907. if (sig <= 0)
  1908. _exit(- sig);
  1909. kill_myself_with_sig(sig); /* does not return */
  1910. }
  1911. #else
  1912. # define disable_restore_tty_pgrp_on_exit() ((void)0)
  1913. # define enable_restore_tty_pgrp_on_exit() ((void)0)
  1914. #endif
  1915. static sighandler_t pick_sighandler(unsigned sig)
  1916. {
  1917. sighandler_t handler = SIG_DFL;
  1918. if (sig < sizeof(unsigned)*8) {
  1919. unsigned sigmask = (1 << sig);
  1920. #if ENABLE_HUSH_JOB
  1921. /* is sig fatal? */
  1922. if (G_fatal_sig_mask & sigmask)
  1923. handler = sigexit;
  1924. else
  1925. #endif
  1926. /* sig has special handling? */
  1927. if (G.special_sig_mask & sigmask) {
  1928. handler = record_pending_signo;
  1929. /* TTIN/TTOU/TSTP can't be set to record_pending_signo
  1930. * in order to ignore them: they will be raised
  1931. * in an endless loop when we try to do some
  1932. * terminal ioctls! We do have to _ignore_ these.
  1933. */
  1934. if (SPECIAL_JOBSTOP_SIGS & sigmask)
  1935. handler = SIG_IGN;
  1936. }
  1937. }
  1938. return handler;
  1939. }
  1940. /* Restores tty foreground process group, and exits. */
  1941. static void hush_exit(int exitcode)
  1942. {
  1943. #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
  1944. if (G.line_input_state)
  1945. save_history(G.line_input_state);
  1946. #endif
  1947. fflush_all();
  1948. if (G.exiting <= 0 && G_traps && G_traps[0] && G_traps[0][0]) {
  1949. char *argv[3];
  1950. /* argv[0] is unused */
  1951. argv[1] = xstrdup(G_traps[0]); /* copy, since EXIT trap handler may modify G_traps[0] */
  1952. argv[2] = NULL;
  1953. G.exiting = 1; /* prevent EXIT trap recursion */
  1954. /* Note: G_traps[0] is not cleared!
  1955. * "trap" will still show it, if executed
  1956. * in the handler */
  1957. builtin_eval(argv);
  1958. }
  1959. #if ENABLE_FEATURE_CLEAN_UP
  1960. {
  1961. struct variable *cur_var;
  1962. if (G.cwd != bb_msg_unknown)
  1963. free((char*)G.cwd);
  1964. cur_var = G.top_var;
  1965. while (cur_var) {
  1966. struct variable *tmp = cur_var;
  1967. if (!cur_var->max_len)
  1968. free(cur_var->varstr);
  1969. cur_var = cur_var->next;
  1970. free(tmp);
  1971. }
  1972. }
  1973. #endif
  1974. fflush_all();
  1975. #if ENABLE_HUSH_JOB
  1976. sigexit(- (exitcode & 0xff));
  1977. #else
  1978. _exit(exitcode);
  1979. #endif
  1980. }
  1981. //TODO: return a mask of ALL handled sigs?
  1982. static int check_and_run_traps(void)
  1983. {
  1984. int last_sig = 0;
  1985. while (1) {
  1986. int sig;
  1987. if (sigisemptyset(&G.pending_set))
  1988. break;
  1989. sig = 0;
  1990. do {
  1991. sig++;
  1992. if (sigismember(&G.pending_set, sig)) {
  1993. sigdelset(&G.pending_set, sig);
  1994. goto got_sig;
  1995. }
  1996. } while (sig < NSIG);
  1997. break;
  1998. got_sig:
  1999. #if ENABLE_HUSH_TRAP
  2000. if (G_traps && G_traps[sig]) {
  2001. debug_printf_exec("%s: sig:%d handler:'%s'\n", __func__, sig, G.traps[sig]);
  2002. if (G_traps[sig][0]) {
  2003. /* We have user-defined handler */
  2004. smalluint save_rcode;
  2005. int save_pre;
  2006. char *argv[3];
  2007. /* argv[0] is unused */
  2008. argv[1] = xstrdup(G_traps[sig]);
  2009. /* why strdup? trap can modify itself: trap 'trap "echo oops" INT' INT */
  2010. argv[2] = NULL;
  2011. save_pre = G.pre_trap_exitcode;
  2012. G.pre_trap_exitcode = save_rcode = G.last_exitcode;
  2013. builtin_eval(argv);
  2014. free(argv[1]);
  2015. G.pre_trap_exitcode = save_pre;
  2016. G.last_exitcode = save_rcode;
  2017. # if ENABLE_HUSH_FUNCTIONS
  2018. if (G.return_exitcode >= 0) {
  2019. debug_printf_exec("trap exitcode:%d\n", G.return_exitcode);
  2020. G.last_exitcode = G.return_exitcode;
  2021. }
  2022. # endif
  2023. last_sig = sig;
  2024. } /* else: "" trap, ignoring signal */
  2025. continue;
  2026. }
  2027. #endif
  2028. /* not a trap: special action */
  2029. switch (sig) {
  2030. case SIGINT:
  2031. debug_printf_exec("%s: sig:%d default SIGINT handler\n", __func__, sig);
  2032. G.flag_SIGINT = 1;
  2033. last_sig = sig;
  2034. break;
  2035. #if ENABLE_HUSH_JOB
  2036. case SIGHUP: {
  2037. //TODO: why are we doing this? ash and dash don't do this,
  2038. //they have no handler for SIGHUP at all,
  2039. //they rely on kernel to send SIGHUP+SIGCONT to orphaned process groups
  2040. struct pipe *job;
  2041. debug_printf_exec("%s: sig:%d default SIGHUP handler\n", __func__, sig);
  2042. /* bash is observed to signal whole process groups,
  2043. * not individual processes */
  2044. for (job = G.job_list; job; job = job->next) {
  2045. if (job->pgrp <= 0)
  2046. continue;
  2047. debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
  2048. if (kill(- job->pgrp, SIGHUP) == 0)
  2049. kill(- job->pgrp, SIGCONT);
  2050. }
  2051. sigexit(SIGHUP);
  2052. }
  2053. #endif
  2054. #if ENABLE_HUSH_FAST
  2055. case SIGCHLD:
  2056. debug_printf_exec("%s: sig:%d default SIGCHLD handler\n", __func__, sig);
  2057. G.count_SIGCHLD++;
  2058. //bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
  2059. /* Note:
  2060. * We don't do 'last_sig = sig' here -> NOT returning this sig.
  2061. * This simplifies wait builtin a bit.
  2062. */
  2063. break;
  2064. #endif
  2065. default: /* ignored: */
  2066. debug_printf_exec("%s: sig:%d default handling is to ignore\n", __func__, sig);
  2067. /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
  2068. /* Note:
  2069. * We don't do 'last_sig = sig' here -> NOT returning this sig.
  2070. * Example: wait is not interrupted by TERM
  2071. * in interactive shell, because TERM is ignored.
  2072. */
  2073. break;
  2074. }
  2075. }
  2076. return last_sig;
  2077. }
  2078. static const char *get_cwd(int force)
  2079. {
  2080. if (force || G.cwd == NULL) {
  2081. /* xrealloc_getcwd_or_warn(arg) calls free(arg),
  2082. * we must not try to free(bb_msg_unknown) */
  2083. if (G.cwd == bb_msg_unknown)
  2084. G.cwd = NULL;
  2085. G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
  2086. if (!G.cwd)
  2087. G.cwd = bb_msg_unknown;
  2088. }
  2089. return G.cwd;
  2090. }
  2091. /*
  2092. * Shell and environment variable support
  2093. */
  2094. static struct variable **get_ptr_to_local_var(const char *name, unsigned len)
  2095. {
  2096. struct variable **pp;
  2097. struct variable *cur;
  2098. pp = &G.top_var;
  2099. while ((cur = *pp) != NULL) {
  2100. if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
  2101. return pp;
  2102. pp = &cur->next;
  2103. }
  2104. return NULL;
  2105. }
  2106. static const char* FAST_FUNC get_local_var_value(const char *name)
  2107. {
  2108. struct variable **vpp;
  2109. unsigned len = strlen(name);
  2110. if (G.expanded_assignments) {
  2111. char **cpp = G.expanded_assignments;
  2112. while (*cpp) {
  2113. char *cp = *cpp;
  2114. if (strncmp(cp, name, len) == 0 && cp[len] == '=')
  2115. return cp + len + 1;
  2116. cpp++;
  2117. }
  2118. }
  2119. vpp = get_ptr_to_local_var(name, len);
  2120. if (vpp)
  2121. return (*vpp)->varstr + len + 1;
  2122. if (strcmp(name, "PPID") == 0)
  2123. return utoa(G.root_ppid);
  2124. // bash compat: UID? EUID?
  2125. #if ENABLE_HUSH_RANDOM_SUPPORT
  2126. if (strcmp(name, "RANDOM") == 0)
  2127. return utoa(next_random(&G.random_gen));
  2128. #endif
  2129. #if ENABLE_HUSH_LINENO_VAR
  2130. if (strcmp(name, "LINENO") == 0)
  2131. return utoa(G.execute_lineno);
  2132. #endif
  2133. #if BASH_EPOCH_VARS
  2134. {
  2135. const char *fmt = NULL;
  2136. if (strcmp(name, "EPOCHSECONDS") == 0)
  2137. fmt = "%lu";
  2138. else if (strcmp(name, "EPOCHREALTIME") == 0)
  2139. fmt = "%lu.%06u";
  2140. if (fmt) {
  2141. struct timeval tv;
  2142. gettimeofday(&tv, NULL);
  2143. sprintf(G.epoch_buf, fmt, (unsigned long)tv.tv_sec,
  2144. (unsigned)tv.tv_usec);
  2145. return G.epoch_buf;
  2146. }
  2147. }
  2148. #endif
  2149. return NULL;
  2150. }
  2151. #if ENABLE_HUSH_GETOPTS
  2152. static void handle_changed_special_names(const char *name, unsigned name_len)
  2153. {
  2154. if (name_len == 6) {
  2155. if (strncmp(name, "OPTIND", 6) == 0) {
  2156. G.getopt_count = 0;
  2157. return;
  2158. }
  2159. }
  2160. }
  2161. #else
  2162. /* Do not even bother evaluating arguments */
  2163. # define handle_changed_special_names(...) ((void)0)
  2164. #endif
  2165. /* str holds "NAME=VAL" and is expected to be malloced.
  2166. * We take ownership of it.
  2167. */
  2168. #define SETFLAG_EXPORT (1 << 0)
  2169. #define SETFLAG_UNEXPORT (1 << 1)
  2170. #define SETFLAG_MAKE_RO (1 << 2)
  2171. #define SETFLAG_VARLVL_SHIFT 3
  2172. static int set_local_var(char *str, unsigned flags)
  2173. {
  2174. struct variable **cur_pp;
  2175. struct variable *cur;
  2176. char *free_me = NULL;
  2177. char *eq_sign;
  2178. int name_len;
  2179. int retval;
  2180. unsigned local_lvl = (flags >> SETFLAG_VARLVL_SHIFT);
  2181. eq_sign = strchr(str, '=');
  2182. if (HUSH_DEBUG && !eq_sign)
  2183. bb_simple_error_msg_and_die("BUG in setvar");
  2184. name_len = eq_sign - str + 1; /* including '=' */
  2185. cur_pp = &G.top_var;
  2186. while ((cur = *cur_pp) != NULL) {
  2187. if (strncmp(cur->varstr, str, name_len) != 0) {
  2188. cur_pp = &cur->next;
  2189. continue;
  2190. }
  2191. /* We found an existing var with this name */
  2192. if (cur->flg_read_only) {
  2193. bb_error_msg("%s: readonly variable", str);
  2194. free(str);
  2195. //NOTE: in bash, assignment in "export READONLY_VAR=Z" fails, and sets $?=1,
  2196. //but export per se succeeds (does put the var in env). We don't mimic that.
  2197. return -1;
  2198. }
  2199. if (flags & SETFLAG_UNEXPORT) { // && cur->flg_export ?
  2200. debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
  2201. *eq_sign = '\0';
  2202. unsetenv(str);
  2203. *eq_sign = '=';
  2204. }
  2205. if (cur->var_nest_level < local_lvl) {
  2206. /* bash 3.2.33(1) and exported vars:
  2207. * # export z=z
  2208. * # f() { local z=a; env | grep ^z; }
  2209. * # f
  2210. * z=a
  2211. * # env | grep ^z
  2212. * z=z
  2213. */
  2214. if (cur->flg_export)
  2215. flags |= SETFLAG_EXPORT;
  2216. /* New variable is local ("local VAR=VAL" or
  2217. * "VAR=VAL cmd")
  2218. * and existing one is global, or local
  2219. * on a lower level that new one.
  2220. * Remove it from global variable list:
  2221. */
  2222. *cur_pp = cur->next;
  2223. if (G.shadowed_vars_pp) {
  2224. /* Save in "shadowed" list */
  2225. debug_printf_env("shadowing %s'%s'/%u by '%s'/%u\n",
  2226. cur->flg_export ? "exported " : "",
  2227. cur->varstr, cur->var_nest_level, str, local_lvl
  2228. );
  2229. cur->next = *G.shadowed_vars_pp;
  2230. *G.shadowed_vars_pp = cur;
  2231. } else {
  2232. /* Came from pseudo_exec_argv(), no need to save: delete it */
  2233. debug_printf_env("shadow-deleting %s'%s'/%u by '%s'/%u\n",
  2234. cur->flg_export ? "exported " : "",
  2235. cur->varstr, cur->var_nest_level, str, local_lvl
  2236. );
  2237. if (cur->max_len == 0) /* allocated "VAR=VAL"? */
  2238. free_me = cur->varstr; /* then free it later */
  2239. free(cur);
  2240. }
  2241. break;
  2242. }
  2243. if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
  2244. debug_printf_env("assignement '%s' does not change anything\n", str);
  2245. free_and_exp:
  2246. free(str);
  2247. goto exp;
  2248. }
  2249. /* Replace the value in the found "struct variable" */
  2250. if (cur->max_len != 0) {
  2251. if (cur->max_len >= strnlen(str, cur->max_len + 1)) {
  2252. /* This one is from startup env, reuse space */
  2253. debug_printf_env("reusing startup env for '%s'\n", str);
  2254. strcpy(cur->varstr, str);
  2255. goto free_and_exp;
  2256. }
  2257. /* Can't reuse */
  2258. cur->max_len = 0;
  2259. goto set_str_and_exp;
  2260. }
  2261. /* max_len == 0 signifies "malloced" var, which we can
  2262. * (and have to) free. But we can't free(cur->varstr) here:
  2263. * if cur->flg_export is 1, it is in the environment.
  2264. * We should either unsetenv+free, or wait until putenv,
  2265. * then putenv(new)+free(old).
  2266. */
  2267. free_me = cur->varstr;
  2268. goto set_str_and_exp;
  2269. }
  2270. /* Not found or shadowed - create new variable struct */
  2271. debug_printf_env("%s: alloc new var '%s'/%u\n", __func__, str, local_lvl);
  2272. cur = xzalloc(sizeof(*cur));
  2273. cur->var_nest_level = local_lvl;
  2274. cur->next = *cur_pp;
  2275. *cur_pp = cur;
  2276. set_str_and_exp:
  2277. cur->varstr = str;
  2278. exp:
  2279. #if !BB_MMU || ENABLE_HUSH_READONLY
  2280. if (flags & SETFLAG_MAKE_RO) {
  2281. cur->flg_read_only = 1;
  2282. }
  2283. #endif
  2284. if (flags & SETFLAG_EXPORT)
  2285. cur->flg_export = 1;
  2286. retval = 0;
  2287. if (cur->flg_export) {
  2288. if (flags & SETFLAG_UNEXPORT) {
  2289. cur->flg_export = 0;
  2290. /* unsetenv was already done */
  2291. } else {
  2292. debug_printf_env("%s: putenv '%s'/%u\n", __func__, cur->varstr, cur->var_nest_level);
  2293. retval = putenv(cur->varstr);
  2294. /* fall through to "free(free_me)" -
  2295. * only now we can free old exported malloced string
  2296. */
  2297. }
  2298. }
  2299. free(free_me);
  2300. handle_changed_special_names(cur->varstr, name_len - 1);
  2301. return retval;
  2302. }
  2303. static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
  2304. {
  2305. char *var = xasprintf("%s=%s", name, val);
  2306. set_local_var(var, /*flag:*/ 0);
  2307. }
  2308. /* Used at startup and after each cd */
  2309. static void set_pwd_var(unsigned flag)
  2310. {
  2311. set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)), flag);
  2312. }
  2313. #if ENABLE_HUSH_UNSET || ENABLE_HUSH_GETOPTS
  2314. static int unset_local_var_len(const char *name, int name_len)
  2315. {
  2316. struct variable *cur;
  2317. struct variable **cur_pp;
  2318. cur_pp = &G.top_var;
  2319. while ((cur = *cur_pp) != NULL) {
  2320. if (strncmp(cur->varstr, name, name_len) == 0
  2321. && cur->varstr[name_len] == '='
  2322. ) {
  2323. if (cur->flg_read_only) {
  2324. bb_error_msg("%s: readonly variable", name);
  2325. return EXIT_FAILURE;
  2326. }
  2327. *cur_pp = cur->next;
  2328. debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
  2329. bb_unsetenv(cur->varstr);
  2330. if (!cur->max_len)
  2331. free(cur->varstr);
  2332. free(cur);
  2333. break;
  2334. }
  2335. cur_pp = &cur->next;
  2336. }
  2337. /* Handle "unset LINENO" et al even if did not find the variable to unset */
  2338. handle_changed_special_names(name, name_len);
  2339. return EXIT_SUCCESS;
  2340. }
  2341. static int unset_local_var(const char *name)
  2342. {
  2343. return unset_local_var_len(name, strlen(name));
  2344. }
  2345. #endif
  2346. /*
  2347. * Helpers for "var1=val1 var2=val2 cmd" feature
  2348. */
  2349. static void add_vars(struct variable *var)
  2350. {
  2351. struct variable *next;
  2352. while (var) {
  2353. next = var->next;
  2354. var->next = G.top_var;
  2355. G.top_var = var;
  2356. if (var->flg_export) {
  2357. debug_printf_env("%s: restoring exported '%s'/%u\n", __func__, var->varstr, var->var_nest_level);
  2358. putenv(var->varstr);
  2359. } else {
  2360. debug_printf_env("%s: restoring variable '%s'/%u\n", __func__, var->varstr, var->var_nest_level);
  2361. }
  2362. var = next;
  2363. }
  2364. }
  2365. /* We put strings[i] into variable table and possibly putenv them.
  2366. * If variable is read only, we can free the strings[i]
  2367. * which attempts to overwrite it.
  2368. * The strings[] vector itself is freed.
  2369. */
  2370. static void set_vars_and_save_old(char **strings)
  2371. {
  2372. char **s;
  2373. if (!strings)
  2374. return;
  2375. s = strings;
  2376. while (*s) {
  2377. struct variable *var_p;
  2378. struct variable **var_pp;
  2379. char *eq;
  2380. eq = strchr(*s, '=');
  2381. if (HUSH_DEBUG && !eq)
  2382. bb_simple_error_msg_and_die("BUG in varexp4");
  2383. var_pp = get_ptr_to_local_var(*s, eq - *s);
  2384. if (var_pp) {
  2385. var_p = *var_pp;
  2386. if (var_p->flg_read_only) {
  2387. char **p;
  2388. bb_error_msg("%s: readonly variable", *s);
  2389. /*
  2390. * "VAR=V BLTIN" unsets VARs after BLTIN completes.
  2391. * If VAR is readonly, leaving it in the list
  2392. * after asssignment error (msg above)
  2393. * causes doubled error message later, on unset.
  2394. */
  2395. debug_printf_env("removing/freeing '%s' element\n", *s);
  2396. free(*s);
  2397. p = s;
  2398. do { *p = p[1]; p++; } while (*p);
  2399. goto next;
  2400. }
  2401. /* below, set_local_var() with nest level will
  2402. * "shadow" (remove) this variable from
  2403. * global linked list.
  2404. */
  2405. }
  2406. debug_printf_env("%s: env override '%s'/%u\n", __func__, *s, G.var_nest_level);
  2407. set_local_var(*s, (G.var_nest_level << SETFLAG_VARLVL_SHIFT) | SETFLAG_EXPORT);
  2408. s++;
  2409. next: ;
  2410. }
  2411. free(strings);
  2412. }
  2413. /*
  2414. * Unicode helper
  2415. */
  2416. static void reinit_unicode_for_hush(void)
  2417. {
  2418. /* Unicode support should be activated even if LANG is set
  2419. * _during_ shell execution, not only if it was set when
  2420. * shell was started. Therefore, re-check LANG every time:
  2421. */
  2422. if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
  2423. || ENABLE_UNICODE_USING_LOCALE
  2424. ) {
  2425. const char *s = get_local_var_value("LC_ALL");
  2426. if (!s) s = get_local_var_value("LC_CTYPE");
  2427. if (!s) s = get_local_var_value("LANG");
  2428. reinit_unicode(s);
  2429. }
  2430. }
  2431. /*
  2432. * in_str support (strings, and "strings" read from files).
  2433. */
  2434. #if ENABLE_HUSH_INTERACTIVE
  2435. /* To test correct lineedit/interactive behavior, type from command line:
  2436. * echo $P\
  2437. * \
  2438. * AT\
  2439. * H\
  2440. * \
  2441. * It exercises a lot of corner cases.
  2442. */
  2443. static const char *setup_prompt_string(void)
  2444. {
  2445. const char *prompt_str;
  2446. debug_printf_prompt("%s promptmode:%d\n", __func__, G.promptmode);
  2447. # if ENABLE_FEATURE_EDITING_FANCY_PROMPT
  2448. prompt_str = get_local_var_value(G.promptmode == 0 ? "PS1" : "PS2");
  2449. if (!prompt_str)
  2450. prompt_str = "";
  2451. # else
  2452. prompt_str = "> "; /* if PS2, else... */
  2453. if (G.promptmode == 0) { /* PS1 */
  2454. /* No fancy prompts supported, (re)generate "CURDIR $ " by hand */
  2455. free(G.PS1);
  2456. /* bash uses $PWD value, even if it is set by user.
  2457. * It uses current dir only if PWD is unset.
  2458. * We always use current dir. */
  2459. G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
  2460. }
  2461. # endif
  2462. debug_printf("prompt_str '%s'\n", prompt_str);
  2463. return prompt_str;
  2464. }
  2465. static int get_user_input(struct in_str *i)
  2466. {
  2467. int r;
  2468. const char *prompt_str;
  2469. prompt_str = setup_prompt_string();
  2470. # if ENABLE_FEATURE_EDITING
  2471. for (;;) {
  2472. reinit_unicode_for_hush();
  2473. G.flag_SIGINT = 0;
  2474. /* buglet: SIGINT will not make new prompt to appear _at once_,
  2475. * only after <Enter>. (^C works immediately) */
  2476. r = read_line_input(G.line_input_state, prompt_str,
  2477. G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1
  2478. );
  2479. /* read_line_input intercepts ^C, "convert" it to SIGINT */
  2480. if (r == 0) {
  2481. G.flag_ctrlC = 1;
  2482. raise(SIGINT);
  2483. }
  2484. check_and_run_traps();
  2485. if (r != 0 && !G.flag_SIGINT)
  2486. break;
  2487. /* ^C or SIGINT: return EOF */
  2488. /* bash prints ^C even on real SIGINT (non-kbd generated) */
  2489. write(STDOUT_FILENO, "^C\n", 3);
  2490. G.last_exitcode = 128 + SIGINT;
  2491. i->p = NULL;
  2492. i->peek_buf[0] = r = EOF;
  2493. return r;
  2494. }
  2495. if (r < 0) {
  2496. /* EOF/error detected */
  2497. i->p = NULL;
  2498. i->peek_buf[0] = r = EOF;
  2499. return r;
  2500. }
  2501. i->p = G.user_input_buf;
  2502. return (unsigned char)*i->p++;
  2503. # else
  2504. for (;;) {
  2505. G.flag_SIGINT = 0;
  2506. if (i->last_char == '\0' || i->last_char == '\n') {
  2507. /* Why check_and_run_traps here? Try this interactively:
  2508. * $ trap 'echo INT' INT; (sleep 2; kill -INT $$) &
  2509. * $ <[enter], repeatedly...>
  2510. * Without check_and_run_traps, handler never runs.
  2511. */
  2512. check_and_run_traps();
  2513. fputs(prompt_str, stdout);
  2514. }
  2515. fflush_all();
  2516. //FIXME: here ^C or SIGINT will have effect only after <Enter>
  2517. r = hfgetc(i->file);
  2518. /* In !ENABLE_FEATURE_EDITING we don't use read_line_input,
  2519. * no ^C masking happens during fgetc, no special code for ^C:
  2520. * it generates SIGINT as usual.
  2521. */
  2522. check_and_run_traps();
  2523. if (G.flag_SIGINT)
  2524. G.last_exitcode = 128 + SIGINT;
  2525. if (r != '\0')
  2526. break;
  2527. }
  2528. return r;
  2529. # endif
  2530. }
  2531. /* This is the magic location that prints prompts
  2532. * and gets data back from the user */
  2533. static int fgetc_interactive(struct in_str *i)
  2534. {
  2535. int ch;
  2536. /* If it's interactive stdin, get new line. */
  2537. if (G_interactive_fd && i->file == G.HFILE_stdin) {
  2538. /* Returns first char (or EOF), the rest is in i->p[] */
  2539. ch = get_user_input(i);
  2540. G.promptmode = 1; /* PS2 */
  2541. debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
  2542. } else {
  2543. /* Not stdin: script file, sourced file, etc */
  2544. do ch = hfgetc(i->file); while (ch == '\0');
  2545. }
  2546. return ch;
  2547. }
  2548. #else
  2549. static ALWAYS_INLINE int fgetc_interactive(struct in_str *i)
  2550. {
  2551. int ch;
  2552. do ch = hfgetc(i->file); while (ch == '\0');
  2553. return ch;
  2554. }
  2555. #endif /* INTERACTIVE */
  2556. static int i_getch(struct in_str *i)
  2557. {
  2558. int ch;
  2559. if (!i->file) {
  2560. /* string-based in_str */
  2561. ch = (unsigned char)*i->p;
  2562. if (ch != '\0') {
  2563. i->p++;
  2564. i->last_char = ch;
  2565. return ch;
  2566. }
  2567. return EOF;
  2568. }
  2569. /* FILE-based in_str */
  2570. #if ENABLE_FEATURE_EDITING
  2571. /* This can be stdin, check line editing char[] buffer */
  2572. if (i->p && *i->p != '\0') {
  2573. ch = (unsigned char)*i->p++;
  2574. goto out;
  2575. }
  2576. #endif
  2577. /* peek_buf[] is an int array, not char. Can contain EOF. */
  2578. ch = i->peek_buf[0];
  2579. if (ch != 0) {
  2580. int ch2 = i->peek_buf[1];
  2581. i->peek_buf[0] = ch2;
  2582. if (ch2 == 0) /* very likely, avoid redundant write */
  2583. goto out;
  2584. i->peek_buf[1] = 0;
  2585. goto out;
  2586. }
  2587. ch = fgetc_interactive(i);
  2588. out:
  2589. debug_printf("file_get: got '%c' %d\n", ch, ch);
  2590. i->last_char = ch;
  2591. #if ENABLE_HUSH_LINENO_VAR
  2592. if (ch == '\n') {
  2593. G.parse_lineno++;
  2594. debug_printf_parse("G.parse_lineno++ = %u\n", G.parse_lineno);
  2595. }
  2596. #endif
  2597. return ch;
  2598. }
  2599. static int i_peek(struct in_str *i)
  2600. {
  2601. int ch;
  2602. if (!i->file) {
  2603. /* string-based in_str */
  2604. /* Doesn't report EOF on NUL. None of the callers care. */
  2605. return (unsigned char)*i->p;
  2606. }
  2607. /* FILE-based in_str */
  2608. #if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
  2609. /* This can be stdin, check line editing char[] buffer */
  2610. if (i->p && *i->p != '\0')
  2611. return (unsigned char)*i->p;
  2612. #endif
  2613. /* peek_buf[] is an int array, not char. Can contain EOF. */
  2614. ch = i->peek_buf[0];
  2615. if (ch != 0)
  2616. return ch;
  2617. /* Need to get a new char */
  2618. ch = fgetc_interactive(i);
  2619. debug_printf("file_peek: got '%c' %d\n", ch, ch);
  2620. /* Save it by either rolling back line editing buffer, or in i->peek_buf[0] */
  2621. #if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
  2622. if (i->p) {
  2623. i->p -= 1;
  2624. return ch;
  2625. }
  2626. #endif
  2627. i->peek_buf[0] = ch;
  2628. /*i->peek_buf[1] = 0; - already is */
  2629. return ch;
  2630. }
  2631. /* Only ever called if i_peek() was called, and did not return EOF.
  2632. * IOW: we know the previous peek saw an ordinary char, not EOF, not NUL,
  2633. * not end-of-line. Therefore we never need to read a new editing line here.
  2634. */
  2635. static int i_peek2(struct in_str *i)
  2636. {
  2637. int ch;
  2638. /* There are two cases when i->p[] buffer exists.
  2639. * (1) it's a string in_str.
  2640. * (2) It's a file, and we have a saved line editing buffer.
  2641. * In both cases, we know that i->p[0] exists and not NUL, and
  2642. * the peek2 result is in i->p[1].
  2643. */
  2644. if (i->p)
  2645. return (unsigned char)i->p[1];
  2646. /* Now we know it is a file-based in_str. */
  2647. /* peek_buf[] is an int array, not char. Can contain EOF. */
  2648. /* Is there 2nd char? */
  2649. ch = i->peek_buf[1];
  2650. if (ch == 0) {
  2651. /* We did not read it yet, get it now */
  2652. do ch = hfgetc(i->file); while (ch == '\0');
  2653. i->peek_buf[1] = ch;
  2654. }
  2655. debug_printf("file_peek2: got '%c' %d\n", ch, ch);
  2656. return ch;
  2657. }
  2658. static int i_getch_and_eat_bkslash_nl(struct in_str *input)
  2659. {
  2660. for (;;) {
  2661. int ch, ch2;
  2662. ch = i_getch(input);
  2663. if (ch != '\\')
  2664. return ch;
  2665. ch2 = i_peek(input);
  2666. if (ch2 != '\n')
  2667. return ch;
  2668. /* backslash+newline, skip it */
  2669. i_getch(input);
  2670. }
  2671. }
  2672. /* Note: this function _eats_ \<newline> pairs, safe to use plain
  2673. * i_getch() after it instead of i_getch_and_eat_bkslash_nl().
  2674. */
  2675. static int i_peek_and_eat_bkslash_nl(struct in_str *input)
  2676. {
  2677. for (;;) {
  2678. int ch, ch2;
  2679. ch = i_peek(input);
  2680. if (ch != '\\')
  2681. return ch;
  2682. ch2 = i_peek2(input);
  2683. if (ch2 != '\n')
  2684. return ch;
  2685. /* backslash+newline, skip it */
  2686. i_getch(input);
  2687. i_getch(input);
  2688. }
  2689. }
  2690. static void setup_file_in_str(struct in_str *i, HFILE *fp)
  2691. {
  2692. memset(i, 0, sizeof(*i));
  2693. i->file = fp;
  2694. /* i->p = NULL; */
  2695. }
  2696. static void setup_string_in_str(struct in_str *i, const char *s)
  2697. {
  2698. memset(i, 0, sizeof(*i));
  2699. /*i->file = NULL */;
  2700. i->p = s;
  2701. }
  2702. /*
  2703. * o_string support
  2704. */
  2705. #define B_CHUNK (32 * sizeof(char*))
  2706. static void o_reset_to_empty_unquoted(o_string *o)
  2707. {
  2708. o->length = 0;
  2709. o->has_quoted_part = 0;
  2710. if (o->data)
  2711. o->data[0] = '\0';
  2712. }
  2713. static void o_free_and_set_NULL(o_string *o)
  2714. {
  2715. free(o->data);
  2716. memset(o, 0, sizeof(*o));
  2717. }
  2718. static ALWAYS_INLINE void o_free(o_string *o)
  2719. {
  2720. free(o->data);
  2721. }
  2722. static void o_grow_by(o_string *o, int len)
  2723. {
  2724. if (o->length + len > o->maxlen) {
  2725. o->maxlen += (2 * len) | (B_CHUNK-1);
  2726. o->data = xrealloc(o->data, 1 + o->maxlen);
  2727. }
  2728. }
  2729. static void o_addchr(o_string *o, int ch)
  2730. {
  2731. debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
  2732. if (o->length < o->maxlen) {
  2733. /* likely. avoid o_grow_by() call */
  2734. add:
  2735. o->data[o->length] = ch;
  2736. o->length++;
  2737. o->data[o->length] = '\0';
  2738. return;
  2739. }
  2740. o_grow_by(o, 1);
  2741. goto add;
  2742. }
  2743. #if 0
  2744. /* Valid only if we know o_string is not empty */
  2745. static void o_delchr(o_string *o)
  2746. {
  2747. o->length--;
  2748. o->data[o->length] = '\0';
  2749. }
  2750. #endif
  2751. static void o_addblock(o_string *o, const char *str, int len)
  2752. {
  2753. o_grow_by(o, len);
  2754. ((char*)mempcpy(&o->data[o->length], str, len))[0] = '\0';
  2755. o->length += len;
  2756. }
  2757. static void o_addstr(o_string *o, const char *str)
  2758. {
  2759. o_addblock(o, str, strlen(str));
  2760. }
  2761. static void o_addstr_with_NUL(o_string *o, const char *str)
  2762. {
  2763. o_addblock(o, str, strlen(str) + 1);
  2764. }
  2765. #if !BB_MMU
  2766. static void nommu_addchr(o_string *o, int ch)
  2767. {
  2768. if (o)
  2769. o_addchr(o, ch);
  2770. }
  2771. #else
  2772. # define nommu_addchr(o, str) ((void)0)
  2773. #endif
  2774. #if ENABLE_HUSH_MODE_X
  2775. static void x_mode_addchr(int ch)
  2776. {
  2777. o_addchr(&G.x_mode_buf, ch);
  2778. }
  2779. static void x_mode_addstr(const char *str)
  2780. {
  2781. o_addstr(&G.x_mode_buf, str);
  2782. }
  2783. static void x_mode_addblock(const char *str, int len)
  2784. {
  2785. o_addblock(&G.x_mode_buf, str, len);
  2786. }
  2787. static void x_mode_prefix(void)
  2788. {
  2789. int n = G.x_mode_depth;
  2790. do x_mode_addchr('+'); while (--n >= 0);
  2791. }
  2792. static void x_mode_flush(void)
  2793. {
  2794. int len = G.x_mode_buf.length;
  2795. if (len <= 0)
  2796. return;
  2797. if (G.x_mode_fd > 0) {
  2798. G.x_mode_buf.data[len] = '\n';
  2799. full_write(G.x_mode_fd, G.x_mode_buf.data, len + 1);
  2800. }
  2801. G.x_mode_buf.length = 0;
  2802. }
  2803. #endif
  2804. /*
  2805. * HUSH_BRACE_EXPANSION code needs corresponding quoting on variable expansion side.
  2806. * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
  2807. * Apparently, on unquoted $v bash still does globbing
  2808. * ("v='*.txt'; echo $v" prints all .txt files),
  2809. * but NOT brace expansion! Thus, there should be TWO independent
  2810. * quoting mechanisms on $v expansion side: one protects
  2811. * $v from brace expansion, and other additionally protects "$v" against globbing.
  2812. * We have only second one.
  2813. */
  2814. #if ENABLE_HUSH_BRACE_EXPANSION
  2815. # define MAYBE_BRACES "{}"
  2816. #else
  2817. # define MAYBE_BRACES ""
  2818. #endif
  2819. /* My analysis of quoting semantics tells me that state information
  2820. * is associated with a destination, not a source.
  2821. */
  2822. static void o_addqchr(o_string *o, int ch)
  2823. {
  2824. int sz = 1;
  2825. /* '-' is included because of this case:
  2826. * >filename0 >filename1 >filename9; v='-'; echo filename[0"$v"9]
  2827. */
  2828. char *found = strchr("*?[-\\" MAYBE_BRACES, ch);
  2829. if (found)
  2830. sz++;
  2831. o_grow_by(o, sz);
  2832. if (found) {
  2833. o->data[o->length] = '\\';
  2834. o->length++;
  2835. }
  2836. o->data[o->length] = ch;
  2837. o->length++;
  2838. o->data[o->length] = '\0';
  2839. }
  2840. static void o_addQchr(o_string *o, int ch)
  2841. {
  2842. int sz = 1;
  2843. if ((o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)
  2844. && strchr("*?[-\\" MAYBE_BRACES, ch)
  2845. ) {
  2846. sz++;
  2847. o->data[o->length] = '\\';
  2848. o->length++;
  2849. }
  2850. o_grow_by(o, sz);
  2851. o->data[o->length] = ch;
  2852. o->length++;
  2853. o->data[o->length] = '\0';
  2854. }
  2855. static void o_addqblock(o_string *o, const char *str, int len)
  2856. {
  2857. while (len) {
  2858. char ch;
  2859. int sz;
  2860. int ordinary_cnt = strcspn(str, "*?[-\\" MAYBE_BRACES);
  2861. if (ordinary_cnt > len) /* paranoia */
  2862. ordinary_cnt = len;
  2863. o_addblock(o, str, ordinary_cnt);
  2864. if (ordinary_cnt == len)
  2865. return; /* NUL is already added by o_addblock */
  2866. str += ordinary_cnt;
  2867. len -= ordinary_cnt + 1; /* we are processing + 1 char below */
  2868. ch = *str++;
  2869. sz = 1;
  2870. if (ch) { /* it is necessarily one of "*?[-\\" MAYBE_BRACES */
  2871. sz++;
  2872. o->data[o->length] = '\\';
  2873. o->length++;
  2874. }
  2875. o_grow_by(o, sz);
  2876. o->data[o->length] = ch;
  2877. o->length++;
  2878. }
  2879. o->data[o->length] = '\0';
  2880. }
  2881. static void o_addQblock(o_string *o, const char *str, int len)
  2882. {
  2883. if (!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)) {
  2884. o_addblock(o, str, len);
  2885. return;
  2886. }
  2887. o_addqblock(o, str, len);
  2888. }
  2889. static void o_addQstr(o_string *o, const char *str)
  2890. {
  2891. o_addQblock(o, str, strlen(str));
  2892. }
  2893. /* A special kind of o_string for $VAR and `cmd` expansion.
  2894. * It contains char* list[] at the beginning, which is grown in 16 element
  2895. * increments. Actual string data starts at the next multiple of 16 * (char*).
  2896. * list[i] contains an INDEX (int!) into this string data.
  2897. * It means that if list[] needs to grow, data needs to be moved higher up
  2898. * but list[i]'s need not be modified.
  2899. * NB: remembering how many list[i]'s you have there is crucial.
  2900. * o_finalize_list() operation post-processes this structure - calculates
  2901. * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
  2902. */
  2903. #if DEBUG_EXPAND || DEBUG_GLOB
  2904. static void debug_print_list(const char *prefix, o_string *o, int n)
  2905. {
  2906. char **list = (char**)o->data;
  2907. int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
  2908. int i = 0;
  2909. indent();
  2910. fdprintf(2, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d glob:%d quoted:%d escape:%d\n",
  2911. prefix, list, n, string_start, o->length, o->maxlen,
  2912. !!(o->o_expflags & EXP_FLAG_GLOB),
  2913. o->has_quoted_part,
  2914. !!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
  2915. while (i < n) {
  2916. indent();
  2917. fdprintf(2, " list[%d]=%d '%s' %p\n", i, (int)(uintptr_t)list[i],
  2918. o->data + (int)(uintptr_t)list[i] + string_start,
  2919. o->data + (int)(uintptr_t)list[i] + string_start);
  2920. i++;
  2921. }
  2922. if (n) {
  2923. const char *p = o->data + (int)(uintptr_t)list[n - 1] + string_start;
  2924. indent();
  2925. fdprintf(2, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
  2926. }
  2927. }
  2928. #else
  2929. # define debug_print_list(prefix, o, n) ((void)0)
  2930. #endif
  2931. /* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
  2932. * in list[n] so that it points past last stored byte so far.
  2933. * It returns n+1. */
  2934. static int o_save_ptr_helper(o_string *o, int n)
  2935. {
  2936. char **list = (char**)o->data;
  2937. int string_start;
  2938. int string_len;
  2939. if (!o->has_empty_slot) {
  2940. string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
  2941. string_len = o->length - string_start;
  2942. if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
  2943. debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
  2944. /* list[n] points to string_start, make space for 16 more pointers */
  2945. o->maxlen += 0x10 * sizeof(list[0]);
  2946. o->data = xrealloc(o->data, o->maxlen + 1);
  2947. list = (char**)o->data;
  2948. memmove(list + n + 0x10, list + n, string_len);
  2949. /*
  2950. * expand_on_ifs() has a "previous argv[] ends in IFS?"
  2951. * check. (grep for -prev-ifs-check-).
  2952. * Ensure that argv[-1][last] is not garbage
  2953. * but zero bytes, to save index check there.
  2954. */
  2955. list[n + 0x10 - 1] = 0;
  2956. o->length += 0x10 * sizeof(list[0]);
  2957. } else {
  2958. debug_printf_list("list[%d]=%d string_start=%d\n",
  2959. n, string_len, string_start);
  2960. }
  2961. } else {
  2962. /* We have empty slot at list[n], reuse without growth */
  2963. string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
  2964. string_len = o->length - string_start;
  2965. debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
  2966. n, string_len, string_start);
  2967. o->has_empty_slot = 0;
  2968. }
  2969. o->has_quoted_part = 0;
  2970. list[n] = (char*)(uintptr_t)string_len;
  2971. return n + 1;
  2972. }
  2973. /* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
  2974. static int o_get_last_ptr(o_string *o, int n)
  2975. {
  2976. char **list = (char**)o->data;
  2977. int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
  2978. return ((int)(uintptr_t)list[n-1]) + string_start;
  2979. }
  2980. /*
  2981. * Globbing routines.
  2982. *
  2983. * Most words in commands need to be globbed, even ones which are
  2984. * (single or double) quoted. This stems from the possiblity of
  2985. * constructs like "abc"* and 'abc'* - these should be globbed.
  2986. * Having a different code path for fully-quoted strings ("abc",
  2987. * 'abc') would only help performance-wise, but we still need
  2988. * code for partially-quoted strings.
  2989. *
  2990. * Unfortunately, if we want to match bash and ash behavior in all cases,
  2991. * the logic can't be "shell-syntax argument is first transformed
  2992. * to a string, then globbed, and if globbing does not match anything,
  2993. * it is used verbatim". Here are two examples where it fails:
  2994. *
  2995. * echo 'b\*'?
  2996. *
  2997. * The globbing can't be avoided (because of '?' at the end).
  2998. * The glob pattern is: b\\\*? - IOW, both \ and * are literals
  2999. * and are glob-escaped. If this does not match, bash/ash print b\*?
  3000. * - IOW: they "unbackslash" the glob pattern.
  3001. * Now, look at this:
  3002. *
  3003. * v='\\\*'; echo b$v?
  3004. *
  3005. * The glob pattern is the same here: b\\\*? - the unquoted $v expansion
  3006. * should be used as glob pattern with no changes. However, if glob
  3007. * does not match, bash/ash print b\\\*? - NOT THE SAME as first example!
  3008. *
  3009. * ash implements this by having an encoded representation of the word
  3010. * to glob, which IS NOT THE SAME as the glob pattern - it has more data.
  3011. * Glob pattern is derived from it. If glob fails, the decision what result
  3012. * should be is made using that encoded representation. Not glob pattern.
  3013. */
  3014. #if ENABLE_HUSH_BRACE_EXPANSION
  3015. /* There in a GNU extension, GLOB_BRACE, but it is not usable:
  3016. * first, it processes even {a} (no commas), second,
  3017. * I didn't manage to make it return strings when they don't match
  3018. * existing files. Need to re-implement it.
  3019. */
  3020. /* Helper */
  3021. static int glob_needed(const char *s)
  3022. {
  3023. while (*s) {
  3024. if (*s == '\\') {
  3025. if (!s[1])
  3026. return 0;
  3027. s += 2;
  3028. continue;
  3029. }
  3030. if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
  3031. return 1;
  3032. s++;
  3033. }
  3034. return 0;
  3035. }
  3036. /* Return pointer to next closing brace or to comma */
  3037. static const char *next_brace_sub(const char *cp)
  3038. {
  3039. unsigned depth = 0;
  3040. cp++;
  3041. while (*cp != '\0') {
  3042. if (*cp == '\\') {
  3043. if (*++cp == '\0')
  3044. break;
  3045. cp++;
  3046. continue;
  3047. }
  3048. if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
  3049. break;
  3050. if (*cp++ == '{')
  3051. depth++;
  3052. }
  3053. return *cp != '\0' ? cp : NULL;
  3054. }
  3055. /* Recursive brace globber. Note: may garble pattern[]. */
  3056. static int glob_brace(char *pattern, o_string *o, int n)
  3057. {
  3058. char *new_pattern_buf;
  3059. const char *begin;
  3060. const char *next;
  3061. const char *rest;
  3062. const char *p;
  3063. size_t rest_len;
  3064. debug_printf_glob("glob_brace('%s')\n", pattern);
  3065. begin = pattern;
  3066. while (1) {
  3067. if (*begin == '\0')
  3068. goto simple_glob;
  3069. if (*begin == '{') {
  3070. /* Find the first sub-pattern and at the same time
  3071. * find the rest after the closing brace */
  3072. next = next_brace_sub(begin);
  3073. if (next == NULL) {
  3074. /* An illegal expression */
  3075. goto simple_glob;
  3076. }
  3077. if (*next == '}') {
  3078. /* "{abc}" with no commas - illegal
  3079. * brace expr, disregard and skip it */
  3080. begin = next + 1;
  3081. continue;
  3082. }
  3083. break;
  3084. }
  3085. if (*begin == '\\' && begin[1] != '\0')
  3086. begin++;
  3087. begin++;
  3088. }
  3089. debug_printf_glob("begin:%s\n", begin);
  3090. debug_printf_glob("next:%s\n", next);
  3091. /* Now find the end of the whole brace expression */
  3092. rest = next;
  3093. while (*rest != '}') {
  3094. rest = next_brace_sub(rest);
  3095. if (rest == NULL) {
  3096. /* An illegal expression */
  3097. goto simple_glob;
  3098. }
  3099. debug_printf_glob("rest:%s\n", rest);
  3100. }
  3101. rest_len = strlen(++rest) + 1;
  3102. /* We are sure the brace expression is well-formed */
  3103. /* Allocate working buffer large enough for our work */
  3104. new_pattern_buf = xmalloc(strlen(pattern));
  3105. /* We have a brace expression. BEGIN points to the opening {,
  3106. * NEXT points past the terminator of the first element, and REST
  3107. * points past the final }. We will accumulate result names from
  3108. * recursive runs for each brace alternative in the buffer using
  3109. * GLOB_APPEND. */
  3110. p = begin + 1;
  3111. while (1) {
  3112. /* Construct the new glob expression */
  3113. memcpy(
  3114. mempcpy(
  3115. mempcpy(new_pattern_buf,
  3116. /* We know the prefix for all sub-patterns */
  3117. pattern, begin - pattern),
  3118. p, next - p),
  3119. rest, rest_len);
  3120. /* Note: glob_brace() may garble new_pattern_buf[].
  3121. * That's why we re-copy prefix every time (1st memcpy above).
  3122. */
  3123. n = glob_brace(new_pattern_buf, o, n);
  3124. if (*next == '}') {
  3125. /* We saw the last entry */
  3126. break;
  3127. }
  3128. p = next + 1;
  3129. next = next_brace_sub(next);
  3130. }
  3131. free(new_pattern_buf);
  3132. return n;
  3133. simple_glob:
  3134. {
  3135. int gr;
  3136. glob_t globdata;
  3137. memset(&globdata, 0, sizeof(globdata));
  3138. gr = glob(pattern, 0, NULL, &globdata);
  3139. debug_printf_glob("glob('%s'):%d\n", pattern, gr);
  3140. if (gr != 0) {
  3141. if (gr == GLOB_NOMATCH) {
  3142. globfree(&globdata);
  3143. /* NB: garbles parameter */
  3144. unbackslash(pattern);
  3145. o_addstr_with_NUL(o, pattern);
  3146. debug_printf_glob("glob pattern '%s' is literal\n", pattern);
  3147. return o_save_ptr_helper(o, n);
  3148. }
  3149. if (gr == GLOB_NOSPACE)
  3150. bb_die_memory_exhausted();
  3151. /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
  3152. * but we didn't specify it. Paranoia again. */
  3153. bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
  3154. }
  3155. if (globdata.gl_pathv && globdata.gl_pathv[0]) {
  3156. char **argv = globdata.gl_pathv;
  3157. while (1) {
  3158. o_addstr_with_NUL(o, *argv);
  3159. n = o_save_ptr_helper(o, n);
  3160. argv++;
  3161. if (!*argv)
  3162. break;
  3163. }
  3164. }
  3165. globfree(&globdata);
  3166. }
  3167. return n;
  3168. }
  3169. /* Performs globbing on last list[],
  3170. * saving each result as a new list[].
  3171. */
  3172. static int perform_glob(o_string *o, int n)
  3173. {
  3174. char *pattern, *copy;
  3175. debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
  3176. if (!o->data)
  3177. return o_save_ptr_helper(o, n);
  3178. pattern = o->data + o_get_last_ptr(o, n);
  3179. debug_printf_glob("glob pattern '%s'\n", pattern);
  3180. if (!glob_needed(pattern)) {
  3181. /* unbackslash last string in o in place, fix length */
  3182. o->length = unbackslash(pattern) - o->data;
  3183. debug_printf_glob("glob pattern '%s' is literal\n", pattern);
  3184. return o_save_ptr_helper(o, n);
  3185. }
  3186. copy = xstrdup(pattern);
  3187. /* "forget" pattern in o */
  3188. o->length = pattern - o->data;
  3189. n = glob_brace(copy, o, n);
  3190. free(copy);
  3191. if (DEBUG_GLOB)
  3192. debug_print_list("perform_glob returning", o, n);
  3193. return n;
  3194. }
  3195. #else /* !HUSH_BRACE_EXPANSION */
  3196. /* Helper */
  3197. static int glob_needed(const char *s)
  3198. {
  3199. while (*s) {
  3200. if (*s == '\\') {
  3201. if (!s[1])
  3202. return 0;
  3203. s += 2;
  3204. continue;
  3205. }
  3206. if (*s == '*' || *s == '[' || *s == '?')
  3207. return 1;
  3208. s++;
  3209. }
  3210. return 0;
  3211. }
  3212. /* Performs globbing on last list[],
  3213. * saving each result as a new list[].
  3214. */
  3215. static int perform_glob(o_string *o, int n)
  3216. {
  3217. glob_t globdata;
  3218. int gr;
  3219. char *pattern;
  3220. debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
  3221. if (!o->data)
  3222. return o_save_ptr_helper(o, n);
  3223. pattern = o->data + o_get_last_ptr(o, n);
  3224. debug_printf_glob("glob pattern '%s'\n", pattern);
  3225. if (!glob_needed(pattern)) {
  3226. literal:
  3227. /* unbackslash last string in o in place, fix length */
  3228. o->length = unbackslash(pattern) - o->data;
  3229. debug_printf_glob("glob pattern '%s' is literal\n", pattern);
  3230. return o_save_ptr_helper(o, n);
  3231. }
  3232. memset(&globdata, 0, sizeof(globdata));
  3233. /* Can't use GLOB_NOCHECK: it does not unescape the string.
  3234. * If we glob "*.\*" and don't find anything, we need
  3235. * to fall back to using literal "*.*", but GLOB_NOCHECK
  3236. * will return "*.\*"!
  3237. */
  3238. gr = glob(pattern, 0, NULL, &globdata);
  3239. debug_printf_glob("glob('%s'):%d\n", pattern, gr);
  3240. if (gr != 0) {
  3241. if (gr == GLOB_NOMATCH) {
  3242. globfree(&globdata);
  3243. goto literal;
  3244. }
  3245. if (gr == GLOB_NOSPACE)
  3246. bb_die_memory_exhausted();
  3247. /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
  3248. * but we didn't specify it. Paranoia again. */
  3249. bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
  3250. }
  3251. if (globdata.gl_pathv && globdata.gl_pathv[0]) {
  3252. char **argv = globdata.gl_pathv;
  3253. /* "forget" pattern in o */
  3254. o->length = pattern - o->data;
  3255. while (1) {
  3256. o_addstr_with_NUL(o, *argv);
  3257. n = o_save_ptr_helper(o, n);
  3258. argv++;
  3259. if (!*argv)
  3260. break;
  3261. }
  3262. }
  3263. globfree(&globdata);
  3264. if (DEBUG_GLOB)
  3265. debug_print_list("perform_glob returning", o, n);
  3266. return n;
  3267. }
  3268. #endif /* !HUSH_BRACE_EXPANSION */
  3269. /* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered.
  3270. * Otherwise, just finish current list[] and start new */
  3271. static int o_save_ptr(o_string *o, int n)
  3272. {
  3273. if (o->o_expflags & EXP_FLAG_GLOB) {
  3274. /* If o->has_empty_slot, list[n] was already globbed
  3275. * (if it was requested back then when it was filled)
  3276. * so don't do that again! */
  3277. if (!o->has_empty_slot)
  3278. return perform_glob(o, n); /* o_save_ptr_helper is inside */
  3279. }
  3280. return o_save_ptr_helper(o, n);
  3281. }
  3282. /* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
  3283. static char **o_finalize_list(o_string *o, int n)
  3284. {
  3285. char **list;
  3286. int string_start;
  3287. if (DEBUG_EXPAND)
  3288. debug_print_list("finalized", o, n);
  3289. debug_printf_expand("finalized n:%d\n", n);
  3290. list = (char**)o->data;
  3291. string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
  3292. list[--n] = NULL;
  3293. while (n) {
  3294. n--;
  3295. list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
  3296. }
  3297. return list;
  3298. }
  3299. static void free_pipe_list(struct pipe *pi);
  3300. /* Returns pi->next - next pipe in the list */
  3301. static struct pipe *free_pipe(struct pipe *pi)
  3302. {
  3303. struct pipe *next;
  3304. int i;
  3305. debug_printf_clean("free_pipe (pid %d)\n", getpid());
  3306. for (i = 0; i < pi->num_cmds; i++) {
  3307. struct command *command;
  3308. struct redir_struct *r, *rnext;
  3309. command = &pi->cmds[i];
  3310. debug_printf_clean(" command %d:\n", i);
  3311. if (command->argv) {
  3312. if (DEBUG_CLEAN) {
  3313. int a;
  3314. char **p;
  3315. for (a = 0, p = command->argv; *p; a++, p++) {
  3316. debug_printf_clean(" argv[%d] = %s\n", a, *p);
  3317. }
  3318. }
  3319. free_strings(command->argv);
  3320. //command->argv = NULL;
  3321. }
  3322. /* not "else if": on syntax error, we may have both! */
  3323. if (command->group) {
  3324. debug_printf_clean(" begin group (cmd_type:%d)\n",
  3325. command->cmd_type);
  3326. free_pipe_list(command->group);
  3327. debug_printf_clean(" end group\n");
  3328. //command->group = NULL;
  3329. }
  3330. /* else is crucial here.
  3331. * If group != NULL, child_func is meaningless */
  3332. #if ENABLE_HUSH_FUNCTIONS
  3333. else if (command->child_func) {
  3334. debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
  3335. command->child_func->parent_cmd = NULL;
  3336. }
  3337. #endif
  3338. #if !BB_MMU
  3339. free(command->group_as_string);
  3340. //command->group_as_string = NULL;
  3341. #endif
  3342. for (r = command->redirects; r; r = rnext) {
  3343. debug_printf_clean(" redirect %d%s",
  3344. r->rd_fd, redir_table[r->rd_type].descrip);
  3345. /* guard against the case >$FOO, where foo is unset or blank */
  3346. if (r->rd_filename) {
  3347. debug_printf_clean(" fname:'%s'\n", r->rd_filename);
  3348. free(r->rd_filename);
  3349. //r->rd_filename = NULL;
  3350. }
  3351. debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
  3352. rnext = r->next;
  3353. free(r);
  3354. }
  3355. //command->redirects = NULL;
  3356. }
  3357. free(pi->cmds); /* children are an array, they get freed all at once */
  3358. //pi->cmds = NULL;
  3359. #if ENABLE_HUSH_JOB
  3360. free(pi->cmdtext);
  3361. //pi->cmdtext = NULL;
  3362. #endif
  3363. next = pi->next;
  3364. free(pi);
  3365. return next;
  3366. }
  3367. static void free_pipe_list(struct pipe *pi)
  3368. {
  3369. while (pi) {
  3370. #if HAS_KEYWORDS
  3371. debug_printf_clean("pipe reserved word %d\n", pi->res_word);
  3372. #endif
  3373. debug_printf_clean("pipe followup code %d\n", pi->followup);
  3374. pi = free_pipe(pi);
  3375. }
  3376. }
  3377. /*** Parsing routines ***/
  3378. #ifndef debug_print_tree
  3379. static void debug_print_tree(struct pipe *pi, int lvl)
  3380. {
  3381. static const char *const PIPE[] = {
  3382. [PIPE_SEQ] = "SEQ",
  3383. [PIPE_AND] = "AND",
  3384. [PIPE_OR ] = "OR" ,
  3385. [PIPE_BG ] = "BG" ,
  3386. };
  3387. static const char *RES[] = {
  3388. [RES_NONE ] = "NONE" ,
  3389. # if ENABLE_HUSH_IF
  3390. [RES_IF ] = "IF" ,
  3391. [RES_THEN ] = "THEN" ,
  3392. [RES_ELIF ] = "ELIF" ,
  3393. [RES_ELSE ] = "ELSE" ,
  3394. [RES_FI ] = "FI" ,
  3395. # endif
  3396. # if ENABLE_HUSH_LOOPS
  3397. [RES_FOR ] = "FOR" ,
  3398. [RES_WHILE] = "WHILE",
  3399. [RES_UNTIL] = "UNTIL",
  3400. [RES_DO ] = "DO" ,
  3401. [RES_DONE ] = "DONE" ,
  3402. # endif
  3403. # if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
  3404. [RES_IN ] = "IN" ,
  3405. # endif
  3406. # if ENABLE_HUSH_CASE
  3407. [RES_CASE ] = "CASE" ,
  3408. [RES_CASE_IN ] = "CASE_IN" ,
  3409. [RES_MATCH] = "MATCH",
  3410. [RES_CASE_BODY] = "CASE_BODY",
  3411. [RES_ESAC ] = "ESAC" ,
  3412. # endif
  3413. [RES_XXXX ] = "XXXX" ,
  3414. [RES_SNTX ] = "SNTX" ,
  3415. };
  3416. static const char *const CMDTYPE[] = {
  3417. "{}",
  3418. "()",
  3419. "[noglob]",
  3420. # if ENABLE_HUSH_FUNCTIONS
  3421. "func()",
  3422. # endif
  3423. };
  3424. int pin, prn;
  3425. pin = 0;
  3426. while (pi) {
  3427. fdprintf(2, "%*spipe %d %sres_word=%s followup=%d %s\n",
  3428. lvl*2, "",
  3429. pin,
  3430. (IF_HAS_KEYWORDS(pi->pi_inverted ? "! " :) ""),
  3431. RES[pi->res_word],
  3432. pi->followup, PIPE[pi->followup]
  3433. );
  3434. prn = 0;
  3435. while (prn < pi->num_cmds) {
  3436. struct command *command = &pi->cmds[prn];
  3437. char **argv = command->argv;
  3438. fdprintf(2, "%*s cmd %d assignment_cnt:%d",
  3439. lvl*2, "", prn,
  3440. command->assignment_cnt);
  3441. # if ENABLE_HUSH_LINENO_VAR
  3442. fdprintf(2, " LINENO:%u", command->lineno);
  3443. # endif
  3444. if (command->group) {
  3445. fdprintf(2, " group %s: (argv=%p)%s%s\n",
  3446. CMDTYPE[command->cmd_type],
  3447. argv
  3448. # if !BB_MMU
  3449. , " group_as_string:", command->group_as_string
  3450. # else
  3451. , "", ""
  3452. # endif
  3453. );
  3454. debug_print_tree(command->group, lvl+1);
  3455. prn++;
  3456. continue;
  3457. }
  3458. if (argv) while (*argv) {
  3459. fdprintf(2, " '%s'", *argv);
  3460. argv++;
  3461. }
  3462. if (command->redirects)
  3463. fdprintf(2, " {redir}");
  3464. fdprintf(2, "\n");
  3465. prn++;
  3466. }
  3467. pi = pi->next;
  3468. pin++;
  3469. }
  3470. }
  3471. #endif /* debug_print_tree */
  3472. static struct pipe *new_pipe(void)
  3473. {
  3474. struct pipe *pi;
  3475. pi = xzalloc(sizeof(struct pipe));
  3476. /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
  3477. return pi;
  3478. }
  3479. /* Command (member of a pipe) is complete, or we start a new pipe
  3480. * if ctx->command is NULL.
  3481. * No errors possible here.
  3482. */
  3483. static int done_command(struct parse_context *ctx)
  3484. {
  3485. /* The command is really already in the pipe structure, so
  3486. * advance the pipe counter and make a new, null command. */
  3487. struct pipe *pi = ctx->pipe;
  3488. struct command *command = ctx->command;
  3489. #if 0 /* Instead we emit error message at run time */
  3490. if (ctx->pending_redirect) {
  3491. /* For example, "cmd >" (no filename to redirect to) */
  3492. syntax_error("invalid redirect");
  3493. ctx->pending_redirect = NULL;
  3494. }
  3495. #endif
  3496. if (command) {
  3497. if (IS_NULL_CMD(command)) {
  3498. debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
  3499. goto clear_and_ret;
  3500. }
  3501. pi->num_cmds++;
  3502. debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
  3503. //debug_print_tree(ctx->list_head, 20);
  3504. } else {
  3505. debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
  3506. }
  3507. /* Only real trickiness here is that the uncommitted
  3508. * command structure is not counted in pi->num_cmds. */
  3509. pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
  3510. ctx->command = command = &pi->cmds[pi->num_cmds];
  3511. clear_and_ret:
  3512. memset(command, 0, sizeof(*command));
  3513. #if ENABLE_HUSH_LINENO_VAR
  3514. command->lineno = G.parse_lineno;
  3515. debug_printf_parse("command->lineno = G.parse_lineno (%u)\n", G.parse_lineno);
  3516. #endif
  3517. return pi->num_cmds; /* used only for 0/nonzero check */
  3518. }
  3519. static void done_pipe(struct parse_context *ctx, pipe_style type)
  3520. {
  3521. int not_null;
  3522. debug_printf_parse("done_pipe entered, followup %d\n", type);
  3523. /* Close previous command */
  3524. not_null = done_command(ctx);
  3525. #if HAS_KEYWORDS
  3526. ctx->pipe->pi_inverted = ctx->ctx_inverted;
  3527. ctx->ctx_inverted = 0;
  3528. ctx->pipe->res_word = ctx->ctx_res_w;
  3529. #endif
  3530. if (type == PIPE_BG && ctx->list_head != ctx->pipe) {
  3531. /* Necessary since && and || have precedence over &:
  3532. * "cmd1 && cmd2 &" must spawn both cmds, not only cmd2,
  3533. * in a backgrounded subshell.
  3534. */
  3535. struct pipe *pi;
  3536. struct command *command;
  3537. /* Is this actually this construct, all pipes end with && or ||? */
  3538. pi = ctx->list_head;
  3539. while (pi != ctx->pipe) {
  3540. if (pi->followup != PIPE_AND && pi->followup != PIPE_OR)
  3541. goto no_conv;
  3542. pi = pi->next;
  3543. }
  3544. debug_printf_parse("BG with more than one pipe, converting to { p1 &&...pN; } &\n");
  3545. pi->followup = PIPE_SEQ; /* close pN _not_ with "&"! */
  3546. pi = xzalloc(sizeof(*pi));
  3547. pi->followup = PIPE_BG;
  3548. pi->num_cmds = 1;
  3549. pi->cmds = xzalloc(sizeof(pi->cmds[0]));
  3550. command = &pi->cmds[0];
  3551. if (CMD_NORMAL != 0) /* "if xzalloc didn't do that already" */
  3552. command->cmd_type = CMD_NORMAL;
  3553. command->group = ctx->list_head;
  3554. #if !BB_MMU
  3555. command->group_as_string = xstrndup(
  3556. ctx->as_string.data,
  3557. ctx->as_string.length - 1 /* do not copy last char, "&" */
  3558. );
  3559. #endif
  3560. /* Replace all pipes in ctx with one newly created */
  3561. ctx->list_head = ctx->pipe = pi;
  3562. } else {
  3563. no_conv:
  3564. ctx->pipe->followup = type;
  3565. }
  3566. /* Without this check, even just <enter> on command line generates
  3567. * tree of three NOPs (!). Which is harmless but annoying.
  3568. * IOW: it is safe to do it unconditionally. */
  3569. if (not_null
  3570. #if ENABLE_HUSH_IF
  3571. || ctx->ctx_res_w == RES_FI
  3572. #endif
  3573. #if ENABLE_HUSH_LOOPS
  3574. || ctx->ctx_res_w == RES_DONE
  3575. || ctx->ctx_res_w == RES_FOR
  3576. || ctx->ctx_res_w == RES_IN
  3577. #endif
  3578. #if ENABLE_HUSH_CASE
  3579. || ctx->ctx_res_w == RES_ESAC
  3580. #endif
  3581. ) {
  3582. struct pipe *new_p;
  3583. debug_printf_parse("done_pipe: adding new pipe: "
  3584. "not_null:%d ctx->ctx_res_w:%d\n",
  3585. not_null, ctx->ctx_res_w);
  3586. new_p = new_pipe();
  3587. ctx->pipe->next = new_p;
  3588. ctx->pipe = new_p;
  3589. /* RES_THEN, RES_DO etc are "sticky" -
  3590. * they remain set for pipes inside if/while.
  3591. * This is used to control execution.
  3592. * RES_FOR and RES_IN are NOT sticky (needed to support
  3593. * cases where variable or value happens to match a keyword):
  3594. */
  3595. #if ENABLE_HUSH_LOOPS
  3596. if (ctx->ctx_res_w == RES_FOR
  3597. || ctx->ctx_res_w == RES_IN)
  3598. ctx->ctx_res_w = RES_NONE;
  3599. #endif
  3600. #if ENABLE_HUSH_CASE
  3601. if (ctx->ctx_res_w == RES_MATCH)
  3602. ctx->ctx_res_w = RES_CASE_BODY;
  3603. if (ctx->ctx_res_w == RES_CASE)
  3604. ctx->ctx_res_w = RES_CASE_IN;
  3605. #endif
  3606. ctx->command = NULL; /* trick done_command below */
  3607. /* Create the memory for command, roughly:
  3608. * ctx->pipe->cmds = new struct command;
  3609. * ctx->command = &ctx->pipe->cmds[0];
  3610. */
  3611. done_command(ctx);
  3612. //debug_print_tree(ctx->list_head, 10);
  3613. }
  3614. debug_printf_parse("done_pipe return\n");
  3615. }
  3616. static void initialize_context(struct parse_context *ctx)
  3617. {
  3618. memset(ctx, 0, sizeof(*ctx));
  3619. if (MAYBE_ASSIGNMENT != 0)
  3620. ctx->is_assignment = MAYBE_ASSIGNMENT;
  3621. ctx->pipe = ctx->list_head = new_pipe();
  3622. /* Create the memory for command, roughly:
  3623. * ctx->pipe->cmds = new struct command;
  3624. * ctx->command = &ctx->pipe->cmds[0];
  3625. */
  3626. done_command(ctx);
  3627. }
  3628. /* If a reserved word is found and processed, parse context is modified
  3629. * and 1 is returned.
  3630. */
  3631. #if HAS_KEYWORDS
  3632. struct reserved_combo {
  3633. char literal[6];
  3634. unsigned char res;
  3635. unsigned char assignment_flag;
  3636. uint32_t flag;
  3637. };
  3638. enum {
  3639. FLAG_END = (1 << RES_NONE ),
  3640. # if ENABLE_HUSH_IF
  3641. FLAG_IF = (1 << RES_IF ),
  3642. FLAG_THEN = (1 << RES_THEN ),
  3643. FLAG_ELIF = (1 << RES_ELIF ),
  3644. FLAG_ELSE = (1 << RES_ELSE ),
  3645. FLAG_FI = (1 << RES_FI ),
  3646. # endif
  3647. # if ENABLE_HUSH_LOOPS
  3648. FLAG_FOR = (1 << RES_FOR ),
  3649. FLAG_WHILE = (1 << RES_WHILE),
  3650. FLAG_UNTIL = (1 << RES_UNTIL),
  3651. FLAG_DO = (1 << RES_DO ),
  3652. FLAG_DONE = (1 << RES_DONE ),
  3653. FLAG_IN = (1 << RES_IN ),
  3654. # endif
  3655. # if ENABLE_HUSH_CASE
  3656. FLAG_MATCH = (1 << RES_MATCH),
  3657. FLAG_ESAC = (1 << RES_ESAC ),
  3658. # endif
  3659. FLAG_START = (1 << RES_XXXX ),
  3660. };
  3661. static const struct reserved_combo* match_reserved_word(o_string *word)
  3662. {
  3663. /* Mostly a list of accepted follow-up reserved words.
  3664. * FLAG_END means we are done with the sequence, and are ready
  3665. * to turn the compound list into a command.
  3666. * FLAG_START means the word must start a new compound list.
  3667. */
  3668. static const struct reserved_combo reserved_list[] ALIGN4 = {
  3669. # if ENABLE_HUSH_IF
  3670. { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
  3671. { "if", RES_IF, MAYBE_ASSIGNMENT, FLAG_THEN | FLAG_START },
  3672. { "then", RES_THEN, MAYBE_ASSIGNMENT, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
  3673. { "elif", RES_ELIF, MAYBE_ASSIGNMENT, FLAG_THEN },
  3674. { "else", RES_ELSE, MAYBE_ASSIGNMENT, FLAG_FI },
  3675. { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
  3676. # endif
  3677. # if ENABLE_HUSH_LOOPS
  3678. { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
  3679. { "while", RES_WHILE, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
  3680. { "until", RES_UNTIL, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
  3681. { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
  3682. { "do", RES_DO, MAYBE_ASSIGNMENT, FLAG_DONE },
  3683. { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
  3684. # endif
  3685. # if ENABLE_HUSH_CASE
  3686. { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
  3687. { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
  3688. # endif
  3689. };
  3690. const struct reserved_combo *r;
  3691. for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
  3692. if (strcmp(word->data, r->literal) == 0)
  3693. return r;
  3694. }
  3695. return NULL;
  3696. }
  3697. /* Return NULL: not a keyword, else: keyword
  3698. */
  3699. static const struct reserved_combo* reserved_word(struct parse_context *ctx)
  3700. {
  3701. # if ENABLE_HUSH_CASE
  3702. static const struct reserved_combo reserved_match = {
  3703. "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
  3704. };
  3705. # endif
  3706. const struct reserved_combo *r;
  3707. if (ctx->word.has_quoted_part)
  3708. return 0;
  3709. r = match_reserved_word(&ctx->word);
  3710. if (!r)
  3711. return r; /* NULL */
  3712. debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
  3713. # if ENABLE_HUSH_CASE
  3714. if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
  3715. /* "case word IN ..." - IN part starts first MATCH part */
  3716. r = &reserved_match;
  3717. } else
  3718. # endif
  3719. if (r->flag == 0) { /* '!' */
  3720. if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
  3721. syntax_error("! ! command");
  3722. ctx->ctx_res_w = RES_SNTX;
  3723. }
  3724. ctx->ctx_inverted = 1;
  3725. return r;
  3726. }
  3727. if (r->flag & FLAG_START) {
  3728. struct parse_context *old;
  3729. old = xmemdup(ctx, sizeof(*ctx));
  3730. debug_printf_parse("push stack %p\n", old);
  3731. initialize_context(ctx);
  3732. ctx->stack = old;
  3733. } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
  3734. syntax_error_at(ctx->word.data);
  3735. ctx->ctx_res_w = RES_SNTX;
  3736. return r;
  3737. } else {
  3738. /* "{...} fi" is ok. "{...} if" is not
  3739. * Example:
  3740. * if { echo foo; } then { echo bar; } fi */
  3741. if (ctx->command->group)
  3742. done_pipe(ctx, PIPE_SEQ);
  3743. }
  3744. ctx->ctx_res_w = r->res;
  3745. ctx->old_flag = r->flag;
  3746. ctx->is_assignment = r->assignment_flag;
  3747. debug_printf_parse("ctx->is_assignment='%s'\n", assignment_flag[ctx->is_assignment]);
  3748. if (ctx->old_flag & FLAG_END) {
  3749. struct parse_context *old;
  3750. done_pipe(ctx, PIPE_SEQ);
  3751. debug_printf_parse("pop stack %p\n", ctx->stack);
  3752. old = ctx->stack;
  3753. old->command->group = ctx->list_head;
  3754. old->command->cmd_type = CMD_NORMAL;
  3755. # if !BB_MMU
  3756. /* At this point, the compound command's string is in
  3757. * ctx->as_string... except for the leading keyword!
  3758. * Consider this example: "echo a | if true; then echo a; fi"
  3759. * ctx->as_string will contain "true; then echo a; fi",
  3760. * with "if " remaining in old->as_string!
  3761. */
  3762. {
  3763. char *str;
  3764. int len = old->as_string.length;
  3765. /* Concatenate halves */
  3766. o_addstr(&old->as_string, ctx->as_string.data);
  3767. o_free(&ctx->as_string);
  3768. /* Find where leading keyword starts in first half */
  3769. str = old->as_string.data + len;
  3770. if (str > old->as_string.data)
  3771. str--; /* skip whitespace after keyword */
  3772. while (str > old->as_string.data && isalpha(str[-1]))
  3773. str--;
  3774. /* Ugh, we're done with this horrid hack */
  3775. old->command->group_as_string = xstrdup(str);
  3776. debug_printf_parse("pop, remembering as:'%s'\n",
  3777. old->command->group_as_string);
  3778. }
  3779. # endif
  3780. *ctx = *old; /* physical copy */
  3781. free(old);
  3782. }
  3783. return r;
  3784. }
  3785. #endif /* HAS_KEYWORDS */
  3786. /* Word is complete, look at it and update parsing context.
  3787. * Normal return is 0. Syntax errors return 1.
  3788. * Note: on return, word is reset, but not o_free'd!
  3789. */
  3790. static int done_word(struct parse_context *ctx)
  3791. {
  3792. struct command *command = ctx->command;
  3793. debug_printf_parse("done_word entered: '%s' %p\n", ctx->word.data, command);
  3794. if (ctx->word.length == 0 && !ctx->word.has_quoted_part) {
  3795. debug_printf_parse("done_word return 0: true null, ignored\n");
  3796. return 0;
  3797. }
  3798. if (ctx->pending_redirect) {
  3799. /* We do not glob in e.g. >*.tmp case. bash seems to glob here
  3800. * only if run as "bash", not "sh" */
  3801. /* http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
  3802. * "2.7 Redirection
  3803. * If the redirection operator is "<<" or "<<-", the word
  3804. * that follows the redirection operator shall be
  3805. * subjected to quote removal; it is unspecified whether
  3806. * any of the other expansions occur. For the other
  3807. * redirection operators, the word that follows the
  3808. * redirection operator shall be subjected to tilde
  3809. * expansion, parameter expansion, command substitution,
  3810. * arithmetic expansion, and quote removal.
  3811. * Pathname expansion shall not be performed
  3812. * on the word by a non-interactive shell; an interactive
  3813. * shell may perform it, but shall do so only when
  3814. * the expansion would result in one word."
  3815. */
  3816. //bash does not do parameter/command substitution or arithmetic expansion
  3817. //for _heredoc_ redirection word: these constructs look for exact eof marker
  3818. // as written:
  3819. // <<EOF$t
  3820. // <<EOF$((1))
  3821. // <<EOF`true` [this case also makes heredoc "quoted", a-la <<"EOF". Probably bash-4.3.43 bug]
  3822. ctx->pending_redirect->rd_filename = xstrdup(ctx->word.data);
  3823. /* Cater for >\file case:
  3824. * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
  3825. * Same with heredocs:
  3826. * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
  3827. */
  3828. if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
  3829. unbackslash(ctx->pending_redirect->rd_filename);
  3830. /* Is it <<"HEREDOC"? */
  3831. if (ctx->word.has_quoted_part) {
  3832. ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
  3833. }
  3834. }
  3835. debug_printf_parse("word stored in rd_filename: '%s'\n", ctx->word.data);
  3836. ctx->pending_redirect = NULL;
  3837. } else {
  3838. #if HAS_KEYWORDS
  3839. # if ENABLE_HUSH_CASE
  3840. if (ctx->ctx_dsemicolon
  3841. && strcmp(ctx->word.data, "esac") != 0 /* not "... pattern) cmd;; esac" */
  3842. ) {
  3843. /* already done when ctx_dsemicolon was set to 1: */
  3844. /* ctx->ctx_res_w = RES_MATCH; */
  3845. ctx->ctx_dsemicolon = 0;
  3846. } else
  3847. # endif
  3848. # if defined(CMD_TEST2_SINGLEWORD_NOGLOB)
  3849. if (command->cmd_type == CMD_TEST2_SINGLEWORD_NOGLOB
  3850. && strcmp(ctx->word.data, "]]") == 0
  3851. ) {
  3852. /* allow "[[ ]] >file" etc */
  3853. command->cmd_type = CMD_SINGLEWORD_NOGLOB;
  3854. } else
  3855. # endif
  3856. if (!command->argv /* if it's the first word... */
  3857. # if ENABLE_HUSH_LOOPS
  3858. && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
  3859. && ctx->ctx_res_w != RES_IN
  3860. # endif
  3861. # if ENABLE_HUSH_CASE
  3862. && ctx->ctx_res_w != RES_CASE
  3863. # endif
  3864. ) {
  3865. const struct reserved_combo *reserved;
  3866. reserved = reserved_word(ctx);
  3867. debug_printf_parse("checking for reserved-ness: %d\n", !!reserved);
  3868. if (reserved) {
  3869. # if ENABLE_HUSH_LINENO_VAR
  3870. /* Case:
  3871. * "while ...; do
  3872. * cmd ..."
  3873. * If we don't close the pipe _now_, immediately after "do", lineno logic
  3874. * sees "cmd" as starting at "do" - i.e., at the previous line.
  3875. */
  3876. if (0
  3877. IF_HUSH_IF(|| reserved->res == RES_THEN)
  3878. IF_HUSH_IF(|| reserved->res == RES_ELIF)
  3879. IF_HUSH_IF(|| reserved->res == RES_ELSE)
  3880. IF_HUSH_LOOPS(|| reserved->res == RES_DO)
  3881. ) {
  3882. done_pipe(ctx, PIPE_SEQ);
  3883. }
  3884. # endif
  3885. o_reset_to_empty_unquoted(&ctx->word);
  3886. debug_printf_parse("done_word return %d\n",
  3887. (ctx->ctx_res_w == RES_SNTX));
  3888. return (ctx->ctx_res_w == RES_SNTX);
  3889. }
  3890. # if defined(CMD_TEST2_SINGLEWORD_NOGLOB)
  3891. if (strcmp(ctx->word.data, "[[") == 0) {
  3892. command->cmd_type = CMD_TEST2_SINGLEWORD_NOGLOB;
  3893. } else
  3894. # endif
  3895. # if defined(CMD_SINGLEWORD_NOGLOB)
  3896. if (0
  3897. /* In bash, local/export/readonly are special, args
  3898. * are assignments and therefore expansion of them
  3899. * should be "one-word" expansion:
  3900. * $ export i=`echo 'a b'` # one arg: "i=a b"
  3901. * compare with:
  3902. * $ ls i=`echo 'a b'` # two args: "i=a" and "b"
  3903. * ls: cannot access i=a: No such file or directory
  3904. * ls: cannot access b: No such file or directory
  3905. * Note: bash 3.2.33(1) does this only if export word
  3906. * itself is not quoted:
  3907. * $ export i=`echo 'aaa bbb'`; echo "$i"
  3908. * aaa bbb
  3909. * $ "export" i=`echo 'aaa bbb'`; echo "$i"
  3910. * aaa
  3911. */
  3912. IF_HUSH_LOCAL( || strcmp(ctx->word.data, "local") == 0)
  3913. IF_HUSH_EXPORT( || strcmp(ctx->word.data, "export") == 0)
  3914. IF_HUSH_READONLY(|| strcmp(ctx->word.data, "readonly") == 0)
  3915. ) {
  3916. command->cmd_type = CMD_SINGLEWORD_NOGLOB;
  3917. }
  3918. # else
  3919. { /* empty block to pair "if ... else" */ }
  3920. # endif
  3921. }
  3922. #endif /* HAS_KEYWORDS */
  3923. if (command->group) {
  3924. /* "{ echo foo; } echo bar" - bad */
  3925. syntax_error_at(ctx->word.data);
  3926. debug_printf_parse("done_word return 1: syntax error, "
  3927. "groups and arglists don't mix\n");
  3928. return 1;
  3929. }
  3930. /* If this word wasn't an assignment, next ones definitely
  3931. * can't be assignments. Even if they look like ones. */
  3932. if (ctx->is_assignment != DEFINITELY_ASSIGNMENT
  3933. && ctx->is_assignment != WORD_IS_KEYWORD
  3934. ) {
  3935. ctx->is_assignment = NOT_ASSIGNMENT;
  3936. } else {
  3937. if (ctx->is_assignment == DEFINITELY_ASSIGNMENT) {
  3938. command->assignment_cnt++;
  3939. debug_printf_parse("++assignment_cnt=%d\n", command->assignment_cnt);
  3940. }
  3941. debug_printf_parse("ctx->is_assignment was:'%s'\n", assignment_flag[ctx->is_assignment]);
  3942. ctx->is_assignment = MAYBE_ASSIGNMENT;
  3943. }
  3944. debug_printf_parse("ctx->is_assignment='%s'\n", assignment_flag[ctx->is_assignment]);
  3945. command->argv = add_string_to_strings(command->argv, xstrdup(ctx->word.data));
  3946. debug_print_strings("word appended to argv", command->argv);
  3947. }
  3948. #if ENABLE_HUSH_LOOPS
  3949. if (ctx->ctx_res_w == RES_FOR) {
  3950. if (ctx->word.has_quoted_part
  3951. || endofname(command->argv[0])[0] != '\0'
  3952. ) {
  3953. /* bash says just "not a valid identifier" */
  3954. syntax_error("not a valid identifier in for");
  3955. return 1;
  3956. }
  3957. /* Force FOR to have just one word (variable name) */
  3958. /* NB: basically, this makes hush see "for v in ..."
  3959. * syntax as if it is "for v; in ...". FOR and IN become
  3960. * two pipe structs in parse tree. */
  3961. done_pipe(ctx, PIPE_SEQ);
  3962. }
  3963. #endif
  3964. #if ENABLE_HUSH_CASE
  3965. /* Force CASE to have just one word */
  3966. if (ctx->ctx_res_w == RES_CASE) {
  3967. done_pipe(ctx, PIPE_SEQ);
  3968. }
  3969. #endif
  3970. o_reset_to_empty_unquoted(&ctx->word);
  3971. debug_printf_parse("done_word return 0\n");
  3972. return 0;
  3973. }
  3974. /* Peek ahead in the input to find out if we have a "&n" construct,
  3975. * as in "2>&1", that represents duplicating a file descriptor.
  3976. * Return:
  3977. * REDIRFD_CLOSE if >&- "close fd" construct is seen,
  3978. * REDIRFD_SYNTAX_ERR if syntax error,
  3979. * REDIRFD_TO_FILE if no & was seen,
  3980. * or the number found.
  3981. */
  3982. #if BB_MMU
  3983. #define parse_redir_right_fd(as_string, input) \
  3984. parse_redir_right_fd(input)
  3985. #endif
  3986. static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
  3987. {
  3988. int ch, d, ok;
  3989. ch = i_peek(input);
  3990. if (ch != '&')
  3991. return REDIRFD_TO_FILE;
  3992. ch = i_getch(input); /* get the & */
  3993. nommu_addchr(as_string, ch);
  3994. ch = i_peek(input);
  3995. if (ch == '-') {
  3996. ch = i_getch(input);
  3997. nommu_addchr(as_string, ch);
  3998. return REDIRFD_CLOSE;
  3999. }
  4000. d = 0;
  4001. ok = 0;
  4002. while (ch != EOF && isdigit(ch)) {
  4003. d = d*10 + (ch-'0');
  4004. ok = 1;
  4005. ch = i_getch(input);
  4006. nommu_addchr(as_string, ch);
  4007. ch = i_peek(input);
  4008. }
  4009. if (ok) return d;
  4010. //TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
  4011. bb_simple_error_msg("ambiguous redirect");
  4012. return REDIRFD_SYNTAX_ERR;
  4013. }
  4014. /* Return code is 0 normal, 1 if a syntax error is detected
  4015. */
  4016. static int parse_redirect(struct parse_context *ctx,
  4017. int fd,
  4018. redir_type style,
  4019. struct in_str *input)
  4020. {
  4021. struct command *command = ctx->command;
  4022. struct redir_struct *redir;
  4023. struct redir_struct **redirp;
  4024. int dup_num;
  4025. dup_num = REDIRFD_TO_FILE;
  4026. if (style != REDIRECT_HEREDOC) {
  4027. /* Check for a '>&1' type redirect */
  4028. dup_num = parse_redir_right_fd(&ctx->as_string, input);
  4029. if (dup_num == REDIRFD_SYNTAX_ERR)
  4030. return 1;
  4031. } else {
  4032. int ch = i_peek_and_eat_bkslash_nl(input);
  4033. dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
  4034. if (dup_num) { /* <<-... */
  4035. ch = i_getch(input);
  4036. nommu_addchr(&ctx->as_string, ch);
  4037. ch = i_peek(input);
  4038. }
  4039. }
  4040. if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
  4041. int ch = i_peek_and_eat_bkslash_nl(input);
  4042. if (ch == '|') {
  4043. /* >|FILE redirect ("clobbering" >).
  4044. * Since we do not support "set -o noclobber" yet,
  4045. * >| and > are the same for now. Just eat |.
  4046. */
  4047. ch = i_getch(input);
  4048. nommu_addchr(&ctx->as_string, ch);
  4049. }
  4050. }
  4051. /* Create a new redir_struct and append it to the linked list */
  4052. redirp = &command->redirects;
  4053. while ((redir = *redirp) != NULL) {
  4054. redirp = &(redir->next);
  4055. }
  4056. *redirp = redir = xzalloc(sizeof(*redir));
  4057. /* redir->next = NULL; */
  4058. /* redir->rd_filename = NULL; */
  4059. redir->rd_type = style;
  4060. redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
  4061. debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
  4062. redir_table[style].descrip);
  4063. redir->rd_dup = dup_num;
  4064. if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
  4065. /* Erik had a check here that the file descriptor in question
  4066. * is legit; I postpone that to "run time"
  4067. * A "-" representation of "close me" shows up as a -3 here */
  4068. debug_printf_parse("duplicating redirect '%d>&%d'\n",
  4069. redir->rd_fd, redir->rd_dup);
  4070. } else {
  4071. #if 0 /* Instead we emit error message at run time */
  4072. if (ctx->pending_redirect) {
  4073. /* For example, "cmd > <file" */
  4074. syntax_error("invalid redirect");
  4075. }
  4076. #endif
  4077. /* Set ctx->pending_redirect, so we know what to do at the
  4078. * end of the next parsed word. */
  4079. ctx->pending_redirect = redir;
  4080. }
  4081. return 0;
  4082. }
  4083. /* If a redirect is immediately preceded by a number, that number is
  4084. * supposed to tell which file descriptor to redirect. This routine
  4085. * looks for such preceding numbers. In an ideal world this routine
  4086. * needs to handle all the following classes of redirects...
  4087. * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
  4088. * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
  4089. * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
  4090. * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
  4091. *
  4092. * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
  4093. * "2.7 Redirection
  4094. * ... If n is quoted, the number shall not be recognized as part of
  4095. * the redirection expression. For example:
  4096. * echo \2>a
  4097. * writes the character 2 into file a"
  4098. * We are getting it right by setting ->has_quoted_part on any \<char>
  4099. *
  4100. * A -1 return means no valid number was found,
  4101. * the caller should use the appropriate default for this redirection.
  4102. */
  4103. static int redirect_opt_num(o_string *o)
  4104. {
  4105. int num;
  4106. if (o->data == NULL)
  4107. return -1;
  4108. num = bb_strtou(o->data, NULL, 10);
  4109. if (errno || num < 0)
  4110. return -1;
  4111. o_reset_to_empty_unquoted(o);
  4112. return num;
  4113. }
  4114. #if BB_MMU
  4115. #define fetch_till_str(as_string, input, word, skip_tabs) \
  4116. fetch_till_str(input, word, skip_tabs)
  4117. #endif
  4118. static char *fetch_till_str(o_string *as_string,
  4119. struct in_str *input,
  4120. const char *word,
  4121. int heredoc_flags)
  4122. {
  4123. o_string heredoc = NULL_O_STRING;
  4124. unsigned past_EOL;
  4125. int prev = 0; /* not \ */
  4126. int ch;
  4127. /* Starting with "" is necessary for this case:
  4128. * cat <<EOF
  4129. *
  4130. * xxx
  4131. * EOF
  4132. */
  4133. heredoc.data = xzalloc(1); /* start as "", not as NULL */
  4134. goto jump_in;
  4135. while (1) {
  4136. ch = i_getch(input);
  4137. if (ch != EOF)
  4138. nommu_addchr(as_string, ch);
  4139. if (ch == '\n' || ch == EOF) {
  4140. check_heredoc_end:
  4141. if ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\') {
  4142. /* End-of-line, and not a line continuation */
  4143. if (strcmp(heredoc.data + past_EOL, word) == 0) {
  4144. heredoc.data[past_EOL] = '\0';
  4145. debug_printf_heredoc("parsed '%s' heredoc '%s'\n", word, heredoc.data);
  4146. return heredoc.data;
  4147. }
  4148. if (ch == '\n') {
  4149. /* This is a new line.
  4150. * Remember position and backslash-escaping status.
  4151. */
  4152. o_addchr(&heredoc, ch);
  4153. prev = ch;
  4154. jump_in:
  4155. past_EOL = heredoc.length;
  4156. /* Get 1st char of next line, possibly skipping leading tabs */
  4157. do {
  4158. ch = i_getch(input);
  4159. if (ch != EOF)
  4160. nommu_addchr(as_string, ch);
  4161. } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
  4162. /* If this immediately ended the line,
  4163. * go back to end-of-line checks.
  4164. */
  4165. if (ch == '\n')
  4166. goto check_heredoc_end;
  4167. }
  4168. } else {
  4169. /* Backslash-line continuation in an unquoted
  4170. * heredoc. This does not need special handling
  4171. * for heredoc body (unquoted heredocs are
  4172. * expanded on "execution" and that would take
  4173. * care of this case too), but not the case
  4174. * of line continuation *in terminator*:
  4175. * cat <<EOF
  4176. * Ok1
  4177. * EO\
  4178. * F
  4179. */
  4180. heredoc.data[--heredoc.length] = '\0';
  4181. prev = 0; /* not '\' */
  4182. continue;
  4183. }
  4184. }
  4185. if (ch == EOF) {
  4186. o_free(&heredoc);
  4187. return NULL; /* error */
  4188. }
  4189. o_addchr(&heredoc, ch);
  4190. nommu_addchr(as_string, ch);
  4191. if (prev == '\\' && ch == '\\')
  4192. /* Correctly handle foo\\<eol> (not a line cont.) */
  4193. prev = 0; /* not '\' */
  4194. else
  4195. prev = ch;
  4196. }
  4197. }
  4198. /* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
  4199. * and load them all. There should be exactly heredoc_cnt of them.
  4200. */
  4201. #if BB_MMU
  4202. #define fetch_heredocs(as_string, pi, heredoc_cnt, input) \
  4203. fetch_heredocs(pi, heredoc_cnt, input)
  4204. #endif
  4205. static int fetch_heredocs(o_string *as_string, struct pipe *pi, int heredoc_cnt, struct in_str *input)
  4206. {
  4207. while (pi && heredoc_cnt) {
  4208. int i;
  4209. struct command *cmd = pi->cmds;
  4210. debug_printf_heredoc("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
  4211. pi->num_cmds,
  4212. cmd->argv ? cmd->argv[0] : "NONE"
  4213. );
  4214. for (i = 0; i < pi->num_cmds; i++) {
  4215. struct redir_struct *redir = cmd->redirects;
  4216. debug_printf_heredoc("fetch_heredocs: %d cmd argv0:'%s'\n",
  4217. i, cmd->argv ? cmd->argv[0] : "NONE");
  4218. while (redir) {
  4219. if (redir->rd_type == REDIRECT_HEREDOC) {
  4220. char *p;
  4221. redir->rd_type = REDIRECT_HEREDOC2;
  4222. /* redir->rd_dup is (ab)used to indicate <<- */
  4223. p = fetch_till_str(as_string, input,
  4224. redir->rd_filename, redir->rd_dup);
  4225. if (!p) {
  4226. syntax_error("unexpected EOF in here document");
  4227. return -1;
  4228. }
  4229. free(redir->rd_filename);
  4230. redir->rd_filename = p;
  4231. heredoc_cnt--;
  4232. }
  4233. redir = redir->next;
  4234. }
  4235. if (cmd->group) {
  4236. //bb_error_msg("%s:%u heredoc_cnt:%d", __func__, __LINE__, heredoc_cnt);
  4237. heredoc_cnt = fetch_heredocs(as_string, cmd->group, heredoc_cnt, input);
  4238. //bb_error_msg("%s:%u heredoc_cnt:%d", __func__, __LINE__, heredoc_cnt);
  4239. if (heredoc_cnt < 0)
  4240. return heredoc_cnt; /* error */
  4241. }
  4242. cmd++;
  4243. }
  4244. pi = pi->next;
  4245. }
  4246. return heredoc_cnt;
  4247. }
  4248. static int run_list(struct pipe *pi);
  4249. #if BB_MMU
  4250. #define parse_stream(pstring, heredoc_cnt_ptr, input, end_trigger) \
  4251. parse_stream(heredoc_cnt_ptr, input, end_trigger)
  4252. #endif
  4253. static struct pipe *parse_stream(char **pstring,
  4254. int *heredoc_cnt_ptr,
  4255. struct in_str *input,
  4256. int end_trigger);
  4257. /* Returns number of heredocs not yet consumed,
  4258. * or -1 on error.
  4259. */
  4260. static int parse_group(struct parse_context *ctx,
  4261. struct in_str *input, int ch)
  4262. {
  4263. /* ctx->word contains characters seen prior to ( or {.
  4264. * Typically it's empty, but for function defs,
  4265. * it contains function name (without '()'). */
  4266. #if BB_MMU
  4267. # define as_string NULL
  4268. #else
  4269. char *as_string = NULL;
  4270. #endif
  4271. struct pipe *pipe_list;
  4272. int heredoc_cnt = 0;
  4273. int endch;
  4274. struct command *command = ctx->command;
  4275. debug_printf_parse("parse_group entered\n");
  4276. #if ENABLE_HUSH_FUNCTIONS
  4277. if (ch == '(' && !ctx->word.has_quoted_part) {
  4278. if (ctx->word.length)
  4279. if (done_word(ctx))
  4280. return -1;
  4281. if (!command->argv)
  4282. goto skip; /* (... */
  4283. if (command->argv[1]) { /* word word ... (... */
  4284. syntax_error_unexpected_ch('(');
  4285. return -1;
  4286. }
  4287. /* it is "word(..." or "word (..." */
  4288. do
  4289. ch = i_getch(input);
  4290. while (ch == ' ' || ch == '\t');
  4291. if (ch != ')') {
  4292. syntax_error_unexpected_ch(ch);
  4293. return -1;
  4294. }
  4295. nommu_addchr(&ctx->as_string, ch);
  4296. do
  4297. ch = i_getch(input);
  4298. while (ch == ' ' || ch == '\t' || ch == '\n');
  4299. if (ch != '{' && ch != '(') {
  4300. syntax_error_unexpected_ch(ch);
  4301. return -1;
  4302. }
  4303. nommu_addchr(&ctx->as_string, ch);
  4304. command->cmd_type = CMD_FUNCDEF;
  4305. goto skip;
  4306. }
  4307. #endif
  4308. #if 0 /* Prevented by caller */
  4309. if (command->argv /* word [word]{... */
  4310. || ctx->word.length /* word{... */
  4311. || ctx->word.has_quoted_part /* ""{... */
  4312. ) {
  4313. syntax_error(NULL);
  4314. debug_printf_parse("parse_group return -1: "
  4315. "syntax error, groups and arglists don't mix\n");
  4316. return -1;
  4317. }
  4318. #endif
  4319. IF_HUSH_FUNCTIONS(skip:)
  4320. endch = '}';
  4321. if (ch == '(') {
  4322. endch = ')';
  4323. IF_HUSH_FUNCTIONS(if (command->cmd_type != CMD_FUNCDEF))
  4324. command->cmd_type = CMD_SUBSHELL;
  4325. } else {
  4326. /* bash does not allow "{echo...", requires whitespace */
  4327. ch = i_peek(input);
  4328. if (ch != ' ' && ch != '\t' && ch != '\n'
  4329. && ch != '(' /* but "{(..." is allowed (without whitespace) */
  4330. ) {
  4331. syntax_error_unexpected_ch(ch);
  4332. return -1;
  4333. }
  4334. if (ch != '(') {
  4335. ch = i_getch(input);
  4336. nommu_addchr(&ctx->as_string, ch);
  4337. }
  4338. }
  4339. debug_printf_heredoc("calling parse_stream, heredoc_cnt:%d\n", heredoc_cnt);
  4340. pipe_list = parse_stream(&as_string, &heredoc_cnt, input, endch);
  4341. debug_printf_heredoc("parse_stream returned: heredoc_cnt:%d\n", heredoc_cnt);
  4342. #if !BB_MMU
  4343. if (as_string)
  4344. o_addstr(&ctx->as_string, as_string);
  4345. #endif
  4346. /* empty ()/{} or parse error? */
  4347. if (!pipe_list || pipe_list == ERR_PTR) {
  4348. /* parse_stream already emitted error msg */
  4349. if (!BB_MMU)
  4350. free(as_string);
  4351. debug_printf_parse("parse_group return -1: "
  4352. "parse_stream returned %p\n", pipe_list);
  4353. return -1;
  4354. }
  4355. #if !BB_MMU
  4356. as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
  4357. command->group_as_string = as_string;
  4358. debug_printf_parse("end of group, remembering as:'%s'\n",
  4359. command->group_as_string);
  4360. #endif
  4361. #if ENABLE_HUSH_FUNCTIONS
  4362. /* Convert "f() (cmds)" to "f() {(cmds)}" */
  4363. if (command->cmd_type == CMD_FUNCDEF && endch == ')') {
  4364. struct command *cmd2;
  4365. cmd2 = xzalloc(sizeof(*cmd2));
  4366. cmd2->cmd_type = CMD_SUBSHELL;
  4367. cmd2->group = pipe_list;
  4368. # if !BB_MMU
  4369. //UNTESTED!
  4370. cmd2->group_as_string = command->group_as_string;
  4371. command->group_as_string = xasprintf("(%s)", command->group_as_string);
  4372. # endif
  4373. pipe_list = new_pipe();
  4374. pipe_list->cmds = cmd2;
  4375. pipe_list->num_cmds = 1;
  4376. }
  4377. #endif
  4378. command->group = pipe_list;
  4379. debug_printf_parse("parse_group return %d\n", heredoc_cnt);
  4380. return heredoc_cnt;
  4381. /* command remains "open", available for possible redirects */
  4382. #undef as_string
  4383. }
  4384. #if ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS
  4385. /* Subroutines for copying $(...) and `...` things */
  4386. /* '...' */
  4387. static int add_till_single_quote(o_string *dest, struct in_str *input)
  4388. {
  4389. while (1) {
  4390. int ch = i_getch(input);
  4391. if (ch == EOF) {
  4392. syntax_error_unterm_ch('\'');
  4393. return 0;
  4394. }
  4395. if (ch == '\'')
  4396. return 1;
  4397. o_addchr(dest, ch);
  4398. }
  4399. }
  4400. static int add_till_single_quote_dquoted(o_string *dest, struct in_str *input)
  4401. {
  4402. while (1) {
  4403. int ch = i_getch(input);
  4404. if (ch == EOF) {
  4405. syntax_error_unterm_ch('\'');
  4406. return 0;
  4407. }
  4408. if (ch == '\'')
  4409. return 1;
  4410. o_addqchr(dest, ch);
  4411. }
  4412. }
  4413. /* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
  4414. static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote);
  4415. static int add_till_double_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. if (ch == '\\') { /* \x. Copy both chars. */
  4426. o_addchr(dest, ch);
  4427. ch = i_getch(input);
  4428. }
  4429. o_addchr(dest, ch);
  4430. if (ch == '`') {
  4431. if (!add_till_backquote(dest, input, /*in_dquote:*/ 1))
  4432. return 0;
  4433. o_addchr(dest, ch);
  4434. continue;
  4435. }
  4436. //if (ch == '$') ...
  4437. }
  4438. }
  4439. /* Process `cmd` - copy contents until "`" is seen. Complicated by
  4440. * \` quoting.
  4441. * "Within the backquoted style of command substitution, backslash
  4442. * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
  4443. * The search for the matching backquote shall be satisfied by the first
  4444. * backquote found without a preceding backslash; during this search,
  4445. * if a non-escaped backquote is encountered within a shell comment,
  4446. * a here-document, an embedded command substitution of the $(command)
  4447. * form, or a quoted string, undefined results occur. A single-quoted
  4448. * or double-quoted string that begins, but does not end, within the
  4449. * "`...`" sequence produces undefined results."
  4450. * Example Output
  4451. * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
  4452. */
  4453. static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote)
  4454. {
  4455. while (1) {
  4456. int ch = i_getch(input);
  4457. if (ch == '`')
  4458. return 1;
  4459. if (ch == '\\') {
  4460. /* \x. Copy both unless it is \`, \$, \\ and maybe \" */
  4461. ch = i_getch(input);
  4462. if (ch != '`'
  4463. && ch != '$'
  4464. && ch != '\\'
  4465. && (!in_dquote || ch != '"')
  4466. ) {
  4467. o_addchr(dest, '\\');
  4468. }
  4469. }
  4470. if (ch == EOF) {
  4471. syntax_error_unterm_ch('`');
  4472. return 0;
  4473. }
  4474. o_addchr(dest, ch);
  4475. }
  4476. }
  4477. /* Process $(cmd) - copy contents until ")" is seen. Complicated by
  4478. * quoting and nested ()s.
  4479. * "With the $(command) style of command substitution, all characters
  4480. * following the open parenthesis to the matching closing parenthesis
  4481. * constitute the command. Any valid shell script can be used for command,
  4482. * except a script consisting solely of redirections which produces
  4483. * unspecified results."
  4484. * Example Output
  4485. * echo $(echo '(TEST)' BEST) (TEST) BEST
  4486. * echo $(echo 'TEST)' BEST) TEST) BEST
  4487. * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
  4488. *
  4489. * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
  4490. * can contain arbitrary constructs, just like $(cmd).
  4491. * In bash compat mode, it needs to also be able to stop on ':' or '/'
  4492. * for ${var:N[:M]} and ${var/P[/R]} parsing.
  4493. */
  4494. #define DOUBLE_CLOSE_CHAR_FLAG 0x80
  4495. static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
  4496. {
  4497. int ch;
  4498. char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
  4499. # if BASH_SUBSTR || BASH_PATTERN_SUBST
  4500. char end_char2 = end_ch >> 8;
  4501. # endif
  4502. end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
  4503. # if ENABLE_HUSH_INTERACTIVE
  4504. G.promptmode = 1; /* PS2 */
  4505. # endif
  4506. debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
  4507. while (1) {
  4508. ch = i_getch(input);
  4509. if (ch == EOF) {
  4510. syntax_error_unterm_ch(end_ch);
  4511. return 0;
  4512. }
  4513. if (ch == end_ch
  4514. # if BASH_SUBSTR || BASH_PATTERN_SUBST
  4515. || ch == end_char2
  4516. # endif
  4517. ) {
  4518. if (!dbl)
  4519. break;
  4520. /* we look for closing )) of $((EXPR)) */
  4521. if (i_peek_and_eat_bkslash_nl(input) == end_ch) {
  4522. i_getch(input); /* eat second ')' */
  4523. break;
  4524. }
  4525. }
  4526. o_addchr(dest, ch);
  4527. //bb_error_msg("%s:o_addchr('%c')", __func__, ch);
  4528. if (ch == '(' || ch == '{') {
  4529. ch = (ch == '(' ? ')' : '}');
  4530. if (!add_till_closing_bracket(dest, input, ch))
  4531. return 0;
  4532. o_addchr(dest, ch);
  4533. continue;
  4534. }
  4535. if (ch == '\'') {
  4536. if (!add_till_single_quote(dest, input))
  4537. return 0;
  4538. o_addchr(dest, ch);
  4539. continue;
  4540. }
  4541. if (ch == '"') {
  4542. if (!add_till_double_quote(dest, input))
  4543. return 0;
  4544. o_addchr(dest, ch);
  4545. continue;
  4546. }
  4547. if (ch == '`') {
  4548. if (!add_till_backquote(dest, input, /*in_dquote:*/ 0))
  4549. return 0;
  4550. o_addchr(dest, ch);
  4551. continue;
  4552. }
  4553. if (ch == '\\') {
  4554. /* \x. Copy verbatim. Important for \(, \) */
  4555. ch = i_getch(input);
  4556. if (ch == EOF) {
  4557. syntax_error_unterm_ch(end_ch);
  4558. return 0;
  4559. }
  4560. # if 0
  4561. if (ch == '\n') {
  4562. /* "backslash+newline", ignore both */
  4563. o_delchr(dest); /* undo insertion of '\' */
  4564. continue;
  4565. }
  4566. # endif
  4567. o_addchr(dest, ch);
  4568. //bb_error_msg("%s:o_addchr('%c') after '\\'", __func__, ch);
  4569. continue;
  4570. }
  4571. }
  4572. debug_printf_parse("%s return '%s' ch:'%c'\n", __func__, dest->data, ch);
  4573. return ch;
  4574. }
  4575. #endif /* ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS */
  4576. /* Return code: 0 for OK, 1 for syntax error */
  4577. #if BB_MMU
  4578. #define parse_dollar(as_string, dest, input, quote_mask) \
  4579. parse_dollar(dest, input, quote_mask)
  4580. #define as_string NULL
  4581. #endif
  4582. static int parse_dollar(o_string *as_string,
  4583. o_string *dest,
  4584. struct in_str *input, unsigned char quote_mask)
  4585. {
  4586. int ch = i_peek_and_eat_bkslash_nl(input); /* first character after the $ */
  4587. debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
  4588. if (isalpha(ch)) {
  4589. make_var:
  4590. ch = i_getch(input);
  4591. nommu_addchr(as_string, ch);
  4592. /*make_var1:*/
  4593. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4594. while (1) {
  4595. debug_printf_parse(": '%c'\n", ch);
  4596. o_addchr(dest, ch | quote_mask);
  4597. quote_mask = 0;
  4598. ch = i_peek_and_eat_bkslash_nl(input);
  4599. if (!isalnum(ch) && ch != '_') {
  4600. /* End of variable name reached */
  4601. break;
  4602. }
  4603. ch = i_getch(input);
  4604. nommu_addchr(as_string, ch);
  4605. }
  4606. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4607. } else if (isdigit(ch)) {
  4608. make_one_char_var:
  4609. ch = i_getch(input);
  4610. nommu_addchr(as_string, ch);
  4611. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4612. debug_printf_parse(": '%c'\n", ch);
  4613. o_addchr(dest, ch | quote_mask);
  4614. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4615. } else switch (ch) {
  4616. case '$': /* pid */
  4617. case '!': /* last bg pid */
  4618. case '?': /* last exit code */
  4619. case '#': /* number of args */
  4620. case '*': /* args */
  4621. case '@': /* args */
  4622. case '-': /* $- option flags set by set builtin or shell options (-i etc) */
  4623. goto make_one_char_var;
  4624. case '{': {
  4625. char len_single_ch;
  4626. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4627. ch = i_getch(input); /* eat '{' */
  4628. nommu_addchr(as_string, ch);
  4629. ch = i_getch_and_eat_bkslash_nl(input); /* first char after '{' */
  4630. /* It should be ${?}, or ${#var},
  4631. * or even ${?+subst} - operator acting on a special variable,
  4632. * or the beginning of variable name.
  4633. */
  4634. if (ch == EOF
  4635. || (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) /* not one of those */
  4636. ) {
  4637. bad_dollar_syntax:
  4638. syntax_error_unterm_str("${name}");
  4639. debug_printf_parse("parse_dollar return 0: unterminated ${name}\n");
  4640. return 0;
  4641. }
  4642. nommu_addchr(as_string, ch);
  4643. len_single_ch = ch;
  4644. ch |= quote_mask;
  4645. /* It's possible to just call add_till_closing_bracket() at this point.
  4646. * However, this regresses some of our testsuite cases
  4647. * which check invalid constructs like ${%}.
  4648. * Oh well... let's check that the var name part is fine... */
  4649. while (1) {
  4650. unsigned pos;
  4651. o_addchr(dest, ch);
  4652. debug_printf_parse(": '%c'\n", ch);
  4653. ch = i_getch(input);
  4654. nommu_addchr(as_string, ch);
  4655. if (ch == '}')
  4656. break;
  4657. if (!isalnum(ch) && ch != '_') {
  4658. unsigned end_ch;
  4659. unsigned char last_ch;
  4660. /* handle parameter expansions
  4661. * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
  4662. */
  4663. if (!strchr(VAR_SUBST_OPS, ch)) { /* ${var<bad_char>... */
  4664. if (len_single_ch != '#'
  4665. /*|| !strchr(SPECIAL_VARS_STR, ch) - disallow errors like ${#+} ? */
  4666. || i_peek(input) != '}'
  4667. ) {
  4668. goto bad_dollar_syntax;
  4669. }
  4670. /* else: it's "length of C" ${#C} op,
  4671. * where C is a single char
  4672. * special var name, e.g. ${#!}.
  4673. */
  4674. }
  4675. /* Eat everything until closing '}' (or ':') */
  4676. end_ch = '}';
  4677. if (BASH_SUBSTR
  4678. && ch == ':'
  4679. && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
  4680. ) {
  4681. /* It's ${var:N[:M]} thing */
  4682. end_ch = '}' * 0x100 + ':';
  4683. }
  4684. if (BASH_PATTERN_SUBST
  4685. && ch == '/'
  4686. ) {
  4687. /* It's ${var/[/]pattern[/repl]} thing */
  4688. if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
  4689. i_getch(input);
  4690. nommu_addchr(as_string, '/');
  4691. ch = '\\';
  4692. }
  4693. end_ch = '}' * 0x100 + '/';
  4694. }
  4695. o_addchr(dest, ch);
  4696. /* The pattern can't be empty.
  4697. * IOW: if the first char after "${v//" is a slash,
  4698. * it does not terminate the pattern - it's the first char of the pattern:
  4699. * v=/dev/ram; echo ${v////-} prints -dev-ram (pattern is "/")
  4700. * v=/dev/ram; echo ${v///r/-} prints /dev-am (pattern is "/r")
  4701. */
  4702. if (i_peek(input) == '/') {
  4703. o_addchr(dest, i_getch(input));
  4704. }
  4705. again:
  4706. if (!BB_MMU)
  4707. pos = dest->length;
  4708. #if ENABLE_HUSH_DOLLAR_OPS
  4709. last_ch = add_till_closing_bracket(dest, input, end_ch);
  4710. if (last_ch == 0) /* error? */
  4711. return 0;
  4712. #else
  4713. # error Simple code to only allow ${var} is not implemented
  4714. #endif
  4715. if (as_string) {
  4716. o_addstr(as_string, dest->data + pos);
  4717. o_addchr(as_string, last_ch);
  4718. }
  4719. if ((BASH_SUBSTR || BASH_PATTERN_SUBST)
  4720. && (end_ch & 0xff00)
  4721. ) {
  4722. /* close the first block: */
  4723. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4724. /* while parsing N from ${var:N[:M]}
  4725. * or pattern from ${var/[/]pattern[/repl]} */
  4726. if ((end_ch & 0xff) == last_ch) {
  4727. /* got ':' or '/'- parse the rest */
  4728. end_ch = '}';
  4729. goto again;
  4730. }
  4731. /* got '}' */
  4732. if (BASH_SUBSTR && end_ch == '}' * 0x100 + ':') {
  4733. /* it's ${var:N} - emulate :999999999 */
  4734. o_addstr(dest, "999999999");
  4735. } /* else: it's ${var/[/]pattern} */
  4736. }
  4737. break;
  4738. }
  4739. len_single_ch = 0; /* it can't be ${#C} op */
  4740. }
  4741. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4742. break;
  4743. }
  4744. #if ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_TICK
  4745. case '(': {
  4746. unsigned pos;
  4747. ch = i_getch(input);
  4748. nommu_addchr(as_string, ch);
  4749. # if ENABLE_FEATURE_SH_MATH
  4750. if (i_peek_and_eat_bkslash_nl(input) == '(') {
  4751. ch = i_getch(input);
  4752. nommu_addchr(as_string, ch);
  4753. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4754. o_addchr(dest, quote_mask | '+');
  4755. if (!BB_MMU)
  4756. pos = dest->length;
  4757. if (!add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG))
  4758. return 0; /* error */
  4759. if (as_string) {
  4760. o_addstr(as_string, dest->data + pos);
  4761. o_addchr(as_string, ')');
  4762. o_addchr(as_string, ')');
  4763. }
  4764. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4765. break;
  4766. }
  4767. # endif
  4768. # if ENABLE_HUSH_TICK
  4769. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4770. o_addchr(dest, quote_mask | '`');
  4771. if (!BB_MMU)
  4772. pos = dest->length;
  4773. if (!add_till_closing_bracket(dest, input, ')'))
  4774. return 0; /* error */
  4775. if (as_string) {
  4776. o_addstr(as_string, dest->data + pos);
  4777. o_addchr(as_string, ')');
  4778. }
  4779. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4780. # endif
  4781. break;
  4782. }
  4783. #endif
  4784. case '_':
  4785. goto make_var;
  4786. #if 0
  4787. /* TODO: $_: */
  4788. /* $_ Shell or shell script name; or last argument of last command
  4789. * (if last command wasn't a pipe; if it was, bash sets $_ to "");
  4790. * but in command's env, set to full pathname used to invoke it */
  4791. ch = i_getch(input);
  4792. nommu_addchr(as_string, ch);
  4793. ch = i_peek_and_eat_bkslash_nl(input);
  4794. if (isalnum(ch)) { /* it's $_name or $_123 */
  4795. ch = '_';
  4796. goto make_var1;
  4797. }
  4798. /* else: it's $_ */
  4799. #endif
  4800. default:
  4801. o_addQchr(dest, '$');
  4802. }
  4803. debug_printf_parse("parse_dollar return 1 (ok)\n");
  4804. return 1;
  4805. #undef as_string
  4806. }
  4807. #if BB_MMU
  4808. #define encode_string(as_string, dest, input, dquote_end) \
  4809. encode_string(dest, input, dquote_end)
  4810. #define as_string NULL
  4811. #endif
  4812. static int encode_string(o_string *as_string,
  4813. o_string *dest,
  4814. struct in_str *input,
  4815. int dquote_end)
  4816. {
  4817. int ch;
  4818. int next;
  4819. again:
  4820. ch = i_getch(input);
  4821. if (ch != EOF)
  4822. nommu_addchr(as_string, ch);
  4823. if (ch == dquote_end) { /* may be only '"' or EOF */
  4824. debug_printf_parse("encode_string return 1 (ok)\n");
  4825. return 1;
  4826. }
  4827. /* note: can't move it above ch == dquote_end check! */
  4828. if (ch == EOF) {
  4829. syntax_error_unterm_ch('"');
  4830. return 0; /* error */
  4831. }
  4832. next = '\0';
  4833. if (ch != '\n') {
  4834. next = i_peek(input);
  4835. }
  4836. debug_printf_parse("\" ch=%c (%d) escape=%d\n",
  4837. ch, ch, !!(dest->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
  4838. if (ch == '\\') {
  4839. if (next == EOF) {
  4840. /* Testcase: in interactive shell a file with
  4841. * echo "unterminated string\<eof>
  4842. * is sourced.
  4843. */
  4844. syntax_error_unterm_ch('"');
  4845. return 0; /* error */
  4846. }
  4847. /* bash:
  4848. * "The backslash retains its special meaning [in "..."]
  4849. * only when followed by one of the following characters:
  4850. * $, `, ", \, or <newline>. A double quote may be quoted
  4851. * within double quotes by preceding it with a backslash."
  4852. * NB: in (unquoted) heredoc, above does not apply to ",
  4853. * therefore we check for it by "next == dquote_end" cond.
  4854. */
  4855. if (next == dquote_end || strchr("$`\\\n", next)) {
  4856. ch = i_getch(input); /* eat next */
  4857. if (ch == '\n')
  4858. goto again; /* skip \<newline> */
  4859. } /* else: ch remains == '\\', and we double it below: */
  4860. o_addqchr(dest, ch); /* \c if c is a glob char, else just c */
  4861. nommu_addchr(as_string, ch);
  4862. goto again;
  4863. }
  4864. if (ch == '$') {
  4865. if (!parse_dollar(as_string, dest, input, /*quote_mask:*/ 0x80)) {
  4866. debug_printf_parse("encode_string return 0: "
  4867. "parse_dollar returned 0 (error)\n");
  4868. return 0;
  4869. }
  4870. goto again;
  4871. }
  4872. #if ENABLE_HUSH_TICK
  4873. if (ch == '`') {
  4874. //unsigned pos = dest->length;
  4875. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4876. o_addchr(dest, 0x80 | '`');
  4877. if (!add_till_backquote(dest, input, /*in_dquote:*/ dquote_end == '"'))
  4878. return 0; /* error */
  4879. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4880. //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
  4881. goto again;
  4882. }
  4883. #endif
  4884. o_addQchr(dest, ch);
  4885. goto again;
  4886. #undef as_string
  4887. }
  4888. /*
  4889. * Scan input until EOF or end_trigger char.
  4890. * Return a list of pipes to execute, or NULL on EOF
  4891. * or if end_trigger character is met.
  4892. * On syntax error, exit if shell is not interactive,
  4893. * reset parsing machinery and start parsing anew,
  4894. * or return ERR_PTR.
  4895. */
  4896. static struct pipe *parse_stream(char **pstring,
  4897. int *heredoc_cnt_ptr,
  4898. struct in_str *input,
  4899. int end_trigger)
  4900. {
  4901. struct parse_context ctx;
  4902. int heredoc_cnt;
  4903. /* Single-quote triggers a bypass of the main loop until its mate is
  4904. * found. When recursing, quote state is passed in via ctx.word.o_expflags.
  4905. */
  4906. debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
  4907. end_trigger ? end_trigger : 'X');
  4908. debug_enter();
  4909. initialize_context(&ctx);
  4910. /* If very first arg is "" or '', ctx.word.data may end up NULL.
  4911. * Preventing this:
  4912. */
  4913. ctx.word.data = xzalloc(1); /* start as "", not as NULL */
  4914. /* We used to separate words on $IFS here. This was wrong.
  4915. * $IFS is used only for word splitting when $var is expanded,
  4916. * here we should use blank chars as separators, not $IFS
  4917. */
  4918. heredoc_cnt = 0;
  4919. while (1) {
  4920. const char *is_blank;
  4921. const char *is_special;
  4922. int ch;
  4923. int next;
  4924. int redir_fd;
  4925. redir_type redir_style;
  4926. ch = i_getch(input);
  4927. debug_printf_parse(": ch=%c (%d) escape=%d\n",
  4928. ch, ch, !!(ctx.word.o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
  4929. if (ch == EOF) {
  4930. struct pipe *pi;
  4931. #if ENABLE_FEATURE_EDITING
  4932. if (G.flag_ctrlC) {
  4933. /* testcase: interactively entering
  4934. * 'qwe <cr> ^C
  4935. * should not leave input in PS2 mode, waiting to close single quote.
  4936. */
  4937. G.flag_ctrlC = 0;
  4938. goto parse_error;
  4939. }
  4940. #endif
  4941. if (heredoc_cnt) {
  4942. syntax_error_unterm_str("here document");
  4943. goto parse_error_exitcode1;
  4944. }
  4945. if (end_trigger == ')') {
  4946. syntax_error_unterm_ch('(');
  4947. goto parse_error_exitcode1;
  4948. }
  4949. if (end_trigger == '}') {
  4950. syntax_error_unterm_ch('{');
  4951. goto parse_error_exitcode1;
  4952. }
  4953. if (done_word(&ctx)) {
  4954. goto parse_error_exitcode1;
  4955. }
  4956. o_free_and_set_NULL(&ctx.word);
  4957. done_pipe(&ctx, PIPE_SEQ);
  4958. pi = ctx.list_head;
  4959. /* If we got nothing... */
  4960. /* (this makes bare "&" cmd a no-op.
  4961. * bash says: "syntax error near unexpected token '&'") */
  4962. if (pi->num_cmds == 0
  4963. IF_HAS_KEYWORDS(&& pi->res_word == RES_NONE)
  4964. ) {
  4965. free_pipe_list(pi);
  4966. pi = NULL;
  4967. }
  4968. #if !BB_MMU
  4969. debug_printf_parse("as_string1 '%s'\n", ctx.as_string.data);
  4970. if (pstring)
  4971. *pstring = ctx.as_string.data;
  4972. else
  4973. o_free(&ctx.as_string);
  4974. #endif
  4975. // heredoc_cnt must be 0 here anyway
  4976. //if (heredoc_cnt_ptr)
  4977. // *heredoc_cnt_ptr = heredoc_cnt;
  4978. debug_leave();
  4979. debug_printf_heredoc("parse_stream return heredoc_cnt:%d\n", heredoc_cnt);
  4980. debug_printf_parse("parse_stream return %p\n", pi);
  4981. return pi;
  4982. }
  4983. /* Handle "'" and "\" first, as they won't play nice with
  4984. * i_peek_and_eat_bkslash_nl() anyway:
  4985. * echo z\\
  4986. * and
  4987. * echo '\
  4988. * '
  4989. * would break.
  4990. */
  4991. if (ch == '\\') {
  4992. ch = i_getch(input);
  4993. if (ch == '\n')
  4994. continue; /* drop \<newline>, get next char */
  4995. nommu_addchr(&ctx.as_string, '\\');
  4996. o_addchr(&ctx.word, '\\');
  4997. if (ch == EOF) {
  4998. /* Testcase: eval 'echo Ok\' */
  4999. /* bash-4.3.43 was removing backslash,
  5000. * but 4.4.19 retains it, most other shells too
  5001. */
  5002. continue; /* get next char */
  5003. }
  5004. /* Example: echo Hello \2>file
  5005. * we need to know that word 2 is quoted
  5006. */
  5007. ctx.word.has_quoted_part = 1;
  5008. nommu_addchr(&ctx.as_string, ch);
  5009. o_addchr(&ctx.word, ch);
  5010. continue; /* get next char */
  5011. }
  5012. nommu_addchr(&ctx.as_string, ch);
  5013. if (ch == '\'') {
  5014. ctx.word.has_quoted_part = 1;
  5015. next = i_getch(input);
  5016. if (next == '\'' && !ctx.pending_redirect)
  5017. goto insert_empty_quoted_str_marker;
  5018. ch = next;
  5019. while (1) {
  5020. if (ch == EOF) {
  5021. syntax_error_unterm_ch('\'');
  5022. goto parse_error_exitcode1;
  5023. }
  5024. nommu_addchr(&ctx.as_string, ch);
  5025. if (ch == '\'')
  5026. break;
  5027. if (ch == SPECIAL_VAR_SYMBOL) {
  5028. /* Convert raw ^C to corresponding special variable reference */
  5029. o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
  5030. o_addchr(&ctx.word, SPECIAL_VAR_QUOTED_SVS);
  5031. }
  5032. o_addqchr(&ctx.word, ch);
  5033. ch = i_getch(input);
  5034. }
  5035. continue; /* get next char */
  5036. }
  5037. next = '\0';
  5038. if (ch != '\n')
  5039. next = i_peek_and_eat_bkslash_nl(input);
  5040. is_special = "{}<>&|();#" /* special outside of "str" */
  5041. "$\"" IF_HUSH_TICK("`") /* always special */
  5042. SPECIAL_VAR_SYMBOL_STR;
  5043. #if defined(CMD_TEST2_SINGLEWORD_NOGLOB)
  5044. if (ctx.command->cmd_type == CMD_TEST2_SINGLEWORD_NOGLOB) {
  5045. /* In [[ ]], {}<>&|() are not special */
  5046. is_special += 8;
  5047. } else
  5048. #endif
  5049. /* Are { and } special here? */
  5050. if (ctx.command->argv /* word [word]{... - non-special */
  5051. || ctx.word.length /* word{... - non-special */
  5052. || ctx.word.has_quoted_part /* ""{... - non-special */
  5053. || (next != ';' /* }; - special */
  5054. && next != ')' /* }) - special */
  5055. && next != '(' /* {( - special */
  5056. && next != '&' /* }& and }&& ... - special */
  5057. && next != '|' /* }|| ... - special */
  5058. && !strchr(defifs, next) /* {word - non-special */
  5059. )
  5060. ) {
  5061. /* They are not special, skip "{}" */
  5062. is_special += 2;
  5063. }
  5064. is_special = strchr(is_special, ch);
  5065. is_blank = strchr(defifs, ch);
  5066. if (!is_special && !is_blank) { /* ordinary char */
  5067. ordinary_char:
  5068. o_addQchr(&ctx.word, ch);
  5069. if ((ctx.is_assignment == MAYBE_ASSIGNMENT
  5070. || ctx.is_assignment == WORD_IS_KEYWORD)
  5071. && ch == '='
  5072. && endofname(ctx.word.data)[0] == '='
  5073. ) {
  5074. ctx.is_assignment = DEFINITELY_ASSIGNMENT;
  5075. debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
  5076. }
  5077. continue;
  5078. }
  5079. if (is_blank) {
  5080. #if ENABLE_HUSH_LINENO_VAR
  5081. /* Case:
  5082. * "while ...; do<whitespace><newline>
  5083. * cmd ..."
  5084. * would think that "cmd" starts in <whitespace> -
  5085. * i.e., at the previous line.
  5086. * We need to skip all whitespace before newlines.
  5087. */
  5088. while (ch != '\n') {
  5089. next = i_peek(input);
  5090. if (next != ' ' && next != '\t' && next != '\n')
  5091. break; /* next char is not ws */
  5092. ch = i_getch(input);
  5093. }
  5094. /* ch == last eaten whitespace char */
  5095. #endif
  5096. if (done_word(&ctx)) {
  5097. goto parse_error_exitcode1;
  5098. }
  5099. if (ch == '\n') {
  5100. /* Is this a case when newline is simply ignored?
  5101. * Some examples:
  5102. * "cmd | <newline> cmd ..."
  5103. * "case ... in <newline> word) ..."
  5104. */
  5105. if (IS_NULL_CMD(ctx.command)
  5106. && ctx.word.length == 0
  5107. && !ctx.word.has_quoted_part
  5108. && heredoc_cnt == 0
  5109. ) {
  5110. /* This newline can be ignored. But...
  5111. * Without check #1, interactive shell
  5112. * ignores even bare <newline>,
  5113. * and shows the continuation prompt:
  5114. * ps1_prompt$ <enter>
  5115. * ps2> _ <=== wrong, should be ps1
  5116. * Without check #2, "cmd & <newline>"
  5117. * is similarly mistreated.
  5118. * (BTW, this makes "cmd & cmd"
  5119. * and "cmd && cmd" non-orthogonal.
  5120. * Really, ask yourself, why
  5121. * "cmd && <newline>" doesn't start
  5122. * cmd but waits for more input?
  5123. * The only reason is that it might be
  5124. * a "cmd1 && <nl> cmd2 &" construct,
  5125. * cmd1 may need to run in BG).
  5126. */
  5127. struct pipe *pi = ctx.list_head;
  5128. if (pi->num_cmds != 0 /* check #1 */
  5129. && pi->followup != PIPE_BG /* check #2 */
  5130. ) {
  5131. continue;
  5132. }
  5133. }
  5134. /* Treat newline as a command separator. */
  5135. done_pipe(&ctx, PIPE_SEQ);
  5136. debug_printf_heredoc("heredoc_cnt:%d\n", heredoc_cnt);
  5137. if (heredoc_cnt) {
  5138. heredoc_cnt = fetch_heredocs(&ctx.as_string, ctx.list_head, heredoc_cnt, input);
  5139. if (heredoc_cnt != 0)
  5140. goto parse_error_exitcode1;
  5141. }
  5142. ctx.is_assignment = MAYBE_ASSIGNMENT;
  5143. debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
  5144. ch = ';';
  5145. /* note: if (is_blank) continue;
  5146. * will still trigger for us */
  5147. }
  5148. }
  5149. /* "cmd}" or "cmd }..." without semicolon or &:
  5150. * } is an ordinary char in this case, even inside { cmd; }
  5151. * Pathological example: { ""}; } should exec "}" cmd
  5152. */
  5153. if (ch == '}') {
  5154. if (ctx.word.length != 0 /* word} */
  5155. || ctx.word.has_quoted_part /* ""} */
  5156. ) {
  5157. goto ordinary_char;
  5158. }
  5159. if (!IS_NULL_CMD(ctx.command)) { /* cmd } */
  5160. /* Generally, there should be semicolon: "cmd; }"
  5161. * However, bash allows to omit it if "cmd" is
  5162. * a group. Examples:
  5163. * { { echo 1; } }
  5164. * {(echo 1)}
  5165. * { echo 0 >&2 | { echo 1; } }
  5166. * { while false; do :; done }
  5167. * { case a in b) ;; esac }
  5168. */
  5169. if (ctx.command->group)
  5170. goto term_group;
  5171. goto ordinary_char;
  5172. }
  5173. if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
  5174. /* Can't be an end of {cmd}, skip the check */
  5175. goto skip_end_trigger;
  5176. /* else: } does terminate a group */
  5177. }
  5178. term_group:
  5179. if (end_trigger && end_trigger == ch
  5180. && (ch != ';' || heredoc_cnt == 0)
  5181. #if ENABLE_HUSH_CASE
  5182. && (ch != ')'
  5183. || ctx.ctx_res_w != RES_MATCH
  5184. || (!ctx.word.has_quoted_part && strcmp(ctx.word.data, "esac") == 0)
  5185. )
  5186. #endif
  5187. ) {
  5188. if (done_word(&ctx)) {
  5189. goto parse_error_exitcode1;
  5190. }
  5191. done_pipe(&ctx, PIPE_SEQ);
  5192. ctx.is_assignment = MAYBE_ASSIGNMENT;
  5193. debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
  5194. /* Do we sit outside of any if's, loops or case's? */
  5195. if (!HAS_KEYWORDS
  5196. IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
  5197. ) {
  5198. o_free_and_set_NULL(&ctx.word);
  5199. #if !BB_MMU
  5200. debug_printf_parse("as_string2 '%s'\n", ctx.as_string.data);
  5201. if (pstring)
  5202. *pstring = ctx.as_string.data;
  5203. else
  5204. o_free(&ctx.as_string);
  5205. #endif
  5206. if (ch != ';' && IS_NULL_PIPE(ctx.list_head)) {
  5207. /* Example: bare "{ }", "()" */
  5208. G.last_exitcode = 2; /* bash compat */
  5209. syntax_error_unexpected_ch(ch);
  5210. goto parse_error;
  5211. }
  5212. if (heredoc_cnt_ptr)
  5213. *heredoc_cnt_ptr = heredoc_cnt;
  5214. debug_printf_heredoc("parse_stream return heredoc_cnt:%d\n", heredoc_cnt);
  5215. debug_printf_parse("parse_stream return %p: "
  5216. "end_trigger char found\n",
  5217. ctx.list_head);
  5218. debug_leave();
  5219. return ctx.list_head;
  5220. }
  5221. }
  5222. if (is_blank)
  5223. continue;
  5224. /* Catch <, > before deciding whether this word is
  5225. * an assignment. a=1 2>z b=2: b=2 is still assignment */
  5226. switch (ch) {
  5227. case '>':
  5228. redir_fd = redirect_opt_num(&ctx.word);
  5229. if (done_word(&ctx)) {
  5230. goto parse_error_exitcode1;
  5231. }
  5232. redir_style = REDIRECT_OVERWRITE;
  5233. if (next == '>') {
  5234. redir_style = REDIRECT_APPEND;
  5235. ch = i_getch(input);
  5236. nommu_addchr(&ctx.as_string, ch);
  5237. }
  5238. #if 0
  5239. else if (next == '(') {
  5240. syntax_error(">(process) not supported");
  5241. goto parse_error_exitcode1;
  5242. }
  5243. #endif
  5244. if (parse_redirect(&ctx, redir_fd, redir_style, input))
  5245. goto parse_error_exitcode1;
  5246. continue; /* get next char */
  5247. case '<':
  5248. redir_fd = redirect_opt_num(&ctx.word);
  5249. if (done_word(&ctx)) {
  5250. goto parse_error_exitcode1;
  5251. }
  5252. redir_style = REDIRECT_INPUT;
  5253. if (next == '<') {
  5254. redir_style = REDIRECT_HEREDOC;
  5255. heredoc_cnt++;
  5256. debug_printf_heredoc("++heredoc_cnt=%d\n", heredoc_cnt);
  5257. ch = i_getch(input);
  5258. nommu_addchr(&ctx.as_string, ch);
  5259. } else if (next == '>') {
  5260. redir_style = REDIRECT_IO;
  5261. ch = i_getch(input);
  5262. nommu_addchr(&ctx.as_string, ch);
  5263. }
  5264. #if 0
  5265. else if (next == '(') {
  5266. syntax_error("<(process) not supported");
  5267. goto parse_error_exitcode1;
  5268. }
  5269. #endif
  5270. if (parse_redirect(&ctx, redir_fd, redir_style, input))
  5271. goto parse_error_exitcode1;
  5272. continue; /* get next char */
  5273. case '#':
  5274. if (ctx.word.length == 0 && !ctx.word.has_quoted_part) {
  5275. /* skip "#comment" */
  5276. /* note: we do not add it to &ctx.as_string */
  5277. /* TODO: in bash:
  5278. * comment inside $() goes to the next \n, even inside quoted string (!):
  5279. * cmd "$(cmd2 #comment)" - syntax error
  5280. * cmd "`cmd2 #comment`" - ok
  5281. * We accept both (comment ends where command subst ends, in both cases).
  5282. */
  5283. while (1) {
  5284. ch = i_peek(input);
  5285. if (ch == '\n') {
  5286. nommu_addchr(&ctx.as_string, '\n');
  5287. break;
  5288. }
  5289. ch = i_getch(input);
  5290. if (ch == EOF)
  5291. break;
  5292. }
  5293. continue; /* get next char */
  5294. }
  5295. break;
  5296. }
  5297. skip_end_trigger:
  5298. if (ctx.is_assignment == MAYBE_ASSIGNMENT
  5299. /* check that we are not in word in "a=1 2>word b=1": */
  5300. && !ctx.pending_redirect
  5301. ) {
  5302. /* ch is a special char and thus this word
  5303. * cannot be an assignment */
  5304. ctx.is_assignment = NOT_ASSIGNMENT;
  5305. debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
  5306. }
  5307. /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
  5308. switch (ch) {
  5309. case SPECIAL_VAR_SYMBOL:
  5310. /* Convert raw ^C to corresponding special variable reference */
  5311. o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
  5312. o_addchr(&ctx.word, SPECIAL_VAR_QUOTED_SVS);
  5313. /* fall through */
  5314. case '#':
  5315. /* non-comment #: "echo a#b" etc */
  5316. o_addchr(&ctx.word, ch);
  5317. continue; /* get next char */
  5318. case '$':
  5319. if (!parse_dollar(&ctx.as_string, &ctx.word, input, /*quote_mask:*/ 0)) {
  5320. debug_printf_parse("parse_stream parse error: "
  5321. "parse_dollar returned 0 (error)\n");
  5322. goto parse_error_exitcode1;
  5323. }
  5324. continue; /* get next char */
  5325. case '"':
  5326. ctx.word.has_quoted_part = 1;
  5327. if (next == '"' && !ctx.pending_redirect) {
  5328. i_getch(input); /* eat second " */
  5329. insert_empty_quoted_str_marker:
  5330. nommu_addchr(&ctx.as_string, next);
  5331. o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
  5332. o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
  5333. continue; /* get next char */
  5334. }
  5335. if (ctx.is_assignment == NOT_ASSIGNMENT)
  5336. ctx.word.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
  5337. if (!encode_string(&ctx.as_string, &ctx.word, input, '"'))
  5338. goto parse_error_exitcode1;
  5339. ctx.word.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
  5340. continue; /* get next char */
  5341. #if ENABLE_HUSH_TICK
  5342. case '`': {
  5343. USE_FOR_NOMMU(unsigned pos;)
  5344. o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
  5345. o_addchr(&ctx.word, '`');
  5346. USE_FOR_NOMMU(pos = ctx.word.length;)
  5347. if (!add_till_backquote(&ctx.word, input, /*in_dquote:*/ 0))
  5348. goto parse_error_exitcode1;
  5349. # if !BB_MMU
  5350. o_addstr(&ctx.as_string, ctx.word.data + pos);
  5351. o_addchr(&ctx.as_string, '`');
  5352. # endif
  5353. o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
  5354. //debug_printf_subst("SUBST RES3 '%s'\n", ctx.word.data + pos);
  5355. continue; /* get next char */
  5356. }
  5357. #endif
  5358. case ';':
  5359. #if ENABLE_HUSH_CASE
  5360. case_semi:
  5361. #endif
  5362. if (done_word(&ctx)) {
  5363. goto parse_error_exitcode1;
  5364. }
  5365. done_pipe(&ctx, PIPE_SEQ);
  5366. #if ENABLE_HUSH_CASE
  5367. /* Eat multiple semicolons, detect
  5368. * whether it means something special */
  5369. while (1) {
  5370. ch = i_peek_and_eat_bkslash_nl(input);
  5371. if (ch != ';')
  5372. break;
  5373. ch = i_getch(input);
  5374. nommu_addchr(&ctx.as_string, ch);
  5375. if (ctx.ctx_res_w == RES_CASE_BODY) {
  5376. ctx.ctx_dsemicolon = 1;
  5377. ctx.ctx_res_w = RES_MATCH;
  5378. break;
  5379. }
  5380. }
  5381. #endif
  5382. new_cmd:
  5383. /* We just finished a cmd. New one may start
  5384. * with an assignment */
  5385. ctx.is_assignment = MAYBE_ASSIGNMENT;
  5386. debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
  5387. continue; /* get next char */
  5388. case '&':
  5389. if (done_word(&ctx)) {
  5390. goto parse_error_exitcode1;
  5391. }
  5392. if (next == '&') {
  5393. ch = i_getch(input);
  5394. nommu_addchr(&ctx.as_string, ch);
  5395. done_pipe(&ctx, PIPE_AND);
  5396. } else {
  5397. done_pipe(&ctx, PIPE_BG);
  5398. }
  5399. goto new_cmd;
  5400. case '|':
  5401. if (done_word(&ctx)) {
  5402. goto parse_error_exitcode1;
  5403. }
  5404. #if ENABLE_HUSH_CASE
  5405. if (ctx.ctx_res_w == RES_MATCH)
  5406. break; /* we are in case's "word | word)" */
  5407. #endif
  5408. if (next == '|') { /* || */
  5409. ch = i_getch(input);
  5410. nommu_addchr(&ctx.as_string, ch);
  5411. done_pipe(&ctx, PIPE_OR);
  5412. } else {
  5413. /* we could pick up a file descriptor choice here
  5414. * with redirect_opt_num(), but bash doesn't do it.
  5415. * "echo foo 2| cat" yields "foo 2". */
  5416. done_command(&ctx);
  5417. }
  5418. goto new_cmd;
  5419. case '(':
  5420. #if ENABLE_HUSH_CASE
  5421. /* "case... in [(]word)..." - skip '(' */
  5422. if (ctx.ctx_res_w == RES_MATCH
  5423. && ctx.command->argv == NULL /* not (word|(... */
  5424. && ctx.word.length == 0 /* not word(... */
  5425. && ctx.word.has_quoted_part == 0 /* not ""(... */
  5426. ) {
  5427. continue; /* get next char */
  5428. }
  5429. #endif
  5430. /* fall through */
  5431. case '{': {
  5432. int n = parse_group(&ctx, input, ch);
  5433. if (n < 0) {
  5434. goto parse_error_exitcode1;
  5435. }
  5436. debug_printf_heredoc("parse_group done, needs heredocs:%d\n", n);
  5437. heredoc_cnt += n;
  5438. goto new_cmd;
  5439. }
  5440. case ')':
  5441. #if ENABLE_HUSH_CASE
  5442. if (ctx.ctx_res_w == RES_MATCH)
  5443. goto case_semi;
  5444. #endif
  5445. case '}':
  5446. /* proper use of this character is caught by end_trigger:
  5447. * if we see {, we call parse_group(..., end_trigger='}')
  5448. * and it will match } earlier (not here). */
  5449. G.last_exitcode = 2;
  5450. syntax_error_unexpected_ch(ch);
  5451. goto parse_error;
  5452. default:
  5453. if (HUSH_DEBUG)
  5454. bb_error_msg_and_die("BUG: unexpected %c", ch);
  5455. }
  5456. } /* while (1) */
  5457. parse_error_exitcode1:
  5458. G.last_exitcode = 1;
  5459. parse_error:
  5460. {
  5461. struct parse_context *pctx;
  5462. IF_HAS_KEYWORDS(struct parse_context *p2;)
  5463. /* Clean up allocated tree.
  5464. * Sample for finding leaks on syntax error recovery path.
  5465. * Run it from interactive shell, watch pmap `pidof hush`.
  5466. * while if false; then false; fi; do break; fi
  5467. * Samples to catch leaks at execution:
  5468. * while if (true | { true;}); then echo ok; fi; do break; done
  5469. * while if (true | { true;}); then echo ok; fi; do (if echo ok; break; then :; fi) | cat; break; done
  5470. */
  5471. pctx = &ctx;
  5472. do {
  5473. /* Update pipe/command counts,
  5474. * otherwise freeing may miss some */
  5475. done_pipe(pctx, PIPE_SEQ);
  5476. debug_printf_clean("freeing list %p from ctx %p\n",
  5477. pctx->list_head, pctx);
  5478. debug_print_tree(pctx->list_head, 0);
  5479. free_pipe_list(pctx->list_head);
  5480. debug_printf_clean("freed list %p\n", pctx->list_head);
  5481. #if !BB_MMU
  5482. o_free(&pctx->as_string);
  5483. #endif
  5484. IF_HAS_KEYWORDS(p2 = pctx->stack;)
  5485. if (pctx != &ctx) {
  5486. free(pctx);
  5487. }
  5488. IF_HAS_KEYWORDS(pctx = p2;)
  5489. } while (HAS_KEYWORDS && pctx);
  5490. o_free(&ctx.word);
  5491. #if !BB_MMU
  5492. if (pstring)
  5493. *pstring = NULL;
  5494. #endif
  5495. debug_leave();
  5496. return ERR_PTR;
  5497. }
  5498. }
  5499. /*** Execution routines ***/
  5500. /* Expansion can recurse, need forward decls: */
  5501. #if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
  5502. #define expand_string_to_string(str, EXP_flags, do_unbackslash) \
  5503. expand_string_to_string(str)
  5504. #endif
  5505. static char *expand_string_to_string(const char *str, int EXP_flags, int do_unbackslash);
  5506. #if ENABLE_HUSH_TICK
  5507. static int process_command_subs(o_string *dest, const char *s);
  5508. #endif
  5509. static int expand_vars_to_list(o_string *output, int n, char *arg);
  5510. /* expand_strvec_to_strvec() takes a list of strings, expands
  5511. * all variable references within and returns a pointer to
  5512. * a list of expanded strings, possibly with larger number
  5513. * of strings. (Think VAR="a b"; echo $VAR).
  5514. * This new list is allocated as a single malloc block.
  5515. * NULL-terminated list of char* pointers is at the beginning of it,
  5516. * followed by strings themselves.
  5517. * Caller can deallocate entire list by single free(list). */
  5518. /* A horde of its helpers come first: */
  5519. static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
  5520. {
  5521. while (--len >= 0) {
  5522. char c = *str++;
  5523. #if ENABLE_HUSH_BRACE_EXPANSION
  5524. if (c == '{' || c == '}') {
  5525. /* { -> \{, } -> \} */
  5526. o_addchr(o, '\\');
  5527. /* And now we want to add { or } and continue:
  5528. * o_addchr(o, c);
  5529. * continue;
  5530. * luckily, just falling through achieves this.
  5531. */
  5532. }
  5533. #endif
  5534. o_addchr(o, c);
  5535. if (c == '\\') {
  5536. /* \z -> \\\z; \<eol> -> \\<eol> */
  5537. o_addchr(o, '\\');
  5538. if (len) {
  5539. len--;
  5540. o_addchr(o, '\\');
  5541. o_addchr(o, *str++);
  5542. }
  5543. }
  5544. }
  5545. }
  5546. /* Store given string, finalizing the word and starting new one whenever
  5547. * we encounter IFS char(s). This is used for expanding variable values.
  5548. * End-of-string does NOT finalize word: think about 'echo -$VAR-'.
  5549. * Return in output->ended_in_ifs:
  5550. * 1 - ended with IFS char, else 0 (this includes case of empty str).
  5551. */
  5552. static int expand_on_ifs(o_string *output, int n, const char *str)
  5553. {
  5554. int last_is_ifs = 0;
  5555. while (1) {
  5556. int word_len;
  5557. if (!*str) /* EOL - do not finalize word */
  5558. break;
  5559. word_len = strcspn(str, G.ifs);
  5560. if (word_len) {
  5561. /* We have WORD_LEN leading non-IFS chars */
  5562. if (!(output->o_expflags & EXP_FLAG_GLOB)) {
  5563. o_addblock(output, str, word_len);
  5564. } else {
  5565. /* Protect backslashes against globbing up :)
  5566. * Example: "v='\*'; echo b$v" prints "b\*"
  5567. * (and does not try to glob on "*")
  5568. */
  5569. o_addblock_duplicate_backslash(output, str, word_len);
  5570. /*/ Why can't we do it easier? */
  5571. /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
  5572. /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
  5573. }
  5574. last_is_ifs = 0;
  5575. str += word_len;
  5576. if (!*str) /* EOL - do not finalize word */
  5577. break;
  5578. }
  5579. /* We know str here points to at least one IFS char */
  5580. last_is_ifs = 1;
  5581. str += strspn(str, G.ifs_whitespace); /* skip IFS whitespace chars */
  5582. if (!*str) /* EOL - do not finalize word */
  5583. break;
  5584. if (G.ifs_whitespace != G.ifs /* usually false ($IFS is usually all whitespace), */
  5585. && strchr(G.ifs, *str) /* the second check would fail */
  5586. ) {
  5587. /* This is a non-whitespace $IFS char */
  5588. /* Skip it and IFS whitespace chars, start new word */
  5589. str++;
  5590. str += strspn(str, G.ifs_whitespace);
  5591. goto new_word;
  5592. }
  5593. /* Start new word... but not always! */
  5594. /* Case "v=' a'; echo ''$v": we do need to finalize empty word: */
  5595. if (output->has_quoted_part
  5596. /*
  5597. * Case "v=' a'; echo $v":
  5598. * here nothing precedes the space in $v expansion,
  5599. * therefore we should not finish the word
  5600. * (IOW: if there *is* word to finalize, only then do it):
  5601. * It's okay if this accesses the byte before first argv[]:
  5602. * past call to o_save_ptr() cleared it to zero byte
  5603. * (grep for -prev-ifs-check-).
  5604. */
  5605. || output->data[output->length - 1]
  5606. ) {
  5607. new_word:
  5608. o_addchr(output, '\0');
  5609. debug_print_list("expand_on_ifs", output, n);
  5610. n = o_save_ptr(output, n);
  5611. }
  5612. }
  5613. output->ended_in_ifs = last_is_ifs;
  5614. debug_print_list("expand_on_ifs[1]", output, n);
  5615. return n;
  5616. }
  5617. /* Helper to expand $((...)) and heredoc body. These act as if
  5618. * they are in double quotes, with the exception that they are not :).
  5619. * Just the rules are similar: "expand only $var and `cmd`"
  5620. *
  5621. * Returns malloced string.
  5622. * As an optimization, we return NULL if expansion is not needed.
  5623. */
  5624. static char *encode_then_expand_string(const char *str)
  5625. {
  5626. char *exp_str;
  5627. struct in_str input;
  5628. o_string dest = NULL_O_STRING;
  5629. const char *cp;
  5630. cp = str;
  5631. for (;;) {
  5632. if (!*cp) return NULL; /* string has no special chars */
  5633. if (*cp == '$') break;
  5634. if (*cp == '\\') break;
  5635. #if ENABLE_HUSH_TICK
  5636. if (*cp == '`') break;
  5637. #endif
  5638. cp++;
  5639. }
  5640. /* We need to expand. Example:
  5641. * echo $(($a + `echo 1`)) $((1 + $((2)) ))
  5642. */
  5643. setup_string_in_str(&input, str);
  5644. encode_string(NULL, &dest, &input, EOF);
  5645. //TODO: error check (encode_string returns 0 on error)?
  5646. //bb_error_msg("'%s' -> '%s'", str, dest.data);
  5647. exp_str = expand_string_to_string(dest.data,
  5648. EXP_FLAG_ESC_GLOB_CHARS,
  5649. /*unbackslash:*/ 1
  5650. );
  5651. //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
  5652. o_free(&dest);
  5653. return exp_str;
  5654. }
  5655. static const char *first_special_char_in_vararg(const char *cp)
  5656. {
  5657. for (;;) {
  5658. if (!*cp) return NULL; /* string has no special chars */
  5659. if (*cp == '$') return cp;
  5660. if (*cp == '\\') return cp;
  5661. if (*cp == '\'') return cp;
  5662. if (*cp == '"') return cp;
  5663. #if ENABLE_HUSH_TICK
  5664. if (*cp == '`') return cp;
  5665. #endif
  5666. /* dquoted "${x:+ARG}" should not glob, therefore
  5667. * '*' et al require some non-literal processing: */
  5668. if (*cp == '*') return cp;
  5669. if (*cp == '?') return cp;
  5670. if (*cp == '[') return cp;
  5671. cp++;
  5672. }
  5673. }
  5674. /* Expanding ARG in ${var#ARG}, ${var%ARG}, or ${var/ARG/ARG}.
  5675. * These can contain single- and double-quoted strings,
  5676. * and treated as if the ARG string is initially unquoted. IOW:
  5677. * ${var#ARG} and "${var#ARG}" treat ARG the same (ARG can even be
  5678. * a dquoted string: "${var#"zz"}"), the difference only comes later
  5679. * (word splitting and globbing of the ${var...} result).
  5680. */
  5681. #if !BASH_PATTERN_SUBST
  5682. #define encode_then_expand_vararg(str, handle_squotes, do_unbackslash) \
  5683. encode_then_expand_vararg(str, handle_squotes)
  5684. #endif
  5685. static char *encode_then_expand_vararg(const char *str, int handle_squotes, int do_unbackslash)
  5686. {
  5687. #if !BASH_PATTERN_SUBST && ENABLE_HUSH_CASE
  5688. const int do_unbackslash = 0;
  5689. #endif
  5690. char *exp_str;
  5691. struct in_str input;
  5692. o_string dest = NULL_O_STRING;
  5693. if (!first_special_char_in_vararg(str)) {
  5694. /* string has no special chars */
  5695. return NULL;
  5696. }
  5697. setup_string_in_str(&input, str);
  5698. dest.data = xzalloc(1); /* start as "", not as NULL */
  5699. exp_str = NULL;
  5700. for (;;) {
  5701. int ch;
  5702. ch = i_getch(&input);
  5703. debug_printf_parse("%s: ch=%c (%d) escape=%d\n",
  5704. __func__, ch, ch, !!dest.o_expflags);
  5705. if (!dest.o_expflags) {
  5706. if (ch == EOF)
  5707. break;
  5708. if (handle_squotes && ch == '\'') {
  5709. if (!add_till_single_quote_dquoted(&dest, &input))
  5710. goto ret; /* error */
  5711. continue;
  5712. }
  5713. }
  5714. if (ch == EOF) {
  5715. syntax_error_unterm_ch('"');
  5716. goto ret; /* error */
  5717. }
  5718. if (ch == '"') {
  5719. dest.o_expflags ^= EXP_FLAG_ESC_GLOB_CHARS;
  5720. continue;
  5721. }
  5722. if (ch == '\\') {
  5723. ch = i_getch(&input);
  5724. if (ch == EOF) {
  5725. //example? error message? syntax_error_unterm_ch('"');
  5726. debug_printf_parse("%s: error: \\<eof>\n", __func__);
  5727. goto ret;
  5728. }
  5729. o_addqchr(&dest, ch);
  5730. continue;
  5731. }
  5732. if (ch == '$') {
  5733. if (!parse_dollar(NULL, &dest, &input, /*quote_mask:*/ 0x80)) {
  5734. debug_printf_parse("%s: error: parse_dollar returned 0 (error)\n", __func__);
  5735. goto ret;
  5736. }
  5737. continue;
  5738. }
  5739. #if ENABLE_HUSH_TICK
  5740. if (ch == '`') {
  5741. //unsigned pos = dest->length;
  5742. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  5743. o_addchr(&dest, 0x80 | '`');
  5744. if (!add_till_backquote(&dest, &input,
  5745. /*in_dquote:*/ dest.o_expflags /* nonzero if EXP_FLAG_ESC_GLOB_CHARS set */
  5746. )
  5747. ) {
  5748. goto ret; /* error */
  5749. }
  5750. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  5751. //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
  5752. continue;
  5753. }
  5754. #endif
  5755. o_addQchr(&dest, ch);
  5756. } /* for (;;) */
  5757. debug_printf_parse("encode: '%s' -> '%s'\n", str, dest.data);
  5758. exp_str = expand_string_to_string(dest.data,
  5759. do_unbackslash ? EXP_FLAG_ESC_GLOB_CHARS : 0,
  5760. do_unbackslash
  5761. );
  5762. ret:
  5763. debug_printf_parse("expand: '%s' -> '%s'\n", dest.data, exp_str);
  5764. o_free(&dest);
  5765. return exp_str;
  5766. }
  5767. /* Expanding ARG in ${var+ARG}, ${var-ARG}
  5768. */
  5769. static int encode_then_append_var_plusminus(o_string *output, int n,
  5770. char *str, int dquoted)
  5771. {
  5772. struct in_str input;
  5773. o_string dest = NULL_O_STRING;
  5774. if (!first_special_char_in_vararg(str)
  5775. && '\0' == str[strcspn(str, G.ifs)]
  5776. ) {
  5777. /* string has no special chars
  5778. * && string has no $IFS chars
  5779. */
  5780. if (dquoted) {
  5781. /* Prints 1 (quoted expansion is a "" word, not nothing):
  5782. * set -- "${notexist-}"; echo $#
  5783. */
  5784. output->has_quoted_part = 1;
  5785. }
  5786. return expand_vars_to_list(output, n, str);
  5787. }
  5788. setup_string_in_str(&input, str);
  5789. for (;;) {
  5790. int ch;
  5791. ch = i_getch(&input);
  5792. debug_printf_parse("%s: ch=%c (%d) escape=%x\n",
  5793. __func__, ch, ch, dest.o_expflags);
  5794. if (!dest.o_expflags) {
  5795. if (ch == EOF)
  5796. break;
  5797. if (!dquoted && strchr(G.ifs, ch)) {
  5798. /* PREFIX${x:d${e}f ...} and we met space: expand "d${e}f" and start new word.
  5799. * do not assume we are at the start of the word (PREFIX above).
  5800. */
  5801. if (dest.data) {
  5802. n = expand_vars_to_list(output, n, dest.data);
  5803. o_free_and_set_NULL(&dest);
  5804. o_addchr(output, '\0');
  5805. n = o_save_ptr(output, n); /* create next word */
  5806. } else
  5807. if (output->length != o_get_last_ptr(output, n)
  5808. || output->has_quoted_part
  5809. ) {
  5810. /* For these cases:
  5811. * f() { for i; do echo "|$i|"; done; }; x=x
  5812. * f a${x:+ }b # 1st condition
  5813. * |a|
  5814. * |b|
  5815. * f ""${x:+ }b # 2nd condition
  5816. * ||
  5817. * |b|
  5818. */
  5819. o_addchr(output, '\0');
  5820. n = o_save_ptr(output, n); /* create next word */
  5821. }
  5822. continue;
  5823. }
  5824. if (!dquoted && ch == '\'') {
  5825. if (!add_till_single_quote_dquoted(&dest, &input))
  5826. goto ret; /* error */
  5827. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  5828. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  5829. continue;
  5830. }
  5831. }
  5832. if (ch == EOF) {
  5833. syntax_error_unterm_ch('"');
  5834. goto ret; /* error */
  5835. }
  5836. if (ch == '"') {
  5837. dest.o_expflags ^= EXP_FLAG_ESC_GLOB_CHARS;
  5838. if (dest.o_expflags) {
  5839. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  5840. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  5841. }
  5842. continue;
  5843. }
  5844. if (ch == '\\') {
  5845. ch = i_getch(&input);
  5846. if (ch == EOF) {
  5847. //example? error message? syntax_error_unterm_ch('"');
  5848. debug_printf_parse("%s: error: \\<eof>\n", __func__);
  5849. goto ret;
  5850. }
  5851. o_addqchr(&dest, ch);
  5852. continue;
  5853. }
  5854. if (ch == '$') {
  5855. if (!parse_dollar(NULL, &dest, &input, /*quote_mask:*/ (dest.o_expflags || dquoted) ? 0x80 : 0)) {
  5856. debug_printf_parse("%s: error: parse_dollar returned 0 (error)\n", __func__);
  5857. goto ret;
  5858. }
  5859. continue;
  5860. }
  5861. #if ENABLE_HUSH_TICK
  5862. if (ch == '`') {
  5863. //unsigned pos = dest->length;
  5864. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  5865. o_addchr(&dest, (dest.o_expflags || dquoted) ? 0x80 | '`' : '`');
  5866. if (!add_till_backquote(&dest, &input,
  5867. /*in_dquote:*/ dest.o_expflags /* nonzero if EXP_FLAG_ESC_GLOB_CHARS set */
  5868. )
  5869. ) {
  5870. goto ret; /* error */
  5871. }
  5872. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  5873. //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
  5874. continue;
  5875. }
  5876. #endif
  5877. if (dquoted) {
  5878. /* Always glob-protect if in dquotes:
  5879. * x=x; echo "${x:+/bin/c*}" - prints: /bin/c*
  5880. * x=x; echo "${x:+"/bin/c*"}" - prints: /bin/c*
  5881. */
  5882. o_addqchr(&dest, ch);
  5883. } else {
  5884. /* Glob-protect only if char is quoted:
  5885. * x=x; echo ${x:+/bin/c*} - prints many filenames
  5886. * x=x; echo ${x:+"/bin/c*"} - prints: /bin/c*
  5887. */
  5888. o_addQchr(&dest, ch);
  5889. }
  5890. } /* for (;;) */
  5891. if (dest.data) {
  5892. n = expand_vars_to_list(output, n, dest.data);
  5893. }
  5894. ret:
  5895. o_free(&dest);
  5896. return n;
  5897. }
  5898. #if ENABLE_FEATURE_SH_MATH
  5899. static arith_t expand_and_evaluate_arith(const char *arg, const char **errmsg_p)
  5900. {
  5901. arith_state_t math_state;
  5902. arith_t res;
  5903. char *exp_str;
  5904. math_state.lookupvar = get_local_var_value;
  5905. math_state.setvar = set_local_var_from_halves;
  5906. //math_state.endofname = endofname;
  5907. exp_str = encode_then_expand_string(arg);
  5908. res = arith(&math_state, exp_str ? exp_str : arg);
  5909. free(exp_str);
  5910. if (errmsg_p)
  5911. *errmsg_p = math_state.errmsg;
  5912. if (math_state.errmsg)
  5913. msg_and_die_if_script(math_state.errmsg);
  5914. return res;
  5915. }
  5916. #endif
  5917. #if BASH_PATTERN_SUBST
  5918. /* ${var/[/]pattern[/repl]} helpers */
  5919. static char *strstr_pattern(char *val, const char *pattern, int *size)
  5920. {
  5921. while (1) {
  5922. char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
  5923. debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
  5924. if (end) {
  5925. *size = end - val;
  5926. return val;
  5927. }
  5928. if (*val == '\0')
  5929. return NULL;
  5930. /* Optimization: if "*pat" did not match the start of "string",
  5931. * we know that "tring", "ring" etc will not match too:
  5932. */
  5933. if (pattern[0] == '*')
  5934. return NULL;
  5935. val++;
  5936. }
  5937. }
  5938. static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
  5939. {
  5940. char *result = NULL;
  5941. unsigned res_len = 0;
  5942. unsigned repl_len = strlen(repl);
  5943. /* Null pattern never matches, including if "var" is empty */
  5944. if (!pattern[0])
  5945. return result; /* NULL, no replaces happened */
  5946. while (1) {
  5947. int size;
  5948. char *s = strstr_pattern(val, pattern, &size);
  5949. if (!s)
  5950. break;
  5951. result = xrealloc(result, res_len + (s - val) + repl_len + 1);
  5952. strcpy(mempcpy(result + res_len, val, s - val), repl);
  5953. res_len += (s - val) + repl_len;
  5954. debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
  5955. val = s + size;
  5956. if (exp_op == '/')
  5957. break;
  5958. }
  5959. if (*val && result) {
  5960. result = xrealloc(result, res_len + strlen(val) + 1);
  5961. strcpy(result + res_len, val);
  5962. debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
  5963. }
  5964. debug_printf_varexp("result:'%s'\n", result);
  5965. return result;
  5966. }
  5967. #endif /* BASH_PATTERN_SUBST */
  5968. static int append_str_maybe_ifs_split(o_string *output, int n,
  5969. int first_ch, const char *val)
  5970. {
  5971. if (!(first_ch & 0x80)) { /* unquoted $VAR */
  5972. debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val,
  5973. !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
  5974. if (val && val[0])
  5975. n = expand_on_ifs(output, n, val);
  5976. } else { /* quoted "$VAR" */
  5977. output->has_quoted_part = 1;
  5978. debug_printf_expand("quoted '%s', output->o_escape:%d\n", val,
  5979. !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
  5980. if (val && val[0])
  5981. o_addQstr(output, val);
  5982. }
  5983. return n;
  5984. }
  5985. /* Handle <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
  5986. */
  5987. static NOINLINE int expand_one_var(o_string *output, int n,
  5988. int first_ch, char *arg, char **pp)
  5989. {
  5990. const char *val;
  5991. char *to_be_freed;
  5992. char *p;
  5993. char *var;
  5994. char exp_op;
  5995. char exp_save = exp_save; /* for compiler */
  5996. char *exp_saveptr; /* points to expansion operator */
  5997. char *exp_word = exp_word; /* for compiler */
  5998. char arg0;
  5999. val = NULL;
  6000. to_be_freed = NULL;
  6001. p = *pp;
  6002. *p = '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
  6003. var = arg;
  6004. exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
  6005. arg0 = arg[0];
  6006. arg[0] = (arg0 & 0x7f);
  6007. exp_op = 0;
  6008. if (arg[0] == '#' && arg[1] /* ${#...} but not ${#} */
  6009. && (!exp_saveptr /* and ( not(${#<op_char>...}) */
  6010. || (arg[2] == '\0' && strchr(SPECIAL_VARS_STR, arg[1])) /* or ${#C} "len of $C" ) */
  6011. ) /* NB: skipping ^^^specvar check mishandles ${#::2} */
  6012. ) {
  6013. /* It must be length operator: ${#var} */
  6014. var++;
  6015. exp_op = 'L';
  6016. } else {
  6017. /* Maybe handle parameter expansion */
  6018. if (exp_saveptr /* if 2nd char is one of expansion operators */
  6019. && strchr(NUMERIC_SPECVARS_STR, arg[0]) /* 1st char is special variable */
  6020. ) {
  6021. /* ${?:0}, ${#[:]%0} etc */
  6022. exp_saveptr = var + 1;
  6023. } else {
  6024. /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
  6025. exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
  6026. }
  6027. exp_op = exp_save = *exp_saveptr;
  6028. if (exp_op) {
  6029. exp_word = exp_saveptr + 1;
  6030. if (exp_op == ':') {
  6031. exp_op = *exp_word++;
  6032. //TODO: try ${var:} and ${var:bogus} in non-bash config
  6033. if (BASH_SUBSTR
  6034. && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
  6035. ) {
  6036. /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
  6037. exp_op = ':';
  6038. exp_word--;
  6039. }
  6040. }
  6041. *exp_saveptr = '\0';
  6042. } /* else: it's not an expansion op, but bare ${var} */
  6043. }
  6044. /* Look up the variable in question */
  6045. if (isdigit(var[0])) {
  6046. /* parse_dollar should have vetted var for us */
  6047. int nn = xatoi_positive(var);
  6048. if (nn < G.global_argc)
  6049. val = G.global_argv[nn];
  6050. /* else val remains NULL: $N with too big N */
  6051. } else {
  6052. switch (var[0]) {
  6053. case '$': /* pid */
  6054. val = utoa(G.root_pid);
  6055. break;
  6056. case '!': /* bg pid */
  6057. val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
  6058. break;
  6059. case '?': /* exitcode */
  6060. val = utoa(G.last_exitcode);
  6061. break;
  6062. case '#': /* argc */
  6063. val = utoa(G.global_argc ? G.global_argc-1 : 0);
  6064. break;
  6065. case '-': { /* active options */
  6066. /* Check set_mode() to see what option chars we support */
  6067. char *cp;
  6068. val = cp = G.optstring_buf;
  6069. if (G.o_opt[OPT_O_ERREXIT])
  6070. *cp++ = 'e';
  6071. if (G_interactive_fd)
  6072. *cp++ = 'i';
  6073. if (G_x_mode)
  6074. *cp++ = 'x';
  6075. /* If G.o_opt[OPT_O_NOEXEC] is true,
  6076. * commands read but are not executed,
  6077. * so $- can not execute too, 'n' is never seen in $-.
  6078. */
  6079. if (G.opt_c)
  6080. *cp++ = 'c';
  6081. if (G.opt_s)
  6082. *cp++ = 's';
  6083. *cp = '\0';
  6084. break;
  6085. }
  6086. default:
  6087. val = get_local_var_value(var);
  6088. }
  6089. }
  6090. /* Handle any expansions */
  6091. if (exp_op == 'L') {
  6092. reinit_unicode_for_hush();
  6093. debug_printf_expand("expand: length(%s)=", val);
  6094. val = utoa(val ? unicode_strlen(val) : 0);
  6095. debug_printf_expand("%s\n", val);
  6096. } else if (exp_op) {
  6097. if (exp_op == '%' || exp_op == '#') {
  6098. /* Standard-mandated substring removal ops:
  6099. * ${parameter%word} - remove smallest suffix pattern
  6100. * ${parameter%%word} - remove largest suffix pattern
  6101. * ${parameter#word} - remove smallest prefix pattern
  6102. * ${parameter##word} - remove largest prefix pattern
  6103. *
  6104. * Word is expanded to produce a glob pattern.
  6105. * Then var's value is matched to it and matching part removed.
  6106. */
  6107. //FIXME: ${x#...${...}...}
  6108. //should evaluate inner ${...} even if x is "" and no shrinking of it is possible -
  6109. //inner ${...} may have side effects!
  6110. if (val && val[0]) {
  6111. char *t;
  6112. char *exp_exp_word;
  6113. char *loc;
  6114. unsigned scan_flags = pick_scan(exp_op, *exp_word);
  6115. if (exp_op == *exp_word) /* ## or %% */
  6116. exp_word++;
  6117. debug_printf_expand("expand: exp_word:'%s'\n", exp_word);
  6118. exp_exp_word = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 0);
  6119. if (exp_exp_word)
  6120. exp_word = exp_exp_word;
  6121. debug_printf_expand("expand: exp_word:'%s'\n", exp_word);
  6122. /*
  6123. * HACK ALERT. We depend here on the fact that
  6124. * G.global_argv and results of utoa and get_local_var_value
  6125. * are actually in writable memory:
  6126. * scan_and_match momentarily stores NULs there.
  6127. */
  6128. t = (char*)val;
  6129. loc = scan_and_match(t, exp_word, scan_flags);
  6130. debug_printf_expand("op:%c str:'%s' pat:'%s' res:'%s'\n", exp_op, t, exp_word, loc);
  6131. free(exp_exp_word);
  6132. if (loc) { /* match was found */
  6133. if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
  6134. val = loc; /* take right part */
  6135. else /* %[%] */
  6136. val = to_be_freed = xstrndup(val, loc - val); /* left */
  6137. }
  6138. }
  6139. }
  6140. #if BASH_PATTERN_SUBST
  6141. else if (exp_op == '/' || exp_op == '\\') {
  6142. /* It's ${var/[/]pattern[/repl]} thing.
  6143. * Note that in encoded form it has TWO parts:
  6144. * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
  6145. * and if // is used, it is encoded as \:
  6146. * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
  6147. */
  6148. if (val && val[0]) {
  6149. /* pattern uses non-standard expansion.
  6150. * repl should be unbackslashed and globbed
  6151. * by the usual expansion rules:
  6152. * >az >bz
  6153. * v='a bz'; echo "${v/a*z/a*z}" #prints "a*z"
  6154. * v='a bz'; echo "${v/a*z/\z}" #prints "z"
  6155. * v='a bz'; echo ${v/a*z/a*z} #prints "az"
  6156. * v='a bz'; echo ${v/a*z/\z} #prints "z"
  6157. * (note that a*z _pattern_ is never globbed!)
  6158. */
  6159. char *pattern, *repl, *t;
  6160. pattern = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 0);
  6161. if (!pattern)
  6162. pattern = xstrdup(exp_word);
  6163. debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
  6164. *p++ = SPECIAL_VAR_SYMBOL;
  6165. exp_word = p;
  6166. p = strchr(p, SPECIAL_VAR_SYMBOL);
  6167. *p = '\0';
  6168. repl = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 1);
  6169. debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
  6170. /* HACK ALERT. We depend here on the fact that
  6171. * G.global_argv and results of utoa and get_local_var_value
  6172. * are actually in writable memory:
  6173. * replace_pattern momentarily stores NULs there. */
  6174. t = (char*)val;
  6175. to_be_freed = replace_pattern(t,
  6176. pattern,
  6177. (repl ? repl : exp_word),
  6178. exp_op);
  6179. if (to_be_freed) /* at least one replace happened */
  6180. val = to_be_freed;
  6181. free(pattern);
  6182. free(repl);
  6183. } else {
  6184. /* Empty variable always gives nothing */
  6185. // "v=''; echo ${v/*/w}" prints "", not "w"
  6186. /* Just skip "replace" part */
  6187. *p++ = SPECIAL_VAR_SYMBOL;
  6188. p = strchr(p, SPECIAL_VAR_SYMBOL);
  6189. *p = '\0';
  6190. }
  6191. }
  6192. #endif /* BASH_PATTERN_SUBST */
  6193. else if (exp_op == ':') {
  6194. #if BASH_SUBSTR && ENABLE_FEATURE_SH_MATH
  6195. /* It's ${var:N[:M]} bashism.
  6196. * Note that in encoded form it has TWO parts:
  6197. * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
  6198. */
  6199. arith_t beg, len;
  6200. const char *errmsg;
  6201. beg = expand_and_evaluate_arith(exp_word, &errmsg);
  6202. if (errmsg)
  6203. goto arith_err;
  6204. debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
  6205. *p++ = SPECIAL_VAR_SYMBOL;
  6206. exp_word = p;
  6207. p = strchr(p, SPECIAL_VAR_SYMBOL);
  6208. *p = '\0';
  6209. len = expand_and_evaluate_arith(exp_word, &errmsg);
  6210. if (errmsg)
  6211. goto arith_err;
  6212. debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
  6213. if (beg < 0) {
  6214. /* negative beg counts from the end */
  6215. beg = (arith_t)strlen(val) + beg;
  6216. if (beg < 0) /* ${v: -999999} is "" */
  6217. beg = len = 0;
  6218. }
  6219. debug_printf_varexp("from val:'%s'\n", val);
  6220. if (len < 0) {
  6221. /* in bash, len=-n means strlen()-n */
  6222. len = (arith_t)strlen(val) - beg + len;
  6223. if (len < 0) /* bash compat */
  6224. msg_and_die_if_script("%s: substring expression < 0", var);
  6225. }
  6226. if (len <= 0 || !val || beg >= strlen(val)) {
  6227. arith_err:
  6228. val = NULL;
  6229. } else {
  6230. /* Paranoia. What if user entered 9999999999999
  6231. * which fits in arith_t but not int? */
  6232. if (len >= INT_MAX)
  6233. len = INT_MAX;
  6234. val = to_be_freed = xstrndup(val + beg, len);
  6235. }
  6236. debug_printf_varexp("val:'%s'\n", val);
  6237. #else /* not (HUSH_SUBSTR_EXPANSION && FEATURE_SH_MATH) */
  6238. msg_and_die_if_script("malformed ${%s:...}", var);
  6239. val = NULL;
  6240. #endif
  6241. } else { /* one of "-=+?" */
  6242. /* Standard-mandated substitution ops:
  6243. * ${var?word} - indicate error if unset
  6244. * If var is unset, word (or a message indicating it is unset
  6245. * if word is null) is written to standard error
  6246. * and the shell exits with a non-zero exit status.
  6247. * Otherwise, the value of var is substituted.
  6248. * ${var-word} - use default value
  6249. * If var is unset, word is substituted.
  6250. * ${var=word} - assign and use default value
  6251. * If var is unset, word is assigned to var.
  6252. * In all cases, final value of var is substituted.
  6253. * ${var+word} - use alternative value
  6254. * If var is unset, null is substituted.
  6255. * Otherwise, word is substituted.
  6256. *
  6257. * Word is subjected to tilde expansion, parameter expansion,
  6258. * command substitution, and arithmetic expansion.
  6259. * If word is not needed, it is not expanded.
  6260. *
  6261. * Colon forms (${var:-word}, ${var:=word} etc) do the same,
  6262. * but also treat null var as if it is unset.
  6263. *
  6264. * Word-splitting and single quote behavior:
  6265. *
  6266. * $ f() { for i; do echo "|$i|"; done; };
  6267. *
  6268. * $ x=; f ${x:?'x y' z}
  6269. * bash: x: x y z #BUG: does not abort, ${} results in empty expansion
  6270. * $ x=; f "${x:?'x y' z}"
  6271. * bash: x: x y z # dash prints: dash: x: 'x y' z #BUG: does not abort, ${} results in ""
  6272. *
  6273. * $ x=; f ${x:='x y' z}
  6274. * |x|
  6275. * |y|
  6276. * |z|
  6277. * $ x=; f "${x:='x y' z}"
  6278. * |'x y' z|
  6279. *
  6280. * $ x=x; f ${x:+'x y' z}
  6281. * |x y|
  6282. * |z|
  6283. * $ x=x; f "${x:+'x y' z}"
  6284. * |'x y' z|
  6285. *
  6286. * $ x=; f ${x:-'x y' z}
  6287. * |x y|
  6288. * |z|
  6289. * $ x=; f "${x:-'x y' z}"
  6290. * |'x y' z|
  6291. */
  6292. int use_word = (!val || ((exp_save == ':') && !val[0]));
  6293. if (exp_op == '+')
  6294. use_word = !use_word;
  6295. debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
  6296. (exp_save == ':') ? "true" : "false", use_word);
  6297. if (use_word) {
  6298. if (exp_op == '+' || exp_op == '-') {
  6299. /* ${var+word} - use alternative value */
  6300. /* ${var-word} - use default value */
  6301. n = encode_then_append_var_plusminus(output, n, exp_word,
  6302. /*dquoted:*/ (arg0 & 0x80)
  6303. );
  6304. val = NULL;
  6305. } else {
  6306. /* ${var?word} - indicate error if unset */
  6307. /* ${var=word} - assign and use default value */
  6308. to_be_freed = encode_then_expand_vararg(exp_word,
  6309. /*handle_squotes:*/ !(arg0 & 0x80),
  6310. /*unbackslash:*/ 0
  6311. );
  6312. if (to_be_freed)
  6313. exp_word = to_be_freed;
  6314. if (exp_op == '?') {
  6315. /* mimic bash message */
  6316. msg_and_die_if_script("%s: %s",
  6317. var,
  6318. exp_word[0]
  6319. ? exp_word
  6320. : "parameter null or not set"
  6321. /* ash has more specific messages, a-la: */
  6322. /*: (exp_save == ':' ? "parameter null or not set" : "parameter not set")*/
  6323. );
  6324. //TODO: how interactive bash aborts expansion mid-command?
  6325. //It aborts the entire line, returns to prompt:
  6326. // $ f() { for i; do echo "|$i|"; done; }; x=; f "${x:?'x y' z}"; echo YO
  6327. // bash: x: x y z
  6328. // $
  6329. // ("echo YO" is not executed, neither the f function call)
  6330. } else {
  6331. val = exp_word;
  6332. }
  6333. if (exp_op == '=') {
  6334. /* ${var=[word]} or ${var:=[word]} */
  6335. if (isdigit(var[0]) || var[0] == '#') {
  6336. /* mimic bash message */
  6337. msg_and_die_if_script("$%s: cannot assign in this way", var);
  6338. val = NULL;
  6339. } else {
  6340. char *new_var = xasprintf("%s=%s", var, val);
  6341. set_local_var(new_var, /*flag:*/ 0);
  6342. }
  6343. }
  6344. }
  6345. }
  6346. } /* one of "-=+?" */
  6347. *exp_saveptr = exp_save;
  6348. } /* if (exp_op) */
  6349. arg[0] = arg0;
  6350. *pp = p;
  6351. n = append_str_maybe_ifs_split(output, n, first_ch, val);
  6352. free(to_be_freed);
  6353. return n;
  6354. }
  6355. /* Expand all variable references in given string, adding words to list[]
  6356. * at n, n+1,... positions. Return updated n (so that list[n] is next one
  6357. * to be filled). This routine is extremely tricky: has to deal with
  6358. * variables/parameters with whitespace, $* and $@, and constructs like
  6359. * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
  6360. static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
  6361. {
  6362. /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
  6363. * expansion of right-hand side of assignment == 1-element expand.
  6364. */
  6365. char cant_be_null = 0; /* only bit 0x80 matters */
  6366. char *p;
  6367. debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
  6368. !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
  6369. debug_print_list("expand_vars_to_list[0]", output, n);
  6370. while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
  6371. char first_ch;
  6372. #if ENABLE_FEATURE_SH_MATH
  6373. char arith_buf[sizeof(arith_t)*3 + 2];
  6374. #endif
  6375. if (output->ended_in_ifs) {
  6376. o_addchr(output, '\0');
  6377. n = o_save_ptr(output, n);
  6378. output->ended_in_ifs = 0;
  6379. }
  6380. o_addblock(output, arg, p - arg);
  6381. debug_print_list("expand_vars_to_list[1]", output, n);
  6382. arg = ++p;
  6383. p = strchr(p, SPECIAL_VAR_SYMBOL);
  6384. /* Fetch special var name (if it is indeed one of them)
  6385. * and quote bit, force the bit on if singleword expansion -
  6386. * important for not getting v=$@ expand to many words. */
  6387. first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
  6388. /* Is this variable quoted and thus expansion can't be null?
  6389. * "$@" is special. Even if quoted, it can still
  6390. * expand to nothing (not even an empty string),
  6391. * thus it is excluded. */
  6392. if ((first_ch & 0x7f) != '@')
  6393. cant_be_null |= first_ch;
  6394. switch (first_ch & 0x7f) {
  6395. /* Highest bit in first_ch indicates that var is double-quoted */
  6396. case '*':
  6397. case '@': {
  6398. int i;
  6399. if (!G.global_argv[1])
  6400. break;
  6401. i = 1;
  6402. cant_be_null |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
  6403. if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
  6404. while (G.global_argv[i]) {
  6405. n = expand_on_ifs(output, n, G.global_argv[i]);
  6406. debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
  6407. if (G.global_argv[i++][0] && G.global_argv[i]) {
  6408. /* this argv[] is not empty and not last:
  6409. * put terminating NUL, start new word */
  6410. o_addchr(output, '\0');
  6411. debug_print_list("expand_vars_to_list[2]", output, n);
  6412. n = o_save_ptr(output, n);
  6413. debug_print_list("expand_vars_to_list[3]", output, n);
  6414. }
  6415. }
  6416. } else
  6417. /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
  6418. * and in this case should treat it like '$*' - see 'else...' below */
  6419. if (first_ch == (char)('@'|0x80) /* quoted $@ */
  6420. && !(output->o_expflags & EXP_FLAG_SINGLEWORD) /* not v="$@" case */
  6421. ) {
  6422. while (1) {
  6423. o_addQstr(output, G.global_argv[i]);
  6424. if (++i >= G.global_argc)
  6425. break;
  6426. o_addchr(output, '\0');
  6427. debug_print_list("expand_vars_to_list[4]", output, n);
  6428. n = o_save_ptr(output, n);
  6429. }
  6430. } else { /* quoted $* (or v="$@" case): add as one word */
  6431. while (1) {
  6432. o_addQstr(output, G.global_argv[i]);
  6433. if (!G.global_argv[++i])
  6434. break;
  6435. if (G.ifs[0])
  6436. o_addchr(output, G.ifs[0]);
  6437. }
  6438. output->has_quoted_part = 1;
  6439. }
  6440. break;
  6441. }
  6442. case SPECIAL_VAR_SYMBOL: {
  6443. /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
  6444. /* "Empty variable", used to make "" etc to not disappear */
  6445. output->has_quoted_part = 1;
  6446. cant_be_null = 0x80;
  6447. arg++;
  6448. break;
  6449. }
  6450. case SPECIAL_VAR_QUOTED_SVS:
  6451. /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_QUOTED_SVS><SPECIAL_VAR_SYMBOL> */
  6452. /* "^C variable", represents literal ^C char (possible in scripts) */
  6453. o_addchr(output, SPECIAL_VAR_SYMBOL);
  6454. arg++;
  6455. break;
  6456. #if ENABLE_HUSH_TICK
  6457. case '`': {
  6458. /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
  6459. o_string subst_result = NULL_O_STRING;
  6460. *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
  6461. arg++;
  6462. /* Can't just stuff it into output o_string,
  6463. * expanded result may need to be globbed
  6464. * and $IFS-split */
  6465. debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
  6466. G.last_exitcode = process_command_subs(&subst_result, arg);
  6467. G.expand_exitcode = G.last_exitcode;
  6468. debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
  6469. n = append_str_maybe_ifs_split(output, n, first_ch, subst_result.data);
  6470. o_free(&subst_result);
  6471. break;
  6472. }
  6473. #endif
  6474. #if ENABLE_FEATURE_SH_MATH
  6475. case '+': {
  6476. /* <SPECIAL_VAR_SYMBOL>+arith<SPECIAL_VAR_SYMBOL> */
  6477. arith_t res;
  6478. arg++; /* skip '+' */
  6479. *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
  6480. debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
  6481. res = expand_and_evaluate_arith(arg, NULL);
  6482. debug_printf_subst("ARITH RES '"ARITH_FMT"'\n", res);
  6483. sprintf(arith_buf, ARITH_FMT, res);
  6484. if (res < 0
  6485. && first_ch == (char)('+'|0x80)
  6486. /* && (output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS) */
  6487. ) {
  6488. /* Quoted negative ariths, like filename[0"$((-9))"],
  6489. * should not be interpreted as glob ranges.
  6490. * Convert leading '-' to '\-':
  6491. */
  6492. o_grow_by(output, 1);
  6493. output->data[output->length++] = '\\';
  6494. }
  6495. o_addstr(output, arith_buf);
  6496. break;
  6497. }
  6498. #endif
  6499. default:
  6500. /* <SPECIAL_VAR_SYMBOL>varname[ops]<SPECIAL_VAR_SYMBOL> */
  6501. n = expand_one_var(output, n, first_ch, arg, &p);
  6502. break;
  6503. } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
  6504. /* Restore NULL'ed SPECIAL_VAR_SYMBOL.
  6505. * Do the check to avoid writing to a const string. */
  6506. if (*p != SPECIAL_VAR_SYMBOL)
  6507. *p = SPECIAL_VAR_SYMBOL;
  6508. arg = ++p;
  6509. } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
  6510. if (*arg) {
  6511. /* handle trailing string */
  6512. if (output->ended_in_ifs) {
  6513. o_addchr(output, '\0');
  6514. n = o_save_ptr(output, n);
  6515. }
  6516. debug_print_list("expand_vars_to_list[a]", output, n);
  6517. /* this part is literal, and it was already pre-quoted
  6518. * if needed (much earlier), do not use o_addQstr here!
  6519. */
  6520. o_addstr(output, arg);
  6521. debug_print_list("expand_vars_to_list[b]", output, n);
  6522. } else
  6523. if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
  6524. && !(cant_be_null & 0x80) /* and all vars were not quoted */
  6525. && !output->has_quoted_part
  6526. ) {
  6527. n--;
  6528. /* allow to reuse list[n] later without re-growth */
  6529. output->has_empty_slot = 1;
  6530. }
  6531. return n;
  6532. }
  6533. static char **expand_variables(char **argv, unsigned expflags)
  6534. {
  6535. int n;
  6536. char **list;
  6537. o_string output = NULL_O_STRING;
  6538. output.o_expflags = expflags;
  6539. n = 0;
  6540. for (;;) {
  6541. /* go to next list[n] */
  6542. output.ended_in_ifs = 0;
  6543. n = o_save_ptr(&output, n);
  6544. if (!*argv)
  6545. break;
  6546. /* expand argv[i] */
  6547. n = expand_vars_to_list(&output, n, *argv++);
  6548. /* if (!output->has_empty_slot) -- need this?? */
  6549. o_addchr(&output, '\0');
  6550. }
  6551. debug_print_list("expand_variables", &output, n);
  6552. /* output.data (malloced in one block) gets returned in "list" */
  6553. list = o_finalize_list(&output, n);
  6554. debug_print_strings("expand_variables[1]", list);
  6555. return list;
  6556. }
  6557. static char **expand_strvec_to_strvec(char **argv)
  6558. {
  6559. return expand_variables(argv, EXP_FLAG_GLOB | EXP_FLAG_ESC_GLOB_CHARS);
  6560. }
  6561. #if defined(CMD_SINGLEWORD_NOGLOB) || defined(CMD_TEST2_SINGLEWORD_NOGLOB)
  6562. static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
  6563. {
  6564. return expand_variables(argv, EXP_FLAG_SINGLEWORD);
  6565. }
  6566. #endif
  6567. /* Used for expansion of right hand of assignments,
  6568. * $((...)), heredocs, variable expansion parts.
  6569. *
  6570. * NB: should NOT do globbing!
  6571. * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*"
  6572. */
  6573. static char *expand_string_to_string(const char *str, int EXP_flags, int do_unbackslash)
  6574. {
  6575. #if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
  6576. const int do_unbackslash = 1;
  6577. const int EXP_flags = EXP_FLAG_ESC_GLOB_CHARS;
  6578. #endif
  6579. char *argv[2], **list;
  6580. debug_printf_expand("string_to_string<='%s'\n", str);
  6581. /* This is generally an optimization, but it also
  6582. * handles "", which otherwise trips over !list[0] check below.
  6583. * (is this ever happens that we actually get str="" here?)
  6584. */
  6585. if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
  6586. //TODO: Can use on strings with \ too, just unbackslash() them?
  6587. debug_printf_expand("string_to_string(fast)=>'%s'\n", str);
  6588. return xstrdup(str);
  6589. }
  6590. argv[0] = (char*)str;
  6591. argv[1] = NULL;
  6592. list = expand_variables(argv, EXP_flags | EXP_FLAG_SINGLEWORD);
  6593. if (!list[0]) {
  6594. /* Example where it happens:
  6595. * x=; echo ${x:-"$@"}
  6596. */
  6597. ((char*)list)[0] = '\0';
  6598. } else {
  6599. if (HUSH_DEBUG)
  6600. if (list[1])
  6601. bb_simple_error_msg_and_die("BUG in varexp2");
  6602. /* actually, just move string 2*sizeof(char*) bytes back */
  6603. overlapping_strcpy((char*)list, list[0]);
  6604. if (do_unbackslash)
  6605. unbackslash((char*)list);
  6606. }
  6607. debug_printf_expand("string_to_string=>'%s'\n", (char*)list);
  6608. return (char*)list;
  6609. }
  6610. #if 0
  6611. static char* expand_strvec_to_string(char **argv)
  6612. {
  6613. char **list;
  6614. list = expand_variables(argv, EXP_FLAG_SINGLEWORD);
  6615. /* Convert all NULs to spaces */
  6616. if (list[0]) {
  6617. int n = 1;
  6618. while (list[n]) {
  6619. if (HUSH_DEBUG)
  6620. if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
  6621. bb_error_msg_and_die("BUG in varexp3");
  6622. /* bash uses ' ' regardless of $IFS contents */
  6623. list[n][-1] = ' ';
  6624. n++;
  6625. }
  6626. }
  6627. overlapping_strcpy((char*)list, list[0] ? list[0] : "");
  6628. debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
  6629. return (char*)list;
  6630. }
  6631. #endif
  6632. static char **expand_assignments(char **argv, int count)
  6633. {
  6634. int i;
  6635. char **p;
  6636. G.expanded_assignments = p = NULL;
  6637. /* Expand assignments into one string each */
  6638. for (i = 0; i < count; i++) {
  6639. p = add_string_to_strings(p,
  6640. expand_string_to_string(argv[i],
  6641. EXP_FLAG_ESC_GLOB_CHARS,
  6642. /*unbackslash:*/ 1
  6643. )
  6644. );
  6645. G.expanded_assignments = p;
  6646. }
  6647. G.expanded_assignments = NULL;
  6648. return p;
  6649. }
  6650. static void switch_off_special_sigs(unsigned mask)
  6651. {
  6652. unsigned sig = 0;
  6653. while ((mask >>= 1) != 0) {
  6654. sig++;
  6655. if (!(mask & 1))
  6656. continue;
  6657. #if ENABLE_HUSH_TRAP
  6658. if (G_traps) {
  6659. if (G_traps[sig] && !G_traps[sig][0])
  6660. /* trap is '', has to remain SIG_IGN */
  6661. continue;
  6662. free(G_traps[sig]);
  6663. G_traps[sig] = NULL;
  6664. }
  6665. #endif
  6666. /* We are here only if no trap or trap was not '' */
  6667. install_sighandler(sig, SIG_DFL);
  6668. }
  6669. }
  6670. #if BB_MMU
  6671. /* never called */
  6672. void re_execute_shell(char ***to_free, const char *s,
  6673. char *g_argv0, char **g_argv,
  6674. char **builtin_argv) NORETURN;
  6675. static void reset_traps_to_defaults(void)
  6676. {
  6677. /* This function is always called in a child shell
  6678. * after fork (not vfork, NOMMU doesn't use this function).
  6679. */
  6680. IF_HUSH_TRAP(unsigned sig;)
  6681. unsigned mask;
  6682. /* Child shells are not interactive.
  6683. * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
  6684. * Testcase: (while :; do :; done) + ^Z should background.
  6685. * Same goes for SIGTERM, SIGHUP, SIGINT.
  6686. */
  6687. mask = (G.special_sig_mask & SPECIAL_INTERACTIVE_SIGS) | G_fatal_sig_mask;
  6688. if (!G_traps && !mask)
  6689. return; /* already no traps and no special sigs */
  6690. /* Switch off special sigs */
  6691. switch_off_special_sigs(mask);
  6692. # if ENABLE_HUSH_JOB
  6693. G_fatal_sig_mask = 0;
  6694. # endif
  6695. G.special_sig_mask &= ~SPECIAL_INTERACTIVE_SIGS;
  6696. /* SIGQUIT,SIGCHLD and maybe SPECIAL_JOBSTOP_SIGS
  6697. * remain set in G.special_sig_mask */
  6698. # if ENABLE_HUSH_TRAP
  6699. if (!G_traps)
  6700. return;
  6701. /* Reset all sigs to default except ones with empty traps */
  6702. for (sig = 0; sig < NSIG; sig++) {
  6703. if (!G_traps[sig])
  6704. continue; /* no trap: nothing to do */
  6705. if (!G_traps[sig][0])
  6706. continue; /* empty trap: has to remain SIG_IGN */
  6707. /* sig has non-empty trap, reset it: */
  6708. free(G_traps[sig]);
  6709. G_traps[sig] = NULL;
  6710. /* There is no signal for trap 0 (EXIT) */
  6711. if (sig == 0)
  6712. continue;
  6713. install_sighandler(sig, pick_sighandler(sig));
  6714. }
  6715. # endif
  6716. }
  6717. #else /* !BB_MMU */
  6718. static void re_execute_shell(char ***to_free, const char *s,
  6719. char *g_argv0, char **g_argv,
  6720. char **builtin_argv) NORETURN;
  6721. static void re_execute_shell(char ***to_free, const char *s,
  6722. char *g_argv0, char **g_argv,
  6723. char **builtin_argv)
  6724. {
  6725. # define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
  6726. /* delims + 2 * (number of bytes in printed hex numbers) */
  6727. char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
  6728. char *heredoc_argv[4];
  6729. struct variable *cur;
  6730. # if ENABLE_HUSH_FUNCTIONS
  6731. struct function *funcp;
  6732. # endif
  6733. char **argv, **pp;
  6734. unsigned cnt;
  6735. unsigned long long empty_trap_mask;
  6736. if (!g_argv0) { /* heredoc */
  6737. argv = heredoc_argv;
  6738. argv[0] = (char *) G.argv0_for_re_execing;
  6739. argv[1] = (char *) "-<";
  6740. argv[2] = (char *) s;
  6741. argv[3] = NULL;
  6742. pp = &argv[3]; /* used as pointer to empty environment */
  6743. goto do_exec;
  6744. }
  6745. cnt = 0;
  6746. pp = builtin_argv;
  6747. if (pp) while (*pp++)
  6748. cnt++;
  6749. empty_trap_mask = 0;
  6750. if (G_traps) {
  6751. int sig;
  6752. for (sig = 1; sig < NSIG; sig++) {
  6753. if (G_traps[sig] && !G_traps[sig][0])
  6754. empty_trap_mask |= 1LL << sig;
  6755. }
  6756. }
  6757. sprintf(param_buf, NOMMU_HACK_FMT
  6758. , (unsigned) G.root_pid
  6759. , (unsigned) G.root_ppid
  6760. , (unsigned) G.last_bg_pid
  6761. , (unsigned) G.last_exitcode
  6762. , cnt
  6763. , empty_trap_mask
  6764. IF_HUSH_LOOPS(, G.depth_of_loop)
  6765. );
  6766. # undef NOMMU_HACK_FMT
  6767. /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
  6768. * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
  6769. */
  6770. cnt += 6;
  6771. for (cur = G.top_var; cur; cur = cur->next) {
  6772. if (!cur->flg_export || cur->flg_read_only)
  6773. cnt += 2;
  6774. }
  6775. # if ENABLE_HUSH_FUNCTIONS
  6776. for (funcp = G.top_func; funcp; funcp = funcp->next)
  6777. cnt += 3;
  6778. # endif
  6779. pp = g_argv;
  6780. while (*pp++)
  6781. cnt++;
  6782. *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
  6783. *pp++ = (char *) G.argv0_for_re_execing;
  6784. *pp++ = param_buf;
  6785. for (cur = G.top_var; cur; cur = cur->next) {
  6786. if (strcmp(cur->varstr, hush_version_str) == 0)
  6787. continue;
  6788. if (cur->flg_read_only) {
  6789. *pp++ = (char *) "-R";
  6790. *pp++ = cur->varstr;
  6791. } else if (!cur->flg_export) {
  6792. *pp++ = (char *) "-V";
  6793. *pp++ = cur->varstr;
  6794. }
  6795. }
  6796. # if ENABLE_HUSH_FUNCTIONS
  6797. for (funcp = G.top_func; funcp; funcp = funcp->next) {
  6798. *pp++ = (char *) "-F";
  6799. *pp++ = funcp->name;
  6800. *pp++ = funcp->body_as_string;
  6801. }
  6802. # endif
  6803. /* We can pass activated traps here. Say, -Tnn:trap_string
  6804. *
  6805. * However, POSIX says that subshells reset signals with traps
  6806. * to SIG_DFL.
  6807. * I tested bash-3.2 and it not only does that with true subshells
  6808. * of the form ( list ), but with any forked children shells.
  6809. * I set trap "echo W" WINCH; and then tried:
  6810. *
  6811. * { echo 1; sleep 20; echo 2; } &
  6812. * while true; do echo 1; sleep 20; echo 2; break; done &
  6813. * true | { echo 1; sleep 20; echo 2; } | cat
  6814. *
  6815. * In all these cases sending SIGWINCH to the child shell
  6816. * did not run the trap. If I add trap "echo V" WINCH;
  6817. * _inside_ group (just before echo 1), it works.
  6818. *
  6819. * I conclude it means we don't need to pass active traps here.
  6820. */
  6821. *pp++ = (char *) "-c";
  6822. *pp++ = (char *) s;
  6823. if (builtin_argv) {
  6824. while (*++builtin_argv)
  6825. *pp++ = *builtin_argv;
  6826. *pp++ = (char *) "";
  6827. }
  6828. *pp++ = g_argv0;
  6829. while (*g_argv)
  6830. *pp++ = *g_argv++;
  6831. /* *pp = NULL; - is already there */
  6832. pp = environ;
  6833. do_exec:
  6834. debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
  6835. /* Don't propagate SIG_IGN to the child */
  6836. if (SPECIAL_JOBSTOP_SIGS != 0)
  6837. switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
  6838. execve(bb_busybox_exec_path, argv, pp);
  6839. /* Fallback. Useful for init=/bin/hush usage etc */
  6840. if (argv[0][0] == '/')
  6841. execve(argv[0], argv, pp);
  6842. xfunc_error_retval = 127;
  6843. bb_simple_error_msg_and_die("can't re-execute the shell");
  6844. }
  6845. #endif /* !BB_MMU */
  6846. static int run_and_free_list(struct pipe *pi);
  6847. /* Executing from string: eval, sh -c '...'
  6848. * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
  6849. * end_trigger controls how often we stop parsing
  6850. * NUL: parse all, execute, return
  6851. * ';': parse till ';' or newline, execute, repeat till EOF
  6852. */
  6853. static void parse_and_run_stream(struct in_str *inp, int end_trigger)
  6854. {
  6855. /* Why we need empty flag?
  6856. * An obscure corner case "false; ``; echo $?":
  6857. * empty command in `` should still set $? to 0.
  6858. * But we can't just set $? to 0 at the start,
  6859. * this breaks "false; echo `echo $?`" case.
  6860. */
  6861. bool empty = 1;
  6862. while (1) {
  6863. struct pipe *pipe_list;
  6864. #if ENABLE_HUSH_INTERACTIVE
  6865. if (end_trigger == ';') {
  6866. G.promptmode = 0; /* PS1 */
  6867. debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
  6868. }
  6869. #endif
  6870. pipe_list = parse_stream(NULL, NULL, inp, end_trigger);
  6871. if (!pipe_list || pipe_list == ERR_PTR) { /* EOF/error */
  6872. /* If we are in "big" script
  6873. * (not in `cmd` or something similar)...
  6874. */
  6875. if (pipe_list == ERR_PTR && end_trigger == ';') {
  6876. /* Discard cached input (rest of line) */
  6877. int ch = inp->last_char;
  6878. while (ch != EOF && ch != '\n') {
  6879. //bb_error_msg("Discarded:'%c'", ch);
  6880. ch = i_getch(inp);
  6881. }
  6882. /* Force prompt */
  6883. inp->p = NULL;
  6884. /* This stream isn't empty */
  6885. empty = 0;
  6886. continue;
  6887. }
  6888. if (!pipe_list && empty)
  6889. G.last_exitcode = 0;
  6890. break;
  6891. }
  6892. debug_print_tree(pipe_list, 0);
  6893. debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
  6894. run_and_free_list(pipe_list);
  6895. empty = 0;
  6896. if (G_flag_return_in_progress == 1)
  6897. break;
  6898. }
  6899. }
  6900. static void parse_and_run_string(const char *s)
  6901. {
  6902. struct in_str input;
  6903. //IF_HUSH_LINENO_VAR(unsigned sv = G.parse_lineno;)
  6904. setup_string_in_str(&input, s);
  6905. parse_and_run_stream(&input, '\0');
  6906. //IF_HUSH_LINENO_VAR(G.parse_lineno = sv;)
  6907. }
  6908. static void parse_and_run_file(HFILE *fp)
  6909. {
  6910. struct in_str input;
  6911. IF_HUSH_LINENO_VAR(unsigned sv = G.parse_lineno;)
  6912. IF_HUSH_LINENO_VAR(G.parse_lineno = 1;)
  6913. setup_file_in_str(&input, fp);
  6914. parse_and_run_stream(&input, ';');
  6915. IF_HUSH_LINENO_VAR(G.parse_lineno = sv;)
  6916. }
  6917. #if ENABLE_HUSH_TICK
  6918. static int generate_stream_from_string(const char *s, pid_t *pid_p)
  6919. {
  6920. pid_t pid;
  6921. int channel[2];
  6922. # if !BB_MMU
  6923. char **to_free = NULL;
  6924. # endif
  6925. xpipe(channel);
  6926. pid = BB_MMU ? xfork() : xvfork();
  6927. if (pid == 0) { /* child */
  6928. disable_restore_tty_pgrp_on_exit();
  6929. /* Process substitution is not considered to be usual
  6930. * 'command execution'.
  6931. * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
  6932. */
  6933. bb_signals(0
  6934. + (1 << SIGTSTP)
  6935. + (1 << SIGTTIN)
  6936. + (1 << SIGTTOU)
  6937. , SIG_IGN);
  6938. close(channel[0]); /* NB: close _first_, then move fd! */
  6939. xmove_fd(channel[1], 1);
  6940. # if ENABLE_HUSH_TRAP
  6941. /* Awful hack for `trap` or $(trap).
  6942. *
  6943. * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
  6944. * contains an example where "trap" is executed in a subshell:
  6945. *
  6946. * save_traps=$(trap)
  6947. * ...
  6948. * eval "$save_traps"
  6949. *
  6950. * Standard does not say that "trap" in subshell shall print
  6951. * parent shell's traps. It only says that its output
  6952. * must have suitable form, but then, in the above example
  6953. * (which is not supposed to be normative), it implies that.
  6954. *
  6955. * bash (and probably other shell) does implement it
  6956. * (traps are reset to defaults, but "trap" still shows them),
  6957. * but as a result, "trap" logic is hopelessly messed up:
  6958. *
  6959. * # trap
  6960. * trap -- 'echo Ho' SIGWINCH <--- we have a handler
  6961. * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
  6962. * # true | trap <--- trap is in subshell - no output (ditto)
  6963. * # echo `true | trap` <--- in subshell - output (but traps are reset!)
  6964. * trap -- 'echo Ho' SIGWINCH
  6965. * # echo `(trap)` <--- in subshell in subshell - output
  6966. * trap -- 'echo Ho' SIGWINCH
  6967. * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
  6968. * trap -- 'echo Ho' SIGWINCH
  6969. *
  6970. * The rules when to forget and when to not forget traps
  6971. * get really complex and nonsensical.
  6972. *
  6973. * Our solution: ONLY bare $(trap) or `trap` is special.
  6974. */
  6975. s = skip_whitespace(s);
  6976. if (is_prefixed_with(s, "trap")
  6977. && skip_whitespace(s + 4)[0] == '\0'
  6978. ) {
  6979. static const char *const argv[] = { NULL, NULL };
  6980. builtin_trap((char**)argv);
  6981. fflush_all(); /* important */
  6982. _exit(0);
  6983. }
  6984. # endif
  6985. # if BB_MMU
  6986. /* Prevent it from trying to handle ctrl-z etc */
  6987. IF_HUSH_JOB(G.run_list_level = 1;)
  6988. CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
  6989. reset_traps_to_defaults();
  6990. IF_HUSH_MODE_X(G.x_mode_depth++;)
  6991. //bb_error_msg("%s: ++x_mode_depth=%d", __func__, G.x_mode_depth);
  6992. parse_and_run_string(s);
  6993. _exit(G.last_exitcode);
  6994. # else
  6995. /* We re-execute after vfork on NOMMU. This makes this script safe:
  6996. * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
  6997. * huge=`cat BIG` # was blocking here forever
  6998. * echo OK
  6999. */
  7000. re_execute_shell(&to_free,
  7001. s,
  7002. G.global_argv[0],
  7003. G.global_argv + 1,
  7004. NULL);
  7005. # endif
  7006. }
  7007. /* parent */
  7008. *pid_p = pid;
  7009. # if ENABLE_HUSH_FAST
  7010. G.count_SIGCHLD++;
  7011. //bb_error_msg("[%d] fork in generate_stream_from_string:"
  7012. // " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
  7013. // getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
  7014. # endif
  7015. enable_restore_tty_pgrp_on_exit();
  7016. # if !BB_MMU
  7017. free(to_free);
  7018. # endif
  7019. close(channel[1]);
  7020. return channel[0];
  7021. }
  7022. /* Return code is exit status of the process that is run. */
  7023. static int process_command_subs(o_string *dest, const char *s)
  7024. {
  7025. FILE *fp;
  7026. pid_t pid;
  7027. int status, ch, eol_cnt;
  7028. fp = xfdopen_for_read(generate_stream_from_string(s, &pid));
  7029. /* Now send results of command back into original context */
  7030. eol_cnt = 0;
  7031. while ((ch = getc(fp)) != EOF) {
  7032. if (ch == '\0')
  7033. continue;
  7034. if (ch == '\n') {
  7035. eol_cnt++;
  7036. continue;
  7037. }
  7038. while (eol_cnt) {
  7039. o_addchr(dest, '\n');
  7040. eol_cnt--;
  7041. }
  7042. o_addQchr(dest, ch);
  7043. }
  7044. debug_printf("done reading from `cmd` pipe, closing it\n");
  7045. fclose(fp);
  7046. /* We need to extract exitcode. Test case
  7047. * "true; echo `sleep 1; false` $?"
  7048. * should print 1 */
  7049. safe_waitpid(pid, &status, 0);
  7050. debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
  7051. return WEXITSTATUS(status);
  7052. }
  7053. #endif /* ENABLE_HUSH_TICK */
  7054. static void setup_heredoc(struct redir_struct *redir)
  7055. {
  7056. struct fd_pair pair;
  7057. pid_t pid;
  7058. int len, written;
  7059. /* the _body_ of heredoc (misleading field name) */
  7060. const char *heredoc = redir->rd_filename;
  7061. char *expanded;
  7062. #if !BB_MMU
  7063. char **to_free;
  7064. #endif
  7065. expanded = NULL;
  7066. if (!(redir->rd_dup & HEREDOC_QUOTED)) {
  7067. expanded = encode_then_expand_string(heredoc);
  7068. if (expanded)
  7069. heredoc = expanded;
  7070. }
  7071. len = strlen(heredoc);
  7072. close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
  7073. xpiped_pair(pair);
  7074. xmove_fd(pair.rd, redir->rd_fd);
  7075. /* Try writing without forking. Newer kernels have
  7076. * dynamically growing pipes. Must use non-blocking write! */
  7077. ndelay_on(pair.wr);
  7078. while (1) {
  7079. written = write(pair.wr, heredoc, len);
  7080. if (written <= 0)
  7081. break;
  7082. len -= written;
  7083. if (len == 0) {
  7084. close(pair.wr);
  7085. free(expanded);
  7086. return;
  7087. }
  7088. heredoc += written;
  7089. }
  7090. ndelay_off(pair.wr);
  7091. /* Okay, pipe buffer was not big enough */
  7092. /* Note: we must not create a stray child (bastard? :)
  7093. * for the unsuspecting parent process. Child creates a grandchild
  7094. * and exits before parent execs the process which consumes heredoc
  7095. * (that exec happens after we return from this function) */
  7096. #if !BB_MMU
  7097. to_free = NULL;
  7098. #endif
  7099. pid = xvfork();
  7100. if (pid == 0) {
  7101. /* child */
  7102. disable_restore_tty_pgrp_on_exit();
  7103. pid = BB_MMU ? xfork() : xvfork();
  7104. if (pid != 0)
  7105. _exit(0);
  7106. /* grandchild */
  7107. close(redir->rd_fd); /* read side of the pipe */
  7108. #if BB_MMU
  7109. full_write(pair.wr, heredoc, len); /* may loop or block */
  7110. _exit(0);
  7111. #else
  7112. /* Delegate blocking writes to another process */
  7113. xmove_fd(pair.wr, STDOUT_FILENO);
  7114. re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
  7115. #endif
  7116. }
  7117. /* parent */
  7118. #if ENABLE_HUSH_FAST
  7119. G.count_SIGCHLD++;
  7120. //bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
  7121. #endif
  7122. enable_restore_tty_pgrp_on_exit();
  7123. #if !BB_MMU
  7124. free(to_free);
  7125. #endif
  7126. close(pair.wr);
  7127. free(expanded);
  7128. wait(NULL); /* wait till child has died */
  7129. }
  7130. struct squirrel {
  7131. int orig_fd;
  7132. int moved_to;
  7133. /* moved_to = n: fd was moved to n; restore back to orig_fd after redir */
  7134. /* moved_to = -1: fd was opened by redirect; close orig_fd after redir */
  7135. };
  7136. static struct squirrel *append_squirrel(struct squirrel *sq, int i, int orig, int moved)
  7137. {
  7138. sq = xrealloc(sq, (i + 2) * sizeof(sq[0]));
  7139. sq[i].orig_fd = orig;
  7140. sq[i].moved_to = moved;
  7141. sq[i+1].orig_fd = -1; /* end marker */
  7142. return sq;
  7143. }
  7144. static struct squirrel *add_squirrel(struct squirrel *sq, int fd, int avoid_fd)
  7145. {
  7146. int moved_to;
  7147. int i;
  7148. i = 0;
  7149. if (sq) for (; sq[i].orig_fd >= 0; i++) {
  7150. /* If we collide with an already moved fd... */
  7151. if (fd == sq[i].moved_to) {
  7152. sq[i].moved_to = dup_CLOEXEC(sq[i].moved_to, avoid_fd);
  7153. debug_printf_redir("redirect_fd %d: already busy, moving to %d\n", fd, sq[i].moved_to);
  7154. if (sq[i].moved_to < 0) /* what? */
  7155. xfunc_die();
  7156. return sq;
  7157. }
  7158. if (fd == sq[i].orig_fd) {
  7159. /* Example: echo Hello >/dev/null 1>&2 */
  7160. debug_printf_redir("redirect_fd %d: already moved\n", fd);
  7161. return sq;
  7162. }
  7163. }
  7164. /* If this fd is open, we move and remember it; if it's closed, moved_to = -1 */
  7165. moved_to = dup_CLOEXEC(fd, avoid_fd);
  7166. debug_printf_redir("redirect_fd %d: previous fd is moved to %d (-1 if it was closed)\n", fd, moved_to);
  7167. if (moved_to < 0 && errno != EBADF)
  7168. xfunc_die();
  7169. return append_squirrel(sq, i, fd, moved_to);
  7170. }
  7171. static struct squirrel *add_squirrel_closed(struct squirrel *sq, int fd)
  7172. {
  7173. int i;
  7174. i = 0;
  7175. if (sq) for (; sq[i].orig_fd >= 0; i++) {
  7176. /* If we collide with an already moved fd... */
  7177. if (fd == sq[i].orig_fd) {
  7178. /* Examples:
  7179. * "echo 3>FILE 3>&- 3>FILE"
  7180. * "echo 3>&- 3>FILE"
  7181. * No need for last redirect to insert
  7182. * another "need to close 3" indicator.
  7183. */
  7184. debug_printf_redir("redirect_fd %d: already moved or closed\n", fd);
  7185. return sq;
  7186. }
  7187. }
  7188. debug_printf_redir("redirect_fd %d: previous fd was closed\n", fd);
  7189. return append_squirrel(sq, i, fd, -1);
  7190. }
  7191. /* fd: redirect wants this fd to be used (e.g. 3>file).
  7192. * Move all conflicting internally used fds,
  7193. * and remember them so that we can restore them later.
  7194. */
  7195. static int save_fd_on_redirect(int fd, int avoid_fd, struct squirrel **sqp)
  7196. {
  7197. if (avoid_fd < 9) /* the important case here is that it can be -1 */
  7198. avoid_fd = 9;
  7199. #if ENABLE_HUSH_INTERACTIVE
  7200. if (fd != 0 /* don't trigger for G_interactive_fd == 0 (that's "not interactive" flag) */
  7201. && fd == G_interactive_fd
  7202. ) {
  7203. /* Testcase: "ls -l /proc/$$/fd 255>&-" should work */
  7204. G_interactive_fd = xdup_CLOEXEC_and_close(G_interactive_fd, avoid_fd);
  7205. debug_printf_redir("redirect_fd %d: matches interactive_fd, moving it to %d\n", fd, G_interactive_fd);
  7206. return 1; /* "we closed fd" */
  7207. }
  7208. #endif
  7209. /* Are we called from setup_redirects(squirrel==NULL)
  7210. * in redirect in a [v]forked child?
  7211. */
  7212. if (sqp == NULL) {
  7213. /* No need to move script fds.
  7214. * For NOMMU case, it's actively wrong: we'd change ->fd
  7215. * fields in memory for the parent, but parent's fds
  7216. * aren't moved, it would use wrong fd!
  7217. * Reproducer: "cmd 3>FILE" in script.
  7218. * If we would call move_HFILEs_on_redirect(), child would:
  7219. * fcntl64(3, F_DUPFD_CLOEXEC, 10) = 10
  7220. * close(3) = 0
  7221. * and change ->fd to 10 if fd#3 is a script fd. WRONG.
  7222. */
  7223. //bb_error_msg("sqp == NULL: [v]forked child");
  7224. return 0;
  7225. }
  7226. /* If this one of script's fds? */
  7227. if (move_HFILEs_on_redirect(fd, avoid_fd))
  7228. return 1; /* yes. "we closed fd" (actually moved it) */
  7229. /* Are we called for "exec 3>FILE"? Came through
  7230. * redirect_and_varexp_helper(squirrel=ERR_PTR) -> setup_redirects(ERR_PTR)
  7231. * This case used to fail for this script:
  7232. * exec 3>FILE
  7233. * echo Ok
  7234. * ...100000 more lines...
  7235. * echo Ok
  7236. * as follows:
  7237. * read(3, "exec 3>FILE\necho Ok\necho Ok"..., 1024) = 1024
  7238. * open("FILE", O_WRONLY|O_CREAT|O_TRUNC|O_LARGEFILE, 0666) = 4
  7239. * dup2(4, 3) = 3
  7240. * ^^^^^^^^ oops, we lost fd#3 opened to our script!
  7241. * close(4) = 0
  7242. * write(1, "Ok\n", 3) = 3
  7243. * ... = 3
  7244. * write(1, "Ok\n", 3) = 3
  7245. * read(3, 0x94fbc08, 1024) = -1 EBADF (Bad file descriptor)
  7246. * ^^^^^^^^ oops, wrong fd!!!
  7247. * With this case separate from sqp == NULL and *after* move_HFILEs,
  7248. * it now works:
  7249. */
  7250. if (sqp == ERR_PTR) {
  7251. /* Don't preserve redirected fds: exec is _meant_ to change these */
  7252. //bb_error_msg("sqp == ERR_PTR: exec >FILE");
  7253. return 0;
  7254. }
  7255. /* Check whether it collides with any open fds (e.g. stdio), save fds as needed */
  7256. *sqp = add_squirrel(*sqp, fd, avoid_fd);
  7257. return 0; /* "we did not close fd" */
  7258. }
  7259. static void restore_redirects(struct squirrel *sq)
  7260. {
  7261. if (sq) {
  7262. int i;
  7263. for (i = 0; sq[i].orig_fd >= 0; i++) {
  7264. if (sq[i].moved_to >= 0) {
  7265. /* We simply die on error */
  7266. debug_printf_redir("restoring redirected fd from %d to %d\n", sq[i].moved_to, sq[i].orig_fd);
  7267. xmove_fd(sq[i].moved_to, sq[i].orig_fd);
  7268. } else {
  7269. /* cmd1 9>FILE; cmd2_should_see_fd9_closed */
  7270. debug_printf_redir("restoring redirected fd %d: closing it\n", sq[i].orig_fd);
  7271. close(sq[i].orig_fd);
  7272. }
  7273. }
  7274. free(sq);
  7275. }
  7276. if (G.HFILE_stdin
  7277. && G.HFILE_stdin->fd != STDIN_FILENO
  7278. ) {
  7279. /* Testcase: interactive "read r <FILE; echo $r; read r; echo $r".
  7280. * Redirect moves ->fd to e.g. 10,
  7281. * and it is not restored above (we do not restore script fds
  7282. * after redirects, we just use new, "moved" fds).
  7283. * However for stdin, get_user_input() -> read_line_input(),
  7284. * and read builtin, depend on fd == STDIN_FILENO.
  7285. */
  7286. debug_printf_redir("restoring %d to stdin\n", G.HFILE_stdin->fd);
  7287. xmove_fd(G.HFILE_stdin->fd, STDIN_FILENO);
  7288. G.HFILE_stdin->fd = STDIN_FILENO;
  7289. }
  7290. /* If moved, G_interactive_fd stays on new fd, not restoring it */
  7291. }
  7292. #if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
  7293. static void close_saved_fds_and_FILE_fds(void)
  7294. {
  7295. if (G_interactive_fd)
  7296. close(G_interactive_fd);
  7297. close_all_HFILE_list();
  7298. }
  7299. #endif
  7300. static int internally_opened_fd(int fd, struct squirrel *sq)
  7301. {
  7302. int i;
  7303. #if ENABLE_HUSH_INTERACTIVE
  7304. if (fd == G_interactive_fd)
  7305. return 1;
  7306. #endif
  7307. /* If this one of script's fds? */
  7308. if (fd_in_HFILEs(fd))
  7309. return 1;
  7310. if (sq) for (i = 0; sq[i].orig_fd >= 0; i++) {
  7311. if (fd == sq[i].moved_to)
  7312. return 1;
  7313. }
  7314. return 0;
  7315. }
  7316. /* squirrel != NULL means we squirrel away copies of stdin, stdout,
  7317. * and stderr if they are redirected. */
  7318. static int setup_redirects(struct command *prog, struct squirrel **sqp)
  7319. {
  7320. struct redir_struct *redir;
  7321. for (redir = prog->redirects; redir; redir = redir->next) {
  7322. int newfd;
  7323. int closed;
  7324. if (redir->rd_type == REDIRECT_HEREDOC2) {
  7325. /* "rd_fd<<HERE" case */
  7326. save_fd_on_redirect(redir->rd_fd, /*avoid:*/ 0, sqp);
  7327. /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
  7328. * of the heredoc */
  7329. debug_printf_redir("set heredoc '%s'\n",
  7330. redir->rd_filename);
  7331. setup_heredoc(redir);
  7332. continue;
  7333. }
  7334. if (redir->rd_dup == REDIRFD_TO_FILE) {
  7335. /* "rd_fd<*>file" case (<*> is <,>,>>,<>) */
  7336. char *p;
  7337. int mode;
  7338. if (redir->rd_filename == NULL) {
  7339. /* Examples:
  7340. * "cmd >" (no filename)
  7341. * "cmd > <file" (2nd redirect starts too early)
  7342. */
  7343. syntax_error("invalid redirect");
  7344. continue;
  7345. }
  7346. mode = redir_table[redir->rd_type].mode;
  7347. p = expand_string_to_string(redir->rd_filename,
  7348. EXP_FLAG_ESC_GLOB_CHARS, /*unbackslash:*/ 1);
  7349. newfd = open_or_warn(p, mode);
  7350. free(p);
  7351. if (newfd < 0) {
  7352. /* Error message from open_or_warn can be lost
  7353. * if stderr has been redirected, but bash
  7354. * and ash both lose it as well
  7355. * (though zsh doesn't!)
  7356. */
  7357. return 1;
  7358. }
  7359. if (newfd == redir->rd_fd && sqp) {
  7360. /* open() gave us precisely the fd we wanted.
  7361. * This means that this fd was not busy
  7362. * (not opened to anywhere).
  7363. * Remember to close it on restore:
  7364. */
  7365. *sqp = add_squirrel_closed(*sqp, newfd);
  7366. debug_printf_redir("redir to previously closed fd %d\n", newfd);
  7367. }
  7368. } else {
  7369. /* "rd_fd>&rd_dup" or "rd_fd>&-" case */
  7370. newfd = redir->rd_dup;
  7371. }
  7372. if (newfd == redir->rd_fd)
  7373. continue;
  7374. /* if "N>FILE": move newfd to redir->rd_fd */
  7375. /* if "N>&M": dup newfd to redir->rd_fd */
  7376. /* if "N>&-": close redir->rd_fd (newfd is REDIRFD_CLOSE) */
  7377. closed = save_fd_on_redirect(redir->rd_fd, /*avoid:*/ newfd, sqp);
  7378. if (newfd == REDIRFD_CLOSE) {
  7379. /* "N>&-" means "close me" */
  7380. if (!closed) {
  7381. /* ^^^ optimization: saving may already
  7382. * have closed it. If not... */
  7383. close(redir->rd_fd);
  7384. }
  7385. /* Sometimes we do another close on restore, getting EBADF.
  7386. * Consider "echo 3>FILE 3>&-"
  7387. * first redirect remembers "need to close 3",
  7388. * and second redirect closes 3! Restore code then closes 3 again.
  7389. */
  7390. } else {
  7391. /* if newfd is a script fd or saved fd, simulate EBADF */
  7392. if (internally_opened_fd(newfd, sqp && sqp != ERR_PTR ? *sqp : NULL)) {
  7393. //errno = EBADF;
  7394. //bb_perror_msg_and_die("can't duplicate file descriptor");
  7395. newfd = -1; /* same effect as code above */
  7396. }
  7397. xdup2(newfd, redir->rd_fd);
  7398. if (redir->rd_dup == REDIRFD_TO_FILE)
  7399. /* "rd_fd > FILE" */
  7400. close(newfd);
  7401. /* else: "rd_fd > rd_dup" */
  7402. }
  7403. }
  7404. return 0;
  7405. }
  7406. static char *find_in_path(const char *arg)
  7407. {
  7408. char *ret = NULL;
  7409. const char *PATH = get_local_var_value("PATH");
  7410. if (!PATH)
  7411. return NULL;
  7412. while (1) {
  7413. const char *end = strchrnul(PATH, ':');
  7414. int sz = end - PATH; /* must be int! */
  7415. free(ret);
  7416. if (sz != 0) {
  7417. ret = xasprintf("%.*s/%s", sz, PATH, arg);
  7418. } else {
  7419. /* We have xxx::yyyy in $PATH,
  7420. * it means "use current dir" */
  7421. ret = xstrdup(arg);
  7422. }
  7423. if (access(ret, F_OK) == 0)
  7424. break;
  7425. if (*end == '\0') {
  7426. free(ret);
  7427. return NULL;
  7428. }
  7429. PATH = end + 1;
  7430. }
  7431. return ret;
  7432. }
  7433. static const struct built_in_command *find_builtin_helper(const char *name,
  7434. const struct built_in_command *x,
  7435. const struct built_in_command *end)
  7436. {
  7437. while (x != end) {
  7438. if (strcmp(name, x->b_cmd) != 0) {
  7439. x++;
  7440. continue;
  7441. }
  7442. debug_printf_exec("found builtin '%s'\n", name);
  7443. return x;
  7444. }
  7445. return NULL;
  7446. }
  7447. static const struct built_in_command *find_builtin1(const char *name)
  7448. {
  7449. return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
  7450. }
  7451. static const struct built_in_command *find_builtin(const char *name)
  7452. {
  7453. const struct built_in_command *x = find_builtin1(name);
  7454. if (x)
  7455. return x;
  7456. return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
  7457. }
  7458. #if ENABLE_HUSH_JOB && EDITING_HAS_get_exe_name
  7459. static const char * FAST_FUNC get_builtin_name(int i)
  7460. {
  7461. if (/*i >= 0 && */ i < ARRAY_SIZE(bltins1)) {
  7462. return bltins1[i].b_cmd;
  7463. }
  7464. i -= ARRAY_SIZE(bltins1);
  7465. if (i < ARRAY_SIZE(bltins2)) {
  7466. return bltins2[i].b_cmd;
  7467. }
  7468. return NULL;
  7469. }
  7470. #endif
  7471. static void remove_nested_vars(void)
  7472. {
  7473. struct variable *cur;
  7474. struct variable **cur_pp;
  7475. cur_pp = &G.top_var;
  7476. while ((cur = *cur_pp) != NULL) {
  7477. if (cur->var_nest_level <= G.var_nest_level) {
  7478. cur_pp = &cur->next;
  7479. continue;
  7480. }
  7481. /* Unexport */
  7482. if (cur->flg_export) {
  7483. debug_printf_env("unexporting nested '%s'/%u\n", cur->varstr, cur->var_nest_level);
  7484. bb_unsetenv(cur->varstr);
  7485. }
  7486. /* Remove from global list */
  7487. *cur_pp = cur->next;
  7488. /* Free */
  7489. if (!cur->max_len) {
  7490. debug_printf_env("freeing nested '%s'/%u\n", cur->varstr, cur->var_nest_level);
  7491. free(cur->varstr);
  7492. }
  7493. free(cur);
  7494. }
  7495. }
  7496. static void enter_var_nest_level(void)
  7497. {
  7498. G.var_nest_level++;
  7499. debug_printf_env("var_nest_level++ %u\n", G.var_nest_level);
  7500. /* Try: f() { echo -n .; f; }; f
  7501. * struct variable::var_nest_level is uint16_t,
  7502. * thus limiting recursion to < 2^16.
  7503. * In any case, with 8 Mbyte stack SEGV happens
  7504. * not too long after 2^16 recursions anyway.
  7505. */
  7506. if (G.var_nest_level > 0xff00)
  7507. bb_error_msg_and_die("fatal recursion (depth %u)", G.var_nest_level);
  7508. }
  7509. static void leave_var_nest_level(void)
  7510. {
  7511. G.var_nest_level--;
  7512. debug_printf_env("var_nest_level-- %u\n", G.var_nest_level);
  7513. if (HUSH_DEBUG && (int)G.var_nest_level < 0)
  7514. bb_simple_error_msg_and_die("BUG: nesting underflow");
  7515. remove_nested_vars();
  7516. }
  7517. #if ENABLE_HUSH_FUNCTIONS
  7518. static struct function **find_function_slot(const char *name)
  7519. {
  7520. struct function *funcp;
  7521. struct function **funcpp = &G.top_func;
  7522. while ((funcp = *funcpp) != NULL) {
  7523. if (strcmp(name, funcp->name) == 0) {
  7524. debug_printf_exec("found function '%s'\n", name);
  7525. break;
  7526. }
  7527. funcpp = &funcp->next;
  7528. }
  7529. return funcpp;
  7530. }
  7531. static ALWAYS_INLINE const struct function *find_function(const char *name)
  7532. {
  7533. const struct function *funcp = *find_function_slot(name);
  7534. return funcp;
  7535. }
  7536. /* Note: takes ownership on name ptr */
  7537. static struct function *new_function(char *name)
  7538. {
  7539. struct function **funcpp = find_function_slot(name);
  7540. struct function *funcp = *funcpp;
  7541. if (funcp != NULL) {
  7542. struct command *cmd = funcp->parent_cmd;
  7543. debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
  7544. if (!cmd) {
  7545. debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
  7546. free(funcp->name);
  7547. /* Note: if !funcp->body, do not free body_as_string!
  7548. * This is a special case of "-F name body" function:
  7549. * body_as_string was not malloced! */
  7550. if (funcp->body) {
  7551. free_pipe_list(funcp->body);
  7552. # if !BB_MMU
  7553. free(funcp->body_as_string);
  7554. # endif
  7555. }
  7556. } else {
  7557. debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
  7558. cmd->argv[0] = funcp->name;
  7559. cmd->group = funcp->body;
  7560. # if !BB_MMU
  7561. cmd->group_as_string = funcp->body_as_string;
  7562. # endif
  7563. }
  7564. } else {
  7565. debug_printf_exec("remembering new function '%s'\n", name);
  7566. funcp = *funcpp = xzalloc(sizeof(*funcp));
  7567. /*funcp->next = NULL;*/
  7568. }
  7569. funcp->name = name;
  7570. return funcp;
  7571. }
  7572. # if ENABLE_HUSH_UNSET
  7573. static void unset_func(const char *name)
  7574. {
  7575. struct function **funcpp = find_function_slot(name);
  7576. struct function *funcp = *funcpp;
  7577. if (funcp != NULL) {
  7578. debug_printf_exec("freeing function '%s'\n", funcp->name);
  7579. *funcpp = funcp->next;
  7580. /* funcp is unlinked now, deleting it.
  7581. * Note: if !funcp->body, the function was created by
  7582. * "-F name body", do not free ->body_as_string
  7583. * and ->name as they were not malloced. */
  7584. if (funcp->body) {
  7585. free_pipe_list(funcp->body);
  7586. free(funcp->name);
  7587. # if !BB_MMU
  7588. free(funcp->body_as_string);
  7589. # endif
  7590. }
  7591. free(funcp);
  7592. }
  7593. }
  7594. # endif
  7595. # if BB_MMU
  7596. #define exec_function(to_free, funcp, argv) \
  7597. exec_function(funcp, argv)
  7598. # endif
  7599. static void exec_function(char ***to_free,
  7600. const struct function *funcp,
  7601. char **argv) NORETURN;
  7602. static void exec_function(char ***to_free,
  7603. const struct function *funcp,
  7604. char **argv)
  7605. {
  7606. # if BB_MMU
  7607. int n;
  7608. argv[0] = G.global_argv[0];
  7609. G.global_argv = argv;
  7610. G.global_argc = n = 1 + string_array_len(argv + 1);
  7611. // Example when we are here: "cmd | func"
  7612. // func will run with saved-redirect fds open.
  7613. // $ f() { echo /proc/self/fd/*; }
  7614. // $ true | f
  7615. // /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3
  7616. // stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ DIR fd for glob
  7617. // Same in script:
  7618. // $ . ./SCRIPT
  7619. // /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3 /proc/self/fd/4
  7620. // stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ opened ./SCRIPT DIR fd for glob
  7621. // They are CLOEXEC so external programs won't see them, but
  7622. // for "more correctness" we might want to close those extra fds here:
  7623. //? close_saved_fds_and_FILE_fds();
  7624. /* "we are in a function, ok to use return" */
  7625. G_flag_return_in_progress = -1;
  7626. enter_var_nest_level();
  7627. IF_HUSH_LOCAL(G.func_nest_level++;)
  7628. /* On MMU, funcp->body is always non-NULL */
  7629. n = run_list(funcp->body);
  7630. fflush_all();
  7631. _exit(n);
  7632. # else
  7633. //? close_saved_fds_and_FILE_fds();
  7634. //TODO: check whether "true | func_with_return" works
  7635. re_execute_shell(to_free,
  7636. funcp->body_as_string,
  7637. G.global_argv[0],
  7638. argv + 1,
  7639. NULL);
  7640. # endif
  7641. }
  7642. static int run_function(const struct function *funcp, char **argv)
  7643. {
  7644. int rc;
  7645. save_arg_t sv;
  7646. smallint sv_flg;
  7647. save_and_replace_G_args(&sv, argv);
  7648. /* "We are in function, ok to use return" */
  7649. sv_flg = G_flag_return_in_progress;
  7650. G_flag_return_in_progress = -1;
  7651. /* Make "local" variables properly shadow previous ones */
  7652. IF_HUSH_LOCAL(enter_var_nest_level();)
  7653. IF_HUSH_LOCAL(G.func_nest_level++;)
  7654. /* On MMU, funcp->body is always non-NULL */
  7655. # if !BB_MMU
  7656. if (!funcp->body) {
  7657. /* Function defined by -F */
  7658. parse_and_run_string(funcp->body_as_string);
  7659. rc = G.last_exitcode;
  7660. } else
  7661. # endif
  7662. {
  7663. rc = run_list(funcp->body);
  7664. }
  7665. IF_HUSH_LOCAL(G.func_nest_level--;)
  7666. IF_HUSH_LOCAL(leave_var_nest_level();)
  7667. G_flag_return_in_progress = sv_flg;
  7668. # if ENABLE_HUSH_TRAP
  7669. debug_printf_exec("G.return_exitcode=-1\n");
  7670. G.return_exitcode = -1; /* invalidate stashed return value */
  7671. # endif
  7672. restore_G_args(&sv, argv);
  7673. return rc;
  7674. }
  7675. #endif /* ENABLE_HUSH_FUNCTIONS */
  7676. #if BB_MMU
  7677. #define exec_builtin(to_free, x, argv) \
  7678. exec_builtin(x, argv)
  7679. #else
  7680. #define exec_builtin(to_free, x, argv) \
  7681. exec_builtin(to_free, argv)
  7682. #endif
  7683. static void exec_builtin(char ***to_free,
  7684. const struct built_in_command *x,
  7685. char **argv) NORETURN;
  7686. static void exec_builtin(char ***to_free,
  7687. const struct built_in_command *x,
  7688. char **argv)
  7689. {
  7690. #if BB_MMU
  7691. int rcode;
  7692. fflush_all();
  7693. //? close_saved_fds_and_FILE_fds();
  7694. rcode = x->b_function(argv);
  7695. fflush_all();
  7696. _exit(rcode);
  7697. #else
  7698. fflush_all();
  7699. /* On NOMMU, we must never block!
  7700. * Example: { sleep 99 | read line; } & echo Ok
  7701. */
  7702. re_execute_shell(to_free,
  7703. argv[0],
  7704. G.global_argv[0],
  7705. G.global_argv + 1,
  7706. argv);
  7707. #endif
  7708. }
  7709. static void execvp_or_die(char **argv) NORETURN;
  7710. static void execvp_or_die(char **argv)
  7711. {
  7712. int e;
  7713. debug_printf_exec("execing '%s'\n", argv[0]);
  7714. /* Don't propagate SIG_IGN to the child */
  7715. if (SPECIAL_JOBSTOP_SIGS != 0)
  7716. switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
  7717. execvp(argv[0], argv);
  7718. e = 2;
  7719. if (errno == EACCES) e = 126;
  7720. if (errno == ENOENT) e = 127;
  7721. bb_perror_msg("can't execute '%s'", argv[0]);
  7722. _exit(e);
  7723. }
  7724. #if ENABLE_HUSH_MODE_X
  7725. static void x_mode_print_optionally_squoted(const char *str)
  7726. {
  7727. unsigned len;
  7728. const char *cp;
  7729. cp = str;
  7730. /* the set of chars which-cause-string-to-be-squoted mimics bash */
  7731. /* test a char with: bash -c 'set -x; echo "CH"' */
  7732. if (str[strcspn(str, "\\\"'`$(){}[]<>;#&|~*?!^"
  7733. " " "\001\002\003\004\005\006\007"
  7734. "\010\011\012\013\014\015\016\017"
  7735. "\020\021\022\023\024\025\026\027"
  7736. "\030\031\032\033\034\035\036\037"
  7737. )
  7738. ] == '\0'
  7739. ) {
  7740. /* string has no special chars */
  7741. x_mode_addstr(str);
  7742. return;
  7743. }
  7744. cp = str;
  7745. for (;;) {
  7746. /* print '....' up to EOL or first squote */
  7747. len = (int)(strchrnul(cp, '\'') - cp);
  7748. if (len != 0) {
  7749. x_mode_addchr('\'');
  7750. x_mode_addblock(cp, len);
  7751. x_mode_addchr('\'');
  7752. cp += len;
  7753. }
  7754. if (*cp == '\0')
  7755. break;
  7756. /* string contains squote(s), print them as \' */
  7757. x_mode_addchr('\\');
  7758. x_mode_addchr('\'');
  7759. cp++;
  7760. }
  7761. }
  7762. static void dump_cmd_in_x_mode(char **argv)
  7763. {
  7764. if (G_x_mode && argv) {
  7765. unsigned n;
  7766. /* "+[+++...][ cmd...]\n\0" */
  7767. x_mode_prefix();
  7768. n = 0;
  7769. while (argv[n]) {
  7770. x_mode_addchr(' ');
  7771. if (argv[n][0] == '\0') {
  7772. x_mode_addchr('\'');
  7773. x_mode_addchr('\'');
  7774. } else {
  7775. x_mode_print_optionally_squoted(argv[n]);
  7776. }
  7777. n++;
  7778. }
  7779. x_mode_flush();
  7780. }
  7781. }
  7782. #else
  7783. # define dump_cmd_in_x_mode(argv) ((void)0)
  7784. #endif
  7785. #if ENABLE_HUSH_COMMAND
  7786. static void if_command_vV_print_and_exit(char opt_vV, char *cmd, const char *explanation)
  7787. {
  7788. char *to_free;
  7789. if (!opt_vV)
  7790. return;
  7791. to_free = NULL;
  7792. if (!explanation) {
  7793. char *path = getenv("PATH");
  7794. explanation = to_free = find_executable(cmd, &path); /* path == NULL is ok */
  7795. if (!explanation)
  7796. _exit(1); /* PROG was not found */
  7797. if (opt_vV != 'V')
  7798. cmd = to_free; /* -v PROG prints "/path/to/PROG" */
  7799. }
  7800. printf((opt_vV == 'V') ? "%s is %s\n" : "%s\n", cmd, explanation);
  7801. free(to_free);
  7802. fflush_all();
  7803. _exit(0);
  7804. }
  7805. #else
  7806. # define if_command_vV_print_and_exit(a,b,c) ((void)0)
  7807. #endif
  7808. #if BB_MMU
  7809. #define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
  7810. pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
  7811. #define pseudo_exec(nommu_save, command, argv_expanded) \
  7812. pseudo_exec(command, argv_expanded)
  7813. #endif
  7814. /* Called after [v]fork() in run_pipe, or from builtin_exec.
  7815. * Never returns.
  7816. * Don't exit() here. If you don't exec, use _exit instead.
  7817. * The at_exit handlers apparently confuse the calling process,
  7818. * in particular stdin handling. Not sure why? -- because of vfork! (vda)
  7819. */
  7820. static void pseudo_exec_argv(nommu_save_t *nommu_save,
  7821. char **argv, int assignment_cnt,
  7822. char **argv_expanded) NORETURN;
  7823. static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
  7824. char **argv, int assignment_cnt,
  7825. char **argv_expanded)
  7826. {
  7827. const struct built_in_command *x;
  7828. struct variable **sv_shadowed;
  7829. char **new_env;
  7830. IF_HUSH_COMMAND(char opt_vV = 0;)
  7831. IF_HUSH_FUNCTIONS(const struct function *funcp;)
  7832. new_env = expand_assignments(argv, assignment_cnt);
  7833. dump_cmd_in_x_mode(new_env);
  7834. if (!argv[assignment_cnt]) {
  7835. /* Case when we are here: ... | var=val | ...
  7836. * (note that we do not exit early, i.e., do not optimize out
  7837. * expand_assignments(): think about ... | var=`sleep 1` | ...
  7838. */
  7839. free_strings(new_env);
  7840. _exit(EXIT_SUCCESS);
  7841. }
  7842. sv_shadowed = G.shadowed_vars_pp;
  7843. #if BB_MMU
  7844. G.shadowed_vars_pp = NULL; /* "don't save, free them instead" */
  7845. #else
  7846. G.shadowed_vars_pp = &nommu_save->old_vars;
  7847. G.var_nest_level++;
  7848. #endif
  7849. set_vars_and_save_old(new_env);
  7850. G.shadowed_vars_pp = sv_shadowed;
  7851. if (argv_expanded) {
  7852. argv = argv_expanded;
  7853. } else {
  7854. argv = expand_strvec_to_strvec(argv + assignment_cnt);
  7855. #if !BB_MMU
  7856. nommu_save->argv = argv;
  7857. #endif
  7858. }
  7859. dump_cmd_in_x_mode(argv);
  7860. #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
  7861. if (strchr(argv[0], '/') != NULL)
  7862. goto skip;
  7863. #endif
  7864. #if ENABLE_HUSH_FUNCTIONS
  7865. /* Check if the command matches any functions (this goes before bltins) */
  7866. funcp = find_function(argv[0]);
  7867. if (funcp)
  7868. exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
  7869. #endif
  7870. #if ENABLE_HUSH_COMMAND
  7871. /* "command BAR": run BAR without looking it up among functions
  7872. * "command -v BAR": print "BAR" or "/path/to/BAR"; or exit 1
  7873. * "command -V BAR": print "BAR is {a function,a shell builtin,/path/to/BAR}"
  7874. */
  7875. while (strcmp(argv[0], "command") == 0 && argv[1]) {
  7876. char *p;
  7877. argv++;
  7878. p = *argv;
  7879. if (p[0] != '-' || !p[1])
  7880. continue; /* bash allows "command command command [-OPT] BAR" */
  7881. for (;;) {
  7882. p++;
  7883. switch (*p) {
  7884. case '\0':
  7885. argv++;
  7886. p = *argv;
  7887. if (p[0] != '-' || !p[1])
  7888. goto after_opts;
  7889. continue; /* next arg is also -opts, process it too */
  7890. case 'v':
  7891. case 'V':
  7892. opt_vV = *p;
  7893. continue;
  7894. default:
  7895. bb_error_msg_and_die("%s: %s: invalid option", "command", argv[0]);
  7896. }
  7897. }
  7898. }
  7899. after_opts:
  7900. # if ENABLE_HUSH_FUNCTIONS
  7901. if (opt_vV && find_function(argv[0]))
  7902. if_command_vV_print_and_exit(opt_vV, argv[0], "a function");
  7903. # endif
  7904. #endif
  7905. /* Check if the command matches any of the builtins.
  7906. * Depending on context, this might be redundant. But it's
  7907. * easier to waste a few CPU cycles than it is to figure out
  7908. * if this is one of those cases.
  7909. */
  7910. /* Why "BB_MMU ? :" difference in logic? -
  7911. * On NOMMU, it is more expensive to re-execute shell
  7912. * just in order to run echo or test builtin.
  7913. * It's better to skip it here and run corresponding
  7914. * non-builtin later. */
  7915. x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
  7916. if (x) {
  7917. if_command_vV_print_and_exit(opt_vV, argv[0], "a shell builtin");
  7918. exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
  7919. }
  7920. #if ENABLE_FEATURE_SH_STANDALONE
  7921. /* Check if the command matches any busybox applets */
  7922. {
  7923. int a = find_applet_by_name(argv[0]);
  7924. if (a >= 0) {
  7925. if_command_vV_print_and_exit(opt_vV, argv[0], "an applet");
  7926. # if BB_MMU /* see above why on NOMMU it is not allowed */
  7927. if (APPLET_IS_NOEXEC(a)) {
  7928. /* Do not leak open fds from opened script files etc.
  7929. * Testcase: interactive "ls -l /proc/self/fd"
  7930. * should not show tty fd open.
  7931. */
  7932. close_saved_fds_and_FILE_fds();
  7933. //FIXME: should also close saved redir fds
  7934. //This casuses test failures in
  7935. //redir_children_should_not_see_saved_fd_2.tests
  7936. //redir_children_should_not_see_saved_fd_3.tests
  7937. //if you replace "busybox find" with just "find" in them
  7938. /* Without this, "rm -i FILE" can't be ^C'ed: */
  7939. switch_off_special_sigs(G.special_sig_mask);
  7940. debug_printf_exec("running applet '%s'\n", argv[0]);
  7941. run_noexec_applet_and_exit(a, argv[0], argv);
  7942. }
  7943. # endif
  7944. /* Re-exec ourselves */
  7945. debug_printf_exec("re-execing applet '%s'\n", argv[0]);
  7946. /* Don't propagate SIG_IGN to the child */
  7947. if (SPECIAL_JOBSTOP_SIGS != 0)
  7948. switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
  7949. execv(bb_busybox_exec_path, argv);
  7950. /* If they called chroot or otherwise made the binary no longer
  7951. * executable, fall through */
  7952. }
  7953. }
  7954. #endif
  7955. #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
  7956. skip:
  7957. #endif
  7958. if_command_vV_print_and_exit(opt_vV, argv[0], NULL);
  7959. execvp_or_die(argv);
  7960. }
  7961. /* Called after [v]fork() in run_pipe
  7962. */
  7963. static void pseudo_exec(nommu_save_t *nommu_save,
  7964. struct command *command,
  7965. char **argv_expanded) NORETURN;
  7966. static void pseudo_exec(nommu_save_t *nommu_save,
  7967. struct command *command,
  7968. char **argv_expanded)
  7969. {
  7970. #if ENABLE_HUSH_FUNCTIONS
  7971. if (command->cmd_type == CMD_FUNCDEF) {
  7972. /* Ignore funcdefs in pipes:
  7973. * true | f() { cmd }
  7974. */
  7975. _exit(0);
  7976. }
  7977. #endif
  7978. if (command->argv) {
  7979. pseudo_exec_argv(nommu_save, command->argv,
  7980. command->assignment_cnt, argv_expanded);
  7981. }
  7982. if (command->group) {
  7983. /* Cases when we are here:
  7984. * ( list )
  7985. * { list } &
  7986. * ... | ( list ) | ...
  7987. * ... | { list } | ...
  7988. */
  7989. #if BB_MMU
  7990. int rcode;
  7991. debug_printf_exec("pseudo_exec: run_list\n");
  7992. reset_traps_to_defaults();
  7993. rcode = run_list(command->group);
  7994. /* OK to leak memory by not calling free_pipe_list,
  7995. * since this process is about to exit */
  7996. _exit(rcode);
  7997. #else
  7998. re_execute_shell(&nommu_save->argv_from_re_execing,
  7999. command->group_as_string,
  8000. G.global_argv[0],
  8001. G.global_argv + 1,
  8002. NULL);
  8003. #endif
  8004. }
  8005. /* Case when we are here: ... | >file */
  8006. debug_printf_exec("pseudo_exec'ed null command\n");
  8007. _exit(EXIT_SUCCESS);
  8008. }
  8009. #if ENABLE_HUSH_JOB
  8010. static const char *get_cmdtext(struct pipe *pi)
  8011. {
  8012. char **argv;
  8013. char *p;
  8014. int len;
  8015. /* This is subtle. ->cmdtext is created only on first backgrounding.
  8016. * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
  8017. * On subsequent bg argv is trashed, but we won't use it */
  8018. if (pi->cmdtext)
  8019. return pi->cmdtext;
  8020. argv = pi->cmds[0].argv;
  8021. if (!argv) {
  8022. pi->cmdtext = xzalloc(1);
  8023. return pi->cmdtext;
  8024. }
  8025. len = 0;
  8026. do {
  8027. len += strlen(*argv) + 1;
  8028. } while (*++argv);
  8029. p = xmalloc(len);
  8030. pi->cmdtext = p;
  8031. argv = pi->cmds[0].argv;
  8032. do {
  8033. p = stpcpy(p, *argv);
  8034. *p++ = ' ';
  8035. } while (*++argv);
  8036. p[-1] = '\0';
  8037. return pi->cmdtext;
  8038. }
  8039. static void remove_job_from_table(struct pipe *pi)
  8040. {
  8041. struct pipe *prev_pipe;
  8042. if (pi == G.job_list) {
  8043. G.job_list = pi->next;
  8044. } else {
  8045. prev_pipe = G.job_list;
  8046. while (prev_pipe->next != pi)
  8047. prev_pipe = prev_pipe->next;
  8048. prev_pipe->next = pi->next;
  8049. }
  8050. G.last_jobid = 0;
  8051. if (G.job_list)
  8052. G.last_jobid = G.job_list->jobid;
  8053. }
  8054. static void delete_finished_job(struct pipe *pi)
  8055. {
  8056. remove_job_from_table(pi);
  8057. free_pipe(pi);
  8058. }
  8059. static void clean_up_last_dead_job(void)
  8060. {
  8061. if (G.job_list && !G.job_list->alive_cmds)
  8062. delete_finished_job(G.job_list);
  8063. }
  8064. static void insert_job_into_table(struct pipe *pi)
  8065. {
  8066. struct pipe *job, **jobp;
  8067. int i;
  8068. clean_up_last_dead_job();
  8069. /* Find the end of the list, and find next job ID to use */
  8070. i = 0;
  8071. jobp = &G.job_list;
  8072. while ((job = *jobp) != NULL) {
  8073. if (job->jobid > i)
  8074. i = job->jobid;
  8075. jobp = &job->next;
  8076. }
  8077. pi->jobid = i + 1;
  8078. /* Create a new job struct at the end */
  8079. job = *jobp = xmemdup(pi, sizeof(*pi));
  8080. job->next = NULL;
  8081. job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
  8082. /* Cannot copy entire pi->cmds[] vector! This causes double frees */
  8083. for (i = 0; i < pi->num_cmds; i++) {
  8084. job->cmds[i].pid = pi->cmds[i].pid;
  8085. /* all other fields are not used and stay zero */
  8086. }
  8087. job->cmdtext = xstrdup(get_cmdtext(pi));
  8088. if (G_interactive_fd)
  8089. printf("[%u] %u %s\n", job->jobid, (unsigned)job->cmds[0].pid, job->cmdtext);
  8090. G.last_jobid = job->jobid;
  8091. }
  8092. #endif /* JOB */
  8093. static int job_exited_or_stopped(struct pipe *pi)
  8094. {
  8095. int rcode, i;
  8096. if (pi->alive_cmds != pi->stopped_cmds)
  8097. return -1;
  8098. /* All processes in fg pipe have exited or stopped */
  8099. rcode = 0;
  8100. i = pi->num_cmds;
  8101. while (--i >= 0) {
  8102. rcode = pi->cmds[i].cmd_exitcode;
  8103. /* usually last process gives overall exitstatus,
  8104. * but with "set -o pipefail", last *failed* process does */
  8105. if (G.o_opt[OPT_O_PIPEFAIL] == 0 || rcode != 0)
  8106. break;
  8107. }
  8108. IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
  8109. return rcode;
  8110. }
  8111. static int process_wait_result(struct pipe *fg_pipe, pid_t childpid, int status)
  8112. {
  8113. #if ENABLE_HUSH_JOB
  8114. struct pipe *pi;
  8115. #endif
  8116. int i, dead;
  8117. dead = WIFEXITED(status) || WIFSIGNALED(status);
  8118. #if DEBUG_JOBS
  8119. if (WIFSTOPPED(status))
  8120. debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
  8121. childpid, WSTOPSIG(status), WEXITSTATUS(status));
  8122. if (WIFSIGNALED(status))
  8123. debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
  8124. childpid, WTERMSIG(status), WEXITSTATUS(status));
  8125. if (WIFEXITED(status))
  8126. debug_printf_jobs("pid %d exited, exitcode %d\n",
  8127. childpid, WEXITSTATUS(status));
  8128. #endif
  8129. /* Were we asked to wait for a fg pipe? */
  8130. if (fg_pipe) {
  8131. i = fg_pipe->num_cmds;
  8132. while (--i >= 0) {
  8133. int rcode;
  8134. debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
  8135. if (fg_pipe->cmds[i].pid != childpid)
  8136. continue;
  8137. if (dead) {
  8138. int ex;
  8139. fg_pipe->cmds[i].pid = 0;
  8140. fg_pipe->alive_cmds--;
  8141. ex = WEXITSTATUS(status);
  8142. /* bash prints killer signal's name for *last*
  8143. * process in pipe (prints just newline for SIGINT/SIGPIPE).
  8144. * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
  8145. */
  8146. if (WIFSIGNALED(status)) {
  8147. int sig = WTERMSIG(status);
  8148. if (G.run_list_level == 1
  8149. /* ^^^^^ Do not print in nested contexts, example:
  8150. * echo `sleep 1; sh -c 'kill -9 $$'` - prints "137", NOT "Killed 137"
  8151. */
  8152. && i == fg_pipe->num_cmds-1
  8153. ) {
  8154. /* strsignal() is for bash compat. ~600 bloat versus bbox's get_signame() */
  8155. puts(sig == SIGINT || sig == SIGPIPE ? "" : strsignal(sig));
  8156. }
  8157. /* TODO: if (WCOREDUMP(status)) + " (core dumped)"; */
  8158. /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
  8159. * Maybe we need to use sig | 128? */
  8160. ex = sig + 128;
  8161. }
  8162. fg_pipe->cmds[i].cmd_exitcode = ex;
  8163. } else {
  8164. fg_pipe->stopped_cmds++;
  8165. }
  8166. debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
  8167. fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
  8168. rcode = job_exited_or_stopped(fg_pipe);
  8169. if (rcode >= 0) {
  8170. /* Note: *non-interactive* bash does not continue if all processes in fg pipe
  8171. * are stopped. Testcase: "cat | cat" in a script (not on command line!)
  8172. * and "killall -STOP cat" */
  8173. if (G_interactive_fd) {
  8174. #if ENABLE_HUSH_JOB
  8175. if (fg_pipe->alive_cmds != 0)
  8176. insert_job_into_table(fg_pipe);
  8177. #endif
  8178. return rcode;
  8179. }
  8180. if (fg_pipe->alive_cmds == 0)
  8181. return rcode;
  8182. }
  8183. /* There are still running processes in the fg_pipe */
  8184. return -1;
  8185. }
  8186. /* It wasn't in fg_pipe, look for process in bg pipes */
  8187. }
  8188. #if ENABLE_HUSH_JOB
  8189. /* We were asked to wait for bg or orphaned children */
  8190. /* No need to remember exitcode in this case */
  8191. for (pi = G.job_list; pi; pi = pi->next) {
  8192. for (i = 0; i < pi->num_cmds; i++) {
  8193. if (pi->cmds[i].pid == childpid)
  8194. goto found_pi_and_prognum;
  8195. }
  8196. }
  8197. /* Happens when shell is used as init process (init=/bin/sh) */
  8198. debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
  8199. return -1; /* this wasn't a process from fg_pipe */
  8200. found_pi_and_prognum:
  8201. if (dead) {
  8202. /* child exited */
  8203. int rcode = WEXITSTATUS(status);
  8204. if (WIFSIGNALED(status))
  8205. rcode = 128 + WTERMSIG(status);
  8206. pi->cmds[i].cmd_exitcode = rcode;
  8207. if (G.last_bg_pid == pi->cmds[i].pid)
  8208. G.last_bg_pid_exitcode = rcode;
  8209. pi->cmds[i].pid = 0;
  8210. pi->alive_cmds--;
  8211. if (!pi->alive_cmds) {
  8212. # if ENABLE_HUSH_BASH_COMPAT
  8213. G.dead_job_exitcode = job_exited_or_stopped(pi);
  8214. # endif
  8215. if (G_interactive_fd) {
  8216. printf(JOB_STATUS_FORMAT, pi->jobid,
  8217. "Done", pi->cmdtext);
  8218. delete_finished_job(pi);
  8219. } else {
  8220. /*
  8221. * bash deletes finished jobs from job table only in interactive mode,
  8222. * after "jobs" cmd, or if pid of a new process matches one of the old ones
  8223. * (see cleanup_dead_jobs(), delete_old_job(), J_NOTIFIED in bash source).
  8224. * Testcase script: "(exit 3) & sleep 1; wait %1; echo $?" prints 3 in bash.
  8225. * We only retain one "dead" job, if it's the single job on the list.
  8226. * This covers most of real-world scenarios where this is useful.
  8227. */
  8228. if (pi != G.job_list)
  8229. delete_finished_job(pi);
  8230. }
  8231. }
  8232. } else {
  8233. /* child stopped */
  8234. pi->stopped_cmds++;
  8235. }
  8236. #endif
  8237. return -1; /* this wasn't a process from fg_pipe */
  8238. }
  8239. /* Check to see if any processes have exited -- if they have,
  8240. * figure out why and see if a job has completed.
  8241. *
  8242. * If non-NULL fg_pipe: wait for its completion or stop.
  8243. * Return its exitcode or zero if stopped.
  8244. *
  8245. * Alternatively (fg_pipe == NULL, waitfor_pid != 0):
  8246. * waitpid(WNOHANG), if waitfor_pid exits or stops, return exitcode+1,
  8247. * else return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
  8248. * or 0 if no children changed status.
  8249. *
  8250. * Alternatively (fg_pipe == NULL, waitfor_pid == 0),
  8251. * return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
  8252. * or 0 if no children changed status.
  8253. */
  8254. static int checkjobs(struct pipe *fg_pipe, pid_t waitfor_pid)
  8255. {
  8256. int attributes;
  8257. int status;
  8258. int rcode = 0;
  8259. debug_printf_jobs("checkjobs %p\n", fg_pipe);
  8260. attributes = WUNTRACED;
  8261. if (fg_pipe == NULL)
  8262. attributes |= WNOHANG;
  8263. errno = 0;
  8264. #if ENABLE_HUSH_FAST
  8265. if (G.handled_SIGCHLD == G.count_SIGCHLD) {
  8266. //bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
  8267. //getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
  8268. /* There was neither fork nor SIGCHLD since last waitpid */
  8269. /* Avoid doing waitpid syscall if possible */
  8270. if (!G.we_have_children) {
  8271. errno = ECHILD;
  8272. return -1;
  8273. }
  8274. if (fg_pipe == NULL) { /* is WNOHANG set? */
  8275. /* We have children, but they did not exit
  8276. * or stop yet (we saw no SIGCHLD) */
  8277. return 0;
  8278. }
  8279. /* else: !WNOHANG, waitpid will block, can't short-circuit */
  8280. }
  8281. #endif
  8282. /* Do we do this right?
  8283. * bash-3.00# sleep 20 | false
  8284. * <ctrl-Z pressed>
  8285. * [3]+ Stopped sleep 20 | false
  8286. * bash-3.00# echo $?
  8287. * 1 <========== bg pipe is not fully done, but exitcode is already known!
  8288. * [hush 1.14.0: yes we do it right]
  8289. */
  8290. while (1) {
  8291. pid_t childpid;
  8292. #if ENABLE_HUSH_FAST
  8293. int i;
  8294. i = G.count_SIGCHLD;
  8295. #endif
  8296. childpid = waitpid(-1, &status, attributes);
  8297. if (childpid <= 0) {
  8298. if (childpid && errno != ECHILD)
  8299. bb_simple_perror_msg("waitpid");
  8300. #if ENABLE_HUSH_FAST
  8301. else { /* Until next SIGCHLD, waitpid's are useless */
  8302. G.we_have_children = (childpid == 0);
  8303. G.handled_SIGCHLD = i;
  8304. //bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
  8305. }
  8306. #endif
  8307. /* ECHILD (no children), or 0 (no change in children status) */
  8308. rcode = childpid;
  8309. break;
  8310. }
  8311. rcode = process_wait_result(fg_pipe, childpid, status);
  8312. if (rcode >= 0) {
  8313. /* fg_pipe exited or stopped */
  8314. break;
  8315. }
  8316. if (childpid == waitfor_pid) { /* "wait PID" */
  8317. debug_printf_exec("childpid==waitfor_pid:%d status:0x%08x\n", childpid, status);
  8318. rcode = WEXITSTATUS(status);
  8319. if (WIFSIGNALED(status))
  8320. rcode = 128 + WTERMSIG(status);
  8321. if (WIFSTOPPED(status))
  8322. /* bash: "cmd & wait $!" and cmd stops: $? = 128 + stopsig */
  8323. rcode = 128 + WSTOPSIG(status);
  8324. rcode++;
  8325. break; /* "wait PID" called us, give it exitcode+1 */
  8326. }
  8327. #if ENABLE_HUSH_BASH_COMPAT
  8328. if (-1 == waitfor_pid /* "wait -n" (wait for any one job) */
  8329. && G.dead_job_exitcode >= 0 /* some job did finish */
  8330. ) {
  8331. debug_printf_exec("waitfor_pid:-1\n");
  8332. rcode = G.dead_job_exitcode + 1;
  8333. break;
  8334. }
  8335. #endif
  8336. /* This wasn't one of our processes, or */
  8337. /* fg_pipe still has running processes, do waitpid again */
  8338. } /* while (waitpid succeeds)... */
  8339. return rcode;
  8340. }
  8341. #if ENABLE_HUSH_JOB
  8342. static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
  8343. {
  8344. pid_t p;
  8345. int rcode = checkjobs(fg_pipe, 0 /*(no pid to wait for)*/);
  8346. if (G_saved_tty_pgrp) {
  8347. /* Job finished, move the shell to the foreground */
  8348. p = getpgrp(); /* our process group id */
  8349. debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
  8350. tcsetpgrp(G_interactive_fd, p);
  8351. }
  8352. return rcode;
  8353. }
  8354. #endif
  8355. /* Start all the jobs, but don't wait for anything to finish.
  8356. * See checkjobs().
  8357. *
  8358. * Return code is normally -1, when the caller has to wait for children
  8359. * to finish to determine the exit status of the pipe. If the pipe
  8360. * is a simple builtin command, however, the action is done by the
  8361. * time run_pipe returns, and the exit code is provided as the
  8362. * return value.
  8363. *
  8364. * Returns -1 only if started some children. IOW: we have to
  8365. * mask out retvals of builtins etc with 0xff!
  8366. *
  8367. * The only case when we do not need to [v]fork is when the pipe
  8368. * is single, non-backgrounded, non-subshell command. Examples:
  8369. * cmd ; ... { list } ; ...
  8370. * cmd && ... { list } && ...
  8371. * cmd || ... { list } || ...
  8372. * If it is, then we can run cmd as a builtin, NOFORK,
  8373. * or (if SH_STANDALONE) an applet, and we can run the { list }
  8374. * with run_list. If it isn't one of these, we fork and exec cmd.
  8375. *
  8376. * Cases when we must fork:
  8377. * non-single: cmd | cmd
  8378. * backgrounded: cmd & { list } &
  8379. * subshell: ( list ) [&]
  8380. */
  8381. #if !ENABLE_HUSH_MODE_X
  8382. #define redirect_and_varexp_helper(command, sqp, argv_expanded) \
  8383. redirect_and_varexp_helper(command, sqp)
  8384. #endif
  8385. static int redirect_and_varexp_helper(
  8386. struct command *command,
  8387. struct squirrel **sqp,
  8388. char **argv_expanded)
  8389. {
  8390. /* Assignments occur before redirects. Try:
  8391. * a=`sleep 1` sleep 2 3>/qwe/rty
  8392. */
  8393. char **new_env = expand_assignments(command->argv, command->assignment_cnt);
  8394. dump_cmd_in_x_mode(new_env);
  8395. dump_cmd_in_x_mode(argv_expanded);
  8396. /* this takes ownership of new_env[i] elements, and frees new_env: */
  8397. set_vars_and_save_old(new_env);
  8398. return setup_redirects(command, sqp);
  8399. }
  8400. static NOINLINE int run_pipe(struct pipe *pi)
  8401. {
  8402. static const char *const null_ptr = NULL;
  8403. int cmd_no;
  8404. int next_infd;
  8405. struct command *command;
  8406. char **argv_expanded;
  8407. char **argv;
  8408. struct squirrel *squirrel = NULL;
  8409. int rcode;
  8410. debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
  8411. debug_enter();
  8412. /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
  8413. * Result should be 3 lines: q w e, qwe, q w e
  8414. */
  8415. if (G.ifs_whitespace != G.ifs)
  8416. free(G.ifs_whitespace);
  8417. G.ifs = get_local_var_value("IFS");
  8418. if (G.ifs) {
  8419. char *p;
  8420. G.ifs_whitespace = (char*)G.ifs;
  8421. p = skip_whitespace(G.ifs);
  8422. if (*p) {
  8423. /* Not all $IFS is whitespace */
  8424. char *d;
  8425. int len = p - G.ifs;
  8426. p = skip_non_whitespace(p);
  8427. G.ifs_whitespace = xmalloc(len + strlen(p) + 1); /* can overestimate */
  8428. d = mempcpy(G.ifs_whitespace, G.ifs, len);
  8429. while (*p) {
  8430. if (isspace(*p))
  8431. *d++ = *p;
  8432. p++;
  8433. }
  8434. *d = '\0';
  8435. }
  8436. } else {
  8437. G.ifs = defifs;
  8438. G.ifs_whitespace = (char*)G.ifs;
  8439. }
  8440. IF_HUSH_JOB(pi->pgrp = -1;)
  8441. pi->stopped_cmds = 0;
  8442. command = &pi->cmds[0];
  8443. argv_expanded = NULL;
  8444. if (pi->num_cmds != 1
  8445. || pi->followup == PIPE_BG
  8446. || command->cmd_type == CMD_SUBSHELL
  8447. ) {
  8448. goto must_fork;
  8449. }
  8450. pi->alive_cmds = 1;
  8451. debug_printf_exec(": group:%p argv:'%s'\n",
  8452. command->group, command->argv ? command->argv[0] : "NONE");
  8453. if (command->group) {
  8454. #if ENABLE_HUSH_FUNCTIONS
  8455. if (command->cmd_type == CMD_FUNCDEF) {
  8456. /* "executing" func () { list } */
  8457. struct function *funcp;
  8458. funcp = new_function(command->argv[0]);
  8459. /* funcp->name is already set to argv[0] */
  8460. funcp->body = command->group;
  8461. # if !BB_MMU
  8462. funcp->body_as_string = command->group_as_string;
  8463. command->group_as_string = NULL;
  8464. # endif
  8465. command->group = NULL;
  8466. command->argv[0] = NULL;
  8467. debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
  8468. funcp->parent_cmd = command;
  8469. command->child_func = funcp;
  8470. debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
  8471. debug_leave();
  8472. return EXIT_SUCCESS;
  8473. }
  8474. #endif
  8475. /* { list } */
  8476. debug_printf_exec("non-subshell group\n");
  8477. rcode = 1; /* exitcode if redir failed */
  8478. if (setup_redirects(command, &squirrel) == 0) {
  8479. debug_printf_exec(": run_list\n");
  8480. //FIXME: we need to pass squirrel down into run_list()
  8481. //for SH_STANDALONE case, or else this construct:
  8482. // { find /proc/self/fd; true; } >FILE; cmd2
  8483. //has no way of closing saved fd#1 for "find",
  8484. //and in SH_STANDALONE mode, "find" is not execed,
  8485. //therefore CLOEXEC on saved fd does not help.
  8486. rcode = run_list(command->group) & 0xff;
  8487. }
  8488. restore_redirects(squirrel);
  8489. IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
  8490. debug_leave();
  8491. debug_printf_exec("run_pipe: return %d\n", rcode);
  8492. return rcode;
  8493. }
  8494. argv = command->argv ? command->argv : (char **) &null_ptr;
  8495. {
  8496. const struct built_in_command *x;
  8497. IF_HUSH_FUNCTIONS(const struct function *funcp;)
  8498. IF_NOT_HUSH_FUNCTIONS(enum { funcp = 0 };)
  8499. struct variable **sv_shadowed;
  8500. struct variable *old_vars;
  8501. #if ENABLE_HUSH_LINENO_VAR
  8502. G.execute_lineno = command->lineno;
  8503. #endif
  8504. if (argv[command->assignment_cnt] == NULL) {
  8505. /* Assignments, but no command.
  8506. * Ensure redirects take effect (that is, create files).
  8507. * Try "a=t >file"
  8508. */
  8509. unsigned i;
  8510. G.expand_exitcode = 0;
  8511. only_assignments:
  8512. rcode = setup_redirects(command, &squirrel);
  8513. restore_redirects(squirrel);
  8514. /* Set shell variables */
  8515. i = 0;
  8516. while (i < command->assignment_cnt) {
  8517. char *p = expand_string_to_string(argv[i],
  8518. EXP_FLAG_ESC_GLOB_CHARS,
  8519. /*unbackslash:*/ 1
  8520. );
  8521. #if ENABLE_HUSH_MODE_X
  8522. if (G_x_mode) {
  8523. char *eq;
  8524. if (i == 0)
  8525. x_mode_prefix();
  8526. x_mode_addchr(' ');
  8527. eq = strchrnul(p, '=');
  8528. if (*eq) eq++;
  8529. x_mode_addblock(p, (eq - p));
  8530. x_mode_print_optionally_squoted(eq);
  8531. x_mode_flush();
  8532. }
  8533. #endif
  8534. debug_printf_env("set shell var:'%s'->'%s'\n", *argv, p);
  8535. if (set_local_var(p, /*flag:*/ 0)) {
  8536. /* assignment to readonly var / putenv error? */
  8537. rcode = 1;
  8538. }
  8539. i++;
  8540. }
  8541. /* Redirect error sets $? to 1. Otherwise,
  8542. * if evaluating assignment value set $?, retain it.
  8543. * Else, clear $?:
  8544. * false; q=`exit 2`; echo $? - should print 2
  8545. * false; x=1; echo $? - should print 0
  8546. * Because of the 2nd case, we can't just use G.last_exitcode.
  8547. */
  8548. if (rcode == 0)
  8549. rcode = G.expand_exitcode;
  8550. IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
  8551. debug_leave();
  8552. debug_printf_exec("run_pipe: return %d\n", rcode);
  8553. return rcode;
  8554. }
  8555. /* Expand the rest into (possibly) many strings each */
  8556. #if defined(CMD_TEST2_SINGLEWORD_NOGLOB)
  8557. if (command->cmd_type == CMD_TEST2_SINGLEWORD_NOGLOB)
  8558. argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
  8559. else
  8560. #endif
  8561. #if defined(CMD_SINGLEWORD_NOGLOB)
  8562. if (command->cmd_type == CMD_SINGLEWORD_NOGLOB)
  8563. argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
  8564. else
  8565. #endif
  8566. argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
  8567. /* If someone gives us an empty string: `cmd with empty output` */
  8568. if (!argv_expanded[0]) {
  8569. free(argv_expanded);
  8570. /* `false` still has to set exitcode 1 */
  8571. G.expand_exitcode = G.last_exitcode;
  8572. goto only_assignments;
  8573. }
  8574. old_vars = NULL;
  8575. sv_shadowed = G.shadowed_vars_pp;
  8576. /* Check if argv[0] matches any functions (this goes before bltins) */
  8577. IF_HUSH_FUNCTIONS(funcp = find_function(argv_expanded[0]);)
  8578. IF_HUSH_FUNCTIONS(x = NULL;)
  8579. IF_HUSH_FUNCTIONS(if (!funcp))
  8580. x = find_builtin(argv_expanded[0]);
  8581. if (x || funcp) {
  8582. if (x && x->b_function == builtin_exec && argv_expanded[1] == NULL) {
  8583. debug_printf("exec with redirects only\n");
  8584. /*
  8585. * Variable assignments are executed, but then "forgotten":
  8586. * a=`sleep 1;echo A` exec 3>&-; echo $a
  8587. * sleeps, but prints nothing.
  8588. */
  8589. enter_var_nest_level();
  8590. G.shadowed_vars_pp = &old_vars;
  8591. rcode = redirect_and_varexp_helper(command,
  8592. /*squirrel:*/ ERR_PTR,
  8593. argv_expanded
  8594. );
  8595. G.shadowed_vars_pp = sv_shadowed;
  8596. /* rcode=1 can be if redir file can't be opened */
  8597. goto clean_up_and_ret1;
  8598. }
  8599. /* Bump var nesting, or this will leak exported $a:
  8600. * a=b true; env | grep ^a=
  8601. */
  8602. enter_var_nest_level();
  8603. /* Collect all variables "shadowed" by helper
  8604. * (IOW: old vars overridden by "var1=val1 var2=val2 cmd..." syntax)
  8605. * into old_vars list:
  8606. */
  8607. G.shadowed_vars_pp = &old_vars;
  8608. rcode = redirect_and_varexp_helper(command, &squirrel, argv_expanded);
  8609. if (rcode == 0) {
  8610. if (!funcp) {
  8611. /* Do not collect *to old_vars list* vars shadowed
  8612. * by e.g. "local VAR" builtin (collect them
  8613. * in the previously nested list instead):
  8614. * don't want them to be restored immediately
  8615. * after "local" completes.
  8616. */
  8617. G.shadowed_vars_pp = sv_shadowed;
  8618. debug_printf_exec(": builtin '%s' '%s'...\n",
  8619. x->b_cmd, argv_expanded[1]);
  8620. fflush_all();
  8621. rcode = x->b_function(argv_expanded) & 0xff;
  8622. fflush_all();
  8623. }
  8624. #if ENABLE_HUSH_FUNCTIONS
  8625. else {
  8626. debug_printf_exec(": function '%s' '%s'...\n",
  8627. funcp->name, argv_expanded[1]);
  8628. rcode = run_function(funcp, argv_expanded) & 0xff;
  8629. /*
  8630. * But do collect *to old_vars list* vars shadowed
  8631. * within function execution. To that end, restore
  8632. * this pointer _after_ function run:
  8633. */
  8634. G.shadowed_vars_pp = sv_shadowed;
  8635. }
  8636. #endif
  8637. }
  8638. } else
  8639. if (ENABLE_FEATURE_SH_NOFORK && NUM_APPLETS > 1) {
  8640. int n = find_applet_by_name(argv_expanded[0]);
  8641. if (n < 0 || !APPLET_IS_NOFORK(n))
  8642. goto must_fork;
  8643. enter_var_nest_level();
  8644. /* Collect all variables "shadowed" by helper into old_vars list */
  8645. G.shadowed_vars_pp = &old_vars;
  8646. rcode = redirect_and_varexp_helper(command, &squirrel, argv_expanded);
  8647. G.shadowed_vars_pp = sv_shadowed;
  8648. if (rcode == 0) {
  8649. debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
  8650. argv_expanded[0], argv_expanded[1]);
  8651. /*
  8652. * Note: signals (^C) can't interrupt here.
  8653. * We remember them and they will be acted upon
  8654. * after applet returns.
  8655. * This makes applets which can run for a long time
  8656. * and/or wait for user input ineligible for NOFORK:
  8657. * for example, "yes" or "rm" (rm -i waits for input).
  8658. */
  8659. rcode = run_nofork_applet(n, argv_expanded);
  8660. }
  8661. } else
  8662. goto must_fork;
  8663. restore_redirects(squirrel);
  8664. clean_up_and_ret1:
  8665. leave_var_nest_level();
  8666. add_vars(old_vars);
  8667. /*
  8668. * Try "usleep 99999999" + ^C + "echo $?"
  8669. * with FEATURE_SH_NOFORK=y.
  8670. */
  8671. if (!funcp) {
  8672. /* It was builtin or nofork.
  8673. * if this would be a real fork/execed program,
  8674. * it should have died if a fatal sig was received.
  8675. * But OTOH, there was no separate process,
  8676. * the sig was sent to _shell_, not to non-existing
  8677. * child.
  8678. * Let's just handle ^C only, this one is obvious:
  8679. * we aren't ok with exitcode 0 when ^C was pressed
  8680. * during builtin/nofork.
  8681. */
  8682. if (sigismember(&G.pending_set, SIGINT))
  8683. rcode = 128 + SIGINT;
  8684. }
  8685. free(argv_expanded);
  8686. IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
  8687. debug_leave();
  8688. debug_printf_exec("run_pipe return %d\n", rcode);
  8689. return rcode;
  8690. }
  8691. must_fork:
  8692. /* NB: argv_expanded may already be created, and that
  8693. * might include `cmd` runs! Do not rerun it! We *must*
  8694. * use argv_expanded if it's non-NULL */
  8695. /* Going to fork a child per each pipe member */
  8696. pi->alive_cmds = 0;
  8697. next_infd = 0;
  8698. cmd_no = 0;
  8699. while (cmd_no < pi->num_cmds) {
  8700. struct fd_pair pipefds;
  8701. #if !BB_MMU
  8702. int sv_var_nest_level = G.var_nest_level;
  8703. volatile nommu_save_t nommu_save;
  8704. nommu_save.old_vars = NULL;
  8705. nommu_save.argv = NULL;
  8706. nommu_save.argv_from_re_execing = NULL;
  8707. #endif
  8708. command = &pi->cmds[cmd_no];
  8709. cmd_no++;
  8710. if (command->argv) {
  8711. debug_printf_exec(": pipe member '%s' '%s'...\n",
  8712. command->argv[0], command->argv[1]);
  8713. } else {
  8714. debug_printf_exec(": pipe member with no argv\n");
  8715. }
  8716. /* pipes are inserted between pairs of commands */
  8717. pipefds.rd = 0;
  8718. pipefds.wr = 1;
  8719. if (cmd_no < pi->num_cmds)
  8720. xpiped_pair(pipefds);
  8721. #if ENABLE_HUSH_LINENO_VAR
  8722. G.execute_lineno = command->lineno;
  8723. #endif
  8724. command->pid = BB_MMU ? fork() : vfork();
  8725. if (!command->pid) { /* child */
  8726. #if ENABLE_HUSH_JOB
  8727. disable_restore_tty_pgrp_on_exit();
  8728. CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
  8729. /* Every child adds itself to new process group
  8730. * with pgid == pid_of_first_child_in_pipe */
  8731. if (G.run_list_level == 1 && G_interactive_fd) {
  8732. pid_t pgrp;
  8733. pgrp = pi->pgrp;
  8734. if (pgrp < 0) /* true for 1st process only */
  8735. pgrp = getpid();
  8736. if (setpgid(0, pgrp) == 0
  8737. && pi->followup != PIPE_BG
  8738. && G_saved_tty_pgrp /* we have ctty */
  8739. ) {
  8740. /* We do it in *every* child, not just first,
  8741. * to avoid races */
  8742. tcsetpgrp(G_interactive_fd, pgrp);
  8743. }
  8744. }
  8745. #endif
  8746. if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
  8747. /* 1st cmd in backgrounded pipe
  8748. * should have its stdin /dev/null'ed */
  8749. close(0);
  8750. if (open(bb_dev_null, O_RDONLY))
  8751. xopen("/", O_RDONLY);
  8752. } else {
  8753. xmove_fd(next_infd, 0);
  8754. }
  8755. xmove_fd(pipefds.wr, 1);
  8756. if (pipefds.rd > 1)
  8757. close(pipefds.rd);
  8758. /* Like bash, explicit redirects override pipes,
  8759. * and the pipe fd (fd#1) is available for dup'ing:
  8760. * "cmd1 2>&1 | cmd2": fd#1 is duped to fd#2, thus stderr
  8761. * of cmd1 goes into pipe.
  8762. */
  8763. if (setup_redirects(command, NULL)) {
  8764. /* Happens when redir file can't be opened:
  8765. * $ hush -c 'echo FOO >&2 | echo BAR 3>/qwe/rty; echo BAZ'
  8766. * FOO
  8767. * hush: can't open '/qwe/rty': No such file or directory
  8768. * BAZ
  8769. * (echo BAR is not executed, it hits _exit(1) below)
  8770. */
  8771. _exit(1);
  8772. }
  8773. /* Stores to nommu_save list of env vars putenv'ed
  8774. * (NOMMU, on MMU we don't need that) */
  8775. /* cast away volatility... */
  8776. pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
  8777. /* pseudo_exec() does not return */
  8778. }
  8779. /* parent or error */
  8780. #if ENABLE_HUSH_FAST
  8781. G.count_SIGCHLD++;
  8782. //bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
  8783. #endif
  8784. enable_restore_tty_pgrp_on_exit();
  8785. #if !BB_MMU
  8786. /* Clean up after vforked child */
  8787. free(nommu_save.argv);
  8788. free(nommu_save.argv_from_re_execing);
  8789. G.var_nest_level = sv_var_nest_level;
  8790. remove_nested_vars();
  8791. add_vars(nommu_save.old_vars);
  8792. #endif
  8793. free(argv_expanded);
  8794. argv_expanded = NULL;
  8795. if (command->pid < 0) { /* [v]fork failed */
  8796. /* Clearly indicate, was it fork or vfork */
  8797. bb_simple_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
  8798. } else {
  8799. pi->alive_cmds++;
  8800. #if ENABLE_HUSH_JOB
  8801. /* Second and next children need to know pid of first one */
  8802. if (pi->pgrp < 0)
  8803. pi->pgrp = command->pid;
  8804. #endif
  8805. }
  8806. if (cmd_no > 1)
  8807. close(next_infd);
  8808. if (cmd_no < pi->num_cmds)
  8809. close(pipefds.wr);
  8810. /* Pass read (output) pipe end to next iteration */
  8811. next_infd = pipefds.rd;
  8812. }
  8813. if (!pi->alive_cmds) {
  8814. debug_leave();
  8815. debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
  8816. return 1;
  8817. }
  8818. debug_leave();
  8819. debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
  8820. return -1;
  8821. }
  8822. /* NB: called by pseudo_exec, and therefore must not modify any
  8823. * global data until exec/_exit (we can be a child after vfork!) */
  8824. static int run_list(struct pipe *pi)
  8825. {
  8826. #if ENABLE_HUSH_CASE
  8827. char *case_word = NULL;
  8828. #endif
  8829. #if ENABLE_HUSH_LOOPS
  8830. struct pipe *loop_top = NULL;
  8831. char **for_lcur = NULL;
  8832. char **for_list = NULL;
  8833. #endif
  8834. smallint last_followup;
  8835. smalluint rcode;
  8836. #if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
  8837. smalluint cond_code = 0;
  8838. #else
  8839. enum { cond_code = 0 };
  8840. #endif
  8841. #if HAS_KEYWORDS
  8842. smallint rword; /* RES_foo */
  8843. smallint last_rword; /* ditto */
  8844. #endif
  8845. debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
  8846. debug_enter();
  8847. #if ENABLE_HUSH_LOOPS
  8848. /* Check syntax for "for" */
  8849. {
  8850. struct pipe *cpipe;
  8851. for (cpipe = pi; cpipe; cpipe = cpipe->next) {
  8852. if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
  8853. continue;
  8854. /* current word is FOR or IN (BOLD in comments below) */
  8855. if (cpipe->next == NULL) {
  8856. syntax_error("malformed for");
  8857. debug_leave();
  8858. debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
  8859. return 1;
  8860. }
  8861. /* "FOR v; do ..." and "for v IN a b; do..." are ok */
  8862. if (cpipe->next->res_word == RES_DO)
  8863. continue;
  8864. /* next word is not "do". It must be "in" then ("FOR v in ...") */
  8865. if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
  8866. || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
  8867. ) {
  8868. syntax_error("malformed for");
  8869. debug_leave();
  8870. debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
  8871. return 1;
  8872. }
  8873. }
  8874. }
  8875. #endif
  8876. /* Past this point, all code paths should jump to ret: label
  8877. * in order to return, no direct "return" statements please.
  8878. * This helps to ensure that no memory is leaked. */
  8879. #if ENABLE_HUSH_JOB
  8880. G.run_list_level++;
  8881. #endif
  8882. #if HAS_KEYWORDS
  8883. rword = RES_NONE;
  8884. last_rword = RES_XXXX;
  8885. #endif
  8886. last_followup = PIPE_SEQ;
  8887. rcode = G.last_exitcode;
  8888. /* Go through list of pipes, (maybe) executing them. */
  8889. for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
  8890. int r;
  8891. int sv_errexit_depth;
  8892. if (G.flag_SIGINT)
  8893. break;
  8894. if (G_flag_return_in_progress == 1)
  8895. break;
  8896. IF_HAS_KEYWORDS(rword = pi->res_word;)
  8897. debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
  8898. rword, cond_code, last_rword);
  8899. sv_errexit_depth = G.errexit_depth;
  8900. if (
  8901. #if ENABLE_HUSH_IF
  8902. rword == RES_IF || rword == RES_ELIF ||
  8903. #endif
  8904. pi->followup != PIPE_SEQ
  8905. ) {
  8906. G.errexit_depth++;
  8907. }
  8908. #if ENABLE_HUSH_LOOPS
  8909. if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
  8910. && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
  8911. ) {
  8912. /* start of a loop: remember where loop starts */
  8913. loop_top = pi;
  8914. G.depth_of_loop++;
  8915. }
  8916. #endif
  8917. /* Still in the same "if...", "then..." or "do..." branch? */
  8918. if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
  8919. if ((rcode == 0 && last_followup == PIPE_OR)
  8920. || (rcode != 0 && last_followup == PIPE_AND)
  8921. ) {
  8922. /* It is "<true> || CMD" or "<false> && CMD"
  8923. * and we should not execute CMD */
  8924. debug_printf_exec("skipped cmd because of || or &&\n");
  8925. last_followup = pi->followup;
  8926. goto dont_check_jobs_but_continue;
  8927. }
  8928. }
  8929. last_followup = pi->followup;
  8930. IF_HAS_KEYWORDS(last_rword = rword;)
  8931. #if ENABLE_HUSH_IF
  8932. if (cond_code) {
  8933. if (rword == RES_THEN) {
  8934. /* if false; then ... fi has exitcode 0! */
  8935. G.last_exitcode = rcode = EXIT_SUCCESS;
  8936. /* "if <false> THEN cmd": skip cmd */
  8937. continue;
  8938. }
  8939. } else {
  8940. if (rword == RES_ELSE || rword == RES_ELIF) {
  8941. /* "if <true> then ... ELSE/ELIF cmd":
  8942. * skip cmd and all following ones */
  8943. break;
  8944. }
  8945. }
  8946. #endif
  8947. #if ENABLE_HUSH_LOOPS
  8948. if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
  8949. if (!for_lcur) {
  8950. /* first loop through for */
  8951. static const char encoded_dollar_at[] ALIGN1 = {
  8952. SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
  8953. }; /* encoded representation of "$@" */
  8954. static const char *const encoded_dollar_at_argv[] = {
  8955. encoded_dollar_at, NULL
  8956. }; /* argv list with one element: "$@" */
  8957. char **vals;
  8958. G.last_exitcode = rcode = EXIT_SUCCESS;
  8959. vals = (char**)encoded_dollar_at_argv;
  8960. if (pi->next->res_word == RES_IN) {
  8961. /* if no variable values after "in" we skip "for" */
  8962. if (!pi->next->cmds[0].argv) {
  8963. debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
  8964. break;
  8965. }
  8966. vals = pi->next->cmds[0].argv;
  8967. } /* else: "for var; do..." -> assume "$@" list */
  8968. /* create list of variable values */
  8969. debug_print_strings("for_list made from", vals);
  8970. for_list = expand_strvec_to_strvec(vals);
  8971. for_lcur = for_list;
  8972. debug_print_strings("for_list", for_list);
  8973. }
  8974. if (!*for_lcur) {
  8975. /* "for" loop is over, clean up */
  8976. free(for_list);
  8977. for_list = NULL;
  8978. for_lcur = NULL;
  8979. break;
  8980. }
  8981. /* Insert next value from for_lcur */
  8982. /* note: *for_lcur already has quotes removed, $var expanded, etc */
  8983. set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*flag:*/ 0);
  8984. continue;
  8985. }
  8986. if (rword == RES_IN) {
  8987. continue; /* "for v IN list;..." - "in" has no cmds anyway */
  8988. }
  8989. if (rword == RES_DONE) {
  8990. continue; /* "done" has no cmds too */
  8991. }
  8992. #endif
  8993. #if ENABLE_HUSH_CASE
  8994. if (rword == RES_CASE) {
  8995. debug_printf_exec("CASE cond_code:%d\n", cond_code);
  8996. case_word = expand_string_to_string(pi->cmds->argv[0],
  8997. EXP_FLAG_ESC_GLOB_CHARS, /*unbackslash:*/ 1);
  8998. debug_printf_exec("CASE word1:'%s'\n", case_word);
  8999. //unbackslash(case_word);
  9000. //debug_printf_exec("CASE word2:'%s'\n", case_word);
  9001. continue;
  9002. }
  9003. if (rword == RES_MATCH) {
  9004. char **argv;
  9005. debug_printf_exec("MATCH cond_code:%d\n", cond_code);
  9006. if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
  9007. break;
  9008. /* all prev words didn't match, does this one match? */
  9009. argv = pi->cmds->argv;
  9010. while (*argv) {
  9011. char *pattern;
  9012. debug_printf_exec("expand_string_to_string('%s')\n", *argv);
  9013. pattern = expand_string_to_string(*argv,
  9014. EXP_FLAG_ESC_GLOB_CHARS,
  9015. /*unbackslash:*/ 0
  9016. );
  9017. /* TODO: which FNM_xxx flags to use? */
  9018. cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
  9019. debug_printf_exec("fnmatch(pattern:'%s',str:'%s'):%d\n",
  9020. pattern, case_word, cond_code);
  9021. free(pattern);
  9022. if (cond_code == 0) {
  9023. /* match! we will execute this branch */
  9024. free(case_word);
  9025. case_word = NULL; /* make future "word)" stop */
  9026. break;
  9027. }
  9028. argv++;
  9029. }
  9030. continue;
  9031. }
  9032. if (rword == RES_CASE_BODY) { /* inside of a case branch */
  9033. debug_printf_exec("CASE_BODY cond_code:%d\n", cond_code);
  9034. if (cond_code != 0)
  9035. continue; /* not matched yet, skip this pipe */
  9036. }
  9037. if (rword == RES_ESAC) {
  9038. debug_printf_exec("ESAC cond_code:%d\n", cond_code);
  9039. if (case_word) {
  9040. /* "case" did not match anything: still set $? (to 0) */
  9041. G.last_exitcode = rcode = EXIT_SUCCESS;
  9042. }
  9043. }
  9044. #endif
  9045. /* Just pressing <enter> in shell should check for jobs.
  9046. * OTOH, in non-interactive shell this is useless
  9047. * and only leads to extra job checks */
  9048. if (pi->num_cmds == 0) {
  9049. if (G_interactive_fd)
  9050. goto check_jobs_and_continue;
  9051. continue;
  9052. }
  9053. /* After analyzing all keywords and conditions, we decided
  9054. * to execute this pipe. NB: have to do checkjobs(NULL)
  9055. * after run_pipe to collect any background children,
  9056. * even if list execution is to be stopped. */
  9057. debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
  9058. #if ENABLE_HUSH_LOOPS
  9059. G.flag_break_continue = 0;
  9060. #endif
  9061. rcode = r = run_pipe(pi); /* NB: rcode is a smalluint, r is int */
  9062. if (r != -1) {
  9063. /* We ran a builtin, function, or group.
  9064. * rcode is already known
  9065. * and we don't need to wait for anything. */
  9066. debug_printf_exec(": builtin/func exitcode %d\n", rcode);
  9067. G.last_exitcode = rcode;
  9068. check_and_run_traps();
  9069. #if ENABLE_HUSH_TRAP && ENABLE_HUSH_FUNCTIONS
  9070. rcode = G.last_exitcode; /* "return" in trap can change it, read back */
  9071. #endif
  9072. #if ENABLE_HUSH_LOOPS
  9073. /* Was it "break" or "continue"? */
  9074. if (G.flag_break_continue) {
  9075. smallint fbc = G.flag_break_continue;
  9076. /* We might fall into outer *loop*,
  9077. * don't want to break it too */
  9078. if (loop_top) {
  9079. G.depth_break_continue--;
  9080. if (G.depth_break_continue == 0)
  9081. G.flag_break_continue = 0;
  9082. /* else: e.g. "continue 2" should *break* once, *then* continue */
  9083. } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
  9084. if (G.depth_break_continue != 0 || fbc == BC_BREAK) {
  9085. checkjobs(NULL, 0 /*(no pid to wait for)*/);
  9086. break;
  9087. }
  9088. /* "continue": simulate end of loop */
  9089. rword = RES_DONE;
  9090. continue;
  9091. }
  9092. #endif
  9093. if (G_flag_return_in_progress == 1) {
  9094. checkjobs(NULL, 0 /*(no pid to wait for)*/);
  9095. break;
  9096. }
  9097. } else if (pi->followup == PIPE_BG) {
  9098. /* What does bash do with attempts to background builtins? */
  9099. /* even bash 3.2 doesn't do that well with nested bg:
  9100. * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
  9101. * I'm NOT treating inner &'s as jobs */
  9102. #if ENABLE_HUSH_JOB
  9103. if (G.run_list_level == 1)
  9104. insert_job_into_table(pi);
  9105. #endif
  9106. /* Last command's pid goes to $! */
  9107. G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
  9108. G.last_bg_pid_exitcode = 0;
  9109. debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
  9110. /* Check pi->pi_inverted? "! sleep 1 & echo $?": bash says 1. dash and ash say 0 */
  9111. rcode = EXIT_SUCCESS;
  9112. goto check_traps;
  9113. } else {
  9114. #if ENABLE_HUSH_JOB
  9115. if (G.run_list_level == 1 && G_interactive_fd) {
  9116. /* Waits for completion, then fg's main shell */
  9117. rcode = checkjobs_and_fg_shell(pi);
  9118. debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
  9119. goto check_traps;
  9120. }
  9121. #endif
  9122. /* This one just waits for completion */
  9123. rcode = checkjobs(pi, 0 /*(no pid to wait for)*/);
  9124. debug_printf_exec(": checkjobs exitcode %d\n", rcode);
  9125. check_traps:
  9126. G.last_exitcode = rcode;
  9127. check_and_run_traps();
  9128. #if ENABLE_HUSH_TRAP && ENABLE_HUSH_FUNCTIONS
  9129. rcode = G.last_exitcode; /* "return" in trap can change it, read back */
  9130. #endif
  9131. }
  9132. /* Handle "set -e" */
  9133. if (rcode != 0 && G.o_opt[OPT_O_ERREXIT]) {
  9134. debug_printf_exec("ERREXIT:1 errexit_depth:%d\n", G.errexit_depth);
  9135. if (G.errexit_depth == 0)
  9136. hush_exit(rcode);
  9137. }
  9138. G.errexit_depth = sv_errexit_depth;
  9139. /* Analyze how result affects subsequent commands */
  9140. #if ENABLE_HUSH_IF
  9141. if (rword == RES_IF || rword == RES_ELIF)
  9142. cond_code = rcode;
  9143. #endif
  9144. check_jobs_and_continue:
  9145. checkjobs(NULL, 0 /*(no pid to wait for)*/);
  9146. dont_check_jobs_but_continue: ;
  9147. #if ENABLE_HUSH_LOOPS
  9148. /* Beware of "while false; true; do ..."! */
  9149. if (pi->next
  9150. && (pi->next->res_word == RES_DO || pi->next->res_word == RES_DONE)
  9151. /* check for RES_DONE is needed for "while ...; do \n done" case */
  9152. ) {
  9153. if (rword == RES_WHILE) {
  9154. if (rcode) {
  9155. /* "while false; do...done" - exitcode 0 */
  9156. G.last_exitcode = rcode = EXIT_SUCCESS;
  9157. debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
  9158. break;
  9159. }
  9160. }
  9161. if (rword == RES_UNTIL) {
  9162. if (!rcode) {
  9163. debug_printf_exec(": until expr is true: breaking\n");
  9164. break;
  9165. }
  9166. }
  9167. }
  9168. #endif
  9169. } /* for (pi) */
  9170. #if ENABLE_HUSH_JOB
  9171. G.run_list_level--;
  9172. #endif
  9173. #if ENABLE_HUSH_LOOPS
  9174. if (loop_top)
  9175. G.depth_of_loop--;
  9176. free(for_list);
  9177. #endif
  9178. #if ENABLE_HUSH_CASE
  9179. free(case_word);
  9180. #endif
  9181. debug_leave();
  9182. debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
  9183. return rcode;
  9184. }
  9185. /* Select which version we will use */
  9186. static int run_and_free_list(struct pipe *pi)
  9187. {
  9188. int rcode = 0;
  9189. debug_printf_exec("run_and_free_list entered\n");
  9190. if (!G.o_opt[OPT_O_NOEXEC]) {
  9191. debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
  9192. rcode = run_list(pi);
  9193. }
  9194. /* free_pipe_list has the side effect of clearing memory.
  9195. * In the long run that function can be merged with run_list,
  9196. * but doing that now would hobble the debugging effort. */
  9197. free_pipe_list(pi);
  9198. debug_printf_exec("run_and_free_list return %d\n", rcode);
  9199. return rcode;
  9200. }
  9201. static void install_sighandlers(unsigned mask)
  9202. {
  9203. sighandler_t old_handler;
  9204. unsigned sig = 0;
  9205. while ((mask >>= 1) != 0) {
  9206. sig++;
  9207. if (!(mask & 1))
  9208. continue;
  9209. old_handler = install_sighandler(sig, pick_sighandler(sig));
  9210. /* POSIX allows shell to re-enable SIGCHLD
  9211. * even if it was SIG_IGN on entry.
  9212. * Therefore we skip IGN check for it:
  9213. */
  9214. if (sig == SIGCHLD)
  9215. continue;
  9216. /* Interactive bash re-enables SIGHUP which is SIG_IGNed on entry.
  9217. * Try:
  9218. * trap '' hup; bash; echo RET # type "kill -hup $$", see SIGHUP having effect
  9219. * trap '' hup; bash -c 'kill -hup $$; echo ALIVE' # here SIGHUP is SIG_IGNed
  9220. */
  9221. if (sig == SIGHUP && G_interactive_fd)
  9222. continue;
  9223. /* Unless one of the above signals, is it SIG_IGN? */
  9224. if (old_handler == SIG_IGN) {
  9225. /* oops... restore back to IGN, and record this fact */
  9226. install_sighandler(sig, old_handler);
  9227. #if ENABLE_HUSH_TRAP
  9228. if (!G_traps)
  9229. G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
  9230. free(G_traps[sig]);
  9231. G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
  9232. #endif
  9233. }
  9234. }
  9235. }
  9236. /* Called a few times only (or even once if "sh -c") */
  9237. static void install_special_sighandlers(void)
  9238. {
  9239. unsigned mask;
  9240. /* Which signals are shell-special? */
  9241. mask = (1 << SIGQUIT) | (1 << SIGCHLD);
  9242. if (G_interactive_fd) {
  9243. mask |= SPECIAL_INTERACTIVE_SIGS;
  9244. if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
  9245. mask |= SPECIAL_JOBSTOP_SIGS;
  9246. }
  9247. /* Careful, do not re-install handlers we already installed */
  9248. if (G.special_sig_mask != mask) {
  9249. unsigned diff = mask & ~G.special_sig_mask;
  9250. G.special_sig_mask = mask;
  9251. install_sighandlers(diff);
  9252. }
  9253. }
  9254. #if ENABLE_HUSH_JOB
  9255. /* helper */
  9256. /* Set handlers to restore tty pgrp and exit */
  9257. static void install_fatal_sighandlers(void)
  9258. {
  9259. unsigned mask;
  9260. /* We will restore tty pgrp on these signals */
  9261. mask = 0
  9262. /*+ (1 << SIGILL ) * HUSH_DEBUG*/
  9263. /*+ (1 << SIGFPE ) * HUSH_DEBUG*/
  9264. + (1 << SIGBUS ) * HUSH_DEBUG
  9265. + (1 << SIGSEGV) * HUSH_DEBUG
  9266. /*+ (1 << SIGTRAP) * HUSH_DEBUG*/
  9267. + (1 << SIGABRT)
  9268. /* bash 3.2 seems to handle these just like 'fatal' ones */
  9269. + (1 << SIGPIPE)
  9270. + (1 << SIGALRM)
  9271. /* if we are interactive, SIGHUP, SIGTERM and SIGINT are special sigs.
  9272. * if we aren't interactive... but in this case
  9273. * we never want to restore pgrp on exit, and this fn is not called
  9274. */
  9275. /*+ (1 << SIGHUP )*/
  9276. /*+ (1 << SIGTERM)*/
  9277. /*+ (1 << SIGINT )*/
  9278. ;
  9279. G_fatal_sig_mask = mask;
  9280. install_sighandlers(mask);
  9281. }
  9282. #endif
  9283. static int set_mode(int state, char mode, const char *o_opt)
  9284. {
  9285. int idx;
  9286. switch (mode) {
  9287. case 'n':
  9288. G.o_opt[OPT_O_NOEXEC] = state;
  9289. break;
  9290. case 'x':
  9291. IF_HUSH_MODE_X(G_x_mode = state;)
  9292. IF_HUSH_MODE_X(if (G.x_mode_fd <= 0) G.x_mode_fd = dup_CLOEXEC(2, 10);)
  9293. break;
  9294. case 'e':
  9295. G.o_opt[OPT_O_ERREXIT] = state;
  9296. break;
  9297. case 'o':
  9298. if (!o_opt) {
  9299. /* "set -o" or "set +o" without parameter.
  9300. * in bash, set -o produces this output:
  9301. * pipefail off
  9302. * and set +o:
  9303. * set +o pipefail
  9304. * We always use the second form.
  9305. */
  9306. const char *p = o_opt_strings;
  9307. idx = 0;
  9308. while (*p) {
  9309. printf("set %co %s\n", (G.o_opt[idx] ? '-' : '+'), p);
  9310. idx++;
  9311. p += strlen(p) + 1;
  9312. }
  9313. break;
  9314. }
  9315. idx = index_in_strings(o_opt_strings, o_opt);
  9316. if (idx >= 0) {
  9317. G.o_opt[idx] = state;
  9318. break;
  9319. }
  9320. /* fall through to error */
  9321. default:
  9322. return EXIT_FAILURE;
  9323. }
  9324. return EXIT_SUCCESS;
  9325. }
  9326. int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  9327. int hush_main(int argc, char **argv)
  9328. {
  9329. enum {
  9330. OPT_login = (1 << 0),
  9331. };
  9332. unsigned flags;
  9333. unsigned builtin_argc;
  9334. char **e;
  9335. struct variable *cur_var;
  9336. struct variable *shell_ver;
  9337. INIT_G();
  9338. if (EXIT_SUCCESS != 0) /* if EXIT_SUCCESS == 0, it is already done */
  9339. G.last_exitcode = EXIT_SUCCESS;
  9340. #if ENABLE_HUSH_TRAP
  9341. # if ENABLE_HUSH_FUNCTIONS
  9342. G.return_exitcode = -1;
  9343. # endif
  9344. G.pre_trap_exitcode = -1;
  9345. #endif
  9346. #if ENABLE_HUSH_FAST
  9347. G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
  9348. #endif
  9349. #if !BB_MMU
  9350. G.argv0_for_re_execing = argv[0];
  9351. #endif
  9352. /* Deal with HUSH_VERSION */
  9353. debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
  9354. unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
  9355. shell_ver = xzalloc(sizeof(*shell_ver));
  9356. shell_ver->flg_export = 1;
  9357. shell_ver->flg_read_only = 1;
  9358. /* Code which handles ${var<op>...} needs writable values for all variables,
  9359. * therefore we xstrdup: */
  9360. shell_ver->varstr = xstrdup(hush_version_str);
  9361. /* Create shell local variables from the values
  9362. * currently living in the environment */
  9363. G.top_var = shell_ver;
  9364. cur_var = G.top_var;
  9365. e = environ;
  9366. if (e) while (*e) {
  9367. char *value = strchr(*e, '=');
  9368. if (value) { /* paranoia */
  9369. cur_var->next = xzalloc(sizeof(*cur_var));
  9370. cur_var = cur_var->next;
  9371. cur_var->varstr = *e;
  9372. cur_var->max_len = strlen(*e);
  9373. cur_var->flg_export = 1;
  9374. }
  9375. e++;
  9376. }
  9377. /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
  9378. debug_printf_env("putenv '%s'\n", shell_ver->varstr);
  9379. putenv(shell_ver->varstr);
  9380. /* Export PWD */
  9381. set_pwd_var(SETFLAG_EXPORT);
  9382. #if BASH_HOSTNAME_VAR
  9383. /* Set (but not export) HOSTNAME unless already set */
  9384. if (!get_local_var_value("HOSTNAME")) {
  9385. struct utsname uts;
  9386. uname(&uts);
  9387. set_local_var_from_halves("HOSTNAME", uts.nodename);
  9388. }
  9389. #endif
  9390. /* IFS is not inherited from the parent environment */
  9391. set_local_var_from_halves("IFS", defifs);
  9392. if (!get_local_var_value("PATH"))
  9393. set_local_var_from_halves("PATH", bb_default_root_path);
  9394. /* PS1/PS2 are set later, if we determine that we are interactive */
  9395. /* bash also exports SHLVL and _,
  9396. * and sets (but doesn't export) the following variables:
  9397. * BASH=/bin/bash
  9398. * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
  9399. * BASH_VERSION='3.2.0(1)-release'
  9400. * HOSTTYPE=i386
  9401. * MACHTYPE=i386-pc-linux-gnu
  9402. * OSTYPE=linux-gnu
  9403. * PPID=<NNNNN> - we also do it elsewhere
  9404. * EUID=<NNNNN>
  9405. * UID=<NNNNN>
  9406. * GROUPS=()
  9407. * LINES=<NNN>
  9408. * COLUMNS=<NNN>
  9409. * BASH_ARGC=()
  9410. * BASH_ARGV=()
  9411. * BASH_LINENO=()
  9412. * BASH_SOURCE=()
  9413. * DIRSTACK=()
  9414. * PIPESTATUS=([0]="0")
  9415. * HISTFILE=/<xxx>/.bash_history
  9416. * HISTFILESIZE=500
  9417. * HISTSIZE=500
  9418. * MAILCHECK=60
  9419. * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
  9420. * SHELL=/bin/bash
  9421. * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
  9422. * TERM=dumb
  9423. * OPTERR=1
  9424. * OPTIND=1
  9425. * PS4='+ '
  9426. */
  9427. /* Initialize some more globals to non-zero values */
  9428. die_func = restore_ttypgrp_and__exit;
  9429. /* Shell is non-interactive at first. We need to call
  9430. * install_special_sighandlers() if we are going to execute "sh <script>",
  9431. * "sh -c <cmds>" or login shell's /etc/profile and friends.
  9432. * If we later decide that we are interactive, we run install_special_sighandlers()
  9433. * in order to intercept (more) signals.
  9434. */
  9435. /* Parse options */
  9436. /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
  9437. flags = (argv[0] && argv[0][0] == '-') ? OPT_login : 0;
  9438. builtin_argc = 0;
  9439. #if NUM_SCRIPTS > 0
  9440. if (argc < 0) {
  9441. optarg = get_script_content(-argc - 1);
  9442. optind = 0;
  9443. argc = string_array_len(argv);
  9444. goto run_script;
  9445. }
  9446. #endif
  9447. while (1) {
  9448. int opt = getopt(argc, argv, "+c:exinsl"
  9449. #if !BB_MMU
  9450. "<:$:R:V:"
  9451. # if ENABLE_HUSH_FUNCTIONS
  9452. "F:"
  9453. # endif
  9454. #endif
  9455. );
  9456. if (opt <= 0)
  9457. break;
  9458. switch (opt) {
  9459. case 'c':
  9460. /* Possibilities:
  9461. * sh ... -c 'script'
  9462. * sh ... -c 'script' ARG0 [ARG1...]
  9463. * On NOMMU, if builtin_argc != 0,
  9464. * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
  9465. * "" needs to be replaced with NULL
  9466. * and BARGV vector fed to builtin function.
  9467. * Note: the form without ARG0 never happens:
  9468. * sh ... -c 'builtin' BARGV... ""
  9469. */
  9470. #if NUM_SCRIPTS > 0
  9471. run_script:
  9472. #endif
  9473. if (!G.root_pid) {
  9474. G.root_pid = getpid();
  9475. G.root_ppid = getppid();
  9476. }
  9477. G.global_argv = argv + optind;
  9478. G.global_argc = argc - optind;
  9479. if (builtin_argc) {
  9480. /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
  9481. const struct built_in_command *x;
  9482. install_special_sighandlers();
  9483. x = find_builtin(optarg);
  9484. if (x) { /* paranoia */
  9485. G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
  9486. G.global_argv += builtin_argc;
  9487. G.global_argv[-1] = NULL; /* replace "" */
  9488. fflush_all();
  9489. G.last_exitcode = x->b_function(argv + optind - 1);
  9490. }
  9491. goto final_return;
  9492. }
  9493. G.opt_c = 1;
  9494. if (!G.global_argv[0]) {
  9495. /* -c 'script' (no params): prevent empty $0 */
  9496. G.global_argv--; /* points to argv[i] of 'script' */
  9497. G.global_argv[0] = argv[0];
  9498. G.global_argc++;
  9499. } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
  9500. install_special_sighandlers();
  9501. parse_and_run_string(optarg);
  9502. goto final_return;
  9503. case 'i':
  9504. /* Well, we cannot just declare interactiveness,
  9505. * we have to have some stuff (ctty, etc) */
  9506. /* G_interactive_fd++; */
  9507. break;
  9508. case 's':
  9509. G.opt_s = 1;
  9510. break;
  9511. case 'l':
  9512. flags |= OPT_login;
  9513. break;
  9514. #if !BB_MMU
  9515. case '<': /* "big heredoc" support */
  9516. full_write1_str(optarg);
  9517. _exit(0);
  9518. case '$': {
  9519. unsigned long long empty_trap_mask;
  9520. G.root_pid = bb_strtou(optarg, &optarg, 16);
  9521. optarg++;
  9522. G.root_ppid = bb_strtou(optarg, &optarg, 16);
  9523. optarg++;
  9524. G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
  9525. optarg++;
  9526. G.last_exitcode = bb_strtou(optarg, &optarg, 16);
  9527. optarg++;
  9528. builtin_argc = bb_strtou(optarg, &optarg, 16);
  9529. optarg++;
  9530. empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
  9531. if (empty_trap_mask != 0) {
  9532. IF_HUSH_TRAP(int sig;)
  9533. install_special_sighandlers();
  9534. # if ENABLE_HUSH_TRAP
  9535. G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
  9536. for (sig = 1; sig < NSIG; sig++) {
  9537. if (empty_trap_mask & (1LL << sig)) {
  9538. G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
  9539. install_sighandler(sig, SIG_IGN);
  9540. }
  9541. }
  9542. # endif
  9543. }
  9544. # if ENABLE_HUSH_LOOPS
  9545. optarg++;
  9546. G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
  9547. # endif
  9548. # if ENABLE_HUSH_FUNCTIONS
  9549. /* nommu uses re-exec trick for "... | func | ...",
  9550. * should allow "return".
  9551. * This accidentally allows returns in subshells.
  9552. */
  9553. G_flag_return_in_progress = -1;
  9554. # endif
  9555. break;
  9556. }
  9557. case 'R':
  9558. case 'V':
  9559. set_local_var(xstrdup(optarg), opt == 'R' ? SETFLAG_MAKE_RO : 0);
  9560. break;
  9561. # if ENABLE_HUSH_FUNCTIONS
  9562. case 'F': {
  9563. struct function *funcp = new_function(optarg);
  9564. /* funcp->name is already set to optarg */
  9565. /* funcp->body is set to NULL. It's a special case. */
  9566. funcp->body_as_string = argv[optind];
  9567. optind++;
  9568. break;
  9569. }
  9570. # endif
  9571. #endif
  9572. case 'n':
  9573. case 'x':
  9574. case 'e':
  9575. if (set_mode(1, opt, NULL) == 0) /* no error */
  9576. break;
  9577. default:
  9578. #ifndef BB_VER
  9579. fprintf(stderr, "Usage: sh [FILE]...\n"
  9580. " or: sh -c command [args]...\n\n");
  9581. exit(EXIT_FAILURE);
  9582. #else
  9583. bb_show_usage();
  9584. #endif
  9585. }
  9586. } /* option parsing loop */
  9587. /* Skip options. Try "hush -l": $1 should not be "-l"! */
  9588. G.global_argc = argc - (optind - 1);
  9589. G.global_argv = argv + (optind - 1);
  9590. G.global_argv[0] = argv[0];
  9591. if (!G.root_pid) {
  9592. G.root_pid = getpid();
  9593. G.root_ppid = getppid();
  9594. }
  9595. /* If we are login shell... */
  9596. if (flags & OPT_login) {
  9597. HFILE *input;
  9598. debug_printf("sourcing /etc/profile\n");
  9599. input = hfopen("/etc/profile");
  9600. if (input != NULL) {
  9601. install_special_sighandlers();
  9602. parse_and_run_file(input);
  9603. hfclose(input);
  9604. }
  9605. /* bash: after sourcing /etc/profile,
  9606. * tries to source (in the given order):
  9607. * ~/.bash_profile, ~/.bash_login, ~/.profile,
  9608. * stopping on first found. --noprofile turns this off.
  9609. * bash also sources ~/.bash_logout on exit.
  9610. * If called as sh, skips .bash_XXX files.
  9611. */
  9612. }
  9613. /* -s is: hush -s ARGV1 ARGV2 (no SCRIPT) */
  9614. if (!G.opt_s && G.global_argv[1]) {
  9615. HFILE *input;
  9616. /*
  9617. * "bash <script>" (which is never interactive (unless -i?))
  9618. * sources $BASH_ENV here (without scanning $PATH).
  9619. * If called as sh, does the same but with $ENV.
  9620. * Also NB, per POSIX, $ENV should undergo parameter expansion.
  9621. */
  9622. G.global_argc--;
  9623. G.global_argv++;
  9624. debug_printf("running script '%s'\n", G.global_argv[0]);
  9625. xfunc_error_retval = 127; /* for "hush /does/not/exist" case */
  9626. input = hfopen(G.global_argv[0]);
  9627. if (!input) {
  9628. bb_simple_perror_msg_and_die(G.global_argv[0]);
  9629. }
  9630. xfunc_error_retval = 1;
  9631. install_special_sighandlers();
  9632. parse_and_run_file(input);
  9633. #if ENABLE_FEATURE_CLEAN_UP
  9634. hfclose(input);
  9635. #endif
  9636. goto final_return;
  9637. }
  9638. /* "implicit" -s: bare interactive hush shows 's' in $- */
  9639. G.opt_s = 1;
  9640. /* Up to here, shell was non-interactive. Now it may become one.
  9641. * NB: don't forget to (re)run install_special_sighandlers() as needed.
  9642. */
  9643. /* A shell is interactive if the '-i' flag was given,
  9644. * or if all of the following conditions are met:
  9645. * no -c command
  9646. * no arguments remaining or the -s flag given
  9647. * standard input is a terminal
  9648. * standard output is a terminal
  9649. * Refer to Posix.2, the description of the 'sh' utility.
  9650. */
  9651. #if ENABLE_HUSH_JOB
  9652. if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
  9653. G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
  9654. debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
  9655. if (G_saved_tty_pgrp < 0)
  9656. G_saved_tty_pgrp = 0;
  9657. /* try to dup stdin to high fd#, >= 255 */
  9658. G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, 254);
  9659. if (G_interactive_fd < 0) {
  9660. /* try to dup to any fd */
  9661. G_interactive_fd = dup(STDIN_FILENO);
  9662. if (G_interactive_fd < 0) {
  9663. /* give up */
  9664. G_interactive_fd = 0;
  9665. G_saved_tty_pgrp = 0;
  9666. }
  9667. }
  9668. }
  9669. debug_printf("interactive_fd:%d\n", G_interactive_fd);
  9670. if (G_interactive_fd) {
  9671. close_on_exec_on(G_interactive_fd);
  9672. if (G_saved_tty_pgrp) {
  9673. /* If we were run as 'hush &', sleep until we are
  9674. * in the foreground (tty pgrp == our pgrp).
  9675. * If we get started under a job aware app (like bash),
  9676. * make sure we are now in charge so we don't fight over
  9677. * who gets the foreground */
  9678. while (1) {
  9679. pid_t shell_pgrp = getpgrp();
  9680. G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
  9681. if (G_saved_tty_pgrp == shell_pgrp)
  9682. break;
  9683. /* send TTIN to ourself (should stop us) */
  9684. kill(- shell_pgrp, SIGTTIN);
  9685. }
  9686. }
  9687. /* Install more signal handlers */
  9688. install_special_sighandlers();
  9689. if (G_saved_tty_pgrp) {
  9690. /* Set other signals to restore saved_tty_pgrp */
  9691. install_fatal_sighandlers();
  9692. /* Put ourselves in our own process group
  9693. * (bash, too, does this only if ctty is available) */
  9694. bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
  9695. /* Grab control of the terminal */
  9696. tcsetpgrp(G_interactive_fd, getpid());
  9697. }
  9698. enable_restore_tty_pgrp_on_exit();
  9699. # if ENABLE_FEATURE_EDITING
  9700. G.line_input_state = new_line_input_t(FOR_SHELL);
  9701. # if EDITING_HAS_get_exe_name
  9702. G.line_input_state->get_exe_name = get_builtin_name;
  9703. # endif
  9704. # endif
  9705. # if ENABLE_HUSH_SAVEHISTORY && MAX_HISTORY > 0
  9706. {
  9707. const char *hp = get_local_var_value("HISTFILE");
  9708. if (!hp) {
  9709. hp = get_local_var_value("HOME");
  9710. if (hp)
  9711. hp = concat_path_file(hp, ".hush_history");
  9712. } else {
  9713. hp = xstrdup(hp);
  9714. }
  9715. if (hp) {
  9716. G.line_input_state->hist_file = hp;
  9717. //set_local_var(xasprintf("HISTFILE=%s", ...));
  9718. }
  9719. # if ENABLE_FEATURE_SH_HISTFILESIZE
  9720. hp = get_local_var_value("HISTFILESIZE");
  9721. G.line_input_state->max_history = size_from_HISTFILESIZE(hp);
  9722. # endif
  9723. }
  9724. # endif
  9725. } else {
  9726. install_special_sighandlers();
  9727. }
  9728. #elif ENABLE_HUSH_INTERACTIVE
  9729. /* No job control compiled in, only prompt/line editing */
  9730. if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
  9731. G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, 254);
  9732. if (G_interactive_fd < 0) {
  9733. /* try to dup to any fd */
  9734. G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, -1);
  9735. if (G_interactive_fd < 0)
  9736. /* give up */
  9737. G_interactive_fd = 0;
  9738. }
  9739. }
  9740. if (G_interactive_fd) {
  9741. close_on_exec_on(G_interactive_fd);
  9742. }
  9743. install_special_sighandlers();
  9744. #else
  9745. /* We have interactiveness code disabled */
  9746. install_special_sighandlers();
  9747. #endif
  9748. /* bash:
  9749. * if interactive but not a login shell, sources ~/.bashrc
  9750. * (--norc turns this off, --rcfile <file> overrides)
  9751. */
  9752. if (G_interactive_fd) {
  9753. #if ENABLE_HUSH_INTERACTIVE && ENABLE_FEATURE_EDITING_FANCY_PROMPT
  9754. /* Set (but not export) PS1/2 unless already set */
  9755. if (!get_local_var_value("PS1"))
  9756. set_local_var_from_halves("PS1", "\\w \\$ ");
  9757. if (!get_local_var_value("PS2"))
  9758. set_local_var_from_halves("PS2", "> ");
  9759. #endif
  9760. if (!ENABLE_FEATURE_SH_EXTRA_QUIET) {
  9761. /* note: ash and hush share this string */
  9762. printf("\n\n%s %s\n"
  9763. IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
  9764. "\n",
  9765. bb_banner,
  9766. "hush - the humble shell"
  9767. );
  9768. }
  9769. }
  9770. parse_and_run_file(hfopen(NULL)); /* stdin */
  9771. final_return:
  9772. hush_exit(G.last_exitcode);
  9773. }
  9774. /*
  9775. * Built-ins
  9776. */
  9777. static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
  9778. {
  9779. return 0;
  9780. }
  9781. #if ENABLE_HUSH_TEST || ENABLE_HUSH_ECHO || ENABLE_HUSH_PRINTF || ENABLE_HUSH_KILL
  9782. static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
  9783. {
  9784. int argc = string_array_len(argv);
  9785. return applet_main_func(argc, argv);
  9786. }
  9787. #endif
  9788. #if ENABLE_HUSH_TEST || BASH_TEST2
  9789. static int FAST_FUNC builtin_test(char **argv)
  9790. {
  9791. return run_applet_main(argv, test_main);
  9792. }
  9793. #endif
  9794. #if ENABLE_HUSH_ECHO
  9795. static int FAST_FUNC builtin_echo(char **argv)
  9796. {
  9797. return run_applet_main(argv, echo_main);
  9798. }
  9799. #endif
  9800. #if ENABLE_HUSH_PRINTF
  9801. static int FAST_FUNC builtin_printf(char **argv)
  9802. {
  9803. return run_applet_main(argv, printf_main);
  9804. }
  9805. #endif
  9806. #if ENABLE_HUSH_HELP
  9807. static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
  9808. {
  9809. const struct built_in_command *x;
  9810. printf(
  9811. "Built-in commands:\n"
  9812. "------------------\n");
  9813. for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
  9814. if (x->b_descr)
  9815. printf("%-10s%s\n", x->b_cmd, x->b_descr);
  9816. }
  9817. return EXIT_SUCCESS;
  9818. }
  9819. #endif
  9820. #if MAX_HISTORY && ENABLE_FEATURE_EDITING
  9821. static int FAST_FUNC builtin_history(char **argv UNUSED_PARAM)
  9822. {
  9823. show_history(G.line_input_state);
  9824. return EXIT_SUCCESS;
  9825. }
  9826. #endif
  9827. static char **skip_dash_dash(char **argv)
  9828. {
  9829. argv++;
  9830. if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
  9831. argv++;
  9832. return argv;
  9833. }
  9834. static int FAST_FUNC builtin_cd(char **argv)
  9835. {
  9836. const char *newdir;
  9837. argv = skip_dash_dash(argv);
  9838. newdir = argv[0];
  9839. if (newdir == NULL) {
  9840. /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
  9841. * bash says "bash: cd: HOME not set" and does nothing
  9842. * (exitcode 1)
  9843. */
  9844. const char *home = get_local_var_value("HOME");
  9845. newdir = home ? home : "/";
  9846. }
  9847. if (chdir(newdir)) {
  9848. /* Mimic bash message exactly */
  9849. bb_perror_msg("cd: %s", newdir);
  9850. return EXIT_FAILURE;
  9851. }
  9852. /* Read current dir (get_cwd(1) is inside) and set PWD.
  9853. * Note: do not enforce exporting. If PWD was unset or unexported,
  9854. * set it again, but do not export. bash does the same.
  9855. */
  9856. set_pwd_var(/*flag:*/ 0);
  9857. return EXIT_SUCCESS;
  9858. }
  9859. static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
  9860. {
  9861. puts(get_cwd(0));
  9862. return EXIT_SUCCESS;
  9863. }
  9864. static int FAST_FUNC builtin_eval(char **argv)
  9865. {
  9866. argv = skip_dash_dash(argv);
  9867. if (!argv[0])
  9868. return EXIT_SUCCESS;
  9869. IF_HUSH_MODE_X(G.x_mode_depth++;)
  9870. //bb_error_msg("%s: ++x_mode_depth=%d", __func__, G.x_mode_depth);
  9871. if (!argv[1]) {
  9872. /* bash:
  9873. * eval "echo Hi; done" ("done" is syntax error):
  9874. * "echo Hi" will not execute too.
  9875. */
  9876. parse_and_run_string(argv[0]);
  9877. } else {
  9878. /* "The eval utility shall construct a command by
  9879. * concatenating arguments together, separating
  9880. * each with a <space> character."
  9881. */
  9882. char *str, *p;
  9883. unsigned len = 0;
  9884. char **pp = argv;
  9885. do
  9886. len += strlen(*pp) + 1;
  9887. while (*++pp);
  9888. str = p = xmalloc(len);
  9889. pp = argv;
  9890. for (;;) {
  9891. p = stpcpy(p, *pp);
  9892. pp++;
  9893. if (!*pp)
  9894. break;
  9895. *p++ = ' ';
  9896. }
  9897. parse_and_run_string(str);
  9898. free(str);
  9899. }
  9900. IF_HUSH_MODE_X(G.x_mode_depth--;)
  9901. //bb_error_msg("%s: --x_mode_depth=%d", __func__, G.x_mode_depth);
  9902. return G.last_exitcode;
  9903. }
  9904. static int FAST_FUNC builtin_exec(char **argv)
  9905. {
  9906. argv = skip_dash_dash(argv);
  9907. if (argv[0] == NULL)
  9908. return EXIT_SUCCESS; /* bash does this */
  9909. /* Careful: we can end up here after [v]fork. Do not restore
  9910. * tty pgrp then, only top-level shell process does that */
  9911. if (G_saved_tty_pgrp && getpid() == G.root_pid)
  9912. tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
  9913. /* Saved-redirect fds, script fds and G_interactive_fd are still
  9914. * open here. However, they are all CLOEXEC, and execv below
  9915. * closes them. Try interactive "exec ls -l /proc/self/fd",
  9916. * it should show no extra open fds in the "ls" process.
  9917. * If we'd try to run builtins/NOEXECs, this would need improving.
  9918. */
  9919. //close_saved_fds_and_FILE_fds();
  9920. /* TODO: if exec fails, bash does NOT exit! We do.
  9921. * We'll need to undo trap cleanup (it's inside execvp_or_die)
  9922. * and tcsetpgrp, and this is inherently racy.
  9923. */
  9924. execvp_or_die(argv);
  9925. }
  9926. static int FAST_FUNC builtin_exit(char **argv)
  9927. {
  9928. debug_printf_exec("%s()\n", __func__);
  9929. /* interactive bash:
  9930. * # trap "echo EEE" EXIT
  9931. * # exit
  9932. * exit
  9933. * There are stopped jobs.
  9934. * (if there are _stopped_ jobs, running ones don't count)
  9935. * # exit
  9936. * exit
  9937. * EEE (then bash exits)
  9938. *
  9939. * TODO: we can use G.exiting = -1 as indicator "last cmd was exit"
  9940. */
  9941. /* note: EXIT trap is run by hush_exit */
  9942. argv = skip_dash_dash(argv);
  9943. if (argv[0] == NULL) {
  9944. #if ENABLE_HUSH_TRAP
  9945. if (G.pre_trap_exitcode >= 0) /* "exit" in trap uses $? from before the trap */
  9946. hush_exit(G.pre_trap_exitcode);
  9947. #endif
  9948. hush_exit(G.last_exitcode);
  9949. }
  9950. /* mimic bash: exit 123abc == exit 255 + error msg */
  9951. xfunc_error_retval = 255;
  9952. /* bash: exit -2 == exit 254, no error msg */
  9953. hush_exit(xatoi(argv[0]) & 0xff);
  9954. }
  9955. #if ENABLE_HUSH_TYPE
  9956. /* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
  9957. static int FAST_FUNC builtin_type(char **argv)
  9958. {
  9959. int ret = EXIT_SUCCESS;
  9960. while (*++argv) {
  9961. const char *type;
  9962. char *path = NULL;
  9963. if (0) {} /* make conditional compile easier below */
  9964. /*else if (find_alias(*argv))
  9965. type = "an alias";*/
  9966. # if ENABLE_HUSH_FUNCTIONS
  9967. else if (find_function(*argv))
  9968. type = "a function";
  9969. # endif
  9970. else if (find_builtin(*argv))
  9971. type = "a shell builtin";
  9972. else if ((path = find_in_path(*argv)) != NULL)
  9973. type = path;
  9974. else {
  9975. bb_error_msg("type: %s: not found", *argv);
  9976. ret = EXIT_FAILURE;
  9977. continue;
  9978. }
  9979. printf("%s is %s\n", *argv, type);
  9980. free(path);
  9981. }
  9982. return ret;
  9983. }
  9984. #endif
  9985. #if ENABLE_HUSH_READ
  9986. /* Interruptibility of read builtin in bash
  9987. * (tested on bash-4.2.8 by sending signals (not by ^C)):
  9988. *
  9989. * Empty trap makes read ignore corresponding signal, for any signal.
  9990. *
  9991. * SIGINT:
  9992. * - terminates non-interactive shell;
  9993. * - interrupts read in interactive shell;
  9994. * if it has non-empty trap:
  9995. * - executes trap and returns to command prompt in interactive shell;
  9996. * - executes trap and returns to read in non-interactive shell;
  9997. * SIGTERM:
  9998. * - is ignored (does not interrupt) read in interactive shell;
  9999. * - terminates non-interactive shell;
  10000. * if it has non-empty trap:
  10001. * - executes trap and returns to read;
  10002. * SIGHUP:
  10003. * - terminates shell (regardless of interactivity);
  10004. * if it has non-empty trap:
  10005. * - executes trap and returns to read;
  10006. * SIGCHLD from children:
  10007. * - does not interrupt read regardless of interactivity:
  10008. * try: sleep 1 & read x; echo $x
  10009. */
  10010. static int FAST_FUNC builtin_read(char **argv)
  10011. {
  10012. const char *r;
  10013. struct builtin_read_params params;
  10014. memset(&params, 0, sizeof(params));
  10015. /* "!": do not abort on errors.
  10016. * Option string must start with "sr" to match BUILTIN_READ_xxx
  10017. */
  10018. params.read_flags = getopt32(argv,
  10019. # if BASH_READ_D
  10020. "!srn:p:t:u:d:", &params.opt_n, &params.opt_p, &params.opt_t, &params.opt_u, &params.opt_d
  10021. # else
  10022. "!srn:p:t:u:", &params.opt_n, &params.opt_p, &params.opt_t, &params.opt_u
  10023. # endif
  10024. );
  10025. if ((uint32_t)params.read_flags == (uint32_t)-1)
  10026. return EXIT_FAILURE;
  10027. argv += optind;
  10028. params.argv = argv;
  10029. params.setvar = set_local_var_from_halves;
  10030. params.ifs = get_local_var_value("IFS"); /* can be NULL */
  10031. again:
  10032. r = shell_builtin_read(&params);
  10033. if ((uintptr_t)r == 1 && errno == EINTR) {
  10034. unsigned sig = check_and_run_traps();
  10035. if (sig != SIGINT)
  10036. goto again;
  10037. }
  10038. if ((uintptr_t)r > 1) {
  10039. bb_simple_error_msg(r);
  10040. r = (char*)(uintptr_t)1;
  10041. }
  10042. return (uintptr_t)r;
  10043. }
  10044. #endif
  10045. #if ENABLE_HUSH_UMASK
  10046. static int FAST_FUNC builtin_umask(char **argv)
  10047. {
  10048. int rc;
  10049. mode_t mask;
  10050. rc = 1;
  10051. mask = umask(0);
  10052. argv = skip_dash_dash(argv);
  10053. if (argv[0]) {
  10054. mode_t old_mask = mask;
  10055. /* numeric umasks are taken as-is */
  10056. /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
  10057. if (!isdigit(argv[0][0]))
  10058. mask ^= 0777;
  10059. mask = bb_parse_mode(argv[0], mask);
  10060. if (!isdigit(argv[0][0]))
  10061. mask ^= 0777;
  10062. if ((unsigned)mask > 0777) {
  10063. mask = old_mask;
  10064. /* bash messages:
  10065. * bash: umask: 'q': invalid symbolic mode operator
  10066. * bash: umask: 999: octal number out of range
  10067. */
  10068. bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
  10069. rc = 0;
  10070. }
  10071. } else {
  10072. /* Mimic bash */
  10073. printf("%04o\n", (unsigned) mask);
  10074. /* fall through and restore mask which we set to 0 */
  10075. }
  10076. umask(mask);
  10077. return !rc; /* rc != 0 - success */
  10078. }
  10079. #endif
  10080. #if ENABLE_HUSH_EXPORT || ENABLE_HUSH_TRAP
  10081. static void print_escaped(const char *s)
  10082. {
  10083. if (*s == '\'')
  10084. goto squote;
  10085. do {
  10086. const char *p = strchrnul(s, '\'');
  10087. /* print 'xxxx', possibly just '' */
  10088. printf("'%.*s'", (int)(p - s), s);
  10089. if (*p == '\0')
  10090. break;
  10091. s = p;
  10092. squote:
  10093. /* s points to '; print "'''...'''" */
  10094. putchar('"');
  10095. do putchar('\''); while (*++s == '\'');
  10096. putchar('"');
  10097. } while (*s);
  10098. }
  10099. #endif
  10100. #if ENABLE_HUSH_EXPORT || ENABLE_HUSH_LOCAL || ENABLE_HUSH_READONLY
  10101. static int helper_export_local(char **argv, unsigned flags)
  10102. {
  10103. do {
  10104. char *name = *argv;
  10105. const char *name_end = endofname(name);
  10106. if (*name_end == '\0') {
  10107. struct variable *var, **vpp;
  10108. vpp = get_ptr_to_local_var(name, name_end - name);
  10109. var = vpp ? *vpp : NULL;
  10110. if (flags & SETFLAG_UNEXPORT) {
  10111. /* export -n NAME (without =VALUE) */
  10112. if (var) {
  10113. var->flg_export = 0;
  10114. debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
  10115. unsetenv(name);
  10116. } /* else: export -n NOT_EXISTING_VAR: no-op */
  10117. continue;
  10118. }
  10119. if (flags & SETFLAG_EXPORT) {
  10120. /* export NAME (without =VALUE) */
  10121. if (var) {
  10122. var->flg_export = 1;
  10123. debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
  10124. putenv(var->varstr);
  10125. continue;
  10126. }
  10127. }
  10128. if (flags & SETFLAG_MAKE_RO) {
  10129. /* readonly NAME (without =VALUE) */
  10130. if (var) {
  10131. var->flg_read_only = 1;
  10132. continue;
  10133. }
  10134. }
  10135. # if ENABLE_HUSH_LOCAL
  10136. /* Is this "local" bltin? */
  10137. if (!(flags & (SETFLAG_EXPORT|SETFLAG_UNEXPORT|SETFLAG_MAKE_RO))) {
  10138. unsigned lvl = flags >> SETFLAG_VARLVL_SHIFT;
  10139. if (var && var->var_nest_level == lvl) {
  10140. /* "local x=abc; ...; local x" - ignore second local decl */
  10141. continue;
  10142. }
  10143. }
  10144. # endif
  10145. /* Exporting non-existing variable.
  10146. * bash does not put it in environment,
  10147. * but remembers that it is exported,
  10148. * and does put it in env when it is set later.
  10149. * We just set it to "" and export.
  10150. */
  10151. /* Or, it's "local NAME" (without =VALUE).
  10152. * bash sets the value to "".
  10153. */
  10154. /* Or, it's "readonly NAME" (without =VALUE).
  10155. * bash remembers NAME and disallows its creation
  10156. * in the future.
  10157. */
  10158. name = xasprintf("%s=", name);
  10159. } else {
  10160. if (*name_end != '=') {
  10161. bb_error_msg("'%s': bad variable name", name);
  10162. /* do not parse following argv[]s: */
  10163. return 1;
  10164. }
  10165. /* (Un)exporting/making local NAME=VALUE */
  10166. name = xstrdup(name);
  10167. /* Testcase: export PS1='\w \$ ' */
  10168. unbackslash(name);
  10169. }
  10170. debug_printf_env("%s: set_local_var('%s')\n", __func__, name);
  10171. if (set_local_var(name, flags))
  10172. return EXIT_FAILURE;
  10173. } while (*++argv);
  10174. return EXIT_SUCCESS;
  10175. }
  10176. #endif
  10177. #if ENABLE_HUSH_EXPORT
  10178. static int FAST_FUNC builtin_export(char **argv)
  10179. {
  10180. unsigned opt_unexport;
  10181. # if ENABLE_HUSH_EXPORT_N
  10182. /* "!": do not abort on errors */
  10183. opt_unexport = getopt32(argv, "!n");
  10184. if (opt_unexport == (uint32_t)-1)
  10185. return EXIT_FAILURE;
  10186. argv += optind;
  10187. # else
  10188. opt_unexport = 0;
  10189. argv++;
  10190. # endif
  10191. if (argv[0] == NULL) {
  10192. char **e = environ;
  10193. if (e) {
  10194. while (*e) {
  10195. # if 0
  10196. puts(*e++);
  10197. # else
  10198. /* ash emits: export VAR='VAL'
  10199. * bash: declare -x VAR="VAL"
  10200. * we follow ash example */
  10201. const char *s = *e++;
  10202. const char *p = strchr(s, '=');
  10203. if (!p) /* wtf? take next variable */
  10204. continue;
  10205. /* export var= */
  10206. printf("export %.*s", (int)(p - s) + 1, s);
  10207. print_escaped(p + 1);
  10208. putchar('\n');
  10209. # endif
  10210. }
  10211. /*fflush_all(); - done after each builtin anyway */
  10212. }
  10213. return EXIT_SUCCESS;
  10214. }
  10215. return helper_export_local(argv, opt_unexport ? SETFLAG_UNEXPORT : SETFLAG_EXPORT);
  10216. }
  10217. #endif
  10218. #if ENABLE_HUSH_LOCAL
  10219. static int FAST_FUNC builtin_local(char **argv)
  10220. {
  10221. if (G.func_nest_level == 0) {
  10222. bb_error_msg("%s: not in a function", argv[0]);
  10223. return EXIT_FAILURE; /* bash compat */
  10224. }
  10225. argv++;
  10226. /* Since all builtins run in a nested variable level,
  10227. * need to use level - 1 here. Or else the variable will be removed at once
  10228. * after builtin returns.
  10229. */
  10230. return helper_export_local(argv, (G.var_nest_level - 1) << SETFLAG_VARLVL_SHIFT);
  10231. }
  10232. #endif
  10233. #if ENABLE_HUSH_READONLY
  10234. static int FAST_FUNC builtin_readonly(char **argv)
  10235. {
  10236. argv++;
  10237. if (*argv == NULL) {
  10238. /* bash: readonly [-p]: list all readonly VARs
  10239. * (-p has no effect in bash)
  10240. */
  10241. struct variable *e;
  10242. for (e = G.top_var; e; e = e->next) {
  10243. if (e->flg_read_only) {
  10244. //TODO: quote value: readonly VAR='VAL'
  10245. printf("readonly %s\n", e->varstr);
  10246. }
  10247. }
  10248. return EXIT_SUCCESS;
  10249. }
  10250. return helper_export_local(argv, SETFLAG_MAKE_RO);
  10251. }
  10252. #endif
  10253. #if ENABLE_HUSH_UNSET
  10254. /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
  10255. static int FAST_FUNC builtin_unset(char **argv)
  10256. {
  10257. int ret;
  10258. unsigned opts;
  10259. /* "!": do not abort on errors */
  10260. /* "+": stop at 1st non-option */
  10261. opts = getopt32(argv, "!+vf");
  10262. if (opts == (unsigned)-1)
  10263. return EXIT_FAILURE;
  10264. if (opts == 3) {
  10265. bb_simple_error_msg("unset: -v and -f are exclusive");
  10266. return EXIT_FAILURE;
  10267. }
  10268. argv += optind;
  10269. ret = EXIT_SUCCESS;
  10270. while (*argv) {
  10271. if (!(opts & 2)) { /* not -f */
  10272. if (unset_local_var(*argv)) {
  10273. /* unset <nonexistent_var> doesn't fail.
  10274. * Error is when one tries to unset RO var.
  10275. * Message was printed by unset_local_var. */
  10276. ret = EXIT_FAILURE;
  10277. }
  10278. }
  10279. # if ENABLE_HUSH_FUNCTIONS
  10280. else {
  10281. unset_func(*argv);
  10282. }
  10283. # endif
  10284. argv++;
  10285. }
  10286. return ret;
  10287. }
  10288. #endif
  10289. #if ENABLE_HUSH_SET
  10290. /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
  10291. * built-in 'set' handler
  10292. * SUSv3 says:
  10293. * set [-abCefhmnuvx] [-o option] [argument...]
  10294. * set [+abCefhmnuvx] [+o option] [argument...]
  10295. * set -- [argument...]
  10296. * set -o
  10297. * set +o
  10298. * Implementations shall support the options in both their hyphen and
  10299. * plus-sign forms. These options can also be specified as options to sh.
  10300. * Examples:
  10301. * Write out all variables and their values: set
  10302. * Set $1, $2, and $3 and set "$#" to 3: set c a b
  10303. * Turn on the -x and -v options: set -xv
  10304. * Unset all positional parameters: set --
  10305. * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
  10306. * Set the positional parameters to the expansion of x, even if x expands
  10307. * with a leading '-' or '+': set -- $x
  10308. *
  10309. * So far, we only support "set -- [argument...]" and some of the short names.
  10310. */
  10311. static int FAST_FUNC builtin_set(char **argv)
  10312. {
  10313. int n;
  10314. char **pp, **g_argv;
  10315. char *arg = *++argv;
  10316. if (arg == NULL) {
  10317. struct variable *e;
  10318. for (e = G.top_var; e; e = e->next)
  10319. puts(e->varstr);
  10320. return EXIT_SUCCESS;
  10321. }
  10322. do {
  10323. if (strcmp(arg, "--") == 0) {
  10324. ++argv;
  10325. goto set_argv;
  10326. }
  10327. if (arg[0] != '+' && arg[0] != '-')
  10328. break;
  10329. for (n = 1; arg[n]; ++n) {
  10330. if (set_mode((arg[0] == '-'), arg[n], argv[1])) {
  10331. bb_error_msg("%s: %s: invalid option", "set", arg);
  10332. return EXIT_FAILURE;
  10333. }
  10334. if (arg[n] == 'o' && argv[1])
  10335. argv++;
  10336. }
  10337. } while ((arg = *++argv) != NULL);
  10338. /* Now argv[0] is 1st argument */
  10339. if (arg == NULL)
  10340. return EXIT_SUCCESS;
  10341. set_argv:
  10342. /* NB: G.global_argv[0] ($0) is never freed/changed */
  10343. g_argv = G.global_argv;
  10344. if (G.global_args_malloced) {
  10345. pp = g_argv;
  10346. while (*++pp)
  10347. free(*pp);
  10348. g_argv[1] = NULL;
  10349. } else {
  10350. G.global_args_malloced = 1;
  10351. pp = xzalloc(sizeof(pp[0]) * 2);
  10352. pp[0] = g_argv[0]; /* retain $0 */
  10353. g_argv = pp;
  10354. }
  10355. /* This realloc's G.global_argv */
  10356. G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
  10357. G.global_argc = 1 + string_array_len(pp + 1);
  10358. return EXIT_SUCCESS;
  10359. }
  10360. #endif
  10361. static int FAST_FUNC builtin_shift(char **argv)
  10362. {
  10363. int n = 1;
  10364. argv = skip_dash_dash(argv);
  10365. if (argv[0]) {
  10366. n = bb_strtou(argv[0], NULL, 10);
  10367. if (errno || n < 0) {
  10368. /* shared string with ash.c */
  10369. bb_error_msg("Illegal number: %s", argv[0]);
  10370. /*
  10371. * ash aborts in this case.
  10372. * bash prints error message and set $? to 1.
  10373. * Interestingly, for "shift 99999" bash does not
  10374. * print error message, but does set $? to 1
  10375. * (and does no shifting at all).
  10376. */
  10377. }
  10378. }
  10379. if (n >= 0 && n < G.global_argc) {
  10380. if (G_global_args_malloced) {
  10381. int m = 1;
  10382. while (m <= n)
  10383. free(G.global_argv[m++]);
  10384. }
  10385. G.global_argc -= n;
  10386. memmove(&G.global_argv[1], &G.global_argv[n+1],
  10387. G.global_argc * sizeof(G.global_argv[0]));
  10388. return EXIT_SUCCESS;
  10389. }
  10390. return EXIT_FAILURE;
  10391. }
  10392. #if ENABLE_HUSH_GETOPTS
  10393. static int FAST_FUNC builtin_getopts(char **argv)
  10394. {
  10395. /* http://pubs.opengroup.org/onlinepubs/9699919799/utilities/getopts.html
  10396. TODO:
  10397. If a required argument is not found, and getopts is not silent,
  10398. a question mark (?) is placed in VAR, OPTARG is unset, and a
  10399. diagnostic message is printed. If getopts is silent, then a
  10400. colon (:) is placed in VAR and OPTARG is set to the option
  10401. character found.
  10402. Test that VAR is a valid variable name?
  10403. "Whenever the shell is invoked, OPTIND shall be initialized to 1"
  10404. */
  10405. char cbuf[2];
  10406. const char *cp, *optstring, *var;
  10407. int c, n, exitcode, my_opterr;
  10408. unsigned count;
  10409. optstring = *++argv;
  10410. if (!optstring || !(var = *++argv)) {
  10411. bb_simple_error_msg("usage: getopts OPTSTRING VAR [ARGS]");
  10412. return EXIT_FAILURE;
  10413. }
  10414. if (argv[1])
  10415. argv[0] = G.global_argv[0]; /* for error messages in getopt() */
  10416. else
  10417. argv = G.global_argv;
  10418. cbuf[1] = '\0';
  10419. my_opterr = 0;
  10420. if (optstring[0] != ':') {
  10421. cp = get_local_var_value("OPTERR");
  10422. /* 0 if "OPTERR=0", 1 otherwise */
  10423. my_opterr = (!cp || NOT_LONE_CHAR(cp, '0'));
  10424. }
  10425. /* getopts stops on first non-option. Add "+" to force that */
  10426. /*if (optstring[0] != '+')*/ {
  10427. char *s = alloca(strlen(optstring) + 2);
  10428. sprintf(s, "+%s", optstring);
  10429. optstring = s;
  10430. }
  10431. /* Naively, now we should just
  10432. * cp = get_local_var_value("OPTIND");
  10433. * optind = cp ? atoi(cp) : 0;
  10434. * optarg = NULL;
  10435. * opterr = my_opterr;
  10436. * c = getopt(string_array_len(argv), argv, optstring);
  10437. * and be done? Not so fast...
  10438. * Unlike normal getopt() usage in C programs, here
  10439. * each successive call will (usually) have the same argv[] CONTENTS,
  10440. * but not the ADDRESSES. Worse yet, it's possible that between
  10441. * invocations of "getopts", there will be calls to shell builtins
  10442. * which use getopt() internally. Example:
  10443. * while getopts "abc" RES -a -bc -abc de; do
  10444. * unset -ff func
  10445. * done
  10446. * This would not work correctly: getopt() call inside "unset"
  10447. * modifies internal libc state which is tracking position in
  10448. * multi-option strings ("-abc"). At best, it can skip options
  10449. * or return the same option infinitely. With glibc implementation
  10450. * of getopt(), it would use outright invalid pointers and return
  10451. * garbage even _without_ "unset" mangling internal state.
  10452. *
  10453. * We resort to resetting getopt() state and calling it N times,
  10454. * until we get Nth result (or failure).
  10455. * (N == G.getopt_count is reset to 0 whenever OPTIND is [un]set).
  10456. */
  10457. GETOPT_RESET();
  10458. count = 0;
  10459. n = string_array_len(argv);
  10460. do {
  10461. optarg = NULL;
  10462. opterr = (count < G.getopt_count) ? 0 : my_opterr;
  10463. c = getopt(n, argv, optstring);
  10464. if (c < 0)
  10465. break;
  10466. count++;
  10467. } while (count <= G.getopt_count);
  10468. /* Set OPTIND. Prevent resetting of the magic counter! */
  10469. set_local_var_from_halves("OPTIND", utoa(optind));
  10470. G.getopt_count = count; /* "next time, give me N+1'th result" */
  10471. GETOPT_RESET(); /* just in case */
  10472. /* Set OPTARG */
  10473. /* Always set or unset, never left as-is, even on exit/error:
  10474. * "If no option was found, or if the option that was found
  10475. * does not have an option-argument, OPTARG shall be unset."
  10476. */
  10477. cp = optarg;
  10478. if (c == '?') {
  10479. /* If ":optstring" and unknown option is seen,
  10480. * it is stored to OPTARG.
  10481. */
  10482. if (optstring[1] == ':') {
  10483. cbuf[0] = optopt;
  10484. cp = cbuf;
  10485. }
  10486. }
  10487. if (cp)
  10488. set_local_var_from_halves("OPTARG", cp);
  10489. else
  10490. unset_local_var("OPTARG");
  10491. /* Convert -1 to "?" */
  10492. exitcode = EXIT_SUCCESS;
  10493. if (c < 0) { /* -1: end of options */
  10494. exitcode = EXIT_FAILURE;
  10495. c = '?';
  10496. }
  10497. /* Set VAR */
  10498. cbuf[0] = c;
  10499. set_local_var_from_halves(var, cbuf);
  10500. return exitcode;
  10501. }
  10502. #endif
  10503. static int FAST_FUNC builtin_source(char **argv)
  10504. {
  10505. char *arg_path, *filename;
  10506. HFILE *input;
  10507. save_arg_t sv;
  10508. char *args_need_save;
  10509. #if ENABLE_HUSH_FUNCTIONS
  10510. smallint sv_flg;
  10511. #endif
  10512. argv = skip_dash_dash(argv);
  10513. filename = argv[0];
  10514. if (!filename) {
  10515. /* bash says: "bash: .: filename argument required" */
  10516. return 2; /* bash compat */
  10517. }
  10518. arg_path = NULL;
  10519. if (!strchr(filename, '/')) {
  10520. arg_path = find_in_path(filename);
  10521. if (arg_path)
  10522. filename = arg_path;
  10523. else if (!ENABLE_HUSH_BASH_SOURCE_CURDIR) {
  10524. errno = ENOENT;
  10525. bb_simple_perror_msg(filename);
  10526. return EXIT_FAILURE;
  10527. }
  10528. }
  10529. input = hfopen(filename);
  10530. free(arg_path);
  10531. if (!input) {
  10532. bb_perror_msg("%s", filename);
  10533. /* POSIX: non-interactive shell should abort here,
  10534. * not merely fail. So far no one complained :)
  10535. */
  10536. return EXIT_FAILURE;
  10537. }
  10538. #if ENABLE_HUSH_FUNCTIONS
  10539. sv_flg = G_flag_return_in_progress;
  10540. /* "we are inside sourced file, ok to use return" */
  10541. G_flag_return_in_progress = -1;
  10542. #endif
  10543. args_need_save = argv[1]; /* used as a boolean variable */
  10544. if (args_need_save)
  10545. save_and_replace_G_args(&sv, argv);
  10546. /* "false; . ./empty_line; echo Zero:$?" should print 0 */
  10547. G.last_exitcode = 0;
  10548. parse_and_run_file(input);
  10549. hfclose(input);
  10550. if (args_need_save) /* can't use argv[1] instead: "shift" can mangle it */
  10551. restore_G_args(&sv, argv);
  10552. #if ENABLE_HUSH_FUNCTIONS
  10553. G_flag_return_in_progress = sv_flg;
  10554. #endif
  10555. return G.last_exitcode;
  10556. }
  10557. #if ENABLE_HUSH_TRAP
  10558. static int FAST_FUNC builtin_trap(char **argv)
  10559. {
  10560. int sig;
  10561. char *new_cmd;
  10562. if (!G_traps)
  10563. G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
  10564. argv++;
  10565. if (!*argv) {
  10566. int i;
  10567. /* No args: print all trapped */
  10568. for (i = 0; i < NSIG; ++i) {
  10569. if (G_traps[i]) {
  10570. printf("trap -- ");
  10571. print_escaped(G_traps[i]);
  10572. /* note: bash adds "SIG", but only if invoked
  10573. * as "bash". If called as "sh", or if set -o posix,
  10574. * then it prints short signal names.
  10575. * We are printing short names: */
  10576. printf(" %s\n", get_signame(i));
  10577. }
  10578. }
  10579. /*fflush_all(); - done after each builtin anyway */
  10580. return EXIT_SUCCESS;
  10581. }
  10582. new_cmd = NULL;
  10583. /* If first arg is a number: reset all specified signals */
  10584. sig = bb_strtou(*argv, NULL, 10);
  10585. if (errno == 0) {
  10586. int ret;
  10587. process_sig_list:
  10588. ret = EXIT_SUCCESS;
  10589. while (*argv) {
  10590. sighandler_t handler;
  10591. sig = get_signum(*argv++);
  10592. if (sig < 0) {
  10593. ret = EXIT_FAILURE;
  10594. /* Mimic bash message exactly */
  10595. bb_error_msg("trap: %s: invalid signal specification", argv[-1]);
  10596. continue;
  10597. }
  10598. free(G_traps[sig]);
  10599. G_traps[sig] = xstrdup(new_cmd);
  10600. debug_printf("trap: setting SIG%s (%i) to '%s'\n",
  10601. get_signame(sig), sig, G_traps[sig]);
  10602. /* There is no signal for 0 (EXIT) */
  10603. if (sig == 0)
  10604. continue;
  10605. if (new_cmd)
  10606. handler = (new_cmd[0] ? record_pending_signo : SIG_IGN);
  10607. else
  10608. /* We are removing trap handler */
  10609. handler = pick_sighandler(sig);
  10610. install_sighandler(sig, handler);
  10611. }
  10612. return ret;
  10613. }
  10614. if (!argv[1]) { /* no second arg */
  10615. bb_simple_error_msg("trap: invalid arguments");
  10616. return EXIT_FAILURE;
  10617. }
  10618. /* First arg is "-": reset all specified to default */
  10619. /* First arg is "--": skip it, the rest is "handler SIGs..." */
  10620. /* Everything else: set arg as signal handler
  10621. * (includes "" case, which ignores signal) */
  10622. if (argv[0][0] == '-') {
  10623. if (argv[0][1] == '\0') { /* "-" */
  10624. /* new_cmd remains NULL: "reset these sigs" */
  10625. goto reset_traps;
  10626. }
  10627. if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
  10628. argv++;
  10629. }
  10630. /* else: "-something", no special meaning */
  10631. }
  10632. new_cmd = *argv;
  10633. reset_traps:
  10634. argv++;
  10635. goto process_sig_list;
  10636. }
  10637. #endif
  10638. #if ENABLE_HUSH_JOB
  10639. static struct pipe *parse_jobspec(const char *str)
  10640. {
  10641. struct pipe *pi;
  10642. unsigned jobnum;
  10643. if (sscanf(str, "%%%u", &jobnum) != 1) {
  10644. if (str[0] != '%'
  10645. || (str[1] != '%' && str[1] != '+' && str[1] != '\0')
  10646. ) {
  10647. bb_error_msg("bad argument '%s'", str);
  10648. return NULL;
  10649. }
  10650. /* It is "%%", "%+" or "%" - current job */
  10651. jobnum = G.last_jobid;
  10652. if (jobnum == 0) {
  10653. bb_simple_error_msg("no current job");
  10654. return NULL;
  10655. }
  10656. }
  10657. for (pi = G.job_list; pi; pi = pi->next) {
  10658. if (pi->jobid == jobnum) {
  10659. return pi;
  10660. }
  10661. }
  10662. bb_error_msg("%u: no such job", jobnum);
  10663. return NULL;
  10664. }
  10665. static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
  10666. {
  10667. struct pipe *job;
  10668. const char *status_string;
  10669. checkjobs(NULL, 0 /*(no pid to wait for)*/);
  10670. for (job = G.job_list; job; job = job->next) {
  10671. if (job->alive_cmds == job->stopped_cmds)
  10672. status_string = "Stopped";
  10673. else
  10674. status_string = "Running";
  10675. printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
  10676. }
  10677. clean_up_last_dead_job();
  10678. return EXIT_SUCCESS;
  10679. }
  10680. /* built-in 'fg' and 'bg' handler */
  10681. static int FAST_FUNC builtin_fg_bg(char **argv)
  10682. {
  10683. int i;
  10684. struct pipe *pi;
  10685. if (!G_interactive_fd)
  10686. return EXIT_FAILURE;
  10687. /* If they gave us no args, assume they want the last backgrounded task */
  10688. if (!argv[1]) {
  10689. for (pi = G.job_list; pi; pi = pi->next) {
  10690. if (pi->jobid == G.last_jobid) {
  10691. goto found;
  10692. }
  10693. }
  10694. bb_error_msg("%s: no current job", argv[0]);
  10695. return EXIT_FAILURE;
  10696. }
  10697. pi = parse_jobspec(argv[1]);
  10698. if (!pi)
  10699. return EXIT_FAILURE;
  10700. found:
  10701. /* TODO: bash prints a string representation
  10702. * of job being foregrounded (like "sleep 1 | cat") */
  10703. if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
  10704. /* Put the job into the foreground. */
  10705. tcsetpgrp(G_interactive_fd, pi->pgrp);
  10706. }
  10707. /* Restart the processes in the job */
  10708. debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
  10709. for (i = 0; i < pi->num_cmds; i++) {
  10710. debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
  10711. }
  10712. pi->stopped_cmds = 0;
  10713. i = kill(- pi->pgrp, SIGCONT);
  10714. if (i < 0) {
  10715. if (errno == ESRCH) {
  10716. delete_finished_job(pi);
  10717. return EXIT_SUCCESS;
  10718. }
  10719. bb_simple_perror_msg("kill (SIGCONT)");
  10720. }
  10721. if (argv[0][0] == 'f') {
  10722. remove_job_from_table(pi); /* FG job shouldn't be in job table */
  10723. return checkjobs_and_fg_shell(pi);
  10724. }
  10725. return EXIT_SUCCESS;
  10726. }
  10727. #endif
  10728. #if ENABLE_HUSH_KILL
  10729. static int FAST_FUNC builtin_kill(char **argv)
  10730. {
  10731. int ret = 0;
  10732. # if ENABLE_HUSH_JOB
  10733. if (argv[1] && strcmp(argv[1], "-l") != 0) {
  10734. int i = 1;
  10735. do {
  10736. struct pipe *pi;
  10737. char *dst;
  10738. int j, n;
  10739. if (argv[i][0] != '%')
  10740. continue;
  10741. /*
  10742. * "kill %N" - job kill
  10743. * Converting to pgrp / pid kill
  10744. */
  10745. pi = parse_jobspec(argv[i]);
  10746. if (!pi) {
  10747. /* Eat bad jobspec */
  10748. j = i;
  10749. do {
  10750. j++;
  10751. argv[j - 1] = argv[j];
  10752. } while (argv[j]);
  10753. ret = 1;
  10754. i--;
  10755. continue;
  10756. }
  10757. /*
  10758. * In jobs started under job control, we signal
  10759. * entire process group by kill -PGRP_ID.
  10760. * This happens, f.e., in interactive shell.
  10761. *
  10762. * Otherwise, we signal each child via
  10763. * kill PID1 PID2 PID3.
  10764. * Testcases:
  10765. * sh -c 'sleep 1|sleep 1 & kill %1'
  10766. * sh -c 'true|sleep 2 & sleep 1; kill %1'
  10767. * sh -c 'true|sleep 1 & sleep 2; kill %1'
  10768. */
  10769. n = G_interactive_fd ? 1 : pi->num_cmds;
  10770. dst = alloca(n * sizeof(int)*4);
  10771. argv[i] = dst;
  10772. if (G_interactive_fd)
  10773. dst += sprintf(dst, " -%u", (int)pi->pgrp);
  10774. else for (j = 0; j < n; j++) {
  10775. struct command *cmd = &pi->cmds[j];
  10776. /* Skip exited members of the job */
  10777. if (cmd->pid == 0)
  10778. continue;
  10779. /*
  10780. * kill_main has matching code to expect
  10781. * leading space. Needed to not confuse
  10782. * negative pids with "kill -SIGNAL_NO" syntax
  10783. */
  10784. dst += sprintf(dst, " %u", (int)cmd->pid);
  10785. }
  10786. *dst = '\0';
  10787. } while (argv[++i]);
  10788. }
  10789. # endif
  10790. if (argv[1] || ret == 0) {
  10791. ret = run_applet_main(argv, kill_main);
  10792. }
  10793. /* else: ret = 1, "kill %bad_jobspec" case */
  10794. return ret;
  10795. }
  10796. #endif
  10797. #if ENABLE_HUSH_WAIT
  10798. /* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
  10799. # if !ENABLE_HUSH_JOB
  10800. # define wait_for_child_or_signal(pipe,pid) wait_for_child_or_signal(pid)
  10801. # endif
  10802. static int wait_for_child_or_signal(struct pipe *waitfor_pipe, pid_t waitfor_pid)
  10803. {
  10804. int ret = 0;
  10805. for (;;) {
  10806. int sig;
  10807. sigset_t oldset;
  10808. if (!sigisemptyset(&G.pending_set))
  10809. goto check_sig;
  10810. /* waitpid is not interruptible by SA_RESTARTed
  10811. * signals which we use. Thus, this ugly dance:
  10812. */
  10813. /* Make sure possible SIGCHLD is stored in kernel's
  10814. * pending signal mask before we call waitpid.
  10815. * Or else we may race with SIGCHLD, lose it,
  10816. * and get stuck in sigsuspend...
  10817. */
  10818. sigfillset(&oldset); /* block all signals, remember old set */
  10819. sigprocmask2(SIG_SETMASK, &oldset);
  10820. if (!sigisemptyset(&G.pending_set)) {
  10821. /* Crap! we raced with some signal! */
  10822. goto restore;
  10823. }
  10824. /*errno = 0; - checkjobs does this */
  10825. /* Can't pass waitfor_pipe into checkjobs(): it won't be interruptible */
  10826. ret = checkjobs(NULL, waitfor_pid); /* waitpid(WNOHANG) inside */
  10827. debug_printf_exec("checkjobs:%d\n", ret);
  10828. # if ENABLE_HUSH_JOB
  10829. if (waitfor_pipe) {
  10830. int rcode = job_exited_or_stopped(waitfor_pipe);
  10831. debug_printf_exec("job_exited_or_stopped:%d\n", rcode);
  10832. if (rcode >= 0) {
  10833. ret = rcode;
  10834. sigprocmask(SIG_SETMASK, &oldset, NULL);
  10835. break;
  10836. }
  10837. }
  10838. # endif
  10839. /* if ECHILD, there are no children (ret is -1 or 0) */
  10840. /* if ret == 0, no children changed state */
  10841. /* if ret != 0, it's exitcode+1 of exited waitfor_pid child */
  10842. if (errno == ECHILD || ret) {
  10843. ret--;
  10844. if (ret < 0) /* if ECHILD, may need to fix "ret" */
  10845. ret = 0;
  10846. # if ENABLE_HUSH_BASH_COMPAT
  10847. if (waitfor_pid == -1 && errno == ECHILD) {
  10848. /* exitcode of "wait -n" with no children is 127, not 0 */
  10849. ret = 127;
  10850. }
  10851. # endif
  10852. sigprocmask(SIG_SETMASK, &oldset, NULL);
  10853. break;
  10854. }
  10855. /* Wait for SIGCHLD or any other signal */
  10856. /* It is vitally important for sigsuspend that SIGCHLD has non-DFL handler! */
  10857. /* Note: sigsuspend invokes signal handler */
  10858. sigsuspend(&oldset);
  10859. /* ^^^ add "sigdelset(&oldset, SIGCHLD)" before sigsuspend
  10860. * to make sure SIGCHLD is not masked off?
  10861. * It was reported that this:
  10862. * fn() { : | return; }
  10863. * shopt -s lastpipe
  10864. * fn
  10865. * exec hush SCRIPT
  10866. * under bash 4.4.23 runs SCRIPT with SIGCHLD masked,
  10867. * making "wait" commands in SCRIPT block forever.
  10868. */
  10869. restore:
  10870. sigprocmask(SIG_SETMASK, &oldset, NULL);
  10871. check_sig:
  10872. /* So, did we get a signal? */
  10873. sig = check_and_run_traps();
  10874. if (sig /*&& sig != SIGCHLD - always true */) {
  10875. /* Do this for any (non-ignored) signal, not only for ^C */
  10876. ret = 128 + sig;
  10877. break;
  10878. }
  10879. /* SIGCHLD, or no signal, or ignored one, such as SIGQUIT. Repeat */
  10880. }
  10881. return ret;
  10882. }
  10883. static int FAST_FUNC builtin_wait(char **argv)
  10884. {
  10885. int ret;
  10886. int status;
  10887. argv = skip_dash_dash(argv);
  10888. # if ENABLE_HUSH_BASH_COMPAT
  10889. if (argv[0] && strcmp(argv[0], "-n") == 0) {
  10890. /* wait -n */
  10891. /* (bash accepts "wait -n PID" too and ignores PID) */
  10892. G.dead_job_exitcode = -1;
  10893. return wait_for_child_or_signal(NULL, -1 /*no job, wait for one job*/);
  10894. }
  10895. # endif
  10896. if (argv[0] == NULL) {
  10897. /* Don't care about wait results */
  10898. /* Note 1: must wait until there are no more children */
  10899. /* Note 2: must be interruptible */
  10900. /* Examples:
  10901. * $ sleep 3 & sleep 6 & wait
  10902. * [1] 30934 sleep 3
  10903. * [2] 30935 sleep 6
  10904. * [1] Done sleep 3
  10905. * [2] Done sleep 6
  10906. * $ sleep 3 & sleep 6 & wait
  10907. * [1] 30936 sleep 3
  10908. * [2] 30937 sleep 6
  10909. * [1] Done sleep 3
  10910. * ^C <-- after ~4 sec from keyboard
  10911. * $
  10912. */
  10913. return wait_for_child_or_signal(NULL, 0 /*no job and no pid to wait for*/);
  10914. }
  10915. do {
  10916. pid_t pid = bb_strtou(*argv, NULL, 10);
  10917. if (errno || pid <= 0) {
  10918. # if ENABLE_HUSH_JOB
  10919. if (argv[0][0] == '%') {
  10920. struct pipe *wait_pipe;
  10921. ret = 127; /* bash compat for bad jobspecs */
  10922. wait_pipe = parse_jobspec(*argv);
  10923. if (wait_pipe) {
  10924. ret = job_exited_or_stopped(wait_pipe);
  10925. if (ret < 0) {
  10926. ret = wait_for_child_or_signal(wait_pipe, 0);
  10927. } else {
  10928. /* waiting on "last dead job" removes it */
  10929. clean_up_last_dead_job();
  10930. }
  10931. }
  10932. /* else: parse_jobspec() already emitted error msg */
  10933. continue;
  10934. }
  10935. # endif
  10936. /* mimic bash message */
  10937. bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
  10938. ret = EXIT_FAILURE;
  10939. continue; /* bash checks all argv[] */
  10940. }
  10941. /* Do we have such child? */
  10942. ret = waitpid(pid, &status, WNOHANG);
  10943. if (ret < 0) {
  10944. /* No */
  10945. ret = 127;
  10946. if (errno == ECHILD) {
  10947. if (pid == G.last_bg_pid) {
  10948. /* "wait $!" but last bg task has already exited. Try:
  10949. * (sleep 1; exit 3) & sleep 2; echo $?; wait $!; echo $?
  10950. * In bash it prints exitcode 0, then 3.
  10951. * In dash, it is 127.
  10952. */
  10953. ret = G.last_bg_pid_exitcode;
  10954. } else {
  10955. /* Example: "wait 1". mimic bash message */
  10956. bb_error_msg("wait: pid %u is not a child of this shell", (unsigned)pid);
  10957. }
  10958. } else {
  10959. /* ??? */
  10960. bb_perror_msg("wait %s", *argv);
  10961. }
  10962. continue; /* bash checks all argv[] */
  10963. }
  10964. if (ret == 0) {
  10965. /* Yes, and it still runs */
  10966. ret = wait_for_child_or_signal(NULL, pid);
  10967. } else {
  10968. /* Yes, and it just exited */
  10969. process_wait_result(NULL, pid, status);
  10970. ret = WEXITSTATUS(status);
  10971. if (WIFSIGNALED(status))
  10972. ret = 128 + WTERMSIG(status);
  10973. }
  10974. } while (*++argv);
  10975. return ret;
  10976. }
  10977. #endif
  10978. #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
  10979. static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
  10980. {
  10981. if (argv[1]) {
  10982. def = bb_strtou(argv[1], NULL, 10);
  10983. if (errno || def < def_min || argv[2]) {
  10984. bb_error_msg("%s: bad arguments", argv[0]);
  10985. def = UINT_MAX;
  10986. }
  10987. }
  10988. return def;
  10989. }
  10990. #endif
  10991. #if ENABLE_HUSH_LOOPS
  10992. static int FAST_FUNC builtin_break(char **argv)
  10993. {
  10994. unsigned depth;
  10995. if (G.depth_of_loop == 0) {
  10996. bb_error_msg("%s: only meaningful in a loop", argv[0]);
  10997. /* if we came from builtin_continue(), need to undo "= 1" */
  10998. G.flag_break_continue = 0;
  10999. return EXIT_SUCCESS; /* bash compat */
  11000. }
  11001. G.flag_break_continue++; /* BC_BREAK = 1, or BC_CONTINUE = 2 */
  11002. G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
  11003. if (depth == UINT_MAX)
  11004. G.flag_break_continue = BC_BREAK;
  11005. if (G.depth_of_loop < depth)
  11006. G.depth_break_continue = G.depth_of_loop;
  11007. return EXIT_SUCCESS;
  11008. }
  11009. static int FAST_FUNC builtin_continue(char **argv)
  11010. {
  11011. G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
  11012. return builtin_break(argv);
  11013. }
  11014. #endif
  11015. #if ENABLE_HUSH_FUNCTIONS
  11016. static int FAST_FUNC builtin_return(char **argv)
  11017. {
  11018. int rc;
  11019. if (G_flag_return_in_progress != -1) {
  11020. bb_error_msg("%s: not in a function or sourced script", argv[0]);
  11021. return EXIT_FAILURE; /* bash compat */
  11022. }
  11023. G_flag_return_in_progress = 1;
  11024. /* bash:
  11025. * out of range: wraps around at 256, does not error out
  11026. * non-numeric param:
  11027. * f() { false; return qwe; }; f; echo $?
  11028. * bash: return: qwe: numeric argument required <== we do this
  11029. * 255 <== we also do this
  11030. */
  11031. rc = parse_numeric_argv1(argv, G.last_exitcode, 0);
  11032. # if ENABLE_HUSH_TRAP
  11033. if (argv[1]) { /* "return ARG" inside a running trap sets $? */
  11034. debug_printf_exec("G.return_exitcode=%d\n", rc);
  11035. G.return_exitcode = rc;
  11036. }
  11037. # endif
  11038. return rc;
  11039. }
  11040. #endif
  11041. #if ENABLE_HUSH_TIMES
  11042. static int FAST_FUNC builtin_times(char **argv UNUSED_PARAM)
  11043. {
  11044. static const uint8_t times_tbl[] ALIGN1 = {
  11045. ' ', offsetof(struct tms, tms_utime),
  11046. '\n', offsetof(struct tms, tms_stime),
  11047. ' ', offsetof(struct tms, tms_cutime),
  11048. '\n', offsetof(struct tms, tms_cstime),
  11049. 0
  11050. };
  11051. const uint8_t *p;
  11052. unsigned clk_tck;
  11053. struct tms buf;
  11054. clk_tck = bb_clk_tck();
  11055. times(&buf);
  11056. p = times_tbl;
  11057. do {
  11058. unsigned sec, frac;
  11059. unsigned long t;
  11060. t = *(clock_t *)(((char *) &buf) + p[1]);
  11061. sec = t / clk_tck;
  11062. frac = t % clk_tck;
  11063. printf("%um%u.%03us%c",
  11064. sec / 60, sec % 60,
  11065. (frac * 1000) / clk_tck,
  11066. p[0]);
  11067. p += 2;
  11068. } while (*p);
  11069. return EXIT_SUCCESS;
  11070. }
  11071. #endif
  11072. #if ENABLE_HUSH_MEMLEAK
  11073. static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
  11074. {
  11075. void *p;
  11076. unsigned long l;
  11077. # ifdef M_TRIM_THRESHOLD
  11078. /* Optional. Reduces probability of false positives */
  11079. malloc_trim(0);
  11080. # endif
  11081. /* Crude attempt to find where "free memory" starts,
  11082. * sans fragmentation. */
  11083. p = malloc(240);
  11084. l = (unsigned long)p;
  11085. free(p);
  11086. p = malloc(3400);
  11087. if (l < (unsigned long)p) l = (unsigned long)p;
  11088. free(p);
  11089. # if 0 /* debug */
  11090. {
  11091. struct mallinfo mi = mallinfo();
  11092. printf("top alloc:0x%lx malloced:%d+%d=%d\n", l,
  11093. mi.arena, mi.hblkhd, mi.arena + mi.hblkhd);
  11094. }
  11095. # endif
  11096. if (!G.memleak_value)
  11097. G.memleak_value = l;
  11098. l -= G.memleak_value;
  11099. if ((long)l < 0)
  11100. l = 0;
  11101. l /= 1024;
  11102. if (l > 127)
  11103. l = 127;
  11104. /* Exitcode is "how many kilobytes we leaked since 1st call" */
  11105. return l;
  11106. }
  11107. #endif