hush.c 271 KB

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