hush.c 291 KB

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