hush.c 323 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * A prototype Bourne shell grammar parser.
  4. * Intended to follow the original Thompson and Ritchie
  5. * "small and simple is beautiful" philosophy, which
  6. * incidentally is a good match to today's BusyBox.
  7. *
  8. * Copyright (C) 2000,2001 Larry Doolittle <larry@doolittle.boa.org>
  9. * Copyright (C) 2008,2009 Denys Vlasenko <vda.linux@googlemail.com>
  10. *
  11. * Licensed under GPLv2 or later, see file LICENSE in this source tree.
  12. *
  13. * Credits:
  14. * The parser routines proper are all original material, first
  15. * written Dec 2000 and Jan 2001 by Larry Doolittle. The
  16. * execution engine, the builtins, and much of the underlying
  17. * support has been adapted from busybox-0.49pre's lash, which is
  18. * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
  19. * written by Erik Andersen <andersen@codepoet.org>. That, in turn,
  20. * is based in part on ladsh.c, by Michael K. Johnson and Erik W.
  21. * Troan, which they placed in the public domain. I don't know
  22. * how much of the Johnson/Troan code has survived the repeated
  23. * rewrites.
  24. *
  25. * Other credits:
  26. * o_addchr derived from similar w_addchar function in glibc-2.2.
  27. * parse_redirect, redirect_opt_num, and big chunks of main
  28. * and many builtins derived from contributions by Erik Andersen.
  29. * Miscellaneous bugfixes from Matt Kraai.
  30. *
  31. * There are two big (and related) architecture differences between
  32. * this parser and the lash parser. One is that this version is
  33. * actually designed from the ground up to understand nearly all
  34. * of the Bourne grammar. The second, consequential change is that
  35. * the parser and input reader have been turned inside out. Now,
  36. * the parser is in control, and asks for input as needed. The old
  37. * way had the input reader in control, and it asked for parsing to
  38. * take place as needed. The new way makes it much easier to properly
  39. * handle the recursion implicit in the various substitutions, especially
  40. * across continuation lines.
  41. *
  42. * TODOs:
  43. * grep for "TODO" and fix (some of them are easy)
  44. * make complex ${var%...} constructs support optional
  45. * make here documents optional
  46. * special variables (done: PWD, PPID, RANDOM)
  47. * follow IFS rules more precisely, including update semantics
  48. * tilde expansion
  49. * aliases
  50. * "command" missing features:
  51. * command -p CMD: run CMD using default $PATH
  52. * (can use this to override standalone shell as well?)
  53. * command BLTIN: disables special-ness (e.g. errors do not abort)
  54. * command -V CMD1 CMD2 CMD3 (multiple args) (not in standard)
  55. * builtins mandated by standards we don't support:
  56. * [un]alias, fc:
  57. * fc -l[nr] [BEG] [END]: list range of commands in history
  58. * fc [-e EDITOR] [BEG] [END]: edit/rerun range of commands
  59. * fc -s [PAT=REP] [CMD]: rerun CMD, replacing PAT with REP
  60. *
  61. * Bash compat TODO:
  62. * redirection of stdout+stderr: &> and >&
  63. * reserved words: function select
  64. * advanced test: [[ ]]
  65. * process substitution: <(list) and >(list)
  66. * =~: regex operator
  67. * let EXPR [EXPR...]
  68. * Each EXPR is an arithmetic expression (ARITHMETIC EVALUATION)
  69. * If the last arg evaluates to 0, let returns 1; 0 otherwise.
  70. * NB: let `echo 'a=a + 1'` - error (IOW: multi-word expansion is used)
  71. * ((EXPR))
  72. * The EXPR is evaluated according to ARITHMETIC EVALUATION.
  73. * This is exactly equivalent to let "EXPR".
  74. * $[EXPR]: synonym for $((EXPR))
  75. * indirect expansion: ${!VAR}
  76. * substring op on @: ${@:n:m}
  77. *
  78. * Won't do:
  79. * Some builtins mandated by standards:
  80. * newgrp [GRP]: not a builtin in bash but a suid binary
  81. * which spawns a new shell with new group ID
  82. *
  83. * Status of [[ support:
  84. * [[ args ]] are CMD_SINGLEWORD_NOGLOB:
  85. * v='a b'; [[ $v = 'a b' ]]; echo 0:$?
  86. * [[ /bin/n* ]]; echo 0:$?
  87. * TODO:
  88. * &&/|| are AND/OR ops, -a/-o are not
  89. * quoting needs to be considered (-f is an operator, "-f" and ""-f are not; etc)
  90. * = is glob match operator, not equality operator: STR = GLOB
  91. * (in GLOB, quoting is significant on char-by-char basis: a*cd"*")
  92. * == same as =
  93. * add =~ regex match operator: STR =~ REGEX
  94. */
  95. //config:config HUSH
  96. //config: bool "hush (68 kb)"
  97. //config: default y
  98. //config: help
  99. //config: hush is a small shell. It handles the normal flow control
  100. //config: constructs such as if/then/elif/else/fi, for/in/do/done, while loops,
  101. //config: case/esac. Redirections, here documents, $((arithmetic))
  102. //config: and functions are supported.
  103. //config:
  104. //config: It will compile and work on no-mmu systems.
  105. //config:
  106. //config: It does not handle select, aliases, tilde expansion,
  107. //config: &>file and >&file redirection of stdout+stderr.
  108. //config:
  109. //config:config HUSH_BASH_COMPAT
  110. //config: bool "bash-compatible extensions"
  111. //config: default y
  112. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  113. //config:
  114. //config:config HUSH_BRACE_EXPANSION
  115. //config: bool "Brace expansion"
  116. //config: default y
  117. //config: depends on HUSH_BASH_COMPAT
  118. //config: help
  119. //config: Enable {abc,def} extension.
  120. //config:
  121. //config:config HUSH_LINENO_VAR
  122. //config: bool "$LINENO variable"
  123. //config: default y
  124. //config: depends on HUSH_BASH_COMPAT
  125. //config:
  126. //config:config HUSH_BASH_SOURCE_CURDIR
  127. //config: bool "'source' and '.' builtins search current directory after $PATH"
  128. //config: default n # do not encourage non-standard behavior
  129. //config: depends on HUSH_BASH_COMPAT
  130. //config: help
  131. //config: This is not compliant with standards. Avoid if possible.
  132. //config:
  133. //config:config HUSH_INTERACTIVE
  134. //config: bool "Interactive mode"
  135. //config: default y
  136. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  137. //config: help
  138. //config: Enable interactive mode (prompt and command editing).
  139. //config: Without this, hush simply reads and executes commands
  140. //config: from stdin just like a shell script from a file.
  141. //config: No prompt, no PS1/PS2 magic shell variables.
  142. //config:
  143. //config:config HUSH_SAVEHISTORY
  144. //config: bool "Save command history to .hush_history"
  145. //config: default y
  146. //config: depends on HUSH_INTERACTIVE && FEATURE_EDITING_SAVEHISTORY
  147. //config:
  148. //config:config HUSH_JOB
  149. //config: bool "Job control"
  150. //config: default y
  151. //config: depends on HUSH_INTERACTIVE
  152. //config: help
  153. //config: Enable job control: Ctrl-Z backgrounds, Ctrl-C interrupts current
  154. //config: command (not entire shell), fg/bg builtins work. Without this option,
  155. //config: "cmd &" still works by simply spawning a process and immediately
  156. //config: prompting for next command (or executing next command in a script),
  157. //config: but no separate process group is formed.
  158. //config:
  159. //config:config HUSH_TICK
  160. //config: bool "Support command substitution"
  161. //config: default y
  162. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  163. //config: help
  164. //config: Enable `command` and $(command).
  165. //config:
  166. //config:config HUSH_IF
  167. //config: bool "Support if/then/elif/else/fi"
  168. //config: default y
  169. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  170. //config:
  171. //config:config HUSH_LOOPS
  172. //config: bool "Support for, while and until loops"
  173. //config: default y
  174. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  175. //config:
  176. //config:config HUSH_CASE
  177. //config: bool "Support case ... esac statement"
  178. //config: default y
  179. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  180. //config: help
  181. //config: Enable case ... esac statement. +400 bytes.
  182. //config:
  183. //config:config HUSH_FUNCTIONS
  184. //config: bool "Support funcname() { commands; } syntax"
  185. //config: default y
  186. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  187. //config: help
  188. //config: Enable support for shell functions. +800 bytes.
  189. //config:
  190. //config:config HUSH_LOCAL
  191. //config: bool "local builtin"
  192. //config: default y
  193. //config: depends on HUSH_FUNCTIONS
  194. //config: help
  195. //config: Enable support for local variables in functions.
  196. //config:
  197. //config:config HUSH_RANDOM_SUPPORT
  198. //config: bool "Pseudorandom generator and $RANDOM variable"
  199. //config: default y
  200. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  201. //config: help
  202. //config: Enable pseudorandom generator and dynamic variable "$RANDOM".
  203. //config: Each read of "$RANDOM" will generate a new pseudorandom value.
  204. //config:
  205. //config:config HUSH_MODE_X
  206. //config: bool "Support 'hush -x' option and 'set -x' command"
  207. //config: default y
  208. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  209. //config: help
  210. //config: This instructs hush to print commands before execution.
  211. //config: Adds ~300 bytes.
  212. //config:
  213. //config:config HUSH_ECHO
  214. //config: bool "echo builtin"
  215. //config: default y
  216. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  217. //config:
  218. //config:config HUSH_PRINTF
  219. //config: bool "printf builtin"
  220. //config: default y
  221. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  222. //config:
  223. //config:config HUSH_TEST
  224. //config: bool "test builtin"
  225. //config: default y
  226. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  227. //config:
  228. //config:config HUSH_HELP
  229. //config: bool "help builtin"
  230. //config: default y
  231. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  232. //config:
  233. //config:config HUSH_EXPORT
  234. //config: bool "export builtin"
  235. //config: default y
  236. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  237. //config:
  238. //config:config HUSH_EXPORT_N
  239. //config: bool "Support 'export -n' option"
  240. //config: default y
  241. //config: depends on HUSH_EXPORT
  242. //config: help
  243. //config: export -n unexports variables. It is a bash extension.
  244. //config:
  245. //config:config HUSH_READONLY
  246. //config: bool "readonly builtin"
  247. //config: default y
  248. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  249. //config: help
  250. //config: Enable support for read-only variables.
  251. //config:
  252. //config:config HUSH_KILL
  253. //config: bool "kill builtin (supports kill %jobspec)"
  254. //config: default y
  255. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  256. //config:
  257. //config:config HUSH_WAIT
  258. //config: bool "wait builtin"
  259. //config: default y
  260. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  261. //config:
  262. //config:config HUSH_COMMAND
  263. //config: bool "command builtin"
  264. //config: default y
  265. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  266. //config:
  267. //config:config HUSH_TRAP
  268. //config: bool "trap builtin"
  269. //config: default y
  270. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  271. //config:
  272. //config:config HUSH_TYPE
  273. //config: bool "type builtin"
  274. //config: default y
  275. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  276. //config:
  277. //config:config HUSH_TIMES
  278. //config: bool "times builtin"
  279. //config: default y
  280. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  281. //config:
  282. //config:config HUSH_READ
  283. //config: bool "read builtin"
  284. //config: default y
  285. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  286. //config:
  287. //config:config HUSH_SET
  288. //config: bool "set builtin"
  289. //config: default y
  290. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  291. //config:
  292. //config:config HUSH_UNSET
  293. //config: bool "unset builtin"
  294. //config: default y
  295. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  296. //config:
  297. //config:config HUSH_ULIMIT
  298. //config: bool "ulimit builtin"
  299. //config: default y
  300. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  301. //config:
  302. //config:config HUSH_UMASK
  303. //config: bool "umask builtin"
  304. //config: default y
  305. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  306. //config:
  307. //config:config HUSH_GETOPTS
  308. //config: bool "getopts builtin"
  309. //config: default y
  310. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  311. //config:
  312. //config:config HUSH_MEMLEAK
  313. //config: bool "memleak builtin (debugging)"
  314. //config: default n
  315. //config: depends on HUSH || SH_IS_HUSH || BASH_IS_HUSH
  316. //applet:IF_HUSH(APPLET(hush, BB_DIR_BIN, BB_SUID_DROP))
  317. // APPLET_ODDNAME:name main location suid_type help
  318. //applet:IF_SH_IS_HUSH( APPLET_ODDNAME(sh, hush, BB_DIR_BIN, BB_SUID_DROP, hush))
  319. //applet:IF_BASH_IS_HUSH(APPLET_ODDNAME(bash, hush, BB_DIR_BIN, BB_SUID_DROP, hush))
  320. //kbuild:lib-$(CONFIG_HUSH) += hush.o match.o shell_common.o
  321. //kbuild:lib-$(CONFIG_SH_IS_HUSH) += hush.o match.o shell_common.o
  322. //kbuild:lib-$(CONFIG_BASH_IS_HUSH) += hush.o match.o shell_common.o
  323. //kbuild:lib-$(CONFIG_HUSH_RANDOM_SUPPORT) += random.o
  324. /* -i (interactive) is also accepted,
  325. * but does nothing, therefore not shown in help.
  326. * NOMMU-specific options are not meant to be used by users,
  327. * therefore we don't show them either.
  328. */
  329. //usage:#define hush_trivial_usage
  330. //usage: "[-enxl] [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS] / -s [ARGS]]"
  331. //usage:#define hush_full_usage "\n\n"
  332. //usage: "Unix shell interpreter"
  333. #if !(defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) \
  334. || defined(__APPLE__) \
  335. )
  336. # include <malloc.h> /* for malloc_trim */
  337. #endif
  338. #include <glob.h>
  339. /* #include <dmalloc.h> */
  340. #if ENABLE_HUSH_CASE
  341. # include <fnmatch.h>
  342. #endif
  343. #include <sys/times.h>
  344. #include <sys/utsname.h> /* for setting $HOSTNAME */
  345. #include "busybox.h" /* for APPLET_IS_NOFORK/NOEXEC */
  346. #include "unicode.h"
  347. #include "shell_common.h"
  348. #include "math.h"
  349. #include "match.h"
  350. #if ENABLE_HUSH_RANDOM_SUPPORT
  351. # include "random.h"
  352. #else
  353. # define CLEAR_RANDOM_T(rnd) ((void)0)
  354. #endif
  355. #ifndef O_CLOEXEC
  356. # define O_CLOEXEC 0
  357. #endif
  358. #ifndef F_DUPFD_CLOEXEC
  359. # define F_DUPFD_CLOEXEC F_DUPFD
  360. #endif
  361. #if ENABLE_FEATURE_SH_EMBEDDED_SCRIPTS && !(ENABLE_ASH || ENABLE_SH_IS_ASH || ENABLE_BASH_IS_ASH)
  362. # include "embedded_scripts.h"
  363. #else
  364. # define NUM_SCRIPTS 0
  365. #endif
  366. /* So far, all bash compat is controlled by one config option */
  367. /* Separate defines document which part of code implements what */
  368. #define BASH_PATTERN_SUBST ENABLE_HUSH_BASH_COMPAT
  369. #define BASH_SUBSTR ENABLE_HUSH_BASH_COMPAT
  370. #define BASH_SOURCE ENABLE_HUSH_BASH_COMPAT
  371. #define BASH_HOSTNAME_VAR ENABLE_HUSH_BASH_COMPAT
  372. #define BASH_EPOCH_VARS ENABLE_HUSH_BASH_COMPAT
  373. #define BASH_TEST2 (ENABLE_HUSH_BASH_COMPAT && ENABLE_HUSH_TEST)
  374. #define BASH_READ_D ENABLE_HUSH_BASH_COMPAT
  375. /* Build knobs */
  376. #define LEAK_HUNTING 0
  377. #define BUILD_AS_NOMMU 0
  378. /* Enable/disable sanity checks. Ok to enable in production,
  379. * only adds a bit of bloat. Set to >1 to get non-production level verbosity.
  380. * Keeping 1 for now even in released versions.
  381. */
  382. #define HUSH_DEBUG 1
  383. /* Slightly bigger (+200 bytes), but faster hush.
  384. * So far it only enables a trick with counting SIGCHLDs and forks,
  385. * which allows us to do fewer waitpid's.
  386. * (we can detect a case where neither forks were done nor SIGCHLDs happened
  387. * and therefore waitpid will return the same result as last time)
  388. */
  389. #define ENABLE_HUSH_FAST 0
  390. /* TODO: implement simplified code for users which do not need ${var%...} ops
  391. * So far ${var%...} ops are always enabled:
  392. */
  393. #define ENABLE_HUSH_DOLLAR_OPS 1
  394. #if BUILD_AS_NOMMU
  395. # undef BB_MMU
  396. # undef USE_FOR_NOMMU
  397. # undef USE_FOR_MMU
  398. # define BB_MMU 0
  399. # define USE_FOR_NOMMU(...) __VA_ARGS__
  400. # define USE_FOR_MMU(...)
  401. #endif
  402. #include "NUM_APPLETS.h"
  403. #if NUM_APPLETS == 1
  404. /* STANDALONE does not make sense, and won't compile */
  405. # undef CONFIG_FEATURE_SH_STANDALONE
  406. # undef ENABLE_FEATURE_SH_STANDALONE
  407. # undef IF_FEATURE_SH_STANDALONE
  408. # undef IF_NOT_FEATURE_SH_STANDALONE
  409. # define ENABLE_FEATURE_SH_STANDALONE 0
  410. # define IF_FEATURE_SH_STANDALONE(...)
  411. # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
  412. #endif
  413. #if !ENABLE_HUSH_INTERACTIVE
  414. # undef ENABLE_FEATURE_EDITING
  415. # define ENABLE_FEATURE_EDITING 0
  416. # undef ENABLE_FEATURE_EDITING_FANCY_PROMPT
  417. # define ENABLE_FEATURE_EDITING_FANCY_PROMPT 0
  418. # undef ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
  419. # define ENABLE_FEATURE_EDITING_SAVE_ON_EXIT 0
  420. #endif
  421. /* Do we support ANY keywords? */
  422. #if ENABLE_HUSH_IF || ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
  423. # define HAS_KEYWORDS 1
  424. # define IF_HAS_KEYWORDS(...) __VA_ARGS__
  425. # define IF_HAS_NO_KEYWORDS(...)
  426. #else
  427. # define HAS_KEYWORDS 0
  428. # define IF_HAS_KEYWORDS(...)
  429. # define IF_HAS_NO_KEYWORDS(...) __VA_ARGS__
  430. #endif
  431. /* If you comment out one of these below, it will be #defined later
  432. * to perform debug printfs to stderr: */
  433. #define debug_printf(...) do {} while (0)
  434. /* Finer-grained debug switches */
  435. #define debug_printf_parse(...) do {} while (0)
  436. #define debug_printf_heredoc(...) do {} while (0)
  437. #define debug_print_tree(a, b) do {} while (0)
  438. #define debug_printf_exec(...) do {} while (0)
  439. #define debug_printf_env(...) do {} while (0)
  440. #define debug_printf_jobs(...) do {} while (0)
  441. #define debug_printf_expand(...) do {} while (0)
  442. #define debug_printf_varexp(...) do {} while (0)
  443. #define debug_printf_glob(...) do {} while (0)
  444. #define debug_printf_redir(...) do {} while (0)
  445. #define debug_printf_list(...) do {} while (0)
  446. #define debug_printf_subst(...) do {} while (0)
  447. #define debug_printf_prompt(...) do {} while (0)
  448. #define debug_printf_clean(...) do {} while (0)
  449. #define ERR_PTR ((void*)(long)1)
  450. #define JOB_STATUS_FORMAT "[%u] %-22s %.40s\n"
  451. #define _SPECIAL_VARS_STR "_*@$!?#-"
  452. #define SPECIAL_VARS_STR ("_*@$!?#-" + 1)
  453. #define NUMERIC_SPECVARS_STR ("_*@$!?#-" + 3)
  454. #if BASH_PATTERN_SUBST
  455. /* Support / and // replace ops */
  456. /* Note that // is stored as \ in "encoded" string representation */
  457. # define VAR_ENCODED_SUBST_OPS "\\/%#:-=+?"
  458. # define VAR_SUBST_OPS ("\\/%#:-=+?" + 1)
  459. # define MINUS_PLUS_EQUAL_QUESTION ("\\/%#:-=+?" + 5)
  460. #else
  461. # define VAR_ENCODED_SUBST_OPS "%#:-=+?"
  462. # define VAR_SUBST_OPS "%#:-=+?"
  463. # define MINUS_PLUS_EQUAL_QUESTION ("%#:-=+?" + 3)
  464. #endif
  465. #define SPECIAL_VAR_SYMBOL_STR "\3"
  466. #define SPECIAL_VAR_SYMBOL 3
  467. /* The "variable" with name "\1" emits string "\3". Testcase: "echo ^C" */
  468. #define SPECIAL_VAR_QUOTED_SVS 1
  469. struct variable;
  470. static const char hush_version_str[] ALIGN1 = "HUSH_VERSION="BB_VER;
  471. /* This supports saving pointers malloced in vfork child,
  472. * to be freed in the parent.
  473. */
  474. #if !BB_MMU
  475. typedef struct nommu_save_t {
  476. struct variable *old_vars;
  477. char **argv;
  478. char **argv_from_re_execing;
  479. } nommu_save_t;
  480. #endif
  481. enum {
  482. RES_NONE = 0,
  483. #if ENABLE_HUSH_IF
  484. RES_IF ,
  485. RES_THEN ,
  486. RES_ELIF ,
  487. RES_ELSE ,
  488. RES_FI ,
  489. #endif
  490. #if ENABLE_HUSH_LOOPS
  491. RES_FOR ,
  492. RES_WHILE ,
  493. RES_UNTIL ,
  494. RES_DO ,
  495. RES_DONE ,
  496. #endif
  497. #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
  498. RES_IN ,
  499. #endif
  500. #if ENABLE_HUSH_CASE
  501. RES_CASE ,
  502. /* three pseudo-keywords support contrived "case" syntax: */
  503. RES_CASE_IN, /* "case ... IN", turns into RES_MATCH when IN is observed */
  504. RES_MATCH , /* "word)" */
  505. RES_CASE_BODY, /* "this command is inside CASE" */
  506. RES_ESAC ,
  507. #endif
  508. RES_XXXX ,
  509. RES_SNTX
  510. };
  511. typedef struct o_string {
  512. char *data;
  513. int length; /* position where data is appended */
  514. int maxlen;
  515. int o_expflags;
  516. /* At least some part of the string was inside '' or "",
  517. * possibly empty one: word"", wo''rd etc. */
  518. smallint has_quoted_part;
  519. smallint has_empty_slot;
  520. smallint ended_in_ifs;
  521. } o_string;
  522. enum {
  523. EXP_FLAG_SINGLEWORD = 0x80, /* must be 0x80 */
  524. EXP_FLAG_GLOB = 0x2,
  525. /* Protect newly added chars against globbing
  526. * by prepending \ to *, ?, [, \ */
  527. EXP_FLAG_ESC_GLOB_CHARS = 0x1,
  528. };
  529. /* Used for initialization: o_string foo = NULL_O_STRING; */
  530. #define NULL_O_STRING { NULL }
  531. #ifndef debug_printf_parse
  532. static const char *const assignment_flag[] = {
  533. "MAYBE_ASSIGNMENT",
  534. "DEFINITELY_ASSIGNMENT",
  535. "NOT_ASSIGNMENT",
  536. "WORD_IS_KEYWORD",
  537. };
  538. #endif
  539. /* We almost can use standard FILE api, but we need an ability to move
  540. * its fd when redirects coincide with it. No api exists for that
  541. * (RFE for it at https://sourceware.org/bugzilla/show_bug.cgi?id=21902).
  542. * HFILE is our internal alternative. Only supports reading.
  543. * Since we now can, we incorporate linked list of all opened HFILEs
  544. * into the struct (used to be a separate mini-list).
  545. */
  546. typedef struct HFILE {
  547. char *cur;
  548. char *end;
  549. struct HFILE *next_hfile;
  550. int is_stdin;
  551. int fd;
  552. char buf[1024];
  553. } HFILE;
  554. typedef struct in_str {
  555. const char *p;
  556. int peek_buf[2];
  557. int last_char;
  558. HFILE *file;
  559. } in_str;
  560. /* The descrip member of this structure is only used to make
  561. * debugging output pretty */
  562. static const struct {
  563. int mode;
  564. signed char default_fd;
  565. char descrip[3];
  566. } redir_table[] = {
  567. { O_RDONLY, 0, "<" },
  568. { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
  569. { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
  570. { O_CREAT|O_RDWR, 1, "<>" },
  571. { O_RDONLY, 0, "<<" },
  572. /* Should not be needed. Bogus default_fd helps in debugging */
  573. /* { O_RDONLY, 77, "<<" }, */
  574. };
  575. struct redir_struct {
  576. struct redir_struct *next;
  577. char *rd_filename; /* filename */
  578. int rd_fd; /* fd to redirect */
  579. /* fd to redirect to, or -3 if rd_fd is to be closed (n>&-) */
  580. int rd_dup;
  581. smallint rd_type; /* (enum redir_type) */
  582. /* note: for heredocs, rd_filename contains heredoc delimiter,
  583. * and subsequently heredoc itself; and rd_dup is a bitmask:
  584. * bit 0: do we need to trim leading tabs?
  585. * bit 1: is heredoc quoted (<<'delim' syntax) ?
  586. */
  587. };
  588. typedef enum redir_type {
  589. REDIRECT_INPUT = 0,
  590. REDIRECT_OVERWRITE = 1,
  591. REDIRECT_APPEND = 2,
  592. REDIRECT_IO = 3,
  593. REDIRECT_HEREDOC = 4,
  594. REDIRECT_HEREDOC2 = 5, /* REDIRECT_HEREDOC after heredoc is loaded */
  595. REDIRFD_CLOSE = -3,
  596. REDIRFD_SYNTAX_ERR = -2,
  597. REDIRFD_TO_FILE = -1,
  598. /* otherwise, rd_fd is redirected to rd_dup */
  599. HEREDOC_SKIPTABS = 1,
  600. HEREDOC_QUOTED = 2,
  601. } redir_type;
  602. struct command {
  603. pid_t pid; /* 0 if exited */
  604. unsigned assignment_cnt; /* how many argv[i] are assignments? */
  605. #if ENABLE_HUSH_LINENO_VAR
  606. unsigned lineno;
  607. #endif
  608. smallint cmd_type; /* CMD_xxx */
  609. #define CMD_NORMAL 0
  610. #define CMD_SUBSHELL 1
  611. #if BASH_TEST2 || ENABLE_HUSH_LOCAL || ENABLE_HUSH_EXPORT || ENABLE_HUSH_READONLY
  612. /* used for "[[ EXPR ]]", and to prevent word splitting and globbing in
  613. * "export v=t*"
  614. */
  615. # define CMD_SINGLEWORD_NOGLOB 2
  616. #endif
  617. #if ENABLE_HUSH_FUNCTIONS
  618. # define CMD_FUNCDEF 3
  619. #endif
  620. smalluint cmd_exitcode;
  621. /* if non-NULL, this "command" is { list }, ( list ), or a compound statement */
  622. struct pipe *group;
  623. #if !BB_MMU
  624. char *group_as_string;
  625. #endif
  626. #if ENABLE_HUSH_FUNCTIONS
  627. struct function *child_func;
  628. /* This field is used to prevent a bug here:
  629. * while...do f1() {a;}; f1; f1() {b;}; f1; done
  630. * When we execute "f1() {a;}" cmd, we create new function and clear
  631. * cmd->group, cmd->group_as_string, cmd->argv[0].
  632. * When we execute "f1() {b;}", we notice that f1 exists,
  633. * and that its "parent cmd" struct is still "alive",
  634. * we put those fields back into cmd->xxx
  635. * (struct function has ->parent_cmd ptr to facilitate that).
  636. * When we loop back, we can execute "f1() {a;}" again and set f1 correctly.
  637. * Without this trick, loop would execute a;b;b;b;...
  638. * instead of correct sequence a;b;a;b;...
  639. * When command is freed, it severs the link
  640. * (sets ->child_func->parent_cmd to NULL).
  641. */
  642. #endif
  643. char **argv; /* command name and arguments */
  644. /* argv vector may contain variable references (^Cvar^C, ^C0^C etc)
  645. * and on execution these are substituted with their values.
  646. * Substitution can make _several_ words out of one argv[n]!
  647. * Example: argv[0]=='.^C*^C.' here: echo .$*.
  648. * References of the form ^C`cmd arg^C are `cmd arg` substitutions.
  649. */
  650. struct redir_struct *redirects; /* I/O redirections */
  651. };
  652. /* Is there anything in this command at all? */
  653. #define IS_NULL_CMD(cmd) \
  654. (!(cmd)->group && !(cmd)->argv && !(cmd)->redirects)
  655. struct pipe {
  656. struct pipe *next;
  657. int num_cmds; /* total number of commands in pipe */
  658. int alive_cmds; /* number of commands running (not exited) */
  659. int stopped_cmds; /* number of commands alive, but stopped */
  660. #if ENABLE_HUSH_JOB
  661. unsigned jobid; /* job number */
  662. pid_t pgrp; /* process group ID for the job */
  663. char *cmdtext; /* name of job */
  664. #endif
  665. struct command *cmds; /* array of commands in pipe */
  666. smallint followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
  667. IF_HAS_KEYWORDS(smallint pi_inverted;) /* "! cmd | cmd" */
  668. IF_HAS_KEYWORDS(smallint res_word;) /* needed for if, for, while, until... */
  669. };
  670. typedef enum pipe_style {
  671. PIPE_SEQ = 0,
  672. PIPE_AND = 1,
  673. PIPE_OR = 2,
  674. PIPE_BG = 3,
  675. } pipe_style;
  676. /* Is there anything in this pipe at all? */
  677. #define IS_NULL_PIPE(pi) \
  678. ((pi)->num_cmds == 0 IF_HAS_KEYWORDS( && (pi)->res_word == RES_NONE))
  679. /* This holds pointers to the various results of parsing */
  680. struct parse_context {
  681. /* linked list of pipes */
  682. struct pipe *list_head;
  683. /* last pipe (being constructed right now) */
  684. struct pipe *pipe;
  685. /* last command in pipe (being constructed right now) */
  686. struct command *command;
  687. /* last redirect in command->redirects list */
  688. struct redir_struct *pending_redirect;
  689. o_string word;
  690. #if !BB_MMU
  691. o_string as_string;
  692. #endif
  693. smallint is_assignment; /* 0:maybe, 1:yes, 2:no, 3:keyword */
  694. #if HAS_KEYWORDS
  695. smallint ctx_res_w;
  696. smallint ctx_inverted; /* "! cmd | cmd" */
  697. #if ENABLE_HUSH_CASE
  698. smallint ctx_dsemicolon; /* ";;" seen */
  699. #endif
  700. /* bitmask of FLAG_xxx, for figuring out valid reserved words */
  701. int old_flag;
  702. /* group we are enclosed in:
  703. * example: "if pipe1; pipe2; then pipe3; fi"
  704. * when we see "if" or "then", we malloc and copy current context,
  705. * and make ->stack point to it. then we parse pipeN.
  706. * when closing "then" / fi" / whatever is found,
  707. * we move list_head into ->stack->command->group,
  708. * copy ->stack into current context, and delete ->stack.
  709. * (parsing of { list } and ( list ) doesn't use this method)
  710. */
  711. struct parse_context *stack;
  712. #endif
  713. };
  714. enum {
  715. MAYBE_ASSIGNMENT = 0,
  716. DEFINITELY_ASSIGNMENT = 1,
  717. NOT_ASSIGNMENT = 2,
  718. /* Not an assignment, but next word may be: "if v=xyz cmd;" */
  719. WORD_IS_KEYWORD = 3,
  720. };
  721. /* On program start, environ points to initial environment.
  722. * putenv adds new pointers into it, unsetenv removes them.
  723. * Neither of these (de)allocates the strings.
  724. * setenv allocates new strings in malloc space and does putenv,
  725. * and thus setenv is unusable (leaky) for shell's purposes */
  726. #define setenv(...) setenv_is_leaky_dont_use()
  727. struct variable {
  728. struct variable *next;
  729. char *varstr; /* points to "name=" portion */
  730. int max_len; /* if > 0, name is part of initial env; else name is malloced */
  731. uint16_t var_nest_level;
  732. smallint flg_export; /* putenv should be done on this var */
  733. smallint flg_read_only;
  734. };
  735. enum {
  736. BC_BREAK = 1,
  737. BC_CONTINUE = 2,
  738. };
  739. #if ENABLE_HUSH_FUNCTIONS
  740. struct function {
  741. struct function *next;
  742. char *name;
  743. struct command *parent_cmd;
  744. struct pipe *body;
  745. # if !BB_MMU
  746. char *body_as_string;
  747. # endif
  748. };
  749. #endif
  750. /* set -/+o OPT support. (TODO: make it optional)
  751. * bash supports the following opts:
  752. * allexport off
  753. * braceexpand on
  754. * emacs on
  755. * errexit off
  756. * errtrace off
  757. * functrace off
  758. * hashall on
  759. * histexpand off
  760. * history on
  761. * ignoreeof off
  762. * interactive-comments on
  763. * keyword off
  764. * monitor on
  765. * noclobber off
  766. * noexec off
  767. * noglob off
  768. * nolog off
  769. * notify off
  770. * nounset off
  771. * onecmd off
  772. * physical off
  773. * pipefail off
  774. * posix off
  775. * privileged off
  776. * verbose off
  777. * vi off
  778. * xtrace off
  779. */
  780. static const char o_opt_strings[] ALIGN1 =
  781. "pipefail\0"
  782. "noexec\0"
  783. "errexit\0"
  784. #if ENABLE_HUSH_MODE_X
  785. "xtrace\0"
  786. #endif
  787. ;
  788. enum {
  789. OPT_O_PIPEFAIL,
  790. OPT_O_NOEXEC,
  791. OPT_O_ERREXIT,
  792. #if ENABLE_HUSH_MODE_X
  793. OPT_O_XTRACE,
  794. #endif
  795. NUM_OPT_O
  796. };
  797. /* "Globals" within this file */
  798. /* Sorted roughly by size (smaller offsets == smaller code) */
  799. struct globals {
  800. /* interactive_fd != 0 means we are an interactive shell.
  801. * If we are, then saved_tty_pgrp can also be != 0, meaning
  802. * that controlling tty is available. With saved_tty_pgrp == 0,
  803. * job control still works, but terminal signals
  804. * (^C, ^Z, ^Y, ^\) won't work at all, and background
  805. * process groups can only be created with "cmd &".
  806. * With saved_tty_pgrp != 0, hush will use tcsetpgrp()
  807. * to give tty to the foreground process group,
  808. * and will take it back when the group is stopped (^Z)
  809. * or killed (^C).
  810. */
  811. #if ENABLE_HUSH_INTERACTIVE
  812. /* 'interactive_fd' is a fd# open to ctty, if we have one
  813. * _AND_ if we decided to act interactively */
  814. int interactive_fd;
  815. IF_NOT_FEATURE_EDITING_FANCY_PROMPT(char *PS1;)
  816. # define G_interactive_fd (G.interactive_fd)
  817. #else
  818. # define G_interactive_fd 0
  819. #endif
  820. #if ENABLE_FEATURE_EDITING
  821. line_input_t *line_input_state;
  822. #endif
  823. pid_t root_pid;
  824. pid_t root_ppid;
  825. pid_t last_bg_pid;
  826. #if ENABLE_HUSH_RANDOM_SUPPORT
  827. random_t random_gen;
  828. #endif
  829. #if ENABLE_HUSH_JOB
  830. int run_list_level;
  831. unsigned last_jobid;
  832. pid_t saved_tty_pgrp;
  833. struct pipe *job_list;
  834. # define G_saved_tty_pgrp (G.saved_tty_pgrp)
  835. #else
  836. # define G_saved_tty_pgrp 0
  837. #endif
  838. /* How deeply are we in context where "set -e" is ignored */
  839. int errexit_depth;
  840. /* "set -e" rules (do we follow them correctly?):
  841. * Exit if pipe, list, or compound command exits with a non-zero status.
  842. * Shell does not exit if failed command is part of condition in
  843. * if/while, part of && or || list except the last command, any command
  844. * in a pipe but the last, or if the command's return value is being
  845. * inverted with !. If a compound command other than a subshell returns a
  846. * non-zero status because a command failed while -e was being ignored, the
  847. * shell does not exit. A trap on ERR, if set, is executed before the shell
  848. * exits [ERR is a bashism].
  849. *
  850. * If a compound command or function executes in a context where -e is
  851. * ignored, none of the commands executed within are affected by the -e
  852. * setting. If a compound command or function sets -e while executing in a
  853. * context where -e is ignored, that setting does not have any effect until
  854. * the compound command or the command containing the function call completes.
  855. */
  856. char o_opt[NUM_OPT_O];
  857. #if ENABLE_HUSH_MODE_X
  858. # define G_x_mode (G.o_opt[OPT_O_XTRACE])
  859. #else
  860. # define G_x_mode 0
  861. #endif
  862. char opt_s;
  863. char opt_c;
  864. #if ENABLE_HUSH_INTERACTIVE
  865. smallint promptmode; /* 0: PS1, 1: PS2 */
  866. #endif
  867. smallint flag_SIGINT;
  868. #if ENABLE_HUSH_LOOPS
  869. smallint flag_break_continue;
  870. #endif
  871. #if ENABLE_HUSH_FUNCTIONS
  872. /* 0: outside of a function (or sourced file)
  873. * -1: inside of a function, ok to use return builtin
  874. * 1: return is invoked, skip all till end of func
  875. */
  876. smallint flag_return_in_progress;
  877. # define G_flag_return_in_progress (G.flag_return_in_progress)
  878. #else
  879. # define G_flag_return_in_progress 0
  880. #endif
  881. smallint exiting; /* used to prevent EXIT trap recursion */
  882. /* These support $? */
  883. smalluint last_exitcode;
  884. smalluint expand_exitcode;
  885. smalluint last_bg_pid_exitcode;
  886. #if ENABLE_HUSH_SET
  887. /* are global_argv and global_argv[1..n] malloced? (note: not [0]) */
  888. smalluint global_args_malloced;
  889. # define G_global_args_malloced (G.global_args_malloced)
  890. #else
  891. # define G_global_args_malloced 0
  892. #endif
  893. #if ENABLE_HUSH_BASH_COMPAT
  894. int dead_job_exitcode; /* for "wait -n" */
  895. #endif
  896. /* how many non-NULL argv's we have. NB: $# + 1 */
  897. int global_argc;
  898. char **global_argv;
  899. #if !BB_MMU
  900. char *argv0_for_re_execing;
  901. #endif
  902. #if ENABLE_HUSH_LOOPS
  903. unsigned depth_break_continue;
  904. unsigned depth_of_loop;
  905. #endif
  906. #if ENABLE_HUSH_GETOPTS
  907. unsigned getopt_count;
  908. #endif
  909. const char *ifs;
  910. char *ifs_whitespace; /* = G.ifs or malloced */
  911. const char *cwd;
  912. struct variable *top_var;
  913. char **expanded_assignments;
  914. struct variable **shadowed_vars_pp;
  915. unsigned var_nest_level;
  916. #if ENABLE_HUSH_FUNCTIONS
  917. # if ENABLE_HUSH_LOCAL
  918. unsigned func_nest_level; /* solely to prevent "local v" in non-functions */
  919. # endif
  920. struct function *top_func;
  921. #endif
  922. /* Signal and trap handling */
  923. #if ENABLE_HUSH_FAST
  924. unsigned count_SIGCHLD;
  925. unsigned handled_SIGCHLD;
  926. smallint we_have_children;
  927. #endif
  928. #if ENABLE_HUSH_LINENO_VAR
  929. unsigned parse_lineno;
  930. unsigned execute_lineno;
  931. #endif
  932. HFILE *HFILE_list;
  933. /* Which signals have non-DFL handler (even with no traps set)?
  934. * Set at the start to:
  935. * (SIGQUIT + maybe SPECIAL_INTERACTIVE_SIGS + maybe SPECIAL_JOBSTOP_SIGS)
  936. * SPECIAL_INTERACTIVE_SIGS are cleared after fork.
  937. * The rest is cleared right before execv syscalls.
  938. * Other than these two times, never modified.
  939. */
  940. unsigned special_sig_mask;
  941. #if ENABLE_HUSH_JOB
  942. unsigned fatal_sig_mask;
  943. # define G_fatal_sig_mask (G.fatal_sig_mask)
  944. #else
  945. # define G_fatal_sig_mask 0
  946. #endif
  947. #if ENABLE_HUSH_TRAP
  948. char **traps; /* char *traps[NSIG] */
  949. # define G_traps G.traps
  950. #else
  951. # define G_traps ((char**)NULL)
  952. #endif
  953. sigset_t pending_set;
  954. #if ENABLE_HUSH_MEMLEAK
  955. unsigned long memleak_value;
  956. #endif
  957. #if ENABLE_HUSH_MODE_X
  958. unsigned x_mode_depth;
  959. /* "set -x" output should not be redirectable with subsequent 2>FILE.
  960. * We dup fd#2 to x_mode_fd when "set -x" is executed, and use it
  961. * for all subsequent output.
  962. */
  963. int x_mode_fd;
  964. o_string x_mode_buf;
  965. #endif
  966. #if HUSH_DEBUG >= 2
  967. int debug_indent;
  968. #endif
  969. struct sigaction sa;
  970. char optstring_buf[sizeof("eixcs")];
  971. #if BASH_EPOCH_VARS
  972. char epoch_buf[sizeof("%lu.nnnnnn") + sizeof(long)*3];
  973. #endif
  974. #if ENABLE_FEATURE_EDITING
  975. char user_input_buf[CONFIG_FEATURE_EDITING_MAX_LEN];
  976. #endif
  977. };
  978. #define G (*ptr_to_globals)
  979. /* Not #defining name to G.name - this quickly gets unwieldy
  980. * (too many defines). Also, I actually prefer to see when a variable
  981. * is global, thus "G." prefix is a useful hint */
  982. #define INIT_G() do { \
  983. SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
  984. /* memset(&G.sa, 0, sizeof(G.sa)); */ \
  985. sigfillset(&G.sa.sa_mask); \
  986. G.sa.sa_flags = SA_RESTART; \
  987. } while (0)
  988. /* Function prototypes for builtins */
  989. static int builtin_cd(char **argv) FAST_FUNC;
  990. #if ENABLE_HUSH_ECHO
  991. static int builtin_echo(char **argv) FAST_FUNC;
  992. #endif
  993. static int builtin_eval(char **argv) FAST_FUNC;
  994. static int builtin_exec(char **argv) FAST_FUNC;
  995. static int builtin_exit(char **argv) FAST_FUNC;
  996. #if ENABLE_HUSH_EXPORT
  997. static int builtin_export(char **argv) FAST_FUNC;
  998. #endif
  999. #if ENABLE_HUSH_READONLY
  1000. static int builtin_readonly(char **argv) FAST_FUNC;
  1001. #endif
  1002. #if ENABLE_HUSH_JOB
  1003. static int builtin_fg_bg(char **argv) FAST_FUNC;
  1004. static int builtin_jobs(char **argv) FAST_FUNC;
  1005. #endif
  1006. #if ENABLE_HUSH_GETOPTS
  1007. static int builtin_getopts(char **argv) FAST_FUNC;
  1008. #endif
  1009. #if ENABLE_HUSH_HELP
  1010. static int builtin_help(char **argv) FAST_FUNC;
  1011. #endif
  1012. #if MAX_HISTORY && ENABLE_FEATURE_EDITING
  1013. static int builtin_history(char **argv) FAST_FUNC;
  1014. #endif
  1015. #if ENABLE_HUSH_LOCAL
  1016. static int builtin_local(char **argv) FAST_FUNC;
  1017. #endif
  1018. #if ENABLE_HUSH_MEMLEAK
  1019. static int builtin_memleak(char **argv) FAST_FUNC;
  1020. #endif
  1021. #if ENABLE_HUSH_PRINTF
  1022. static int builtin_printf(char **argv) FAST_FUNC;
  1023. #endif
  1024. static int builtin_pwd(char **argv) FAST_FUNC;
  1025. #if ENABLE_HUSH_READ
  1026. static int builtin_read(char **argv) FAST_FUNC;
  1027. #endif
  1028. #if ENABLE_HUSH_SET
  1029. static int builtin_set(char **argv) FAST_FUNC;
  1030. #endif
  1031. static int builtin_shift(char **argv) FAST_FUNC;
  1032. static int builtin_source(char **argv) FAST_FUNC;
  1033. #if ENABLE_HUSH_TEST || BASH_TEST2
  1034. static int builtin_test(char **argv) FAST_FUNC;
  1035. #endif
  1036. #if ENABLE_HUSH_TRAP
  1037. static int builtin_trap(char **argv) FAST_FUNC;
  1038. #endif
  1039. #if ENABLE_HUSH_TYPE
  1040. static int builtin_type(char **argv) FAST_FUNC;
  1041. #endif
  1042. #if ENABLE_HUSH_TIMES
  1043. static int builtin_times(char **argv) FAST_FUNC;
  1044. #endif
  1045. static int builtin_true(char **argv) FAST_FUNC;
  1046. #if ENABLE_HUSH_UMASK
  1047. static int builtin_umask(char **argv) FAST_FUNC;
  1048. #endif
  1049. #if ENABLE_HUSH_UNSET
  1050. static int builtin_unset(char **argv) FAST_FUNC;
  1051. #endif
  1052. #if ENABLE_HUSH_KILL
  1053. static int builtin_kill(char **argv) FAST_FUNC;
  1054. #endif
  1055. #if ENABLE_HUSH_WAIT
  1056. static int builtin_wait(char **argv) FAST_FUNC;
  1057. #endif
  1058. #if ENABLE_HUSH_LOOPS
  1059. static int builtin_break(char **argv) FAST_FUNC;
  1060. static int builtin_continue(char **argv) FAST_FUNC;
  1061. #endif
  1062. #if ENABLE_HUSH_FUNCTIONS
  1063. static int builtin_return(char **argv) FAST_FUNC;
  1064. #endif
  1065. /* Table of built-in functions. They can be forked or not, depending on
  1066. * context: within pipes, they fork. As simple commands, they do not.
  1067. * When used in non-forking context, they can change global variables
  1068. * in the parent shell process. If forked, of course they cannot.
  1069. * For example, 'unset foo | whatever' will parse and run, but foo will
  1070. * still be set at the end. */
  1071. struct built_in_command {
  1072. const char *b_cmd;
  1073. int (*b_function)(char **argv) FAST_FUNC;
  1074. #if ENABLE_HUSH_HELP
  1075. const char *b_descr;
  1076. # define BLTIN(cmd, func, help) { cmd, func, help }
  1077. #else
  1078. # define BLTIN(cmd, func, help) { cmd, func }
  1079. #endif
  1080. };
  1081. static const struct built_in_command bltins1[] = {
  1082. BLTIN("." , builtin_source , "Run commands in file"),
  1083. BLTIN(":" , builtin_true , NULL),
  1084. #if ENABLE_HUSH_JOB
  1085. BLTIN("bg" , builtin_fg_bg , "Resume job in background"),
  1086. #endif
  1087. #if ENABLE_HUSH_LOOPS
  1088. BLTIN("break" , builtin_break , "Exit loop"),
  1089. #endif
  1090. BLTIN("cd" , builtin_cd , "Change directory"),
  1091. #if ENABLE_HUSH_LOOPS
  1092. BLTIN("continue" , builtin_continue, "Start new loop iteration"),
  1093. #endif
  1094. BLTIN("eval" , builtin_eval , "Construct and run shell command"),
  1095. BLTIN("exec" , builtin_exec , "Execute command, don't return to shell"),
  1096. BLTIN("exit" , builtin_exit , NULL),
  1097. #if ENABLE_HUSH_EXPORT
  1098. BLTIN("export" , builtin_export , "Set environment variables"),
  1099. #endif
  1100. #if ENABLE_HUSH_JOB
  1101. BLTIN("fg" , builtin_fg_bg , "Bring job to foreground"),
  1102. #endif
  1103. #if ENABLE_HUSH_GETOPTS
  1104. BLTIN("getopts" , builtin_getopts , NULL),
  1105. #endif
  1106. #if ENABLE_HUSH_HELP
  1107. BLTIN("help" , builtin_help , NULL),
  1108. #endif
  1109. #if MAX_HISTORY && ENABLE_FEATURE_EDITING
  1110. BLTIN("history" , builtin_history , "Show history"),
  1111. #endif
  1112. #if ENABLE_HUSH_JOB
  1113. BLTIN("jobs" , builtin_jobs , "List jobs"),
  1114. #endif
  1115. #if ENABLE_HUSH_KILL
  1116. BLTIN("kill" , builtin_kill , "Send signals to processes"),
  1117. #endif
  1118. #if ENABLE_HUSH_LOCAL
  1119. BLTIN("local" , builtin_local , "Set local variables"),
  1120. #endif
  1121. #if ENABLE_HUSH_MEMLEAK
  1122. BLTIN("memleak" , builtin_memleak , NULL),
  1123. #endif
  1124. #if ENABLE_HUSH_READ
  1125. BLTIN("read" , builtin_read , "Input into variable"),
  1126. #endif
  1127. #if ENABLE_HUSH_READONLY
  1128. BLTIN("readonly" , builtin_readonly, "Make variables read-only"),
  1129. #endif
  1130. #if ENABLE_HUSH_FUNCTIONS
  1131. BLTIN("return" , builtin_return , "Return from function"),
  1132. #endif
  1133. #if ENABLE_HUSH_SET
  1134. BLTIN("set" , builtin_set , "Set positional parameters"),
  1135. #endif
  1136. BLTIN("shift" , builtin_shift , "Shift positional parameters"),
  1137. #if BASH_SOURCE
  1138. BLTIN("source" , builtin_source , NULL),
  1139. #endif
  1140. #if ENABLE_HUSH_TIMES
  1141. BLTIN("times" , builtin_times , NULL),
  1142. #endif
  1143. #if ENABLE_HUSH_TRAP
  1144. BLTIN("trap" , builtin_trap , "Trap signals"),
  1145. #endif
  1146. BLTIN("true" , builtin_true , NULL),
  1147. #if ENABLE_HUSH_TYPE
  1148. BLTIN("type" , builtin_type , "Show command type"),
  1149. #endif
  1150. #if ENABLE_HUSH_ULIMIT
  1151. BLTIN("ulimit" , shell_builtin_ulimit, "Control resource limits"),
  1152. #endif
  1153. #if ENABLE_HUSH_UMASK
  1154. BLTIN("umask" , builtin_umask , "Set file creation mask"),
  1155. #endif
  1156. #if ENABLE_HUSH_UNSET
  1157. BLTIN("unset" , builtin_unset , "Unset variables"),
  1158. #endif
  1159. #if ENABLE_HUSH_WAIT
  1160. BLTIN("wait" , builtin_wait , "Wait for process to finish"),
  1161. #endif
  1162. };
  1163. /* These builtins won't be used if we are on NOMMU and need to re-exec
  1164. * (it's cheaper to run an external program in this case):
  1165. */
  1166. static const struct built_in_command bltins2[] = {
  1167. #if ENABLE_HUSH_TEST
  1168. BLTIN("[" , builtin_test , NULL),
  1169. #endif
  1170. #if BASH_TEST2
  1171. BLTIN("[[" , builtin_test , NULL),
  1172. #endif
  1173. #if ENABLE_HUSH_ECHO
  1174. BLTIN("echo" , builtin_echo , NULL),
  1175. #endif
  1176. #if ENABLE_HUSH_PRINTF
  1177. BLTIN("printf" , builtin_printf , NULL),
  1178. #endif
  1179. BLTIN("pwd" , builtin_pwd , NULL),
  1180. #if ENABLE_HUSH_TEST
  1181. BLTIN("test" , builtin_test , NULL),
  1182. #endif
  1183. };
  1184. /* Debug printouts.
  1185. */
  1186. #if HUSH_DEBUG >= 2
  1187. /* prevent disasters with G.debug_indent < 0 */
  1188. # define indent() fdprintf(2, "%*s", (G.debug_indent * 2) & 0xff, "")
  1189. # define debug_enter() (G.debug_indent++)
  1190. # define debug_leave() (G.debug_indent--)
  1191. #else
  1192. # define indent() ((void)0)
  1193. # define debug_enter() ((void)0)
  1194. # define debug_leave() ((void)0)
  1195. #endif
  1196. #ifndef debug_printf
  1197. # define debug_printf(...) (indent(), fdprintf(2, __VA_ARGS__))
  1198. #endif
  1199. #ifndef debug_printf_parse
  1200. # define debug_printf_parse(...) (indent(), fdprintf(2, __VA_ARGS__))
  1201. #endif
  1202. #ifndef debug_printf_heredoc
  1203. # define debug_printf_heredoc(...) (indent(), fdprintf(2, __VA_ARGS__))
  1204. #endif
  1205. #ifndef debug_printf_exec
  1206. #define debug_printf_exec(...) (indent(), fdprintf(2, __VA_ARGS__))
  1207. #endif
  1208. #ifndef debug_printf_env
  1209. # define debug_printf_env(...) (indent(), fdprintf(2, __VA_ARGS__))
  1210. #endif
  1211. #ifndef debug_printf_jobs
  1212. # define debug_printf_jobs(...) (indent(), fdprintf(2, __VA_ARGS__))
  1213. # define DEBUG_JOBS 1
  1214. #else
  1215. # define DEBUG_JOBS 0
  1216. #endif
  1217. #ifndef debug_printf_expand
  1218. # define debug_printf_expand(...) (indent(), fdprintf(2, __VA_ARGS__))
  1219. # define DEBUG_EXPAND 1
  1220. #else
  1221. # define DEBUG_EXPAND 0
  1222. #endif
  1223. #ifndef debug_printf_varexp
  1224. # define debug_printf_varexp(...) (indent(), fdprintf(2, __VA_ARGS__))
  1225. #endif
  1226. #ifndef debug_printf_glob
  1227. # define debug_printf_glob(...) (indent(), fdprintf(2, __VA_ARGS__))
  1228. # define DEBUG_GLOB 1
  1229. #else
  1230. # define DEBUG_GLOB 0
  1231. #endif
  1232. #ifndef debug_printf_redir
  1233. # define debug_printf_redir(...) (indent(), fdprintf(2, __VA_ARGS__))
  1234. #endif
  1235. #ifndef debug_printf_list
  1236. # define debug_printf_list(...) (indent(), fdprintf(2, __VA_ARGS__))
  1237. #endif
  1238. #ifndef debug_printf_subst
  1239. # define debug_printf_subst(...) (indent(), fdprintf(2, __VA_ARGS__))
  1240. #endif
  1241. #ifndef debug_printf_prompt
  1242. # define debug_printf_prompt(...) (indent(), fdprintf(2, __VA_ARGS__))
  1243. #endif
  1244. #ifndef debug_printf_clean
  1245. # define debug_printf_clean(...) (indent(), fdprintf(2, __VA_ARGS__))
  1246. # define DEBUG_CLEAN 1
  1247. #else
  1248. # define DEBUG_CLEAN 0
  1249. #endif
  1250. #if DEBUG_EXPAND
  1251. static void debug_print_strings(const char *prefix, char **vv)
  1252. {
  1253. indent();
  1254. fdprintf(2, "%s:\n", prefix);
  1255. while (*vv)
  1256. fdprintf(2, " '%s'\n", *vv++);
  1257. }
  1258. #else
  1259. # define debug_print_strings(prefix, vv) ((void)0)
  1260. #endif
  1261. /* Leak hunting. Use hush_leaktool.sh for post-processing.
  1262. */
  1263. #if LEAK_HUNTING
  1264. static void *xxmalloc(int lineno, size_t size)
  1265. {
  1266. void *ptr = xmalloc((size + 0xff) & ~0xff);
  1267. fdprintf(2, "line %d: malloc %p\n", lineno, ptr);
  1268. return ptr;
  1269. }
  1270. static void *xxrealloc(int lineno, void *ptr, size_t size)
  1271. {
  1272. ptr = xrealloc(ptr, (size + 0xff) & ~0xff);
  1273. fdprintf(2, "line %d: realloc %p\n", lineno, ptr);
  1274. return ptr;
  1275. }
  1276. static char *xxstrdup(int lineno, const char *str)
  1277. {
  1278. char *ptr = xstrdup(str);
  1279. fdprintf(2, "line %d: strdup %p\n", lineno, ptr);
  1280. return ptr;
  1281. }
  1282. static void xxfree(void *ptr)
  1283. {
  1284. fdprintf(2, "free %p\n", ptr);
  1285. free(ptr);
  1286. }
  1287. # define xmalloc(s) xxmalloc(__LINE__, s)
  1288. # define xrealloc(p, s) xxrealloc(__LINE__, p, s)
  1289. # define xstrdup(s) xxstrdup(__LINE__, s)
  1290. # define free(p) xxfree(p)
  1291. #endif
  1292. /* Syntax and runtime errors. They always abort scripts.
  1293. * In interactive use they usually discard unparsed and/or unexecuted commands
  1294. * and return to the prompt.
  1295. * HUSH_DEBUG >= 2 prints line number in this file where it was detected.
  1296. */
  1297. #if HUSH_DEBUG < 2
  1298. # define msg_and_die_if_script(lineno, ...) msg_and_die_if_script(__VA_ARGS__)
  1299. # define syntax_error(lineno, msg) syntax_error(msg)
  1300. # define syntax_error_at(lineno, msg) syntax_error_at(msg)
  1301. # define syntax_error_unterm_ch(lineno, ch) syntax_error_unterm_ch(ch)
  1302. # define syntax_error_unterm_str(lineno, s) syntax_error_unterm_str(s)
  1303. # define syntax_error_unexpected_ch(lineno, ch) syntax_error_unexpected_ch(ch)
  1304. #endif
  1305. static void die_if_script(void)
  1306. {
  1307. if (!G_interactive_fd) {
  1308. if (G.last_exitcode) /* sometines it's 2, not 1 (bash compat) */
  1309. xfunc_error_retval = G.last_exitcode;
  1310. xfunc_die();
  1311. }
  1312. }
  1313. static void msg_and_die_if_script(unsigned lineno, const char *fmt, ...)
  1314. {
  1315. va_list p;
  1316. #if HUSH_DEBUG >= 2
  1317. bb_error_msg("hush.c:%u", lineno);
  1318. #endif
  1319. va_start(p, fmt);
  1320. bb_verror_msg(fmt, p, NULL);
  1321. va_end(p);
  1322. die_if_script();
  1323. }
  1324. static void syntax_error(unsigned lineno UNUSED_PARAM, const char *msg)
  1325. {
  1326. if (msg)
  1327. bb_error_msg("syntax error: %s", msg);
  1328. else
  1329. bb_error_msg("syntax error");
  1330. die_if_script();
  1331. }
  1332. static void syntax_error_at(unsigned lineno UNUSED_PARAM, const char *msg)
  1333. {
  1334. bb_error_msg("syntax error at '%s'", msg);
  1335. die_if_script();
  1336. }
  1337. static void syntax_error_unterm_str(unsigned lineno UNUSED_PARAM, const char *s)
  1338. {
  1339. bb_error_msg("syntax error: unterminated %s", s);
  1340. //? source4.tests fails: in bash, echo ${^} in script does not terminate the script
  1341. // die_if_script();
  1342. }
  1343. static void syntax_error_unterm_ch(unsigned lineno, char ch)
  1344. {
  1345. char msg[2] = { ch, '\0' };
  1346. syntax_error_unterm_str(lineno, msg);
  1347. }
  1348. static void syntax_error_unexpected_ch(unsigned lineno UNUSED_PARAM, int ch)
  1349. {
  1350. char msg[2];
  1351. msg[0] = ch;
  1352. msg[1] = '\0';
  1353. #if HUSH_DEBUG >= 2
  1354. bb_error_msg("hush.c:%u", lineno);
  1355. #endif
  1356. bb_error_msg("syntax error: unexpected %s", ch == EOF ? "EOF" : msg);
  1357. die_if_script();
  1358. }
  1359. #if HUSH_DEBUG < 2
  1360. # undef msg_and_die_if_script
  1361. # undef syntax_error
  1362. # undef syntax_error_at
  1363. # undef syntax_error_unterm_ch
  1364. # undef syntax_error_unterm_str
  1365. # undef syntax_error_unexpected_ch
  1366. #else
  1367. # define msg_and_die_if_script(...) msg_and_die_if_script(__LINE__, __VA_ARGS__)
  1368. # define syntax_error(msg) syntax_error(__LINE__, msg)
  1369. # define syntax_error_at(msg) syntax_error_at(__LINE__, msg)
  1370. # define syntax_error_unterm_ch(ch) syntax_error_unterm_ch(__LINE__, ch)
  1371. # define syntax_error_unterm_str(s) syntax_error_unterm_str(__LINE__, s)
  1372. # define syntax_error_unexpected_ch(ch) syntax_error_unexpected_ch(__LINE__, ch)
  1373. #endif
  1374. /* Utility functions
  1375. */
  1376. /* Replace each \x with x in place, return ptr past NUL. */
  1377. static char *unbackslash(char *src)
  1378. {
  1379. char *dst = src = strchrnul(src, '\\');
  1380. while (1) {
  1381. if (*src == '\\') {
  1382. src++;
  1383. if (*src != '\0') {
  1384. /* \x -> x */
  1385. *dst++ = *src++;
  1386. continue;
  1387. }
  1388. /* else: "\<nul>". Do not delete this backslash.
  1389. * Testcase: eval 'echo ok\'
  1390. */
  1391. *dst++ = '\\';
  1392. /* fallthrough */
  1393. }
  1394. if ((*dst++ = *src++) == '\0')
  1395. break;
  1396. }
  1397. return dst;
  1398. }
  1399. static char **add_strings_to_strings(char **strings, char **add, int need_to_dup)
  1400. {
  1401. int i;
  1402. unsigned count1;
  1403. unsigned count2;
  1404. char **v;
  1405. v = strings;
  1406. count1 = 0;
  1407. if (v) {
  1408. while (*v) {
  1409. count1++;
  1410. v++;
  1411. }
  1412. }
  1413. count2 = 0;
  1414. v = add;
  1415. while (*v) {
  1416. count2++;
  1417. v++;
  1418. }
  1419. v = xrealloc(strings, (count1 + count2 + 1) * sizeof(char*));
  1420. v[count1 + count2] = NULL;
  1421. i = count2;
  1422. while (--i >= 0)
  1423. v[count1 + i] = (need_to_dup ? xstrdup(add[i]) : add[i]);
  1424. return v;
  1425. }
  1426. #if LEAK_HUNTING
  1427. static char **xx_add_strings_to_strings(int lineno, char **strings, char **add, int need_to_dup)
  1428. {
  1429. char **ptr = add_strings_to_strings(strings, add, need_to_dup);
  1430. fdprintf(2, "line %d: add_strings_to_strings %p\n", lineno, ptr);
  1431. return ptr;
  1432. }
  1433. #define add_strings_to_strings(strings, add, need_to_dup) \
  1434. xx_add_strings_to_strings(__LINE__, strings, add, need_to_dup)
  1435. #endif
  1436. /* Note: takes ownership of "add" ptr (it is not strdup'ed) */
  1437. static char **add_string_to_strings(char **strings, char *add)
  1438. {
  1439. char *v[2];
  1440. v[0] = add;
  1441. v[1] = NULL;
  1442. return add_strings_to_strings(strings, v, /*dup:*/ 0);
  1443. }
  1444. #if LEAK_HUNTING
  1445. static char **xx_add_string_to_strings(int lineno, char **strings, char *add)
  1446. {
  1447. char **ptr = add_string_to_strings(strings, add);
  1448. fdprintf(2, "line %d: add_string_to_strings %p\n", lineno, ptr);
  1449. return ptr;
  1450. }
  1451. #define add_string_to_strings(strings, add) \
  1452. xx_add_string_to_strings(__LINE__, strings, add)
  1453. #endif
  1454. static void free_strings(char **strings)
  1455. {
  1456. char **v;
  1457. if (!strings)
  1458. return;
  1459. v = strings;
  1460. while (*v) {
  1461. free(*v);
  1462. v++;
  1463. }
  1464. free(strings);
  1465. }
  1466. static int dup_CLOEXEC(int fd, int avoid_fd)
  1467. {
  1468. int newfd;
  1469. repeat:
  1470. newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
  1471. if (newfd >= 0) {
  1472. if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
  1473. fcntl(newfd, F_SETFD, FD_CLOEXEC);
  1474. } else { /* newfd < 0 */
  1475. if (errno == EBUSY)
  1476. goto repeat;
  1477. if (errno == EINTR)
  1478. goto repeat;
  1479. }
  1480. return newfd;
  1481. }
  1482. static int xdup_CLOEXEC_and_close(int fd, int avoid_fd)
  1483. {
  1484. int newfd;
  1485. repeat:
  1486. newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
  1487. if (newfd < 0) {
  1488. if (errno == EBUSY)
  1489. goto repeat;
  1490. if (errno == EINTR)
  1491. goto repeat;
  1492. /* fd was not open? */
  1493. if (errno == EBADF)
  1494. return fd;
  1495. xfunc_die();
  1496. }
  1497. if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
  1498. fcntl(newfd, F_SETFD, FD_CLOEXEC);
  1499. close(fd);
  1500. return newfd;
  1501. }
  1502. /* Manipulating HFILEs */
  1503. static HFILE *hfopen(const char *name)
  1504. {
  1505. HFILE *fp;
  1506. int fd;
  1507. fd = STDIN_FILENO;
  1508. if (name) {
  1509. fd = open(name, O_RDONLY | O_CLOEXEC);
  1510. if (fd < 0)
  1511. return NULL;
  1512. if (O_CLOEXEC == 0) /* ancient libc */
  1513. close_on_exec_on(fd);
  1514. }
  1515. fp = xmalloc(sizeof(*fp));
  1516. fp->is_stdin = (name == NULL);
  1517. fp->fd = fd;
  1518. fp->cur = fp->end = fp->buf;
  1519. fp->next_hfile = G.HFILE_list;
  1520. G.HFILE_list = fp;
  1521. return fp;
  1522. }
  1523. static void hfclose(HFILE *fp)
  1524. {
  1525. HFILE **pp = &G.HFILE_list;
  1526. while (*pp) {
  1527. HFILE *cur = *pp;
  1528. if (cur == fp) {
  1529. *pp = cur->next_hfile;
  1530. break;
  1531. }
  1532. pp = &cur->next_hfile;
  1533. }
  1534. if (fp->fd >= 0)
  1535. close(fp->fd);
  1536. free(fp);
  1537. }
  1538. static int refill_HFILE_and_getc(HFILE *fp)
  1539. {
  1540. int n;
  1541. if (fp->fd < 0) {
  1542. /* Already saw EOF */
  1543. return EOF;
  1544. }
  1545. /* Try to buffer more input */
  1546. fp->cur = fp->buf;
  1547. n = safe_read(fp->fd, fp->buf, sizeof(fp->buf));
  1548. if (n < 0) {
  1549. bb_perror_msg("read error");
  1550. n = 0;
  1551. }
  1552. fp->end = fp->buf + n;
  1553. if (n == 0) {
  1554. /* EOF/error */
  1555. close(fp->fd);
  1556. fp->fd = -1;
  1557. return EOF;
  1558. }
  1559. return (unsigned char)(*fp->cur++);
  1560. }
  1561. /* Inlined for common case of non-empty buffer.
  1562. */
  1563. static ALWAYS_INLINE int hfgetc(HFILE *fp)
  1564. {
  1565. if (fp->cur < fp->end)
  1566. return (unsigned char)(*fp->cur++);
  1567. /* Buffer empty */
  1568. return refill_HFILE_and_getc(fp);
  1569. }
  1570. static int move_HFILEs_on_redirect(int fd, int avoid_fd)
  1571. {
  1572. HFILE *fl = G.HFILE_list;
  1573. while (fl) {
  1574. if (fd == fl->fd) {
  1575. /* We use it only on script files, they are all CLOEXEC */
  1576. fl->fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
  1577. debug_printf_redir("redirect_fd %d: matches a script fd, moving it to %d\n", fd, fl->fd);
  1578. return 1; /* "found and moved" */
  1579. }
  1580. fl = fl->next_hfile;
  1581. }
  1582. #if ENABLE_HUSH_MODE_X
  1583. if (G.x_mode_fd > 0 && fd == G.x_mode_fd) {
  1584. G.x_mode_fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
  1585. return 1; /* "found and moved" */
  1586. }
  1587. #endif
  1588. return 0; /* "not in the list" */
  1589. }
  1590. #if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
  1591. static void close_all_HFILE_list(void)
  1592. {
  1593. HFILE *fl = G.HFILE_list;
  1594. while (fl) {
  1595. /* hfclose would also free HFILE object.
  1596. * It is disastrous if we share memory with a vforked parent.
  1597. * I'm not sure we never come here after vfork.
  1598. * Therefore just close fd, nothing more.
  1599. *
  1600. * ">" instead of ">=": we don't close fd#0,
  1601. * interactive shell uses hfopen(NULL) as stdin input
  1602. * which has fl->fd == 0, but fd#0 gets redirected in pipes.
  1603. * If we'd close it here, then e.g. interactive "set | sort"
  1604. * with NOFORKed sort, would have sort's input fd closed.
  1605. */
  1606. if (fl->fd > 0)
  1607. /*hfclose(fl); - unsafe */
  1608. close(fl->fd);
  1609. fl = fl->next_hfile;
  1610. }
  1611. }
  1612. #endif
  1613. static int fd_in_HFILEs(int fd)
  1614. {
  1615. HFILE *fl = G.HFILE_list;
  1616. while (fl) {
  1617. if (fl->fd == fd)
  1618. return 1;
  1619. fl = fl->next_hfile;
  1620. }
  1621. return 0;
  1622. }
  1623. /* Helpers for setting new $n and restoring them back
  1624. */
  1625. typedef struct save_arg_t {
  1626. char *sv_argv0;
  1627. char **sv_g_argv;
  1628. int sv_g_argc;
  1629. IF_HUSH_SET(smallint sv_g_malloced;)
  1630. } save_arg_t;
  1631. static void save_and_replace_G_args(save_arg_t *sv, char **argv)
  1632. {
  1633. sv->sv_argv0 = argv[0];
  1634. sv->sv_g_argv = G.global_argv;
  1635. sv->sv_g_argc = G.global_argc;
  1636. IF_HUSH_SET(sv->sv_g_malloced = G.global_args_malloced;)
  1637. argv[0] = G.global_argv[0]; /* retain $0 */
  1638. G.global_argv = argv;
  1639. IF_HUSH_SET(G.global_args_malloced = 0;)
  1640. G.global_argc = 1 + string_array_len(argv + 1);
  1641. }
  1642. static void restore_G_args(save_arg_t *sv, char **argv)
  1643. {
  1644. #if ENABLE_HUSH_SET
  1645. if (G.global_args_malloced) {
  1646. /* someone ran "set -- arg1 arg2 ...", undo */
  1647. char **pp = G.global_argv;
  1648. while (*++pp) /* note: does not free $0 */
  1649. free(*pp);
  1650. free(G.global_argv);
  1651. }
  1652. #endif
  1653. argv[0] = sv->sv_argv0;
  1654. G.global_argv = sv->sv_g_argv;
  1655. G.global_argc = sv->sv_g_argc;
  1656. IF_HUSH_SET(G.global_args_malloced = sv->sv_g_malloced;)
  1657. }
  1658. /* Basic theory of signal handling in shell
  1659. * ========================================
  1660. * This does not describe what hush does, rather, it is current understanding
  1661. * what it _should_ do. If it doesn't, it's a bug.
  1662. * http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#trap
  1663. *
  1664. * Signals are handled only after each pipe ("cmd | cmd | cmd" thing)
  1665. * is finished or backgrounded. It is the same in interactive and
  1666. * non-interactive shells, and is the same regardless of whether
  1667. * a user trap handler is installed or a shell special one is in effect.
  1668. * ^C or ^Z from keyboard seems to execute "at once" because it usually
  1669. * backgrounds (i.e. stops) or kills all members of currently running
  1670. * pipe.
  1671. *
  1672. * Wait builtin is interruptible by signals for which user trap is set
  1673. * or by SIGINT in interactive shell.
  1674. *
  1675. * Trap handlers will execute even within trap handlers. (right?)
  1676. *
  1677. * User trap handlers are forgotten when subshell ("(cmd)") is entered,
  1678. * except for handlers set to '' (empty string).
  1679. *
  1680. * If job control is off, backgrounded commands ("cmd &")
  1681. * have SIGINT, SIGQUIT set to SIG_IGN.
  1682. *
  1683. * Commands which are run in command substitution ("`cmd`")
  1684. * have SIGTTIN, SIGTTOU, SIGTSTP set to SIG_IGN.
  1685. *
  1686. * Ordinary commands have signals set to SIG_IGN/DFL as inherited
  1687. * by the shell from its parent.
  1688. *
  1689. * Signals which differ from SIG_DFL action
  1690. * (note: child (i.e., [v]forked) shell is not an interactive shell):
  1691. *
  1692. * SIGQUIT: ignore
  1693. * SIGTERM (interactive): ignore
  1694. * SIGHUP (interactive):
  1695. * send SIGCONT to stopped jobs, send SIGHUP to all jobs and exit
  1696. * SIGTTIN, SIGTTOU, SIGTSTP (if job control is on): ignore
  1697. * Note that ^Z is handled not by trapping SIGTSTP, but by seeing
  1698. * that all pipe members are stopped. Try this in bash:
  1699. * while :; do :; done - ^Z does not background it
  1700. * (while :; do :; done) - ^Z backgrounds it
  1701. * SIGINT (interactive): wait for last pipe, ignore the rest
  1702. * of the command line, show prompt. NB: ^C does not send SIGINT
  1703. * to interactive shell while shell is waiting for a pipe,
  1704. * since shell is bg'ed (is not in foreground process group).
  1705. * Example 1: this waits 5 sec, but does not execute ls:
  1706. * "echo $$; sleep 5; ls -l" + "kill -INT <pid>"
  1707. * Example 2: this does not wait and does not execute ls:
  1708. * "echo $$; sleep 5 & wait; ls -l" + "kill -INT <pid>"
  1709. * Example 3: this does not wait 5 sec, but executes ls:
  1710. * "sleep 5; ls -l" + press ^C
  1711. * Example 4: this does not wait and does not execute ls:
  1712. * "sleep 5 & wait; ls -l" + press ^C
  1713. *
  1714. * (What happens to signals which are IGN on shell start?)
  1715. * (What happens with signal mask on shell start?)
  1716. *
  1717. * Old implementation
  1718. * ==================
  1719. * We use in-kernel pending signal mask to determine which signals were sent.
  1720. * We block all signals which we don't want to take action immediately,
  1721. * i.e. we block all signals which need to have special handling as described
  1722. * above, and all signals which have traps set.
  1723. * After each pipe execution, we extract any pending signals via sigtimedwait()
  1724. * and act on them.
  1725. *
  1726. * unsigned special_sig_mask: a mask of such "special" signals
  1727. * sigset_t blocked_set: current blocked signal set
  1728. *
  1729. * "trap - SIGxxx":
  1730. * clear bit in blocked_set unless it is also in special_sig_mask
  1731. * "trap 'cmd' SIGxxx":
  1732. * set bit in blocked_set (even if 'cmd' is '')
  1733. * after [v]fork, if we plan to be a shell:
  1734. * unblock signals with special interactive handling
  1735. * (child shell is not interactive),
  1736. * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
  1737. * after [v]fork, if we plan to exec:
  1738. * POSIX says fork clears pending signal mask in child - no need to clear it.
  1739. * Restore blocked signal set to one inherited by shell just prior to exec.
  1740. *
  1741. * Note: as a result, we do not use signal handlers much. The only uses
  1742. * are to count SIGCHLDs
  1743. * and to restore tty pgrp on signal-induced exit.
  1744. *
  1745. * Note 2 (compat):
  1746. * Standard says "When a subshell is entered, traps that are not being ignored
  1747. * are set to the default actions". bash interprets it so that traps which
  1748. * are set to '' (ignore) are NOT reset to defaults. We do the same.
  1749. *
  1750. * Problem: the above approach makes it unwieldy to catch signals while
  1751. * we are in read builtin, or while we read commands from stdin:
  1752. * masked signals are not visible!
  1753. *
  1754. * New implementation
  1755. * ==================
  1756. * We record each signal we are interested in by installing signal handler
  1757. * for them - a bit like emulating kernel pending signal mask in userspace.
  1758. * We are interested in: signals which need to have special handling
  1759. * as described above, and all signals which have traps set.
  1760. * Signals are recorded in pending_set.
  1761. * After each pipe execution, we extract any pending signals
  1762. * and act on them.
  1763. *
  1764. * unsigned special_sig_mask: a mask of shell-special signals.
  1765. * unsigned fatal_sig_mask: a mask of signals on which we restore tty pgrp.
  1766. * char *traps[sig] if trap for sig is set (even if it's '').
  1767. * sigset_t pending_set: set of sigs we received.
  1768. *
  1769. * "trap - SIGxxx":
  1770. * if sig is in special_sig_mask, set handler back to:
  1771. * record_pending_signo, or to IGN if it's a tty stop signal
  1772. * if sig is in fatal_sig_mask, set handler back to sigexit.
  1773. * else: set handler back to SIG_DFL
  1774. * "trap 'cmd' SIGxxx":
  1775. * set handler to record_pending_signo.
  1776. * "trap '' SIGxxx":
  1777. * set handler to SIG_IGN.
  1778. * after [v]fork, if we plan to be a shell:
  1779. * set signals with special interactive handling to SIG_DFL
  1780. * (because child shell is not interactive),
  1781. * unset all traps except '' (note: regardless of child shell's type - {}, (), etc)
  1782. * after [v]fork, if we plan to exec:
  1783. * POSIX says fork clears pending signal mask in child - no need to clear it.
  1784. *
  1785. * To make wait builtin interruptible, we handle SIGCHLD as special signal,
  1786. * otherwise (if we leave it SIG_DFL) sigsuspend in wait builtin will not wake up on it.
  1787. *
  1788. * Note (compat):
  1789. * Standard says "When a subshell is entered, traps that are not being ignored
  1790. * are set to the default actions". bash interprets it so that traps which
  1791. * are set to '' (ignore) are NOT reset to defaults. We do the same.
  1792. */
  1793. enum {
  1794. SPECIAL_INTERACTIVE_SIGS = 0
  1795. | (1 << SIGTERM)
  1796. | (1 << SIGINT)
  1797. | (1 << SIGHUP)
  1798. ,
  1799. SPECIAL_JOBSTOP_SIGS = 0
  1800. #if ENABLE_HUSH_JOB
  1801. | (1 << SIGTTIN)
  1802. | (1 << SIGTTOU)
  1803. | (1 << SIGTSTP)
  1804. #endif
  1805. ,
  1806. };
  1807. static void record_pending_signo(int sig)
  1808. {
  1809. sigaddset(&G.pending_set, sig);
  1810. #if ENABLE_HUSH_FAST
  1811. if (sig == SIGCHLD) {
  1812. G.count_SIGCHLD++;
  1813. //bb_error_msg("[%d] SIGCHLD_handler: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
  1814. }
  1815. #endif
  1816. }
  1817. static sighandler_t install_sighandler(int sig, sighandler_t handler)
  1818. {
  1819. struct sigaction old_sa;
  1820. /* We could use signal() to install handlers... almost:
  1821. * except that we need to mask ALL signals while handlers run.
  1822. * I saw signal nesting in strace, race window isn't small.
  1823. * SA_RESTART is also needed, but in Linux, signal()
  1824. * sets SA_RESTART too.
  1825. */
  1826. /* memset(&G.sa, 0, sizeof(G.sa)); - already done */
  1827. /* sigfillset(&G.sa.sa_mask); - already done */
  1828. /* G.sa.sa_flags = SA_RESTART; - already done */
  1829. G.sa.sa_handler = handler;
  1830. sigaction(sig, &G.sa, &old_sa);
  1831. return old_sa.sa_handler;
  1832. }
  1833. static void hush_exit(int exitcode) NORETURN;
  1834. static void restore_ttypgrp_and__exit(void) NORETURN;
  1835. static void restore_ttypgrp_and__exit(void)
  1836. {
  1837. /* xfunc has failed! die die die */
  1838. /* no EXIT traps, this is an escape hatch! */
  1839. G.exiting = 1;
  1840. hush_exit(xfunc_error_retval);
  1841. }
  1842. #if ENABLE_HUSH_JOB
  1843. /* Needed only on some libc:
  1844. * It was observed that on exit(), fgetc'ed buffered data
  1845. * gets "unwound" via lseek(fd, -NUM, SEEK_CUR).
  1846. * With the net effect that even after fork(), not vfork(),
  1847. * exit() in NOEXECed applet in "sh SCRIPT":
  1848. * noexec_applet_here
  1849. * echo END_OF_SCRIPT
  1850. * lseeks fd in input FILE object from EOF to "e" in "echo END_OF_SCRIPT".
  1851. * This makes "echo END_OF_SCRIPT" executed twice.
  1852. * Similar problems can be seen with msg_and_die_if_script() -> xfunc_die()
  1853. * and in `cmd` handling.
  1854. * If set as die_func(), this makes xfunc_die() exit via _exit(), not exit():
  1855. */
  1856. static void fflush_and__exit(void) NORETURN;
  1857. static void fflush_and__exit(void)
  1858. {
  1859. fflush_all();
  1860. _exit(xfunc_error_retval);
  1861. }
  1862. /* After [v]fork, in child: do not restore tty pgrp on xfunc death */
  1863. # define disable_restore_tty_pgrp_on_exit() (die_func = fflush_and__exit)
  1864. /* After [v]fork, in parent: restore tty pgrp on xfunc death */
  1865. # define enable_restore_tty_pgrp_on_exit() (die_func = restore_ttypgrp_and__exit)
  1866. /* Restores tty foreground process group, and exits.
  1867. * May be called as signal handler for fatal signal
  1868. * (will resend signal to itself, producing correct exit state)
  1869. * or called directly with -EXITCODE.
  1870. * We also call it if xfunc is exiting.
  1871. */
  1872. static void sigexit(int sig) NORETURN;
  1873. static void sigexit(int sig)
  1874. {
  1875. /* Careful: we can end up here after [v]fork. Do not restore
  1876. * tty pgrp then, only top-level shell process does that */
  1877. if (G_saved_tty_pgrp && getpid() == G.root_pid) {
  1878. /* Disable all signals: job control, SIGPIPE, etc.
  1879. * Mostly paranoid measure, to prevent infinite SIGTTOU.
  1880. */
  1881. sigprocmask_allsigs(SIG_BLOCK);
  1882. tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
  1883. }
  1884. /* Not a signal, just exit */
  1885. if (sig <= 0)
  1886. _exit(- sig);
  1887. kill_myself_with_sig(sig); /* does not return */
  1888. }
  1889. #else
  1890. # define disable_restore_tty_pgrp_on_exit() ((void)0)
  1891. # define enable_restore_tty_pgrp_on_exit() ((void)0)
  1892. #endif
  1893. static sighandler_t pick_sighandler(unsigned sig)
  1894. {
  1895. sighandler_t handler = SIG_DFL;
  1896. if (sig < sizeof(unsigned)*8) {
  1897. unsigned sigmask = (1 << sig);
  1898. #if ENABLE_HUSH_JOB
  1899. /* is sig fatal? */
  1900. if (G_fatal_sig_mask & sigmask)
  1901. handler = sigexit;
  1902. else
  1903. #endif
  1904. /* sig has special handling? */
  1905. if (G.special_sig_mask & sigmask) {
  1906. handler = record_pending_signo;
  1907. /* TTIN/TTOU/TSTP can't be set to record_pending_signo
  1908. * in order to ignore them: they will be raised
  1909. * in an endless loop when we try to do some
  1910. * terminal ioctls! We do have to _ignore_ these.
  1911. */
  1912. if (SPECIAL_JOBSTOP_SIGS & sigmask)
  1913. handler = SIG_IGN;
  1914. }
  1915. }
  1916. return handler;
  1917. }
  1918. /* Restores tty foreground process group, and exits. */
  1919. static void hush_exit(int exitcode)
  1920. {
  1921. #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
  1922. if (G.line_input_state)
  1923. save_history(G.line_input_state);
  1924. #endif
  1925. fflush_all();
  1926. if (G.exiting <= 0 && G_traps && G_traps[0] && G_traps[0][0]) {
  1927. char *argv[3];
  1928. /* argv[0] is unused */
  1929. argv[1] = xstrdup(G_traps[0]); /* copy, since EXIT trap handler may modify G_traps[0] */
  1930. argv[2] = NULL;
  1931. G.exiting = 1; /* prevent EXIT trap recursion */
  1932. /* Note: G_traps[0] is not cleared!
  1933. * "trap" will still show it, if executed
  1934. * in the handler */
  1935. builtin_eval(argv);
  1936. }
  1937. #if ENABLE_FEATURE_CLEAN_UP
  1938. {
  1939. struct variable *cur_var;
  1940. if (G.cwd != bb_msg_unknown)
  1941. free((char*)G.cwd);
  1942. cur_var = G.top_var;
  1943. while (cur_var) {
  1944. struct variable *tmp = cur_var;
  1945. if (!cur_var->max_len)
  1946. free(cur_var->varstr);
  1947. cur_var = cur_var->next;
  1948. free(tmp);
  1949. }
  1950. }
  1951. #endif
  1952. fflush_all();
  1953. #if ENABLE_HUSH_JOB
  1954. sigexit(- (exitcode & 0xff));
  1955. #else
  1956. _exit(exitcode);
  1957. #endif
  1958. }
  1959. //TODO: return a mask of ALL handled sigs?
  1960. static int check_and_run_traps(void)
  1961. {
  1962. int last_sig = 0;
  1963. while (1) {
  1964. int sig;
  1965. if (sigisemptyset(&G.pending_set))
  1966. break;
  1967. sig = 0;
  1968. do {
  1969. sig++;
  1970. if (sigismember(&G.pending_set, sig)) {
  1971. sigdelset(&G.pending_set, sig);
  1972. goto got_sig;
  1973. }
  1974. } while (sig < NSIG);
  1975. break;
  1976. got_sig:
  1977. if (G_traps && G_traps[sig]) {
  1978. debug_printf_exec("%s: sig:%d handler:'%s'\n", __func__, sig, G.traps[sig]);
  1979. if (G_traps[sig][0]) {
  1980. /* We have user-defined handler */
  1981. smalluint save_rcode;
  1982. char *argv[3];
  1983. /* argv[0] is unused */
  1984. argv[1] = xstrdup(G_traps[sig]);
  1985. /* why strdup? trap can modify itself: trap 'trap "echo oops" INT' INT */
  1986. argv[2] = NULL;
  1987. save_rcode = G.last_exitcode;
  1988. builtin_eval(argv);
  1989. free(argv[1]);
  1990. //FIXME: shouldn't it be set to 128 + sig instead?
  1991. G.last_exitcode = save_rcode;
  1992. last_sig = sig;
  1993. } /* else: "" trap, ignoring signal */
  1994. continue;
  1995. }
  1996. /* not a trap: special action */
  1997. switch (sig) {
  1998. case SIGINT:
  1999. debug_printf_exec("%s: sig:%d default SIGINT handler\n", __func__, sig);
  2000. G.flag_SIGINT = 1;
  2001. last_sig = sig;
  2002. break;
  2003. #if ENABLE_HUSH_JOB
  2004. case SIGHUP: {
  2005. //TODO: why are we doing this? ash and dash don't do this,
  2006. //they have no handler for SIGHUP at all,
  2007. //they rely on kernel to send SIGHUP+SIGCONT to orphaned process groups
  2008. struct pipe *job;
  2009. debug_printf_exec("%s: sig:%d default SIGHUP handler\n", __func__, sig);
  2010. /* bash is observed to signal whole process groups,
  2011. * not individual processes */
  2012. for (job = G.job_list; job; job = job->next) {
  2013. if (job->pgrp <= 0)
  2014. continue;
  2015. debug_printf_exec("HUPing pgrp %d\n", job->pgrp);
  2016. if (kill(- job->pgrp, SIGHUP) == 0)
  2017. kill(- job->pgrp, SIGCONT);
  2018. }
  2019. sigexit(SIGHUP);
  2020. }
  2021. #endif
  2022. #if ENABLE_HUSH_FAST
  2023. case SIGCHLD:
  2024. debug_printf_exec("%s: sig:%d default SIGCHLD handler\n", __func__, sig);
  2025. G.count_SIGCHLD++;
  2026. //bb_error_msg("[%d] check_and_run_traps: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
  2027. /* Note:
  2028. * We don't do 'last_sig = sig' here -> NOT returning this sig.
  2029. * This simplifies wait builtin a bit.
  2030. */
  2031. break;
  2032. #endif
  2033. default: /* ignored: */
  2034. debug_printf_exec("%s: sig:%d default handling is to ignore\n", __func__, sig);
  2035. /* SIGTERM, SIGQUIT, SIGTTIN, SIGTTOU, SIGTSTP */
  2036. /* Note:
  2037. * We don't do 'last_sig = sig' here -> NOT returning this sig.
  2038. * Example: wait is not interrupted by TERM
  2039. * in interactive shell, because TERM is ignored.
  2040. */
  2041. break;
  2042. }
  2043. }
  2044. return last_sig;
  2045. }
  2046. static const char *get_cwd(int force)
  2047. {
  2048. if (force || G.cwd == NULL) {
  2049. /* xrealloc_getcwd_or_warn(arg) calls free(arg),
  2050. * we must not try to free(bb_msg_unknown) */
  2051. if (G.cwd == bb_msg_unknown)
  2052. G.cwd = NULL;
  2053. G.cwd = xrealloc_getcwd_or_warn((char *)G.cwd);
  2054. if (!G.cwd)
  2055. G.cwd = bb_msg_unknown;
  2056. }
  2057. return G.cwd;
  2058. }
  2059. /*
  2060. * Shell and environment variable support
  2061. */
  2062. static struct variable **get_ptr_to_local_var(const char *name, unsigned len)
  2063. {
  2064. struct variable **pp;
  2065. struct variable *cur;
  2066. pp = &G.top_var;
  2067. while ((cur = *pp) != NULL) {
  2068. if (strncmp(cur->varstr, name, len) == 0 && cur->varstr[len] == '=')
  2069. return pp;
  2070. pp = &cur->next;
  2071. }
  2072. return NULL;
  2073. }
  2074. static const char* FAST_FUNC get_local_var_value(const char *name)
  2075. {
  2076. struct variable **vpp;
  2077. unsigned len = strlen(name);
  2078. if (G.expanded_assignments) {
  2079. char **cpp = G.expanded_assignments;
  2080. while (*cpp) {
  2081. char *cp = *cpp;
  2082. if (strncmp(cp, name, len) == 0 && cp[len] == '=')
  2083. return cp + len + 1;
  2084. cpp++;
  2085. }
  2086. }
  2087. vpp = get_ptr_to_local_var(name, len);
  2088. if (vpp)
  2089. return (*vpp)->varstr + len + 1;
  2090. if (strcmp(name, "PPID") == 0)
  2091. return utoa(G.root_ppid);
  2092. // bash compat: UID? EUID?
  2093. #if ENABLE_HUSH_RANDOM_SUPPORT
  2094. if (strcmp(name, "RANDOM") == 0)
  2095. return utoa(next_random(&G.random_gen));
  2096. #endif
  2097. #if ENABLE_HUSH_LINENO_VAR
  2098. if (strcmp(name, "LINENO") == 0)
  2099. return utoa(G.execute_lineno);
  2100. #endif
  2101. #if BASH_EPOCH_VARS
  2102. {
  2103. const char *fmt = NULL;
  2104. if (strcmp(name, "EPOCHSECONDS") == 0)
  2105. fmt = "%lu";
  2106. else if (strcmp(name, "EPOCHREALTIME") == 0)
  2107. fmt = "%lu.%06u";
  2108. if (fmt) {
  2109. struct timeval tv;
  2110. gettimeofday(&tv, NULL);
  2111. sprintf(G.epoch_buf, fmt, (unsigned long)tv.tv_sec,
  2112. (unsigned)tv.tv_usec);
  2113. return G.epoch_buf;
  2114. }
  2115. }
  2116. #endif
  2117. return NULL;
  2118. }
  2119. #if ENABLE_HUSH_GETOPTS
  2120. static void handle_changed_special_names(const char *name, unsigned name_len)
  2121. {
  2122. if (name_len == 6) {
  2123. if (strncmp(name, "OPTIND", 6) == 0) {
  2124. G.getopt_count = 0;
  2125. return;
  2126. }
  2127. }
  2128. }
  2129. #else
  2130. /* Do not even bother evaluating arguments */
  2131. # define handle_changed_special_names(...) ((void)0)
  2132. #endif
  2133. /* str holds "NAME=VAL" and is expected to be malloced.
  2134. * We take ownership of it.
  2135. */
  2136. #define SETFLAG_EXPORT (1 << 0)
  2137. #define SETFLAG_UNEXPORT (1 << 1)
  2138. #define SETFLAG_MAKE_RO (1 << 2)
  2139. #define SETFLAG_VARLVL_SHIFT 3
  2140. static int set_local_var(char *str, unsigned flags)
  2141. {
  2142. struct variable **cur_pp;
  2143. struct variable *cur;
  2144. char *free_me = NULL;
  2145. char *eq_sign;
  2146. int name_len;
  2147. int retval;
  2148. unsigned local_lvl = (flags >> SETFLAG_VARLVL_SHIFT);
  2149. eq_sign = strchr(str, '=');
  2150. if (HUSH_DEBUG && !eq_sign)
  2151. bb_error_msg_and_die("BUG in setvar");
  2152. name_len = eq_sign - str + 1; /* including '=' */
  2153. cur_pp = &G.top_var;
  2154. while ((cur = *cur_pp) != NULL) {
  2155. if (strncmp(cur->varstr, str, name_len) != 0) {
  2156. cur_pp = &cur->next;
  2157. continue;
  2158. }
  2159. /* We found an existing var with this name */
  2160. if (cur->flg_read_only) {
  2161. bb_error_msg("%s: readonly variable", str);
  2162. free(str);
  2163. //NOTE: in bash, assignment in "export READONLY_VAR=Z" fails, and sets $?=1,
  2164. //but export per se succeeds (does put the var in env). We don't mimic that.
  2165. return -1;
  2166. }
  2167. if (flags & SETFLAG_UNEXPORT) { // && cur->flg_export ?
  2168. debug_printf_env("%s: unsetenv '%s'\n", __func__, str);
  2169. *eq_sign = '\0';
  2170. unsetenv(str);
  2171. *eq_sign = '=';
  2172. }
  2173. if (cur->var_nest_level < local_lvl) {
  2174. /* bash 3.2.33(1) and exported vars:
  2175. * # export z=z
  2176. * # f() { local z=a; env | grep ^z; }
  2177. * # f
  2178. * z=a
  2179. * # env | grep ^z
  2180. * z=z
  2181. */
  2182. if (cur->flg_export)
  2183. flags |= SETFLAG_EXPORT;
  2184. /* New variable is local ("local VAR=VAL" or
  2185. * "VAR=VAL cmd")
  2186. * and existing one is global, or local
  2187. * on a lower level that new one.
  2188. * Remove it from global variable list:
  2189. */
  2190. *cur_pp = cur->next;
  2191. if (G.shadowed_vars_pp) {
  2192. /* Save in "shadowed" list */
  2193. debug_printf_env("shadowing %s'%s'/%u by '%s'/%u\n",
  2194. cur->flg_export ? "exported " : "",
  2195. cur->varstr, cur->var_nest_level, str, local_lvl
  2196. );
  2197. cur->next = *G.shadowed_vars_pp;
  2198. *G.shadowed_vars_pp = cur;
  2199. } else {
  2200. /* Came from pseudo_exec_argv(), no need to save: delete it */
  2201. debug_printf_env("shadow-deleting %s'%s'/%u by '%s'/%u\n",
  2202. cur->flg_export ? "exported " : "",
  2203. cur->varstr, cur->var_nest_level, str, local_lvl
  2204. );
  2205. if (cur->max_len == 0) /* allocated "VAR=VAL"? */
  2206. free_me = cur->varstr; /* then free it later */
  2207. free(cur);
  2208. }
  2209. break;
  2210. }
  2211. if (strcmp(cur->varstr + name_len, eq_sign + 1) == 0) {
  2212. debug_printf_env("assignement '%s' does not change anything\n", str);
  2213. free_and_exp:
  2214. free(str);
  2215. goto exp;
  2216. }
  2217. /* Replace the value in the found "struct variable" */
  2218. if (cur->max_len != 0) {
  2219. if (cur->max_len >= strnlen(str, cur->max_len + 1)) {
  2220. /* This one is from startup env, reuse space */
  2221. debug_printf_env("reusing startup env for '%s'\n", str);
  2222. strcpy(cur->varstr, str);
  2223. goto free_and_exp;
  2224. }
  2225. /* Can't reuse */
  2226. cur->max_len = 0;
  2227. goto set_str_and_exp;
  2228. }
  2229. /* max_len == 0 signifies "malloced" var, which we can
  2230. * (and have to) free. But we can't free(cur->varstr) here:
  2231. * if cur->flg_export is 1, it is in the environment.
  2232. * We should either unsetenv+free, or wait until putenv,
  2233. * then putenv(new)+free(old).
  2234. */
  2235. free_me = cur->varstr;
  2236. goto set_str_and_exp;
  2237. }
  2238. /* Not found or shadowed - create new variable struct */
  2239. debug_printf_env("%s: alloc new var '%s'/%u\n", __func__, str, local_lvl);
  2240. cur = xzalloc(sizeof(*cur));
  2241. cur->var_nest_level = local_lvl;
  2242. cur->next = *cur_pp;
  2243. *cur_pp = cur;
  2244. set_str_and_exp:
  2245. cur->varstr = str;
  2246. exp:
  2247. #if !BB_MMU || ENABLE_HUSH_READONLY
  2248. if (flags & SETFLAG_MAKE_RO) {
  2249. cur->flg_read_only = 1;
  2250. }
  2251. #endif
  2252. if (flags & SETFLAG_EXPORT)
  2253. cur->flg_export = 1;
  2254. retval = 0;
  2255. if (cur->flg_export) {
  2256. if (flags & SETFLAG_UNEXPORT) {
  2257. cur->flg_export = 0;
  2258. /* unsetenv was already done */
  2259. } else {
  2260. debug_printf_env("%s: putenv '%s'/%u\n", __func__, cur->varstr, cur->var_nest_level);
  2261. retval = putenv(cur->varstr);
  2262. /* fall through to "free(free_me)" -
  2263. * only now we can free old exported malloced string
  2264. */
  2265. }
  2266. }
  2267. free(free_me);
  2268. handle_changed_special_names(cur->varstr, name_len - 1);
  2269. return retval;
  2270. }
  2271. static void FAST_FUNC set_local_var_from_halves(const char *name, const char *val)
  2272. {
  2273. char *var = xasprintf("%s=%s", name, val);
  2274. set_local_var(var, /*flag:*/ 0);
  2275. }
  2276. /* Used at startup and after each cd */
  2277. static void set_pwd_var(unsigned flag)
  2278. {
  2279. set_local_var(xasprintf("PWD=%s", get_cwd(/*force:*/ 1)), flag);
  2280. }
  2281. #if ENABLE_HUSH_UNSET || ENABLE_HUSH_GETOPTS
  2282. static int unset_local_var_len(const char *name, int name_len)
  2283. {
  2284. struct variable *cur;
  2285. struct variable **cur_pp;
  2286. cur_pp = &G.top_var;
  2287. while ((cur = *cur_pp) != NULL) {
  2288. if (strncmp(cur->varstr, name, name_len) == 0
  2289. && cur->varstr[name_len] == '='
  2290. ) {
  2291. if (cur->flg_read_only) {
  2292. bb_error_msg("%s: readonly variable", name);
  2293. return EXIT_FAILURE;
  2294. }
  2295. *cur_pp = cur->next;
  2296. debug_printf_env("%s: unsetenv '%s'\n", __func__, cur->varstr);
  2297. bb_unsetenv(cur->varstr);
  2298. if (!cur->max_len)
  2299. free(cur->varstr);
  2300. free(cur);
  2301. break;
  2302. }
  2303. cur_pp = &cur->next;
  2304. }
  2305. /* Handle "unset LINENO" et al even if did not find the variable to unset */
  2306. handle_changed_special_names(name, name_len);
  2307. return EXIT_SUCCESS;
  2308. }
  2309. static int unset_local_var(const char *name)
  2310. {
  2311. return unset_local_var_len(name, strlen(name));
  2312. }
  2313. #endif
  2314. /*
  2315. * Helpers for "var1=val1 var2=val2 cmd" feature
  2316. */
  2317. static void add_vars(struct variable *var)
  2318. {
  2319. struct variable *next;
  2320. while (var) {
  2321. next = var->next;
  2322. var->next = G.top_var;
  2323. G.top_var = var;
  2324. if (var->flg_export) {
  2325. debug_printf_env("%s: restoring exported '%s'/%u\n", __func__, var->varstr, var->var_nest_level);
  2326. putenv(var->varstr);
  2327. } else {
  2328. debug_printf_env("%s: restoring variable '%s'/%u\n", __func__, var->varstr, var->var_nest_level);
  2329. }
  2330. var = next;
  2331. }
  2332. }
  2333. /* We put strings[i] into variable table and possibly putenv them.
  2334. * If variable is read only, we can free the strings[i]
  2335. * which attempts to overwrite it.
  2336. * The strings[] vector itself is freed.
  2337. */
  2338. static void set_vars_and_save_old(char **strings)
  2339. {
  2340. char **s;
  2341. if (!strings)
  2342. return;
  2343. s = strings;
  2344. while (*s) {
  2345. struct variable *var_p;
  2346. struct variable **var_pp;
  2347. char *eq;
  2348. eq = strchr(*s, '=');
  2349. if (HUSH_DEBUG && !eq)
  2350. bb_error_msg_and_die("BUG in varexp4");
  2351. var_pp = get_ptr_to_local_var(*s, eq - *s);
  2352. if (var_pp) {
  2353. var_p = *var_pp;
  2354. if (var_p->flg_read_only) {
  2355. char **p;
  2356. bb_error_msg("%s: readonly variable", *s);
  2357. /*
  2358. * "VAR=V BLTIN" unsets VARs after BLTIN completes.
  2359. * If VAR is readonly, leaving it in the list
  2360. * after asssignment error (msg above)
  2361. * causes doubled error message later, on unset.
  2362. */
  2363. debug_printf_env("removing/freeing '%s' element\n", *s);
  2364. free(*s);
  2365. p = s;
  2366. do { *p = p[1]; p++; } while (*p);
  2367. goto next;
  2368. }
  2369. /* below, set_local_var() with nest level will
  2370. * "shadow" (remove) this variable from
  2371. * global linked list.
  2372. */
  2373. }
  2374. debug_printf_env("%s: env override '%s'/%u\n", __func__, *s, G.var_nest_level);
  2375. set_local_var(*s, (G.var_nest_level << SETFLAG_VARLVL_SHIFT) | SETFLAG_EXPORT);
  2376. s++;
  2377. next: ;
  2378. }
  2379. free(strings);
  2380. }
  2381. /*
  2382. * Unicode helper
  2383. */
  2384. static void reinit_unicode_for_hush(void)
  2385. {
  2386. /* Unicode support should be activated even if LANG is set
  2387. * _during_ shell execution, not only if it was set when
  2388. * shell was started. Therefore, re-check LANG every time:
  2389. */
  2390. if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
  2391. || ENABLE_UNICODE_USING_LOCALE
  2392. ) {
  2393. const char *s = get_local_var_value("LC_ALL");
  2394. if (!s) s = get_local_var_value("LC_CTYPE");
  2395. if (!s) s = get_local_var_value("LANG");
  2396. reinit_unicode(s);
  2397. }
  2398. }
  2399. /*
  2400. * in_str support (strings, and "strings" read from files).
  2401. */
  2402. #if ENABLE_HUSH_INTERACTIVE
  2403. /* To test correct lineedit/interactive behavior, type from command line:
  2404. * echo $P\
  2405. * \
  2406. * AT\
  2407. * H\
  2408. * \
  2409. * It exercises a lot of corner cases.
  2410. */
  2411. static const char *setup_prompt_string(void)
  2412. {
  2413. const char *prompt_str;
  2414. debug_printf_prompt("%s promptmode:%d\n", __func__, G.promptmode);
  2415. # if ENABLE_FEATURE_EDITING_FANCY_PROMPT
  2416. prompt_str = get_local_var_value(G.promptmode == 0 ? "PS1" : "PS2");
  2417. if (!prompt_str)
  2418. prompt_str = "";
  2419. # else
  2420. prompt_str = "> "; /* if PS2, else... */
  2421. if (G.promptmode == 0) { /* PS1 */
  2422. /* No fancy prompts supported, (re)generate "CURDIR $ " by hand */
  2423. free(G.PS1);
  2424. /* bash uses $PWD value, even if it is set by user.
  2425. * It uses current dir only if PWD is unset.
  2426. * We always use current dir. */
  2427. G.PS1 = xasprintf("%s %c ", get_cwd(0), (geteuid() != 0) ? '$' : '#');
  2428. }
  2429. # endif
  2430. debug_printf("prompt_str '%s'\n", prompt_str);
  2431. return prompt_str;
  2432. }
  2433. static int get_user_input(struct in_str *i)
  2434. {
  2435. int r;
  2436. const char *prompt_str;
  2437. prompt_str = setup_prompt_string();
  2438. # if ENABLE_FEATURE_EDITING
  2439. for (;;) {
  2440. reinit_unicode_for_hush();
  2441. if (G.flag_SIGINT) {
  2442. /* There was ^C'ed, make it look prettier: */
  2443. bb_putchar('\n');
  2444. G.flag_SIGINT = 0;
  2445. }
  2446. /* buglet: SIGINT will not make new prompt to appear _at once_,
  2447. * only after <Enter>. (^C works immediately) */
  2448. r = read_line_input(G.line_input_state, prompt_str,
  2449. G.user_input_buf, CONFIG_FEATURE_EDITING_MAX_LEN-1
  2450. );
  2451. /* read_line_input intercepts ^C, "convert" it to SIGINT */
  2452. if (r == 0)
  2453. raise(SIGINT);
  2454. check_and_run_traps();
  2455. if (r != 0 && !G.flag_SIGINT)
  2456. break;
  2457. /* ^C or SIGINT: repeat */
  2458. /* bash prints ^C even on real SIGINT (non-kbd generated) */
  2459. write(STDOUT_FILENO, "^C", 2);
  2460. G.last_exitcode = 128 + SIGINT;
  2461. }
  2462. if (r < 0) {
  2463. /* EOF/error detected */
  2464. i->p = NULL;
  2465. i->peek_buf[0] = r = EOF;
  2466. return r;
  2467. }
  2468. i->p = G.user_input_buf;
  2469. return (unsigned char)*i->p++;
  2470. # else
  2471. for (;;) {
  2472. G.flag_SIGINT = 0;
  2473. if (i->last_char == '\0' || i->last_char == '\n') {
  2474. /* Why check_and_run_traps here? Try this interactively:
  2475. * $ trap 'echo INT' INT; (sleep 2; kill -INT $$) &
  2476. * $ <[enter], repeatedly...>
  2477. * Without check_and_run_traps, handler never runs.
  2478. */
  2479. check_and_run_traps();
  2480. fputs(prompt_str, stdout);
  2481. }
  2482. fflush_all();
  2483. //FIXME: here ^C or SIGINT will have effect only after <Enter>
  2484. r = hfgetc(i->file);
  2485. /* In !ENABLE_FEATURE_EDITING we don't use read_line_input,
  2486. * no ^C masking happens during fgetc, no special code for ^C:
  2487. * it generates SIGINT as usual.
  2488. */
  2489. check_and_run_traps();
  2490. if (G.flag_SIGINT)
  2491. G.last_exitcode = 128 + SIGINT;
  2492. if (r != '\0')
  2493. break;
  2494. }
  2495. return r;
  2496. # endif
  2497. }
  2498. /* This is the magic location that prints prompts
  2499. * and gets data back from the user */
  2500. static int fgetc_interactive(struct in_str *i)
  2501. {
  2502. int ch;
  2503. /* If it's interactive stdin, get new line. */
  2504. if (G_interactive_fd && i->file->is_stdin) {
  2505. /* Returns first char (or EOF), the rest is in i->p[] */
  2506. ch = get_user_input(i);
  2507. G.promptmode = 1; /* PS2 */
  2508. debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
  2509. } else {
  2510. /* Not stdin: script file, sourced file, etc */
  2511. do ch = hfgetc(i->file); while (ch == '\0');
  2512. }
  2513. return ch;
  2514. }
  2515. #else
  2516. static ALWAYS_INLINE int fgetc_interactive(struct in_str *i)
  2517. {
  2518. int ch;
  2519. do ch = hfgetc(i->file); while (ch == '\0');
  2520. return ch;
  2521. }
  2522. #endif /* INTERACTIVE */
  2523. static int i_getch(struct in_str *i)
  2524. {
  2525. int ch;
  2526. if (!i->file) {
  2527. /* string-based in_str */
  2528. ch = (unsigned char)*i->p;
  2529. if (ch != '\0') {
  2530. i->p++;
  2531. i->last_char = ch;
  2532. return ch;
  2533. }
  2534. return EOF;
  2535. }
  2536. /* FILE-based in_str */
  2537. #if ENABLE_FEATURE_EDITING
  2538. /* This can be stdin, check line editing char[] buffer */
  2539. if (i->p && *i->p != '\0') {
  2540. ch = (unsigned char)*i->p++;
  2541. goto out;
  2542. }
  2543. #endif
  2544. /* peek_buf[] is an int array, not char. Can contain EOF. */
  2545. ch = i->peek_buf[0];
  2546. if (ch != 0) {
  2547. int ch2 = i->peek_buf[1];
  2548. i->peek_buf[0] = ch2;
  2549. if (ch2 == 0) /* very likely, avoid redundant write */
  2550. goto out;
  2551. i->peek_buf[1] = 0;
  2552. goto out;
  2553. }
  2554. ch = fgetc_interactive(i);
  2555. out:
  2556. debug_printf("file_get: got '%c' %d\n", ch, ch);
  2557. i->last_char = ch;
  2558. #if ENABLE_HUSH_LINENO_VAR
  2559. if (ch == '\n') {
  2560. G.parse_lineno++;
  2561. debug_printf_parse("G.parse_lineno++ = %u\n", G.parse_lineno);
  2562. }
  2563. #endif
  2564. return ch;
  2565. }
  2566. static int i_peek(struct in_str *i)
  2567. {
  2568. int ch;
  2569. if (!i->file) {
  2570. /* string-based in_str */
  2571. /* Doesn't report EOF on NUL. None of the callers care. */
  2572. return (unsigned char)*i->p;
  2573. }
  2574. /* FILE-based in_str */
  2575. #if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
  2576. /* This can be stdin, check line editing char[] buffer */
  2577. if (i->p && *i->p != '\0')
  2578. return (unsigned char)*i->p;
  2579. #endif
  2580. /* peek_buf[] is an int array, not char. Can contain EOF. */
  2581. ch = i->peek_buf[0];
  2582. if (ch != 0)
  2583. return ch;
  2584. /* Need to get a new char */
  2585. ch = fgetc_interactive(i);
  2586. debug_printf("file_peek: got '%c' %d\n", ch, ch);
  2587. /* Save it by either rolling back line editing buffer, or in i->peek_buf[0] */
  2588. #if ENABLE_FEATURE_EDITING && ENABLE_HUSH_INTERACTIVE
  2589. if (i->p) {
  2590. i->p -= 1;
  2591. return ch;
  2592. }
  2593. #endif
  2594. i->peek_buf[0] = ch;
  2595. /*i->peek_buf[1] = 0; - already is */
  2596. return ch;
  2597. }
  2598. /* Only ever called if i_peek() was called, and did not return EOF.
  2599. * IOW: we know the previous peek saw an ordinary char, not EOF, not NUL,
  2600. * not end-of-line. Therefore we never need to read a new editing line here.
  2601. */
  2602. static int i_peek2(struct in_str *i)
  2603. {
  2604. int ch;
  2605. /* There are two cases when i->p[] buffer exists.
  2606. * (1) it's a string in_str.
  2607. * (2) It's a file, and we have a saved line editing buffer.
  2608. * In both cases, we know that i->p[0] exists and not NUL, and
  2609. * the peek2 result is in i->p[1].
  2610. */
  2611. if (i->p)
  2612. return (unsigned char)i->p[1];
  2613. /* Now we know it is a file-based in_str. */
  2614. /* peek_buf[] is an int array, not char. Can contain EOF. */
  2615. /* Is there 2nd char? */
  2616. ch = i->peek_buf[1];
  2617. if (ch == 0) {
  2618. /* We did not read it yet, get it now */
  2619. do ch = hfgetc(i->file); while (ch == '\0');
  2620. i->peek_buf[1] = ch;
  2621. }
  2622. debug_printf("file_peek2: got '%c' %d\n", ch, ch);
  2623. return ch;
  2624. }
  2625. static int i_getch_and_eat_bkslash_nl(struct in_str *input)
  2626. {
  2627. for (;;) {
  2628. int ch, ch2;
  2629. ch = i_getch(input);
  2630. if (ch != '\\')
  2631. return ch;
  2632. ch2 = i_peek(input);
  2633. if (ch2 != '\n')
  2634. return ch;
  2635. /* backslash+newline, skip it */
  2636. i_getch(input);
  2637. }
  2638. }
  2639. /* Note: this function _eats_ \<newline> pairs, safe to use plain
  2640. * i_getch() after it instead of i_getch_and_eat_bkslash_nl().
  2641. */
  2642. static int i_peek_and_eat_bkslash_nl(struct in_str *input)
  2643. {
  2644. for (;;) {
  2645. int ch, ch2;
  2646. ch = i_peek(input);
  2647. if (ch != '\\')
  2648. return ch;
  2649. ch2 = i_peek2(input);
  2650. if (ch2 != '\n')
  2651. return ch;
  2652. /* backslash+newline, skip it */
  2653. i_getch(input);
  2654. i_getch(input);
  2655. }
  2656. }
  2657. static void setup_file_in_str(struct in_str *i, HFILE *fp)
  2658. {
  2659. memset(i, 0, sizeof(*i));
  2660. i->file = fp;
  2661. /* i->p = NULL; */
  2662. }
  2663. static void setup_string_in_str(struct in_str *i, const char *s)
  2664. {
  2665. memset(i, 0, sizeof(*i));
  2666. /*i->file = NULL */;
  2667. i->p = s;
  2668. }
  2669. /*
  2670. * o_string support
  2671. */
  2672. #define B_CHUNK (32 * sizeof(char*))
  2673. static void o_reset_to_empty_unquoted(o_string *o)
  2674. {
  2675. o->length = 0;
  2676. o->has_quoted_part = 0;
  2677. if (o->data)
  2678. o->data[0] = '\0';
  2679. }
  2680. static void o_free_and_set_NULL(o_string *o)
  2681. {
  2682. free(o->data);
  2683. memset(o, 0, sizeof(*o));
  2684. }
  2685. static ALWAYS_INLINE void o_free(o_string *o)
  2686. {
  2687. free(o->data);
  2688. }
  2689. static void o_grow_by(o_string *o, int len)
  2690. {
  2691. if (o->length + len > o->maxlen) {
  2692. o->maxlen += (2 * len) | (B_CHUNK-1);
  2693. o->data = xrealloc(o->data, 1 + o->maxlen);
  2694. }
  2695. }
  2696. static void o_addchr(o_string *o, int ch)
  2697. {
  2698. debug_printf("o_addchr: '%c' o->length=%d o=%p\n", ch, o->length, o);
  2699. if (o->length < o->maxlen) {
  2700. /* likely. avoid o_grow_by() call */
  2701. add:
  2702. o->data[o->length] = ch;
  2703. o->length++;
  2704. o->data[o->length] = '\0';
  2705. return;
  2706. }
  2707. o_grow_by(o, 1);
  2708. goto add;
  2709. }
  2710. #if 0
  2711. /* Valid only if we know o_string is not empty */
  2712. static void o_delchr(o_string *o)
  2713. {
  2714. o->length--;
  2715. o->data[o->length] = '\0';
  2716. }
  2717. #endif
  2718. static void o_addblock(o_string *o, const char *str, int len)
  2719. {
  2720. o_grow_by(o, len);
  2721. ((char*)mempcpy(&o->data[o->length], str, len))[0] = '\0';
  2722. o->length += len;
  2723. }
  2724. static void o_addstr(o_string *o, const char *str)
  2725. {
  2726. o_addblock(o, str, strlen(str));
  2727. }
  2728. static void o_addstr_with_NUL(o_string *o, const char *str)
  2729. {
  2730. o_addblock(o, str, strlen(str) + 1);
  2731. }
  2732. #if !BB_MMU
  2733. static void nommu_addchr(o_string *o, int ch)
  2734. {
  2735. if (o)
  2736. o_addchr(o, ch);
  2737. }
  2738. #else
  2739. # define nommu_addchr(o, str) ((void)0)
  2740. #endif
  2741. #if ENABLE_HUSH_MODE_X
  2742. static void x_mode_addchr(int ch)
  2743. {
  2744. o_addchr(&G.x_mode_buf, ch);
  2745. }
  2746. static void x_mode_addstr(const char *str)
  2747. {
  2748. o_addstr(&G.x_mode_buf, str);
  2749. }
  2750. static void x_mode_addblock(const char *str, int len)
  2751. {
  2752. o_addblock(&G.x_mode_buf, str, len);
  2753. }
  2754. static void x_mode_prefix(void)
  2755. {
  2756. int n = G.x_mode_depth;
  2757. do x_mode_addchr('+'); while (--n >= 0);
  2758. }
  2759. static void x_mode_flush(void)
  2760. {
  2761. int len = G.x_mode_buf.length;
  2762. if (len <= 0)
  2763. return;
  2764. if (G.x_mode_fd > 0) {
  2765. G.x_mode_buf.data[len] = '\n';
  2766. full_write(G.x_mode_fd, G.x_mode_buf.data, len + 1);
  2767. }
  2768. G.x_mode_buf.length = 0;
  2769. }
  2770. #endif
  2771. /*
  2772. * HUSH_BRACE_EXPANSION code needs corresponding quoting on variable expansion side.
  2773. * Currently, "v='{q,w}'; echo $v" erroneously expands braces in $v.
  2774. * Apparently, on unquoted $v bash still does globbing
  2775. * ("v='*.txt'; echo $v" prints all .txt files),
  2776. * but NOT brace expansion! Thus, there should be TWO independent
  2777. * quoting mechanisms on $v expansion side: one protects
  2778. * $v from brace expansion, and other additionally protects "$v" against globbing.
  2779. * We have only second one.
  2780. */
  2781. #if ENABLE_HUSH_BRACE_EXPANSION
  2782. # define MAYBE_BRACES "{}"
  2783. #else
  2784. # define MAYBE_BRACES ""
  2785. #endif
  2786. /* My analysis of quoting semantics tells me that state information
  2787. * is associated with a destination, not a source.
  2788. */
  2789. static void o_addqchr(o_string *o, int ch)
  2790. {
  2791. int sz = 1;
  2792. char *found = strchr("*?[\\" MAYBE_BRACES, ch);
  2793. if (found)
  2794. sz++;
  2795. o_grow_by(o, sz);
  2796. if (found) {
  2797. o->data[o->length] = '\\';
  2798. o->length++;
  2799. }
  2800. o->data[o->length] = ch;
  2801. o->length++;
  2802. o->data[o->length] = '\0';
  2803. }
  2804. static void o_addQchr(o_string *o, int ch)
  2805. {
  2806. int sz = 1;
  2807. if ((o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)
  2808. && strchr("*?[\\" MAYBE_BRACES, ch)
  2809. ) {
  2810. sz++;
  2811. o->data[o->length] = '\\';
  2812. o->length++;
  2813. }
  2814. o_grow_by(o, sz);
  2815. o->data[o->length] = ch;
  2816. o->length++;
  2817. o->data[o->length] = '\0';
  2818. }
  2819. static void o_addqblock(o_string *o, const char *str, int len)
  2820. {
  2821. while (len) {
  2822. char ch;
  2823. int sz;
  2824. int ordinary_cnt = strcspn(str, "*?[\\" MAYBE_BRACES);
  2825. if (ordinary_cnt > len) /* paranoia */
  2826. ordinary_cnt = len;
  2827. o_addblock(o, str, ordinary_cnt);
  2828. if (ordinary_cnt == len)
  2829. return; /* NUL is already added by o_addblock */
  2830. str += ordinary_cnt;
  2831. len -= ordinary_cnt + 1; /* we are processing + 1 char below */
  2832. ch = *str++;
  2833. sz = 1;
  2834. if (ch) { /* it is necessarily one of "*?[\\" MAYBE_BRACES */
  2835. sz++;
  2836. o->data[o->length] = '\\';
  2837. o->length++;
  2838. }
  2839. o_grow_by(o, sz);
  2840. o->data[o->length] = ch;
  2841. o->length++;
  2842. }
  2843. o->data[o->length] = '\0';
  2844. }
  2845. static void o_addQblock(o_string *o, const char *str, int len)
  2846. {
  2847. if (!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS)) {
  2848. o_addblock(o, str, len);
  2849. return;
  2850. }
  2851. o_addqblock(o, str, len);
  2852. }
  2853. static void o_addQstr(o_string *o, const char *str)
  2854. {
  2855. o_addQblock(o, str, strlen(str));
  2856. }
  2857. /* A special kind of o_string for $VAR and `cmd` expansion.
  2858. * It contains char* list[] at the beginning, which is grown in 16 element
  2859. * increments. Actual string data starts at the next multiple of 16 * (char*).
  2860. * list[i] contains an INDEX (int!) into this string data.
  2861. * It means that if list[] needs to grow, data needs to be moved higher up
  2862. * but list[i]'s need not be modified.
  2863. * NB: remembering how many list[i]'s you have there is crucial.
  2864. * o_finalize_list() operation post-processes this structure - calculates
  2865. * and stores actual char* ptrs in list[]. Oh, it NULL terminates it as well.
  2866. */
  2867. #if DEBUG_EXPAND || DEBUG_GLOB
  2868. static void debug_print_list(const char *prefix, o_string *o, int n)
  2869. {
  2870. char **list = (char**)o->data;
  2871. int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
  2872. int i = 0;
  2873. indent();
  2874. fdprintf(2, "%s: list:%p n:%d string_start:%d length:%d maxlen:%d glob:%d quoted:%d escape:%d\n",
  2875. prefix, list, n, string_start, o->length, o->maxlen,
  2876. !!(o->o_expflags & EXP_FLAG_GLOB),
  2877. o->has_quoted_part,
  2878. !!(o->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
  2879. while (i < n) {
  2880. indent();
  2881. fdprintf(2, " list[%d]=%d '%s' %p\n", i, (int)(uintptr_t)list[i],
  2882. o->data + (int)(uintptr_t)list[i] + string_start,
  2883. o->data + (int)(uintptr_t)list[i] + string_start);
  2884. i++;
  2885. }
  2886. if (n) {
  2887. const char *p = o->data + (int)(uintptr_t)list[n - 1] + string_start;
  2888. indent();
  2889. fdprintf(2, " total_sz:%ld\n", (long)((p + strlen(p) + 1) - o->data));
  2890. }
  2891. }
  2892. #else
  2893. # define debug_print_list(prefix, o, n) ((void)0)
  2894. #endif
  2895. /* n = o_save_ptr_helper(str, n) "starts new string" by storing an index value
  2896. * in list[n] so that it points past last stored byte so far.
  2897. * It returns n+1. */
  2898. static int o_save_ptr_helper(o_string *o, int n)
  2899. {
  2900. char **list = (char**)o->data;
  2901. int string_start;
  2902. int string_len;
  2903. if (!o->has_empty_slot) {
  2904. string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
  2905. string_len = o->length - string_start;
  2906. if (!(n & 0xf)) { /* 0, 0x10, 0x20...? */
  2907. debug_printf_list("list[%d]=%d string_start=%d (growing)\n", n, string_len, string_start);
  2908. /* list[n] points to string_start, make space for 16 more pointers */
  2909. o->maxlen += 0x10 * sizeof(list[0]);
  2910. o->data = xrealloc(o->data, o->maxlen + 1);
  2911. list = (char**)o->data;
  2912. memmove(list + n + 0x10, list + n, string_len);
  2913. /*
  2914. * expand_on_ifs() has a "previous argv[] ends in IFS?"
  2915. * check. (grep for -prev-ifs-check-).
  2916. * Ensure that argv[-1][last] is not garbage
  2917. * but zero bytes, to save index check there.
  2918. */
  2919. list[n + 0x10 - 1] = 0;
  2920. o->length += 0x10 * sizeof(list[0]);
  2921. } else {
  2922. debug_printf_list("list[%d]=%d string_start=%d\n",
  2923. n, string_len, string_start);
  2924. }
  2925. } else {
  2926. /* We have empty slot at list[n], reuse without growth */
  2927. string_start = ((n+1 + 0xf) & ~0xf) * sizeof(list[0]); /* NB: n+1! */
  2928. string_len = o->length - string_start;
  2929. debug_printf_list("list[%d]=%d string_start=%d (empty slot)\n",
  2930. n, string_len, string_start);
  2931. o->has_empty_slot = 0;
  2932. }
  2933. o->has_quoted_part = 0;
  2934. list[n] = (char*)(uintptr_t)string_len;
  2935. return n + 1;
  2936. }
  2937. /* "What was our last o_save_ptr'ed position (byte offset relative o->data)?" */
  2938. static int o_get_last_ptr(o_string *o, int n)
  2939. {
  2940. char **list = (char**)o->data;
  2941. int string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
  2942. return ((int)(uintptr_t)list[n-1]) + string_start;
  2943. }
  2944. /*
  2945. * Globbing routines.
  2946. *
  2947. * Most words in commands need to be globbed, even ones which are
  2948. * (single or double) quoted. This stems from the possiblity of
  2949. * constructs like "abc"* and 'abc'* - these should be globbed.
  2950. * Having a different code path for fully-quoted strings ("abc",
  2951. * 'abc') would only help performance-wise, but we still need
  2952. * code for partially-quoted strings.
  2953. *
  2954. * Unfortunately, if we want to match bash and ash behavior in all cases,
  2955. * the logic can't be "shell-syntax argument is first transformed
  2956. * to a string, then globbed, and if globbing does not match anything,
  2957. * it is used verbatim". Here are two examples where it fails:
  2958. *
  2959. * echo 'b\*'?
  2960. *
  2961. * The globbing can't be avoided (because of '?' at the end).
  2962. * The glob pattern is: b\\\*? - IOW, both \ and * are literals
  2963. * and are glob-escaped. If this does not match, bash/ash print b\*?
  2964. * - IOW: they "unbackslash" the glob pattern.
  2965. * Now, look at this:
  2966. *
  2967. * v='\\\*'; echo b$v?
  2968. *
  2969. * The glob pattern is the same here: b\\\*? - the unquoted $v expansion
  2970. * should be used as glob pattern with no changes. However, if glob
  2971. * does not match, bash/ash print b\\\*? - NOT THE SAME as first example!
  2972. *
  2973. * ash implements this by having an encoded representation of the word
  2974. * to glob, which IS NOT THE SAME as the glob pattern - it has more data.
  2975. * Glob pattern is derived from it. If glob fails, the decision what result
  2976. * should be is made using that encoded representation. Not glob pattern.
  2977. */
  2978. #if ENABLE_HUSH_BRACE_EXPANSION
  2979. /* There in a GNU extension, GLOB_BRACE, but it is not usable:
  2980. * first, it processes even {a} (no commas), second,
  2981. * I didn't manage to make it return strings when they don't match
  2982. * existing files. Need to re-implement it.
  2983. */
  2984. /* Helper */
  2985. static int glob_needed(const char *s)
  2986. {
  2987. while (*s) {
  2988. if (*s == '\\') {
  2989. if (!s[1])
  2990. return 0;
  2991. s += 2;
  2992. continue;
  2993. }
  2994. if (*s == '*' || *s == '[' || *s == '?' || *s == '{')
  2995. return 1;
  2996. s++;
  2997. }
  2998. return 0;
  2999. }
  3000. /* Return pointer to next closing brace or to comma */
  3001. static const char *next_brace_sub(const char *cp)
  3002. {
  3003. unsigned depth = 0;
  3004. cp++;
  3005. while (*cp != '\0') {
  3006. if (*cp == '\\') {
  3007. if (*++cp == '\0')
  3008. break;
  3009. cp++;
  3010. continue;
  3011. }
  3012. if ((*cp == '}' && depth-- == 0) || (*cp == ',' && depth == 0))
  3013. break;
  3014. if (*cp++ == '{')
  3015. depth++;
  3016. }
  3017. return *cp != '\0' ? cp : NULL;
  3018. }
  3019. /* Recursive brace globber. Note: may garble pattern[]. */
  3020. static int glob_brace(char *pattern, o_string *o, int n)
  3021. {
  3022. char *new_pattern_buf;
  3023. const char *begin;
  3024. const char *next;
  3025. const char *rest;
  3026. const char *p;
  3027. size_t rest_len;
  3028. debug_printf_glob("glob_brace('%s')\n", pattern);
  3029. begin = pattern;
  3030. while (1) {
  3031. if (*begin == '\0')
  3032. goto simple_glob;
  3033. if (*begin == '{') {
  3034. /* Find the first sub-pattern and at the same time
  3035. * find the rest after the closing brace */
  3036. next = next_brace_sub(begin);
  3037. if (next == NULL) {
  3038. /* An illegal expression */
  3039. goto simple_glob;
  3040. }
  3041. if (*next == '}') {
  3042. /* "{abc}" with no commas - illegal
  3043. * brace expr, disregard and skip it */
  3044. begin = next + 1;
  3045. continue;
  3046. }
  3047. break;
  3048. }
  3049. if (*begin == '\\' && begin[1] != '\0')
  3050. begin++;
  3051. begin++;
  3052. }
  3053. debug_printf_glob("begin:%s\n", begin);
  3054. debug_printf_glob("next:%s\n", next);
  3055. /* Now find the end of the whole brace expression */
  3056. rest = next;
  3057. while (*rest != '}') {
  3058. rest = next_brace_sub(rest);
  3059. if (rest == NULL) {
  3060. /* An illegal expression */
  3061. goto simple_glob;
  3062. }
  3063. debug_printf_glob("rest:%s\n", rest);
  3064. }
  3065. rest_len = strlen(++rest) + 1;
  3066. /* We are sure the brace expression is well-formed */
  3067. /* Allocate working buffer large enough for our work */
  3068. new_pattern_buf = xmalloc(strlen(pattern));
  3069. /* We have a brace expression. BEGIN points to the opening {,
  3070. * NEXT points past the terminator of the first element, and REST
  3071. * points past the final }. We will accumulate result names from
  3072. * recursive runs for each brace alternative in the buffer using
  3073. * GLOB_APPEND. */
  3074. p = begin + 1;
  3075. while (1) {
  3076. /* Construct the new glob expression */
  3077. memcpy(
  3078. mempcpy(
  3079. mempcpy(new_pattern_buf,
  3080. /* We know the prefix for all sub-patterns */
  3081. pattern, begin - pattern),
  3082. p, next - p),
  3083. rest, rest_len);
  3084. /* Note: glob_brace() may garble new_pattern_buf[].
  3085. * That's why we re-copy prefix every time (1st memcpy above).
  3086. */
  3087. n = glob_brace(new_pattern_buf, o, n);
  3088. if (*next == '}') {
  3089. /* We saw the last entry */
  3090. break;
  3091. }
  3092. p = next + 1;
  3093. next = next_brace_sub(next);
  3094. }
  3095. free(new_pattern_buf);
  3096. return n;
  3097. simple_glob:
  3098. {
  3099. int gr;
  3100. glob_t globdata;
  3101. memset(&globdata, 0, sizeof(globdata));
  3102. gr = glob(pattern, 0, NULL, &globdata);
  3103. debug_printf_glob("glob('%s'):%d\n", pattern, gr);
  3104. if (gr != 0) {
  3105. if (gr == GLOB_NOMATCH) {
  3106. globfree(&globdata);
  3107. /* NB: garbles parameter */
  3108. unbackslash(pattern);
  3109. o_addstr_with_NUL(o, pattern);
  3110. debug_printf_glob("glob pattern '%s' is literal\n", pattern);
  3111. return o_save_ptr_helper(o, n);
  3112. }
  3113. if (gr == GLOB_NOSPACE)
  3114. bb_die_memory_exhausted();
  3115. /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
  3116. * but we didn't specify it. Paranoia again. */
  3117. bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
  3118. }
  3119. if (globdata.gl_pathv && globdata.gl_pathv[0]) {
  3120. char **argv = globdata.gl_pathv;
  3121. while (1) {
  3122. o_addstr_with_NUL(o, *argv);
  3123. n = o_save_ptr_helper(o, n);
  3124. argv++;
  3125. if (!*argv)
  3126. break;
  3127. }
  3128. }
  3129. globfree(&globdata);
  3130. }
  3131. return n;
  3132. }
  3133. /* Performs globbing on last list[],
  3134. * saving each result as a new list[].
  3135. */
  3136. static int perform_glob(o_string *o, int n)
  3137. {
  3138. char *pattern, *copy;
  3139. debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
  3140. if (!o->data)
  3141. return o_save_ptr_helper(o, n);
  3142. pattern = o->data + o_get_last_ptr(o, n);
  3143. debug_printf_glob("glob pattern '%s'\n", pattern);
  3144. if (!glob_needed(pattern)) {
  3145. /* unbackslash last string in o in place, fix length */
  3146. o->length = unbackslash(pattern) - o->data;
  3147. debug_printf_glob("glob pattern '%s' is literal\n", pattern);
  3148. return o_save_ptr_helper(o, n);
  3149. }
  3150. copy = xstrdup(pattern);
  3151. /* "forget" pattern in o */
  3152. o->length = pattern - o->data;
  3153. n = glob_brace(copy, o, n);
  3154. free(copy);
  3155. if (DEBUG_GLOB)
  3156. debug_print_list("perform_glob returning", o, n);
  3157. return n;
  3158. }
  3159. #else /* !HUSH_BRACE_EXPANSION */
  3160. /* Helper */
  3161. static int glob_needed(const char *s)
  3162. {
  3163. while (*s) {
  3164. if (*s == '\\') {
  3165. if (!s[1])
  3166. return 0;
  3167. s += 2;
  3168. continue;
  3169. }
  3170. if (*s == '*' || *s == '[' || *s == '?')
  3171. return 1;
  3172. s++;
  3173. }
  3174. return 0;
  3175. }
  3176. /* Performs globbing on last list[],
  3177. * saving each result as a new list[].
  3178. */
  3179. static int perform_glob(o_string *o, int n)
  3180. {
  3181. glob_t globdata;
  3182. int gr;
  3183. char *pattern;
  3184. debug_printf_glob("start perform_glob: n:%d o->data:%p\n", n, o->data);
  3185. if (!o->data)
  3186. return o_save_ptr_helper(o, n);
  3187. pattern = o->data + o_get_last_ptr(o, n);
  3188. debug_printf_glob("glob pattern '%s'\n", pattern);
  3189. if (!glob_needed(pattern)) {
  3190. literal:
  3191. /* unbackslash last string in o in place, fix length */
  3192. o->length = unbackslash(pattern) - o->data;
  3193. debug_printf_glob("glob pattern '%s' is literal\n", pattern);
  3194. return o_save_ptr_helper(o, n);
  3195. }
  3196. memset(&globdata, 0, sizeof(globdata));
  3197. /* Can't use GLOB_NOCHECK: it does not unescape the string.
  3198. * If we glob "*.\*" and don't find anything, we need
  3199. * to fall back to using literal "*.*", but GLOB_NOCHECK
  3200. * will return "*.\*"!
  3201. */
  3202. gr = glob(pattern, 0, NULL, &globdata);
  3203. debug_printf_glob("glob('%s'):%d\n", pattern, gr);
  3204. if (gr != 0) {
  3205. if (gr == GLOB_NOMATCH) {
  3206. globfree(&globdata);
  3207. goto literal;
  3208. }
  3209. if (gr == GLOB_NOSPACE)
  3210. bb_die_memory_exhausted();
  3211. /* GLOB_ABORTED? Only happens with GLOB_ERR flag,
  3212. * but we didn't specify it. Paranoia again. */
  3213. bb_error_msg_and_die("glob error %d on '%s'", gr, pattern);
  3214. }
  3215. if (globdata.gl_pathv && globdata.gl_pathv[0]) {
  3216. char **argv = globdata.gl_pathv;
  3217. /* "forget" pattern in o */
  3218. o->length = pattern - o->data;
  3219. while (1) {
  3220. o_addstr_with_NUL(o, *argv);
  3221. n = o_save_ptr_helper(o, n);
  3222. argv++;
  3223. if (!*argv)
  3224. break;
  3225. }
  3226. }
  3227. globfree(&globdata);
  3228. if (DEBUG_GLOB)
  3229. debug_print_list("perform_glob returning", o, n);
  3230. return n;
  3231. }
  3232. #endif /* !HUSH_BRACE_EXPANSION */
  3233. /* If o->o_expflags & EXP_FLAG_GLOB, glob the string so far remembered.
  3234. * Otherwise, just finish current list[] and start new */
  3235. static int o_save_ptr(o_string *o, int n)
  3236. {
  3237. if (o->o_expflags & EXP_FLAG_GLOB) {
  3238. /* If o->has_empty_slot, list[n] was already globbed
  3239. * (if it was requested back then when it was filled)
  3240. * so don't do that again! */
  3241. if (!o->has_empty_slot)
  3242. return perform_glob(o, n); /* o_save_ptr_helper is inside */
  3243. }
  3244. return o_save_ptr_helper(o, n);
  3245. }
  3246. /* "Please convert list[n] to real char* ptrs, and NULL terminate it." */
  3247. static char **o_finalize_list(o_string *o, int n)
  3248. {
  3249. char **list;
  3250. int string_start;
  3251. if (DEBUG_EXPAND)
  3252. debug_print_list("finalized", o, n);
  3253. debug_printf_expand("finalized n:%d\n", n);
  3254. list = (char**)o->data;
  3255. string_start = ((n + 0xf) & ~0xf) * sizeof(list[0]);
  3256. list[--n] = NULL;
  3257. while (n) {
  3258. n--;
  3259. list[n] = o->data + (int)(uintptr_t)list[n] + string_start;
  3260. }
  3261. return list;
  3262. }
  3263. static void free_pipe_list(struct pipe *pi);
  3264. /* Returns pi->next - next pipe in the list */
  3265. static struct pipe *free_pipe(struct pipe *pi)
  3266. {
  3267. struct pipe *next;
  3268. int i;
  3269. debug_printf_clean("free_pipe (pid %d)\n", getpid());
  3270. for (i = 0; i < pi->num_cmds; i++) {
  3271. struct command *command;
  3272. struct redir_struct *r, *rnext;
  3273. command = &pi->cmds[i];
  3274. debug_printf_clean(" command %d:\n", i);
  3275. if (command->argv) {
  3276. if (DEBUG_CLEAN) {
  3277. int a;
  3278. char **p;
  3279. for (a = 0, p = command->argv; *p; a++, p++) {
  3280. debug_printf_clean(" argv[%d] = %s\n", a, *p);
  3281. }
  3282. }
  3283. free_strings(command->argv);
  3284. //command->argv = NULL;
  3285. }
  3286. /* not "else if": on syntax error, we may have both! */
  3287. if (command->group) {
  3288. debug_printf_clean(" begin group (cmd_type:%d)\n",
  3289. command->cmd_type);
  3290. free_pipe_list(command->group);
  3291. debug_printf_clean(" end group\n");
  3292. //command->group = NULL;
  3293. }
  3294. /* else is crucial here.
  3295. * If group != NULL, child_func is meaningless */
  3296. #if ENABLE_HUSH_FUNCTIONS
  3297. else if (command->child_func) {
  3298. debug_printf_exec("cmd %p releases child func at %p\n", command, command->child_func);
  3299. command->child_func->parent_cmd = NULL;
  3300. }
  3301. #endif
  3302. #if !BB_MMU
  3303. free(command->group_as_string);
  3304. //command->group_as_string = NULL;
  3305. #endif
  3306. for (r = command->redirects; r; r = rnext) {
  3307. debug_printf_clean(" redirect %d%s",
  3308. r->rd_fd, redir_table[r->rd_type].descrip);
  3309. /* guard against the case >$FOO, where foo is unset or blank */
  3310. if (r->rd_filename) {
  3311. debug_printf_clean(" fname:'%s'\n", r->rd_filename);
  3312. free(r->rd_filename);
  3313. //r->rd_filename = NULL;
  3314. }
  3315. debug_printf_clean(" rd_dup:%d\n", r->rd_dup);
  3316. rnext = r->next;
  3317. free(r);
  3318. }
  3319. //command->redirects = NULL;
  3320. }
  3321. free(pi->cmds); /* children are an array, they get freed all at once */
  3322. //pi->cmds = NULL;
  3323. #if ENABLE_HUSH_JOB
  3324. free(pi->cmdtext);
  3325. //pi->cmdtext = NULL;
  3326. #endif
  3327. next = pi->next;
  3328. free(pi);
  3329. return next;
  3330. }
  3331. static void free_pipe_list(struct pipe *pi)
  3332. {
  3333. while (pi) {
  3334. #if HAS_KEYWORDS
  3335. debug_printf_clean("pipe reserved word %d\n", pi->res_word);
  3336. #endif
  3337. debug_printf_clean("pipe followup code %d\n", pi->followup);
  3338. pi = free_pipe(pi);
  3339. }
  3340. }
  3341. /*** Parsing routines ***/
  3342. #ifndef debug_print_tree
  3343. static void debug_print_tree(struct pipe *pi, int lvl)
  3344. {
  3345. static const char *const PIPE[] = {
  3346. [PIPE_SEQ] = "SEQ",
  3347. [PIPE_AND] = "AND",
  3348. [PIPE_OR ] = "OR" ,
  3349. [PIPE_BG ] = "BG" ,
  3350. };
  3351. static const char *RES[] = {
  3352. [RES_NONE ] = "NONE" ,
  3353. # if ENABLE_HUSH_IF
  3354. [RES_IF ] = "IF" ,
  3355. [RES_THEN ] = "THEN" ,
  3356. [RES_ELIF ] = "ELIF" ,
  3357. [RES_ELSE ] = "ELSE" ,
  3358. [RES_FI ] = "FI" ,
  3359. # endif
  3360. # if ENABLE_HUSH_LOOPS
  3361. [RES_FOR ] = "FOR" ,
  3362. [RES_WHILE] = "WHILE",
  3363. [RES_UNTIL] = "UNTIL",
  3364. [RES_DO ] = "DO" ,
  3365. [RES_DONE ] = "DONE" ,
  3366. # endif
  3367. # if ENABLE_HUSH_LOOPS || ENABLE_HUSH_CASE
  3368. [RES_IN ] = "IN" ,
  3369. # endif
  3370. # if ENABLE_HUSH_CASE
  3371. [RES_CASE ] = "CASE" ,
  3372. [RES_CASE_IN ] = "CASE_IN" ,
  3373. [RES_MATCH] = "MATCH",
  3374. [RES_CASE_BODY] = "CASE_BODY",
  3375. [RES_ESAC ] = "ESAC" ,
  3376. # endif
  3377. [RES_XXXX ] = "XXXX" ,
  3378. [RES_SNTX ] = "SNTX" ,
  3379. };
  3380. static const char *const CMDTYPE[] = {
  3381. "{}",
  3382. "()",
  3383. "[noglob]",
  3384. # if ENABLE_HUSH_FUNCTIONS
  3385. "func()",
  3386. # endif
  3387. };
  3388. int pin, prn;
  3389. pin = 0;
  3390. while (pi) {
  3391. fdprintf(2, "%*spipe %d %sres_word=%s followup=%d %s\n",
  3392. lvl*2, "",
  3393. pin,
  3394. (IF_HAS_KEYWORDS(pi->pi_inverted ? "! " :) ""),
  3395. RES[pi->res_word],
  3396. pi->followup, PIPE[pi->followup]
  3397. );
  3398. prn = 0;
  3399. while (prn < pi->num_cmds) {
  3400. struct command *command = &pi->cmds[prn];
  3401. char **argv = command->argv;
  3402. fdprintf(2, "%*s cmd %d assignment_cnt:%d",
  3403. lvl*2, "", prn,
  3404. command->assignment_cnt);
  3405. #if ENABLE_HUSH_LINENO_VAR
  3406. fdprintf(2, " LINENO:%u", command->lineno);
  3407. #endif
  3408. if (command->group) {
  3409. fdprintf(2, " group %s: (argv=%p)%s%s\n",
  3410. CMDTYPE[command->cmd_type],
  3411. argv
  3412. # if !BB_MMU
  3413. , " group_as_string:", command->group_as_string
  3414. # else
  3415. , "", ""
  3416. # endif
  3417. );
  3418. debug_print_tree(command->group, lvl+1);
  3419. prn++;
  3420. continue;
  3421. }
  3422. if (argv) while (*argv) {
  3423. fdprintf(2, " '%s'", *argv);
  3424. argv++;
  3425. }
  3426. if (command->redirects)
  3427. fdprintf(2, " {redir}");
  3428. fdprintf(2, "\n");
  3429. prn++;
  3430. }
  3431. pi = pi->next;
  3432. pin++;
  3433. }
  3434. }
  3435. #endif /* debug_print_tree */
  3436. static struct pipe *new_pipe(void)
  3437. {
  3438. struct pipe *pi;
  3439. pi = xzalloc(sizeof(struct pipe));
  3440. /*pi->res_word = RES_NONE; - RES_NONE is 0 anyway */
  3441. return pi;
  3442. }
  3443. /* Command (member of a pipe) is complete, or we start a new pipe
  3444. * if ctx->command is NULL.
  3445. * No errors possible here.
  3446. */
  3447. static int done_command(struct parse_context *ctx)
  3448. {
  3449. /* The command is really already in the pipe structure, so
  3450. * advance the pipe counter and make a new, null command. */
  3451. struct pipe *pi = ctx->pipe;
  3452. struct command *command = ctx->command;
  3453. #if 0 /* Instead we emit error message at run time */
  3454. if (ctx->pending_redirect) {
  3455. /* For example, "cmd >" (no filename to redirect to) */
  3456. syntax_error("invalid redirect");
  3457. ctx->pending_redirect = NULL;
  3458. }
  3459. #endif
  3460. if (command) {
  3461. if (IS_NULL_CMD(command)) {
  3462. debug_printf_parse("done_command: skipping null cmd, num_cmds=%d\n", pi->num_cmds);
  3463. goto clear_and_ret;
  3464. }
  3465. pi->num_cmds++;
  3466. debug_printf_parse("done_command: ++num_cmds=%d\n", pi->num_cmds);
  3467. //debug_print_tree(ctx->list_head, 20);
  3468. } else {
  3469. debug_printf_parse("done_command: initializing, num_cmds=%d\n", pi->num_cmds);
  3470. }
  3471. /* Only real trickiness here is that the uncommitted
  3472. * command structure is not counted in pi->num_cmds. */
  3473. pi->cmds = xrealloc(pi->cmds, sizeof(*pi->cmds) * (pi->num_cmds+1));
  3474. ctx->command = command = &pi->cmds[pi->num_cmds];
  3475. clear_and_ret:
  3476. memset(command, 0, sizeof(*command));
  3477. #if ENABLE_HUSH_LINENO_VAR
  3478. command->lineno = G.parse_lineno;
  3479. debug_printf_parse("command->lineno = G.parse_lineno (%u)\n", G.parse_lineno);
  3480. #endif
  3481. return pi->num_cmds; /* used only for 0/nonzero check */
  3482. }
  3483. static void done_pipe(struct parse_context *ctx, pipe_style type)
  3484. {
  3485. int not_null;
  3486. debug_printf_parse("done_pipe entered, followup %d\n", type);
  3487. /* Close previous command */
  3488. not_null = done_command(ctx);
  3489. #if HAS_KEYWORDS
  3490. ctx->pipe->pi_inverted = ctx->ctx_inverted;
  3491. ctx->ctx_inverted = 0;
  3492. ctx->pipe->res_word = ctx->ctx_res_w;
  3493. #endif
  3494. if (type == PIPE_BG && ctx->list_head != ctx->pipe) {
  3495. /* Necessary since && and || have precedence over &:
  3496. * "cmd1 && cmd2 &" must spawn both cmds, not only cmd2,
  3497. * in a backgrounded subshell.
  3498. */
  3499. struct pipe *pi;
  3500. struct command *command;
  3501. /* Is this actually this construct, all pipes end with && or ||? */
  3502. pi = ctx->list_head;
  3503. while (pi != ctx->pipe) {
  3504. if (pi->followup != PIPE_AND && pi->followup != PIPE_OR)
  3505. goto no_conv;
  3506. pi = pi->next;
  3507. }
  3508. debug_printf_parse("BG with more than one pipe, converting to { p1 &&...pN; } &\n");
  3509. pi->followup = PIPE_SEQ; /* close pN _not_ with "&"! */
  3510. pi = xzalloc(sizeof(*pi));
  3511. pi->followup = PIPE_BG;
  3512. pi->num_cmds = 1;
  3513. pi->cmds = xzalloc(sizeof(pi->cmds[0]));
  3514. command = &pi->cmds[0];
  3515. if (CMD_NORMAL != 0) /* "if xzalloc didn't do that already" */
  3516. command->cmd_type = CMD_NORMAL;
  3517. command->group = ctx->list_head;
  3518. #if !BB_MMU
  3519. command->group_as_string = xstrndup(
  3520. ctx->as_string.data,
  3521. ctx->as_string.length - 1 /* do not copy last char, "&" */
  3522. );
  3523. #endif
  3524. /* Replace all pipes in ctx with one newly created */
  3525. ctx->list_head = ctx->pipe = pi;
  3526. } else {
  3527. no_conv:
  3528. ctx->pipe->followup = type;
  3529. }
  3530. /* Without this check, even just <enter> on command line generates
  3531. * tree of three NOPs (!). Which is harmless but annoying.
  3532. * IOW: it is safe to do it unconditionally. */
  3533. if (not_null
  3534. #if ENABLE_HUSH_IF
  3535. || ctx->ctx_res_w == RES_FI
  3536. #endif
  3537. #if ENABLE_HUSH_LOOPS
  3538. || ctx->ctx_res_w == RES_DONE
  3539. || ctx->ctx_res_w == RES_FOR
  3540. || ctx->ctx_res_w == RES_IN
  3541. #endif
  3542. #if ENABLE_HUSH_CASE
  3543. || ctx->ctx_res_w == RES_ESAC
  3544. #endif
  3545. ) {
  3546. struct pipe *new_p;
  3547. debug_printf_parse("done_pipe: adding new pipe: "
  3548. "not_null:%d ctx->ctx_res_w:%d\n",
  3549. not_null, ctx->ctx_res_w);
  3550. new_p = new_pipe();
  3551. ctx->pipe->next = new_p;
  3552. ctx->pipe = new_p;
  3553. /* RES_THEN, RES_DO etc are "sticky" -
  3554. * they remain set for pipes inside if/while.
  3555. * This is used to control execution.
  3556. * RES_FOR and RES_IN are NOT sticky (needed to support
  3557. * cases where variable or value happens to match a keyword):
  3558. */
  3559. #if ENABLE_HUSH_LOOPS
  3560. if (ctx->ctx_res_w == RES_FOR
  3561. || ctx->ctx_res_w == RES_IN)
  3562. ctx->ctx_res_w = RES_NONE;
  3563. #endif
  3564. #if ENABLE_HUSH_CASE
  3565. if (ctx->ctx_res_w == RES_MATCH)
  3566. ctx->ctx_res_w = RES_CASE_BODY;
  3567. if (ctx->ctx_res_w == RES_CASE)
  3568. ctx->ctx_res_w = RES_CASE_IN;
  3569. #endif
  3570. ctx->command = NULL; /* trick done_command below */
  3571. /* Create the memory for command, roughly:
  3572. * ctx->pipe->cmds = new struct command;
  3573. * ctx->command = &ctx->pipe->cmds[0];
  3574. */
  3575. done_command(ctx);
  3576. //debug_print_tree(ctx->list_head, 10);
  3577. }
  3578. debug_printf_parse("done_pipe return\n");
  3579. }
  3580. static void initialize_context(struct parse_context *ctx)
  3581. {
  3582. memset(ctx, 0, sizeof(*ctx));
  3583. if (MAYBE_ASSIGNMENT != 0)
  3584. ctx->is_assignment = MAYBE_ASSIGNMENT;
  3585. ctx->pipe = ctx->list_head = new_pipe();
  3586. /* Create the memory for command, roughly:
  3587. * ctx->pipe->cmds = new struct command;
  3588. * ctx->command = &ctx->pipe->cmds[0];
  3589. */
  3590. done_command(ctx);
  3591. }
  3592. /* If a reserved word is found and processed, parse context is modified
  3593. * and 1 is returned.
  3594. */
  3595. #if HAS_KEYWORDS
  3596. struct reserved_combo {
  3597. char literal[6];
  3598. unsigned char res;
  3599. unsigned char assignment_flag;
  3600. int flag;
  3601. };
  3602. enum {
  3603. FLAG_END = (1 << RES_NONE ),
  3604. # if ENABLE_HUSH_IF
  3605. FLAG_IF = (1 << RES_IF ),
  3606. FLAG_THEN = (1 << RES_THEN ),
  3607. FLAG_ELIF = (1 << RES_ELIF ),
  3608. FLAG_ELSE = (1 << RES_ELSE ),
  3609. FLAG_FI = (1 << RES_FI ),
  3610. # endif
  3611. # if ENABLE_HUSH_LOOPS
  3612. FLAG_FOR = (1 << RES_FOR ),
  3613. FLAG_WHILE = (1 << RES_WHILE),
  3614. FLAG_UNTIL = (1 << RES_UNTIL),
  3615. FLAG_DO = (1 << RES_DO ),
  3616. FLAG_DONE = (1 << RES_DONE ),
  3617. FLAG_IN = (1 << RES_IN ),
  3618. # endif
  3619. # if ENABLE_HUSH_CASE
  3620. FLAG_MATCH = (1 << RES_MATCH),
  3621. FLAG_ESAC = (1 << RES_ESAC ),
  3622. # endif
  3623. FLAG_START = (1 << RES_XXXX ),
  3624. };
  3625. static const struct reserved_combo* match_reserved_word(o_string *word)
  3626. {
  3627. /* Mostly a list of accepted follow-up reserved words.
  3628. * FLAG_END means we are done with the sequence, and are ready
  3629. * to turn the compound list into a command.
  3630. * FLAG_START means the word must start a new compound list.
  3631. */
  3632. static const struct reserved_combo reserved_list[] = {
  3633. # if ENABLE_HUSH_IF
  3634. { "!", RES_NONE, NOT_ASSIGNMENT , 0 },
  3635. { "if", RES_IF, MAYBE_ASSIGNMENT, FLAG_THEN | FLAG_START },
  3636. { "then", RES_THEN, MAYBE_ASSIGNMENT, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
  3637. { "elif", RES_ELIF, MAYBE_ASSIGNMENT, FLAG_THEN },
  3638. { "else", RES_ELSE, MAYBE_ASSIGNMENT, FLAG_FI },
  3639. { "fi", RES_FI, NOT_ASSIGNMENT , FLAG_END },
  3640. # endif
  3641. # if ENABLE_HUSH_LOOPS
  3642. { "for", RES_FOR, NOT_ASSIGNMENT , FLAG_IN | FLAG_DO | FLAG_START },
  3643. { "while", RES_WHILE, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
  3644. { "until", RES_UNTIL, MAYBE_ASSIGNMENT, FLAG_DO | FLAG_START },
  3645. { "in", RES_IN, NOT_ASSIGNMENT , FLAG_DO },
  3646. { "do", RES_DO, MAYBE_ASSIGNMENT, FLAG_DONE },
  3647. { "done", RES_DONE, NOT_ASSIGNMENT , FLAG_END },
  3648. # endif
  3649. # if ENABLE_HUSH_CASE
  3650. { "case", RES_CASE, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_START },
  3651. { "esac", RES_ESAC, NOT_ASSIGNMENT , FLAG_END },
  3652. # endif
  3653. };
  3654. const struct reserved_combo *r;
  3655. for (r = reserved_list; r < reserved_list + ARRAY_SIZE(reserved_list); r++) {
  3656. if (strcmp(word->data, r->literal) == 0)
  3657. return r;
  3658. }
  3659. return NULL;
  3660. }
  3661. /* Return NULL: not a keyword, else: keyword
  3662. */
  3663. static const struct reserved_combo* reserved_word(struct parse_context *ctx)
  3664. {
  3665. # if ENABLE_HUSH_CASE
  3666. static const struct reserved_combo reserved_match = {
  3667. "", RES_MATCH, NOT_ASSIGNMENT , FLAG_MATCH | FLAG_ESAC
  3668. };
  3669. # endif
  3670. const struct reserved_combo *r;
  3671. if (ctx->word.has_quoted_part)
  3672. return 0;
  3673. r = match_reserved_word(&ctx->word);
  3674. if (!r)
  3675. return r; /* NULL */
  3676. debug_printf("found reserved word %s, res %d\n", r->literal, r->res);
  3677. # if ENABLE_HUSH_CASE
  3678. if (r->res == RES_IN && ctx->ctx_res_w == RES_CASE_IN) {
  3679. /* "case word IN ..." - IN part starts first MATCH part */
  3680. r = &reserved_match;
  3681. } else
  3682. # endif
  3683. if (r->flag == 0) { /* '!' */
  3684. if (ctx->ctx_inverted) { /* bash doesn't accept '! ! true' */
  3685. syntax_error("! ! command");
  3686. ctx->ctx_res_w = RES_SNTX;
  3687. }
  3688. ctx->ctx_inverted = 1;
  3689. return r;
  3690. }
  3691. if (r->flag & FLAG_START) {
  3692. struct parse_context *old;
  3693. old = xmemdup(ctx, sizeof(*ctx));
  3694. debug_printf_parse("push stack %p\n", old);
  3695. initialize_context(ctx);
  3696. ctx->stack = old;
  3697. } else if (/*ctx->ctx_res_w == RES_NONE ||*/ !(ctx->old_flag & (1 << r->res))) {
  3698. syntax_error_at(ctx->word.data);
  3699. ctx->ctx_res_w = RES_SNTX;
  3700. return r;
  3701. } else {
  3702. /* "{...} fi" is ok. "{...} if" is not
  3703. * Example:
  3704. * if { echo foo; } then { echo bar; } fi */
  3705. if (ctx->command->group)
  3706. done_pipe(ctx, PIPE_SEQ);
  3707. }
  3708. ctx->ctx_res_w = r->res;
  3709. ctx->old_flag = r->flag;
  3710. ctx->is_assignment = r->assignment_flag;
  3711. debug_printf_parse("ctx->is_assignment='%s'\n", assignment_flag[ctx->is_assignment]);
  3712. if (ctx->old_flag & FLAG_END) {
  3713. struct parse_context *old;
  3714. done_pipe(ctx, PIPE_SEQ);
  3715. debug_printf_parse("pop stack %p\n", ctx->stack);
  3716. old = ctx->stack;
  3717. old->command->group = ctx->list_head;
  3718. old->command->cmd_type = CMD_NORMAL;
  3719. # if !BB_MMU
  3720. /* At this point, the compound command's string is in
  3721. * ctx->as_string... except for the leading keyword!
  3722. * Consider this example: "echo a | if true; then echo a; fi"
  3723. * ctx->as_string will contain "true; then echo a; fi",
  3724. * with "if " remaining in old->as_string!
  3725. */
  3726. {
  3727. char *str;
  3728. int len = old->as_string.length;
  3729. /* Concatenate halves */
  3730. o_addstr(&old->as_string, ctx->as_string.data);
  3731. o_free(&ctx->as_string);
  3732. /* Find where leading keyword starts in first half */
  3733. str = old->as_string.data + len;
  3734. if (str > old->as_string.data)
  3735. str--; /* skip whitespace after keyword */
  3736. while (str > old->as_string.data && isalpha(str[-1]))
  3737. str--;
  3738. /* Ugh, we're done with this horrid hack */
  3739. old->command->group_as_string = xstrdup(str);
  3740. debug_printf_parse("pop, remembering as:'%s'\n",
  3741. old->command->group_as_string);
  3742. }
  3743. # endif
  3744. *ctx = *old; /* physical copy */
  3745. free(old);
  3746. }
  3747. return r;
  3748. }
  3749. #endif /* HAS_KEYWORDS */
  3750. /* Word is complete, look at it and update parsing context.
  3751. * Normal return is 0. Syntax errors return 1.
  3752. * Note: on return, word is reset, but not o_free'd!
  3753. */
  3754. static int done_word(struct parse_context *ctx)
  3755. {
  3756. struct command *command = ctx->command;
  3757. debug_printf_parse("done_word entered: '%s' %p\n", ctx->word.data, command);
  3758. if (ctx->word.length == 0 && !ctx->word.has_quoted_part) {
  3759. debug_printf_parse("done_word return 0: true null, ignored\n");
  3760. return 0;
  3761. }
  3762. if (ctx->pending_redirect) {
  3763. /* We do not glob in e.g. >*.tmp case. bash seems to glob here
  3764. * only if run as "bash", not "sh" */
  3765. /* http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
  3766. * "2.7 Redirection
  3767. * If the redirection operator is "<<" or "<<-", the word
  3768. * that follows the redirection operator shall be
  3769. * subjected to quote removal; it is unspecified whether
  3770. * any of the other expansions occur. For the other
  3771. * redirection operators, the word that follows the
  3772. * redirection operator shall be subjected to tilde
  3773. * expansion, parameter expansion, command substitution,
  3774. * arithmetic expansion, and quote removal.
  3775. * Pathname expansion shall not be performed
  3776. * on the word by a non-interactive shell; an interactive
  3777. * shell may perform it, but shall do so only when
  3778. * the expansion would result in one word."
  3779. */
  3780. //bash does not do parameter/command substitution or arithmetic expansion
  3781. //for _heredoc_ redirection word: these constructs look for exact eof marker
  3782. // as written:
  3783. // <<EOF$t
  3784. // <<EOF$((1))
  3785. // <<EOF`true` [this case also makes heredoc "quoted", a-la <<"EOF". Probably bash-4.3.43 bug]
  3786. ctx->pending_redirect->rd_filename = xstrdup(ctx->word.data);
  3787. /* Cater for >\file case:
  3788. * >\a creates file a; >\\a, >"\a", >"\\a" create file \a
  3789. * Same with heredocs:
  3790. * for <<\H delim is H; <<\\H, <<"\H", <<"\\H" - \H
  3791. */
  3792. if (ctx->pending_redirect->rd_type == REDIRECT_HEREDOC) {
  3793. unbackslash(ctx->pending_redirect->rd_filename);
  3794. /* Is it <<"HEREDOC"? */
  3795. if (ctx->word.has_quoted_part) {
  3796. ctx->pending_redirect->rd_dup |= HEREDOC_QUOTED;
  3797. }
  3798. }
  3799. debug_printf_parse("word stored in rd_filename: '%s'\n", ctx->word.data);
  3800. ctx->pending_redirect = NULL;
  3801. } else {
  3802. #if HAS_KEYWORDS
  3803. # if ENABLE_HUSH_CASE
  3804. if (ctx->ctx_dsemicolon
  3805. && strcmp(ctx->word.data, "esac") != 0 /* not "... pattern) cmd;; esac" */
  3806. ) {
  3807. /* already done when ctx_dsemicolon was set to 1: */
  3808. /* ctx->ctx_res_w = RES_MATCH; */
  3809. ctx->ctx_dsemicolon = 0;
  3810. } else
  3811. # endif
  3812. if (!command->argv /* if it's the first word... */
  3813. # if ENABLE_HUSH_LOOPS
  3814. && ctx->ctx_res_w != RES_FOR /* ...not after FOR or IN */
  3815. && ctx->ctx_res_w != RES_IN
  3816. # endif
  3817. # if ENABLE_HUSH_CASE
  3818. && ctx->ctx_res_w != RES_CASE
  3819. # endif
  3820. ) {
  3821. const struct reserved_combo *reserved;
  3822. reserved = reserved_word(ctx);
  3823. debug_printf_parse("checking for reserved-ness: %d\n", !!reserved);
  3824. if (reserved) {
  3825. # if ENABLE_HUSH_LINENO_VAR
  3826. /* Case:
  3827. * "while ...; do
  3828. * cmd ..."
  3829. * If we don't close the pipe _now_, immediately after "do", lineno logic
  3830. * sees "cmd" as starting at "do" - i.e., at the previous line.
  3831. */
  3832. if (0
  3833. IF_HUSH_IF(|| reserved->res == RES_THEN)
  3834. IF_HUSH_IF(|| reserved->res == RES_ELIF)
  3835. IF_HUSH_IF(|| reserved->res == RES_ELSE)
  3836. IF_HUSH_LOOPS(|| reserved->res == RES_DO)
  3837. ) {
  3838. done_pipe(ctx, PIPE_SEQ);
  3839. }
  3840. # endif
  3841. o_reset_to_empty_unquoted(&ctx->word);
  3842. debug_printf_parse("done_word return %d\n",
  3843. (ctx->ctx_res_w == RES_SNTX));
  3844. return (ctx->ctx_res_w == RES_SNTX);
  3845. }
  3846. # if defined(CMD_SINGLEWORD_NOGLOB)
  3847. if (0
  3848. # if BASH_TEST2
  3849. || strcmp(ctx->word.data, "[[") == 0
  3850. # endif
  3851. /* In bash, local/export/readonly are special, args
  3852. * are assignments and therefore expansion of them
  3853. * should be "one-word" expansion:
  3854. * $ export i=`echo 'a b'` # one arg: "i=a b"
  3855. * compare with:
  3856. * $ ls i=`echo 'a b'` # two args: "i=a" and "b"
  3857. * ls: cannot access i=a: No such file or directory
  3858. * ls: cannot access b: No such file or directory
  3859. * Note: bash 3.2.33(1) does this only if export word
  3860. * itself is not quoted:
  3861. * $ export i=`echo 'aaa bbb'`; echo "$i"
  3862. * aaa bbb
  3863. * $ "export" i=`echo 'aaa bbb'`; echo "$i"
  3864. * aaa
  3865. */
  3866. IF_HUSH_LOCAL( || strcmp(ctx->word.data, "local") == 0)
  3867. IF_HUSH_EXPORT( || strcmp(ctx->word.data, "export") == 0)
  3868. IF_HUSH_READONLY(|| strcmp(ctx->word.data, "readonly") == 0)
  3869. ) {
  3870. command->cmd_type = CMD_SINGLEWORD_NOGLOB;
  3871. }
  3872. /* fall through */
  3873. # endif
  3874. }
  3875. #endif /* HAS_KEYWORDS */
  3876. if (command->group) {
  3877. /* "{ echo foo; } echo bar" - bad */
  3878. syntax_error_at(ctx->word.data);
  3879. debug_printf_parse("done_word return 1: syntax error, "
  3880. "groups and arglists don't mix\n");
  3881. return 1;
  3882. }
  3883. /* If this word wasn't an assignment, next ones definitely
  3884. * can't be assignments. Even if they look like ones. */
  3885. if (ctx->is_assignment != DEFINITELY_ASSIGNMENT
  3886. && ctx->is_assignment != WORD_IS_KEYWORD
  3887. ) {
  3888. ctx->is_assignment = NOT_ASSIGNMENT;
  3889. } else {
  3890. if (ctx->is_assignment == DEFINITELY_ASSIGNMENT) {
  3891. command->assignment_cnt++;
  3892. debug_printf_parse("++assignment_cnt=%d\n", command->assignment_cnt);
  3893. }
  3894. debug_printf_parse("ctx->is_assignment was:'%s'\n", assignment_flag[ctx->is_assignment]);
  3895. ctx->is_assignment = MAYBE_ASSIGNMENT;
  3896. }
  3897. debug_printf_parse("ctx->is_assignment='%s'\n", assignment_flag[ctx->is_assignment]);
  3898. command->argv = add_string_to_strings(command->argv, xstrdup(ctx->word.data));
  3899. debug_print_strings("word appended to argv", command->argv);
  3900. }
  3901. #if ENABLE_HUSH_LOOPS
  3902. if (ctx->ctx_res_w == RES_FOR) {
  3903. if (ctx->word.has_quoted_part
  3904. || endofname(command->argv[0])[0] != '\0'
  3905. ) {
  3906. /* bash says just "not a valid identifier" */
  3907. syntax_error("not a valid identifier in for");
  3908. return 1;
  3909. }
  3910. /* Force FOR to have just one word (variable name) */
  3911. /* NB: basically, this makes hush see "for v in ..."
  3912. * syntax as if it is "for v; in ...". FOR and IN become
  3913. * two pipe structs in parse tree. */
  3914. done_pipe(ctx, PIPE_SEQ);
  3915. }
  3916. #endif
  3917. #if ENABLE_HUSH_CASE
  3918. /* Force CASE to have just one word */
  3919. if (ctx->ctx_res_w == RES_CASE) {
  3920. done_pipe(ctx, PIPE_SEQ);
  3921. }
  3922. #endif
  3923. o_reset_to_empty_unquoted(&ctx->word);
  3924. debug_printf_parse("done_word return 0\n");
  3925. return 0;
  3926. }
  3927. /* Peek ahead in the input to find out if we have a "&n" construct,
  3928. * as in "2>&1", that represents duplicating a file descriptor.
  3929. * Return:
  3930. * REDIRFD_CLOSE if >&- "close fd" construct is seen,
  3931. * REDIRFD_SYNTAX_ERR if syntax error,
  3932. * REDIRFD_TO_FILE if no & was seen,
  3933. * or the number found.
  3934. */
  3935. #if BB_MMU
  3936. #define parse_redir_right_fd(as_string, input) \
  3937. parse_redir_right_fd(input)
  3938. #endif
  3939. static int parse_redir_right_fd(o_string *as_string, struct in_str *input)
  3940. {
  3941. int ch, d, ok;
  3942. ch = i_peek(input);
  3943. if (ch != '&')
  3944. return REDIRFD_TO_FILE;
  3945. ch = i_getch(input); /* get the & */
  3946. nommu_addchr(as_string, ch);
  3947. ch = i_peek(input);
  3948. if (ch == '-') {
  3949. ch = i_getch(input);
  3950. nommu_addchr(as_string, ch);
  3951. return REDIRFD_CLOSE;
  3952. }
  3953. d = 0;
  3954. ok = 0;
  3955. while (ch != EOF && isdigit(ch)) {
  3956. d = d*10 + (ch-'0');
  3957. ok = 1;
  3958. ch = i_getch(input);
  3959. nommu_addchr(as_string, ch);
  3960. ch = i_peek(input);
  3961. }
  3962. if (ok) return d;
  3963. //TODO: this is the place to catch ">&file" bashism (redirect both fd 1 and 2)
  3964. bb_error_msg("ambiguous redirect");
  3965. return REDIRFD_SYNTAX_ERR;
  3966. }
  3967. /* Return code is 0 normal, 1 if a syntax error is detected
  3968. */
  3969. static int parse_redirect(struct parse_context *ctx,
  3970. int fd,
  3971. redir_type style,
  3972. struct in_str *input)
  3973. {
  3974. struct command *command = ctx->command;
  3975. struct redir_struct *redir;
  3976. struct redir_struct **redirp;
  3977. int dup_num;
  3978. dup_num = REDIRFD_TO_FILE;
  3979. if (style != REDIRECT_HEREDOC) {
  3980. /* Check for a '>&1' type redirect */
  3981. dup_num = parse_redir_right_fd(&ctx->as_string, input);
  3982. if (dup_num == REDIRFD_SYNTAX_ERR)
  3983. return 1;
  3984. } else {
  3985. int ch = i_peek_and_eat_bkslash_nl(input);
  3986. dup_num = (ch == '-'); /* HEREDOC_SKIPTABS bit is 1 */
  3987. if (dup_num) { /* <<-... */
  3988. ch = i_getch(input);
  3989. nommu_addchr(&ctx->as_string, ch);
  3990. ch = i_peek(input);
  3991. }
  3992. }
  3993. if (style == REDIRECT_OVERWRITE && dup_num == REDIRFD_TO_FILE) {
  3994. int ch = i_peek_and_eat_bkslash_nl(input);
  3995. if (ch == '|') {
  3996. /* >|FILE redirect ("clobbering" >).
  3997. * Since we do not support "set -o noclobber" yet,
  3998. * >| and > are the same for now. Just eat |.
  3999. */
  4000. ch = i_getch(input);
  4001. nommu_addchr(&ctx->as_string, ch);
  4002. }
  4003. }
  4004. /* Create a new redir_struct and append it to the linked list */
  4005. redirp = &command->redirects;
  4006. while ((redir = *redirp) != NULL) {
  4007. redirp = &(redir->next);
  4008. }
  4009. *redirp = redir = xzalloc(sizeof(*redir));
  4010. /* redir->next = NULL; */
  4011. /* redir->rd_filename = NULL; */
  4012. redir->rd_type = style;
  4013. redir->rd_fd = (fd == -1) ? redir_table[style].default_fd : fd;
  4014. debug_printf_parse("redirect type %d %s\n", redir->rd_fd,
  4015. redir_table[style].descrip);
  4016. redir->rd_dup = dup_num;
  4017. if (style != REDIRECT_HEREDOC && dup_num != REDIRFD_TO_FILE) {
  4018. /* Erik had a check here that the file descriptor in question
  4019. * is legit; I postpone that to "run time"
  4020. * A "-" representation of "close me" shows up as a -3 here */
  4021. debug_printf_parse("duplicating redirect '%d>&%d'\n",
  4022. redir->rd_fd, redir->rd_dup);
  4023. } else {
  4024. #if 0 /* Instead we emit error message at run time */
  4025. if (ctx->pending_redirect) {
  4026. /* For example, "cmd > <file" */
  4027. syntax_error("invalid redirect");
  4028. }
  4029. #endif
  4030. /* Set ctx->pending_redirect, so we know what to do at the
  4031. * end of the next parsed word. */
  4032. ctx->pending_redirect = redir;
  4033. }
  4034. return 0;
  4035. }
  4036. /* If a redirect is immediately preceded by a number, that number is
  4037. * supposed to tell which file descriptor to redirect. This routine
  4038. * looks for such preceding numbers. In an ideal world this routine
  4039. * needs to handle all the following classes of redirects...
  4040. * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
  4041. * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
  4042. * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
  4043. * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
  4044. *
  4045. * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html
  4046. * "2.7 Redirection
  4047. * ... If n is quoted, the number shall not be recognized as part of
  4048. * the redirection expression. For example:
  4049. * echo \2>a
  4050. * writes the character 2 into file a"
  4051. * We are getting it right by setting ->has_quoted_part on any \<char>
  4052. *
  4053. * A -1 return means no valid number was found,
  4054. * the caller should use the appropriate default for this redirection.
  4055. */
  4056. static int redirect_opt_num(o_string *o)
  4057. {
  4058. int num;
  4059. if (o->data == NULL)
  4060. return -1;
  4061. num = bb_strtou(o->data, NULL, 10);
  4062. if (errno || num < 0)
  4063. return -1;
  4064. o_reset_to_empty_unquoted(o);
  4065. return num;
  4066. }
  4067. #if BB_MMU
  4068. #define fetch_till_str(as_string, input, word, skip_tabs) \
  4069. fetch_till_str(input, word, skip_tabs)
  4070. #endif
  4071. static char *fetch_till_str(o_string *as_string,
  4072. struct in_str *input,
  4073. const char *word,
  4074. int heredoc_flags)
  4075. {
  4076. o_string heredoc = NULL_O_STRING;
  4077. unsigned past_EOL;
  4078. int prev = 0; /* not \ */
  4079. int ch;
  4080. /* Starting with "" is necessary for this case:
  4081. * cat <<EOF
  4082. *
  4083. * xxx
  4084. * EOF
  4085. */
  4086. heredoc.data = xzalloc(1); /* start as "", not as NULL */
  4087. goto jump_in;
  4088. while (1) {
  4089. ch = i_getch(input);
  4090. if (ch != EOF)
  4091. nommu_addchr(as_string, ch);
  4092. if (ch == '\n' || ch == EOF) {
  4093. check_heredoc_end:
  4094. if ((heredoc_flags & HEREDOC_QUOTED) || prev != '\\') {
  4095. /* End-of-line, and not a line continuation */
  4096. if (strcmp(heredoc.data + past_EOL, word) == 0) {
  4097. heredoc.data[past_EOL] = '\0';
  4098. debug_printf_heredoc("parsed '%s' heredoc '%s'\n", word, heredoc.data);
  4099. return heredoc.data;
  4100. }
  4101. if (ch == '\n') {
  4102. /* This is a new line.
  4103. * Remember position and backslash-escaping status.
  4104. */
  4105. o_addchr(&heredoc, ch);
  4106. prev = ch;
  4107. jump_in:
  4108. past_EOL = heredoc.length;
  4109. /* Get 1st char of next line, possibly skipping leading tabs */
  4110. do {
  4111. ch = i_getch(input);
  4112. if (ch != EOF)
  4113. nommu_addchr(as_string, ch);
  4114. } while ((heredoc_flags & HEREDOC_SKIPTABS) && ch == '\t');
  4115. /* If this immediately ended the line,
  4116. * go back to end-of-line checks.
  4117. */
  4118. if (ch == '\n')
  4119. goto check_heredoc_end;
  4120. }
  4121. } else {
  4122. /* Backslash-line continuation in an unquoted
  4123. * heredoc. This does not need special handling
  4124. * for heredoc body (unquoted heredocs are
  4125. * expanded on "execution" and that would take
  4126. * care of this case too), but not the case
  4127. * of line continuation *in terminator*:
  4128. * cat <<EOF
  4129. * Ok1
  4130. * EO\
  4131. * F
  4132. */
  4133. heredoc.data[--heredoc.length] = '\0';
  4134. prev = 0; /* not '\' */
  4135. continue;
  4136. }
  4137. }
  4138. if (ch == EOF) {
  4139. o_free(&heredoc);
  4140. return NULL; /* error */
  4141. }
  4142. o_addchr(&heredoc, ch);
  4143. nommu_addchr(as_string, ch);
  4144. if (prev == '\\' && ch == '\\')
  4145. /* Correctly handle foo\\<eol> (not a line cont.) */
  4146. prev = 0; /* not '\' */
  4147. else
  4148. prev = ch;
  4149. }
  4150. }
  4151. /* Look at entire parse tree for not-yet-loaded REDIRECT_HEREDOCs
  4152. * and load them all. There should be exactly heredoc_cnt of them.
  4153. */
  4154. #if BB_MMU
  4155. #define fetch_heredocs(as_string, pi, heredoc_cnt, input) \
  4156. fetch_heredocs(pi, heredoc_cnt, input)
  4157. #endif
  4158. static int fetch_heredocs(o_string *as_string, struct pipe *pi, int heredoc_cnt, struct in_str *input)
  4159. {
  4160. while (pi && heredoc_cnt) {
  4161. int i;
  4162. struct command *cmd = pi->cmds;
  4163. debug_printf_heredoc("fetch_heredocs: num_cmds:%d cmd argv0:'%s'\n",
  4164. pi->num_cmds,
  4165. cmd->argv ? cmd->argv[0] : "NONE"
  4166. );
  4167. for (i = 0; i < pi->num_cmds; i++) {
  4168. struct redir_struct *redir = cmd->redirects;
  4169. debug_printf_heredoc("fetch_heredocs: %d cmd argv0:'%s'\n",
  4170. i, cmd->argv ? cmd->argv[0] : "NONE");
  4171. while (redir) {
  4172. if (redir->rd_type == REDIRECT_HEREDOC) {
  4173. char *p;
  4174. redir->rd_type = REDIRECT_HEREDOC2;
  4175. /* redir->rd_dup is (ab)used to indicate <<- */
  4176. p = fetch_till_str(as_string, input,
  4177. redir->rd_filename, redir->rd_dup);
  4178. if (!p) {
  4179. syntax_error("unexpected EOF in here document");
  4180. return -1;
  4181. }
  4182. free(redir->rd_filename);
  4183. redir->rd_filename = p;
  4184. heredoc_cnt--;
  4185. }
  4186. redir = redir->next;
  4187. }
  4188. if (cmd->group) {
  4189. //bb_error_msg("%s:%u heredoc_cnt:%d", __func__, __LINE__, heredoc_cnt);
  4190. heredoc_cnt = fetch_heredocs(as_string, cmd->group, heredoc_cnt, input);
  4191. //bb_error_msg("%s:%u heredoc_cnt:%d", __func__, __LINE__, heredoc_cnt);
  4192. if (heredoc_cnt < 0)
  4193. return heredoc_cnt; /* error */
  4194. }
  4195. cmd++;
  4196. }
  4197. pi = pi->next;
  4198. }
  4199. return heredoc_cnt;
  4200. }
  4201. static int run_list(struct pipe *pi);
  4202. #if BB_MMU
  4203. #define parse_stream(pstring, heredoc_cnt_ptr, input, end_trigger) \
  4204. parse_stream(heredoc_cnt_ptr, input, end_trigger)
  4205. #endif
  4206. static struct pipe *parse_stream(char **pstring,
  4207. int *heredoc_cnt_ptr,
  4208. struct in_str *input,
  4209. int end_trigger);
  4210. /* Returns number of heredocs not yet consumed,
  4211. * or -1 on error.
  4212. */
  4213. static int parse_group(struct parse_context *ctx,
  4214. struct in_str *input, int ch)
  4215. {
  4216. /* ctx->word contains characters seen prior to ( or {.
  4217. * Typically it's empty, but for function defs,
  4218. * it contains function name (without '()'). */
  4219. #if BB_MMU
  4220. # define as_string NULL
  4221. #else
  4222. char *as_string = NULL;
  4223. #endif
  4224. struct pipe *pipe_list;
  4225. int heredoc_cnt = 0;
  4226. int endch;
  4227. struct command *command = ctx->command;
  4228. debug_printf_parse("parse_group entered\n");
  4229. #if ENABLE_HUSH_FUNCTIONS
  4230. if (ch == '(' && !ctx->word.has_quoted_part) {
  4231. if (ctx->word.length)
  4232. if (done_word(ctx))
  4233. return -1;
  4234. if (!command->argv)
  4235. goto skip; /* (... */
  4236. if (command->argv[1]) { /* word word ... (... */
  4237. syntax_error_unexpected_ch('(');
  4238. return -1;
  4239. }
  4240. /* it is "word(..." or "word (..." */
  4241. do
  4242. ch = i_getch(input);
  4243. while (ch == ' ' || ch == '\t');
  4244. if (ch != ')') {
  4245. syntax_error_unexpected_ch(ch);
  4246. return -1;
  4247. }
  4248. nommu_addchr(&ctx->as_string, ch);
  4249. do
  4250. ch = i_getch(input);
  4251. while (ch == ' ' || ch == '\t' || ch == '\n');
  4252. if (ch != '{' && ch != '(') {
  4253. syntax_error_unexpected_ch(ch);
  4254. return -1;
  4255. }
  4256. nommu_addchr(&ctx->as_string, ch);
  4257. command->cmd_type = CMD_FUNCDEF;
  4258. goto skip;
  4259. }
  4260. #endif
  4261. #if 0 /* Prevented by caller */
  4262. if (command->argv /* word [word]{... */
  4263. || ctx->word.length /* word{... */
  4264. || ctx->word.has_quoted_part /* ""{... */
  4265. ) {
  4266. syntax_error(NULL);
  4267. debug_printf_parse("parse_group return -1: "
  4268. "syntax error, groups and arglists don't mix\n");
  4269. return -1;
  4270. }
  4271. #endif
  4272. IF_HUSH_FUNCTIONS(skip:)
  4273. endch = '}';
  4274. if (ch == '(') {
  4275. endch = ')';
  4276. IF_HUSH_FUNCTIONS(if (command->cmd_type != CMD_FUNCDEF))
  4277. command->cmd_type = CMD_SUBSHELL;
  4278. } else {
  4279. /* bash does not allow "{echo...", requires whitespace */
  4280. ch = i_peek(input);
  4281. if (ch != ' ' && ch != '\t' && ch != '\n'
  4282. && ch != '(' /* but "{(..." is allowed (without whitespace) */
  4283. ) {
  4284. syntax_error_unexpected_ch(ch);
  4285. return -1;
  4286. }
  4287. if (ch != '(') {
  4288. ch = i_getch(input);
  4289. nommu_addchr(&ctx->as_string, ch);
  4290. }
  4291. }
  4292. debug_printf_heredoc("calling parse_stream, heredoc_cnt:%d\n", heredoc_cnt);
  4293. pipe_list = parse_stream(&as_string, &heredoc_cnt, input, endch);
  4294. debug_printf_heredoc("parse_stream returned: heredoc_cnt:%d\n", heredoc_cnt);
  4295. #if !BB_MMU
  4296. if (as_string)
  4297. o_addstr(&ctx->as_string, as_string);
  4298. #endif
  4299. /* empty ()/{} or parse error? */
  4300. if (!pipe_list || pipe_list == ERR_PTR) {
  4301. /* parse_stream already emitted error msg */
  4302. if (!BB_MMU)
  4303. free(as_string);
  4304. debug_printf_parse("parse_group return -1: "
  4305. "parse_stream returned %p\n", pipe_list);
  4306. return -1;
  4307. }
  4308. #if !BB_MMU
  4309. as_string[strlen(as_string) - 1] = '\0'; /* plink ')' or '}' */
  4310. command->group_as_string = as_string;
  4311. debug_printf_parse("end of group, remembering as:'%s'\n",
  4312. command->group_as_string);
  4313. #endif
  4314. #if ENABLE_HUSH_FUNCTIONS
  4315. /* Convert "f() (cmds)" to "f() {(cmds)}" */
  4316. if (command->cmd_type == CMD_FUNCDEF && endch == ')') {
  4317. struct command *cmd2;
  4318. cmd2 = xzalloc(sizeof(*cmd2));
  4319. cmd2->cmd_type = CMD_SUBSHELL;
  4320. cmd2->group = pipe_list;
  4321. # if !BB_MMU
  4322. //UNTESTED!
  4323. cmd2->group_as_string = command->group_as_string;
  4324. command->group_as_string = xasprintf("(%s)", command->group_as_string);
  4325. # endif
  4326. pipe_list = new_pipe();
  4327. pipe_list->cmds = cmd2;
  4328. pipe_list->num_cmds = 1;
  4329. }
  4330. #endif
  4331. command->group = pipe_list;
  4332. debug_printf_parse("parse_group return %d\n", heredoc_cnt);
  4333. return heredoc_cnt;
  4334. /* command remains "open", available for possible redirects */
  4335. #undef as_string
  4336. }
  4337. #if ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS
  4338. /* Subroutines for copying $(...) and `...` things */
  4339. /* '...' */
  4340. static int add_till_single_quote(o_string *dest, struct in_str *input)
  4341. {
  4342. while (1) {
  4343. int ch = i_getch(input);
  4344. if (ch == EOF) {
  4345. syntax_error_unterm_ch('\'');
  4346. return 0;
  4347. }
  4348. if (ch == '\'')
  4349. return 1;
  4350. o_addchr(dest, ch);
  4351. }
  4352. }
  4353. static int add_till_single_quote_dquoted(o_string *dest, struct in_str *input)
  4354. {
  4355. while (1) {
  4356. int ch = i_getch(input);
  4357. if (ch == EOF) {
  4358. syntax_error_unterm_ch('\'');
  4359. return 0;
  4360. }
  4361. if (ch == '\'')
  4362. return 1;
  4363. o_addqchr(dest, ch);
  4364. }
  4365. }
  4366. /* "...\"...`..`...." - do we need to handle "...$(..)..." too? */
  4367. static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote);
  4368. static int add_till_double_quote(o_string *dest, struct in_str *input)
  4369. {
  4370. while (1) {
  4371. int ch = i_getch(input);
  4372. if (ch == EOF) {
  4373. syntax_error_unterm_ch('"');
  4374. return 0;
  4375. }
  4376. if (ch == '"')
  4377. return 1;
  4378. if (ch == '\\') { /* \x. Copy both chars. */
  4379. o_addchr(dest, ch);
  4380. ch = i_getch(input);
  4381. }
  4382. o_addchr(dest, ch);
  4383. if (ch == '`') {
  4384. if (!add_till_backquote(dest, input, /*in_dquote:*/ 1))
  4385. return 0;
  4386. o_addchr(dest, ch);
  4387. continue;
  4388. }
  4389. //if (ch == '$') ...
  4390. }
  4391. }
  4392. /* Process `cmd` - copy contents until "`" is seen. Complicated by
  4393. * \` quoting.
  4394. * "Within the backquoted style of command substitution, backslash
  4395. * shall retain its literal meaning, except when followed by: '$', '`', or '\'.
  4396. * The search for the matching backquote shall be satisfied by the first
  4397. * backquote found without a preceding backslash; during this search,
  4398. * if a non-escaped backquote is encountered within a shell comment,
  4399. * a here-document, an embedded command substitution of the $(command)
  4400. * form, or a quoted string, undefined results occur. A single-quoted
  4401. * or double-quoted string that begins, but does not end, within the
  4402. * "`...`" sequence produces undefined results."
  4403. * Example Output
  4404. * echo `echo '\'TEST\`echo ZZ\`BEST` \TESTZZBEST
  4405. */
  4406. static int add_till_backquote(o_string *dest, struct in_str *input, int in_dquote)
  4407. {
  4408. while (1) {
  4409. int ch = i_getch(input);
  4410. if (ch == '`')
  4411. return 1;
  4412. if (ch == '\\') {
  4413. /* \x. Copy both unless it is \`, \$, \\ and maybe \" */
  4414. ch = i_getch(input);
  4415. if (ch != '`'
  4416. && ch != '$'
  4417. && ch != '\\'
  4418. && (!in_dquote || ch != '"')
  4419. ) {
  4420. o_addchr(dest, '\\');
  4421. }
  4422. }
  4423. if (ch == EOF) {
  4424. syntax_error_unterm_ch('`');
  4425. return 0;
  4426. }
  4427. o_addchr(dest, ch);
  4428. }
  4429. }
  4430. /* Process $(cmd) - copy contents until ")" is seen. Complicated by
  4431. * quoting and nested ()s.
  4432. * "With the $(command) style of command substitution, all characters
  4433. * following the open parenthesis to the matching closing parenthesis
  4434. * constitute the command. Any valid shell script can be used for command,
  4435. * except a script consisting solely of redirections which produces
  4436. * unspecified results."
  4437. * Example Output
  4438. * echo $(echo '(TEST)' BEST) (TEST) BEST
  4439. * echo $(echo 'TEST)' BEST) TEST) BEST
  4440. * echo $(echo \(\(TEST\) BEST) ((TEST) BEST
  4441. *
  4442. * Also adapted to eat ${var%...} and $((...)) constructs, since ... part
  4443. * can contain arbitrary constructs, just like $(cmd).
  4444. * In bash compat mode, it needs to also be able to stop on ':' or '/'
  4445. * for ${var:N[:M]} and ${var/P[/R]} parsing.
  4446. */
  4447. #define DOUBLE_CLOSE_CHAR_FLAG 0x80
  4448. static int add_till_closing_bracket(o_string *dest, struct in_str *input, unsigned end_ch)
  4449. {
  4450. int ch;
  4451. char dbl = end_ch & DOUBLE_CLOSE_CHAR_FLAG;
  4452. # if BASH_SUBSTR || BASH_PATTERN_SUBST
  4453. char end_char2 = end_ch >> 8;
  4454. # endif
  4455. end_ch &= (DOUBLE_CLOSE_CHAR_FLAG - 1);
  4456. #if ENABLE_HUSH_INTERACTIVE
  4457. G.promptmode = 1; /* PS2 */
  4458. #endif
  4459. debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
  4460. while (1) {
  4461. ch = i_getch(input);
  4462. if (ch == EOF) {
  4463. syntax_error_unterm_ch(end_ch);
  4464. return 0;
  4465. }
  4466. if (ch == end_ch
  4467. # if BASH_SUBSTR || BASH_PATTERN_SUBST
  4468. || ch == end_char2
  4469. # endif
  4470. ) {
  4471. if (!dbl)
  4472. break;
  4473. /* we look for closing )) of $((EXPR)) */
  4474. if (i_peek_and_eat_bkslash_nl(input) == end_ch) {
  4475. i_getch(input); /* eat second ')' */
  4476. break;
  4477. }
  4478. }
  4479. o_addchr(dest, ch);
  4480. //bb_error_msg("%s:o_addchr('%c')", __func__, ch);
  4481. if (ch == '(' || ch == '{') {
  4482. ch = (ch == '(' ? ')' : '}');
  4483. if (!add_till_closing_bracket(dest, input, ch))
  4484. return 0;
  4485. o_addchr(dest, ch);
  4486. continue;
  4487. }
  4488. if (ch == '\'') {
  4489. if (!add_till_single_quote(dest, input))
  4490. return 0;
  4491. o_addchr(dest, ch);
  4492. continue;
  4493. }
  4494. if (ch == '"') {
  4495. if (!add_till_double_quote(dest, input))
  4496. return 0;
  4497. o_addchr(dest, ch);
  4498. continue;
  4499. }
  4500. if (ch == '`') {
  4501. if (!add_till_backquote(dest, input, /*in_dquote:*/ 0))
  4502. return 0;
  4503. o_addchr(dest, ch);
  4504. continue;
  4505. }
  4506. if (ch == '\\') {
  4507. /* \x. Copy verbatim. Important for \(, \) */
  4508. ch = i_getch(input);
  4509. if (ch == EOF) {
  4510. syntax_error_unterm_ch(end_ch);
  4511. return 0;
  4512. }
  4513. #if 0
  4514. if (ch == '\n') {
  4515. /* "backslash+newline", ignore both */
  4516. o_delchr(dest); /* undo insertion of '\' */
  4517. continue;
  4518. }
  4519. #endif
  4520. o_addchr(dest, ch);
  4521. //bb_error_msg("%s:o_addchr('%c') after '\\'", __func__, ch);
  4522. continue;
  4523. }
  4524. }
  4525. debug_printf_parse("%s return '%s' ch:'%c'\n", __func__, dest->data, ch);
  4526. return ch;
  4527. }
  4528. #endif /* ENABLE_HUSH_TICK || ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_DOLLAR_OPS */
  4529. /* Return code: 0 for OK, 1 for syntax error */
  4530. #if BB_MMU
  4531. #define parse_dollar(as_string, dest, input, quote_mask) \
  4532. parse_dollar(dest, input, quote_mask)
  4533. #define as_string NULL
  4534. #endif
  4535. static int parse_dollar(o_string *as_string,
  4536. o_string *dest,
  4537. struct in_str *input, unsigned char quote_mask)
  4538. {
  4539. int ch = i_peek_and_eat_bkslash_nl(input); /* first character after the $ */
  4540. debug_printf_parse("parse_dollar entered: ch='%c'\n", ch);
  4541. if (isalpha(ch)) {
  4542. make_var:
  4543. ch = i_getch(input);
  4544. nommu_addchr(as_string, ch);
  4545. /*make_var1:*/
  4546. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4547. while (1) {
  4548. debug_printf_parse(": '%c'\n", ch);
  4549. o_addchr(dest, ch | quote_mask);
  4550. quote_mask = 0;
  4551. ch = i_peek_and_eat_bkslash_nl(input);
  4552. if (!isalnum(ch) && ch != '_') {
  4553. /* End of variable name reached */
  4554. break;
  4555. }
  4556. ch = i_getch(input);
  4557. nommu_addchr(as_string, ch);
  4558. }
  4559. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4560. } else if (isdigit(ch)) {
  4561. make_one_char_var:
  4562. ch = i_getch(input);
  4563. nommu_addchr(as_string, ch);
  4564. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4565. debug_printf_parse(": '%c'\n", ch);
  4566. o_addchr(dest, ch | quote_mask);
  4567. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4568. } else switch (ch) {
  4569. case '$': /* pid */
  4570. case '!': /* last bg pid */
  4571. case '?': /* last exit code */
  4572. case '#': /* number of args */
  4573. case '*': /* args */
  4574. case '@': /* args */
  4575. case '-': /* $- option flags set by set builtin or shell options (-i etc) */
  4576. goto make_one_char_var;
  4577. case '{': {
  4578. char len_single_ch;
  4579. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4580. ch = i_getch(input); /* eat '{' */
  4581. nommu_addchr(as_string, ch);
  4582. ch = i_getch_and_eat_bkslash_nl(input); /* first char after '{' */
  4583. /* It should be ${?}, or ${#var},
  4584. * or even ${?+subst} - operator acting on a special variable,
  4585. * or the beginning of variable name.
  4586. */
  4587. if (ch == EOF
  4588. || (!strchr(_SPECIAL_VARS_STR, ch) && !isalnum(ch)) /* not one of those */
  4589. ) {
  4590. bad_dollar_syntax:
  4591. syntax_error_unterm_str("${name}");
  4592. debug_printf_parse("parse_dollar return 0: unterminated ${name}\n");
  4593. return 0;
  4594. }
  4595. nommu_addchr(as_string, ch);
  4596. len_single_ch = ch;
  4597. ch |= quote_mask;
  4598. /* It's possible to just call add_till_closing_bracket() at this point.
  4599. * However, this regresses some of our testsuite cases
  4600. * which check invalid constructs like ${%}.
  4601. * Oh well... let's check that the var name part is fine... */
  4602. while (1) {
  4603. unsigned pos;
  4604. o_addchr(dest, ch);
  4605. debug_printf_parse(": '%c'\n", ch);
  4606. ch = i_getch(input);
  4607. nommu_addchr(as_string, ch);
  4608. if (ch == '}')
  4609. break;
  4610. if (!isalnum(ch) && ch != '_') {
  4611. unsigned end_ch;
  4612. unsigned char last_ch;
  4613. /* handle parameter expansions
  4614. * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02
  4615. */
  4616. if (!strchr(VAR_SUBST_OPS, ch)) { /* ${var<bad_char>... */
  4617. if (len_single_ch != '#'
  4618. /*|| !strchr(SPECIAL_VARS_STR, ch) - disallow errors like ${#+} ? */
  4619. || i_peek(input) != '}'
  4620. ) {
  4621. goto bad_dollar_syntax;
  4622. }
  4623. /* else: it's "length of C" ${#C} op,
  4624. * where C is a single char
  4625. * special var name, e.g. ${#!}.
  4626. */
  4627. }
  4628. /* Eat everything until closing '}' (or ':') */
  4629. end_ch = '}';
  4630. if (BASH_SUBSTR
  4631. && ch == ':'
  4632. && !strchr(MINUS_PLUS_EQUAL_QUESTION, i_peek(input))
  4633. ) {
  4634. /* It's ${var:N[:M]} thing */
  4635. end_ch = '}' * 0x100 + ':';
  4636. }
  4637. if (BASH_PATTERN_SUBST
  4638. && ch == '/'
  4639. ) {
  4640. /* It's ${var/[/]pattern[/repl]} thing */
  4641. if (i_peek(input) == '/') { /* ${var//pattern[/repl]}? */
  4642. i_getch(input);
  4643. nommu_addchr(as_string, '/');
  4644. ch = '\\';
  4645. }
  4646. end_ch = '}' * 0x100 + '/';
  4647. }
  4648. o_addchr(dest, ch);
  4649. /* The pattern can't be empty.
  4650. * IOW: if the first char after "${v//" is a slash,
  4651. * it does not terminate the pattern - it's the first char of the pattern:
  4652. * v=/dev/ram; echo ${v////-} prints -dev-ram (pattern is "/")
  4653. * v=/dev/ram; echo ${v///r/-} prints /dev-am (pattern is "/r")
  4654. */
  4655. if (i_peek(input) == '/') {
  4656. o_addchr(dest, i_getch(input));
  4657. }
  4658. again:
  4659. if (!BB_MMU)
  4660. pos = dest->length;
  4661. #if ENABLE_HUSH_DOLLAR_OPS
  4662. last_ch = add_till_closing_bracket(dest, input, end_ch);
  4663. if (last_ch == 0) /* error? */
  4664. return 0;
  4665. #else
  4666. #error Simple code to only allow ${var} is not implemented
  4667. #endif
  4668. if (as_string) {
  4669. o_addstr(as_string, dest->data + pos);
  4670. o_addchr(as_string, last_ch);
  4671. }
  4672. if ((BASH_SUBSTR || BASH_PATTERN_SUBST)
  4673. && (end_ch & 0xff00)
  4674. ) {
  4675. /* close the first block: */
  4676. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4677. /* while parsing N from ${var:N[:M]}
  4678. * or pattern from ${var/[/]pattern[/repl]} */
  4679. if ((end_ch & 0xff) == last_ch) {
  4680. /* got ':' or '/'- parse the rest */
  4681. end_ch = '}';
  4682. goto again;
  4683. }
  4684. /* got '}' */
  4685. if (BASH_SUBSTR && end_ch == '}' * 0x100 + ':') {
  4686. /* it's ${var:N} - emulate :999999999 */
  4687. o_addstr(dest, "999999999");
  4688. } /* else: it's ${var/[/]pattern} */
  4689. }
  4690. break;
  4691. }
  4692. len_single_ch = 0; /* it can't be ${#C} op */
  4693. }
  4694. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4695. break;
  4696. }
  4697. #if ENABLE_FEATURE_SH_MATH || ENABLE_HUSH_TICK
  4698. case '(': {
  4699. unsigned pos;
  4700. ch = i_getch(input);
  4701. nommu_addchr(as_string, ch);
  4702. # if ENABLE_FEATURE_SH_MATH
  4703. if (i_peek_and_eat_bkslash_nl(input) == '(') {
  4704. ch = i_getch(input);
  4705. nommu_addchr(as_string, ch);
  4706. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4707. o_addchr(dest, /*quote_mask |*/ '+');
  4708. if (!BB_MMU)
  4709. pos = dest->length;
  4710. if (!add_till_closing_bracket(dest, input, ')' | DOUBLE_CLOSE_CHAR_FLAG))
  4711. return 0; /* error */
  4712. if (as_string) {
  4713. o_addstr(as_string, dest->data + pos);
  4714. o_addchr(as_string, ')');
  4715. o_addchr(as_string, ')');
  4716. }
  4717. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4718. break;
  4719. }
  4720. # endif
  4721. # if ENABLE_HUSH_TICK
  4722. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4723. o_addchr(dest, quote_mask | '`');
  4724. if (!BB_MMU)
  4725. pos = dest->length;
  4726. if (!add_till_closing_bracket(dest, input, ')'))
  4727. return 0; /* error */
  4728. if (as_string) {
  4729. o_addstr(as_string, dest->data + pos);
  4730. o_addchr(as_string, ')');
  4731. }
  4732. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4733. # endif
  4734. break;
  4735. }
  4736. #endif
  4737. case '_':
  4738. goto make_var;
  4739. #if 0
  4740. /* TODO: $_: */
  4741. /* $_ Shell or shell script name; or last argument of last command
  4742. * (if last command wasn't a pipe; if it was, bash sets $_ to "");
  4743. * but in command's env, set to full pathname used to invoke it */
  4744. ch = i_getch(input);
  4745. nommu_addchr(as_string, ch);
  4746. ch = i_peek_and_eat_bkslash_nl(input);
  4747. if (isalnum(ch)) { /* it's $_name or $_123 */
  4748. ch = '_';
  4749. goto make_var1;
  4750. }
  4751. /* else: it's $_ */
  4752. #endif
  4753. default:
  4754. o_addQchr(dest, '$');
  4755. }
  4756. debug_printf_parse("parse_dollar return 1 (ok)\n");
  4757. return 1;
  4758. #undef as_string
  4759. }
  4760. #if BB_MMU
  4761. #define encode_string(as_string, dest, input, dquote_end) \
  4762. encode_string(dest, input, dquote_end)
  4763. #define as_string NULL
  4764. #endif
  4765. static int encode_string(o_string *as_string,
  4766. o_string *dest,
  4767. struct in_str *input,
  4768. int dquote_end)
  4769. {
  4770. int ch;
  4771. int next;
  4772. again:
  4773. ch = i_getch(input);
  4774. if (ch != EOF)
  4775. nommu_addchr(as_string, ch);
  4776. if (ch == dquote_end) { /* may be only '"' or EOF */
  4777. debug_printf_parse("encode_string return 1 (ok)\n");
  4778. return 1;
  4779. }
  4780. /* note: can't move it above ch == dquote_end check! */
  4781. if (ch == EOF) {
  4782. syntax_error_unterm_ch('"');
  4783. return 0; /* error */
  4784. }
  4785. next = '\0';
  4786. if (ch != '\n') {
  4787. next = i_peek(input);
  4788. }
  4789. debug_printf_parse("\" ch=%c (%d) escape=%d\n",
  4790. ch, ch, !!(dest->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
  4791. if (ch == '\\') {
  4792. if (next == EOF) {
  4793. /* Testcase: in interactive shell a file with
  4794. * echo "unterminated string\<eof>
  4795. * is sourced.
  4796. */
  4797. syntax_error_unterm_ch('"');
  4798. return 0; /* error */
  4799. }
  4800. /* bash:
  4801. * "The backslash retains its special meaning [in "..."]
  4802. * only when followed by one of the following characters:
  4803. * $, `, ", \, or <newline>. A double quote may be quoted
  4804. * within double quotes by preceding it with a backslash."
  4805. * NB: in (unquoted) heredoc, above does not apply to ",
  4806. * therefore we check for it by "next == dquote_end" cond.
  4807. */
  4808. if (next == dquote_end || strchr("$`\\\n", next)) {
  4809. ch = i_getch(input); /* eat next */
  4810. if (ch == '\n')
  4811. goto again; /* skip \<newline> */
  4812. } /* else: ch remains == '\\', and we double it below: */
  4813. o_addqchr(dest, ch); /* \c if c is a glob char, else just c */
  4814. nommu_addchr(as_string, ch);
  4815. goto again;
  4816. }
  4817. if (ch == '$') {
  4818. if (!parse_dollar(as_string, dest, input, /*quote_mask:*/ 0x80)) {
  4819. debug_printf_parse("encode_string return 0: "
  4820. "parse_dollar returned 0 (error)\n");
  4821. return 0;
  4822. }
  4823. goto again;
  4824. }
  4825. #if ENABLE_HUSH_TICK
  4826. if (ch == '`') {
  4827. //unsigned pos = dest->length;
  4828. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4829. o_addchr(dest, 0x80 | '`');
  4830. if (!add_till_backquote(dest, input, /*in_dquote:*/ dquote_end == '"'))
  4831. return 0; /* error */
  4832. o_addchr(dest, SPECIAL_VAR_SYMBOL);
  4833. //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
  4834. goto again;
  4835. }
  4836. #endif
  4837. o_addQchr(dest, ch);
  4838. goto again;
  4839. #undef as_string
  4840. }
  4841. /*
  4842. * Scan input until EOF or end_trigger char.
  4843. * Return a list of pipes to execute, or NULL on EOF
  4844. * or if end_trigger character is met.
  4845. * On syntax error, exit if shell is not interactive,
  4846. * reset parsing machinery and start parsing anew,
  4847. * or return ERR_PTR.
  4848. */
  4849. static struct pipe *parse_stream(char **pstring,
  4850. int *heredoc_cnt_ptr,
  4851. struct in_str *input,
  4852. int end_trigger)
  4853. {
  4854. struct parse_context ctx;
  4855. int heredoc_cnt;
  4856. /* Single-quote triggers a bypass of the main loop until its mate is
  4857. * found. When recursing, quote state is passed in via ctx.word.o_expflags.
  4858. */
  4859. debug_printf_parse("parse_stream entered, end_trigger='%c'\n",
  4860. end_trigger ? end_trigger : 'X');
  4861. debug_enter();
  4862. initialize_context(&ctx);
  4863. /* If very first arg is "" or '', ctx.word.data may end up NULL.
  4864. * Preventing this:
  4865. */
  4866. ctx.word.data = xzalloc(1); /* start as "", not as NULL */
  4867. /* We used to separate words on $IFS here. This was wrong.
  4868. * $IFS is used only for word splitting when $var is expanded,
  4869. * here we should use blank chars as separators, not $IFS
  4870. */
  4871. heredoc_cnt = 0;
  4872. while (1) {
  4873. const char *is_blank;
  4874. const char *is_special;
  4875. int ch;
  4876. int next;
  4877. int redir_fd;
  4878. redir_type redir_style;
  4879. ch = i_getch(input);
  4880. debug_printf_parse(": ch=%c (%d) escape=%d\n",
  4881. ch, ch, !!(ctx.word.o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
  4882. if (ch == EOF) {
  4883. struct pipe *pi;
  4884. if (heredoc_cnt) {
  4885. syntax_error_unterm_str("here document");
  4886. goto parse_error;
  4887. }
  4888. if (end_trigger == ')') {
  4889. syntax_error_unterm_ch('(');
  4890. goto parse_error;
  4891. }
  4892. if (end_trigger == '}') {
  4893. syntax_error_unterm_ch('{');
  4894. goto parse_error;
  4895. }
  4896. if (done_word(&ctx)) {
  4897. goto parse_error;
  4898. }
  4899. o_free_and_set_NULL(&ctx.word);
  4900. done_pipe(&ctx, PIPE_SEQ);
  4901. pi = ctx.list_head;
  4902. /* If we got nothing... */
  4903. /* (this makes bare "&" cmd a no-op.
  4904. * bash says: "syntax error near unexpected token '&'") */
  4905. if (pi->num_cmds == 0
  4906. IF_HAS_KEYWORDS(&& pi->res_word == RES_NONE)
  4907. ) {
  4908. free_pipe_list(pi);
  4909. pi = NULL;
  4910. }
  4911. #if !BB_MMU
  4912. debug_printf_parse("as_string1 '%s'\n", ctx.as_string.data);
  4913. if (pstring)
  4914. *pstring = ctx.as_string.data;
  4915. else
  4916. o_free(&ctx.as_string);
  4917. #endif
  4918. // heredoc_cnt must be 0 here anyway
  4919. //if (heredoc_cnt_ptr)
  4920. // *heredoc_cnt_ptr = heredoc_cnt;
  4921. debug_leave();
  4922. debug_printf_heredoc("parse_stream return heredoc_cnt:%d\n", heredoc_cnt);
  4923. debug_printf_parse("parse_stream return %p\n", pi);
  4924. return pi;
  4925. }
  4926. /* Handle "'" and "\" first, as they won't play nice with
  4927. * i_peek_and_eat_bkslash_nl() anyway:
  4928. * echo z\\
  4929. * and
  4930. * echo '\
  4931. * '
  4932. * would break.
  4933. */
  4934. if (ch == '\\') {
  4935. ch = i_getch(input);
  4936. if (ch == '\n')
  4937. continue; /* drop \<newline>, get next char */
  4938. nommu_addchr(&ctx.as_string, '\\');
  4939. o_addchr(&ctx.word, '\\');
  4940. if (ch == EOF) {
  4941. /* Testcase: eval 'echo Ok\' */
  4942. /* bash-4.3.43 was removing backslash,
  4943. * but 4.4.19 retains it, most other shells too
  4944. */
  4945. continue; /* get next char */
  4946. }
  4947. /* Example: echo Hello \2>file
  4948. * we need to know that word 2 is quoted
  4949. */
  4950. ctx.word.has_quoted_part = 1;
  4951. nommu_addchr(&ctx.as_string, ch);
  4952. o_addchr(&ctx.word, ch);
  4953. continue; /* get next char */
  4954. }
  4955. nommu_addchr(&ctx.as_string, ch);
  4956. if (ch == '\'') {
  4957. ctx.word.has_quoted_part = 1;
  4958. next = i_getch(input);
  4959. if (next == '\'' && !ctx.pending_redirect)
  4960. goto insert_empty_quoted_str_marker;
  4961. ch = next;
  4962. while (1) {
  4963. if (ch == EOF) {
  4964. syntax_error_unterm_ch('\'');
  4965. goto parse_error;
  4966. }
  4967. nommu_addchr(&ctx.as_string, ch);
  4968. if (ch == '\'')
  4969. break;
  4970. if (ch == SPECIAL_VAR_SYMBOL) {
  4971. /* Convert raw ^C to corresponding special variable reference */
  4972. o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
  4973. o_addchr(&ctx.word, SPECIAL_VAR_QUOTED_SVS);
  4974. }
  4975. o_addqchr(&ctx.word, ch);
  4976. ch = i_getch(input);
  4977. }
  4978. continue; /* get next char */
  4979. }
  4980. next = '\0';
  4981. if (ch != '\n')
  4982. next = i_peek_and_eat_bkslash_nl(input);
  4983. is_special = "{}<>;&|()#" /* special outside of "str" */
  4984. "$\"" IF_HUSH_TICK("`") /* always special */
  4985. SPECIAL_VAR_SYMBOL_STR;
  4986. /* Are { and } special here? */
  4987. if (ctx.command->argv /* word [word]{... - non-special */
  4988. || ctx.word.length /* word{... - non-special */
  4989. || ctx.word.has_quoted_part /* ""{... - non-special */
  4990. || (next != ';' /* }; - special */
  4991. && next != ')' /* }) - special */
  4992. && next != '(' /* {( - special */
  4993. && next != '&' /* }& and }&& ... - special */
  4994. && next != '|' /* }|| ... - special */
  4995. && !strchr(defifs, next) /* {word - non-special */
  4996. )
  4997. ) {
  4998. /* They are not special, skip "{}" */
  4999. is_special += 2;
  5000. }
  5001. is_special = strchr(is_special, ch);
  5002. is_blank = strchr(defifs, ch);
  5003. if (!is_special && !is_blank) { /* ordinary char */
  5004. ordinary_char:
  5005. o_addQchr(&ctx.word, ch);
  5006. if ((ctx.is_assignment == MAYBE_ASSIGNMENT
  5007. || ctx.is_assignment == WORD_IS_KEYWORD)
  5008. && ch == '='
  5009. && endofname(ctx.word.data)[0] == '='
  5010. ) {
  5011. ctx.is_assignment = DEFINITELY_ASSIGNMENT;
  5012. debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
  5013. }
  5014. continue;
  5015. }
  5016. if (is_blank) {
  5017. #if ENABLE_HUSH_LINENO_VAR
  5018. /* Case:
  5019. * "while ...; do<whitespace><newline>
  5020. * cmd ..."
  5021. * would think that "cmd" starts in <whitespace> -
  5022. * i.e., at the previous line.
  5023. * We need to skip all whitespace before newlines.
  5024. */
  5025. while (ch != '\n') {
  5026. next = i_peek(input);
  5027. if (next != ' ' && next != '\t' && next != '\n')
  5028. break; /* next char is not ws */
  5029. ch = i_getch(input);
  5030. }
  5031. /* ch == last eaten whitespace char */
  5032. #endif
  5033. if (done_word(&ctx)) {
  5034. goto parse_error;
  5035. }
  5036. if (ch == '\n') {
  5037. /* Is this a case when newline is simply ignored?
  5038. * Some examples:
  5039. * "cmd | <newline> cmd ..."
  5040. * "case ... in <newline> word) ..."
  5041. */
  5042. if (IS_NULL_CMD(ctx.command)
  5043. && ctx.word.length == 0
  5044. && !ctx.word.has_quoted_part
  5045. && heredoc_cnt == 0
  5046. ) {
  5047. /* This newline can be ignored. But...
  5048. * Without check #1, interactive shell
  5049. * ignores even bare <newline>,
  5050. * and shows the continuation prompt:
  5051. * ps1_prompt$ <enter>
  5052. * ps2> _ <=== wrong, should be ps1
  5053. * Without check #2, "cmd & <newline>"
  5054. * is similarly mistreated.
  5055. * (BTW, this makes "cmd & cmd"
  5056. * and "cmd && cmd" non-orthogonal.
  5057. * Really, ask yourself, why
  5058. * "cmd && <newline>" doesn't start
  5059. * cmd but waits for more input?
  5060. * The only reason is that it might be
  5061. * a "cmd1 && <nl> cmd2 &" construct,
  5062. * cmd1 may need to run in BG).
  5063. */
  5064. struct pipe *pi = ctx.list_head;
  5065. if (pi->num_cmds != 0 /* check #1 */
  5066. && pi->followup != PIPE_BG /* check #2 */
  5067. ) {
  5068. continue;
  5069. }
  5070. }
  5071. /* Treat newline as a command separator. */
  5072. done_pipe(&ctx, PIPE_SEQ);
  5073. debug_printf_heredoc("heredoc_cnt:%d\n", heredoc_cnt);
  5074. if (heredoc_cnt) {
  5075. heredoc_cnt = fetch_heredocs(&ctx.as_string, ctx.list_head, heredoc_cnt, input);
  5076. if (heredoc_cnt != 0)
  5077. goto parse_error;
  5078. }
  5079. ctx.is_assignment = MAYBE_ASSIGNMENT;
  5080. debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
  5081. ch = ';';
  5082. /* note: if (is_blank) continue;
  5083. * will still trigger for us */
  5084. }
  5085. }
  5086. /* "cmd}" or "cmd }..." without semicolon or &:
  5087. * } is an ordinary char in this case, even inside { cmd; }
  5088. * Pathological example: { ""}; } should exec "}" cmd
  5089. */
  5090. if (ch == '}') {
  5091. if (ctx.word.length != 0 /* word} */
  5092. || ctx.word.has_quoted_part /* ""} */
  5093. ) {
  5094. goto ordinary_char;
  5095. }
  5096. if (!IS_NULL_CMD(ctx.command)) { /* cmd } */
  5097. /* Generally, there should be semicolon: "cmd; }"
  5098. * However, bash allows to omit it if "cmd" is
  5099. * a group. Examples:
  5100. * { { echo 1; } }
  5101. * {(echo 1)}
  5102. * { echo 0 >&2 | { echo 1; } }
  5103. * { while false; do :; done }
  5104. * { case a in b) ;; esac }
  5105. */
  5106. if (ctx.command->group)
  5107. goto term_group;
  5108. goto ordinary_char;
  5109. }
  5110. if (!IS_NULL_PIPE(ctx.pipe)) /* cmd | } */
  5111. /* Can't be an end of {cmd}, skip the check */
  5112. goto skip_end_trigger;
  5113. /* else: } does terminate a group */
  5114. }
  5115. term_group:
  5116. if (end_trigger && end_trigger == ch
  5117. && (ch != ';' || heredoc_cnt == 0)
  5118. #if ENABLE_HUSH_CASE
  5119. && (ch != ')'
  5120. || ctx.ctx_res_w != RES_MATCH
  5121. || (!ctx.word.has_quoted_part && strcmp(ctx.word.data, "esac") == 0)
  5122. )
  5123. #endif
  5124. ) {
  5125. if (done_word(&ctx)) {
  5126. goto parse_error;
  5127. }
  5128. done_pipe(&ctx, PIPE_SEQ);
  5129. ctx.is_assignment = MAYBE_ASSIGNMENT;
  5130. debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
  5131. /* Do we sit outside of any if's, loops or case's? */
  5132. if (!HAS_KEYWORDS
  5133. IF_HAS_KEYWORDS(|| (ctx.ctx_res_w == RES_NONE && ctx.old_flag == 0))
  5134. ) {
  5135. o_free_and_set_NULL(&ctx.word);
  5136. #if !BB_MMU
  5137. debug_printf_parse("as_string2 '%s'\n", ctx.as_string.data);
  5138. if (pstring)
  5139. *pstring = ctx.as_string.data;
  5140. else
  5141. o_free(&ctx.as_string);
  5142. #endif
  5143. if (ch != ';' && IS_NULL_PIPE(ctx.list_head)) {
  5144. /* Example: bare "{ }", "()" */
  5145. G.last_exitcode = 2; /* bash compat */
  5146. syntax_error_unexpected_ch(ch);
  5147. goto parse_error2;
  5148. }
  5149. if (heredoc_cnt_ptr)
  5150. *heredoc_cnt_ptr = heredoc_cnt;
  5151. debug_printf_heredoc("parse_stream return heredoc_cnt:%d\n", heredoc_cnt);
  5152. debug_printf_parse("parse_stream return %p: "
  5153. "end_trigger char found\n",
  5154. ctx.list_head);
  5155. debug_leave();
  5156. return ctx.list_head;
  5157. }
  5158. }
  5159. if (is_blank)
  5160. continue;
  5161. /* Catch <, > before deciding whether this word is
  5162. * an assignment. a=1 2>z b=2: b=2 is still assignment */
  5163. switch (ch) {
  5164. case '>':
  5165. redir_fd = redirect_opt_num(&ctx.word);
  5166. if (done_word(&ctx)) {
  5167. goto parse_error;
  5168. }
  5169. redir_style = REDIRECT_OVERWRITE;
  5170. if (next == '>') {
  5171. redir_style = REDIRECT_APPEND;
  5172. ch = i_getch(input);
  5173. nommu_addchr(&ctx.as_string, ch);
  5174. }
  5175. #if 0
  5176. else if (next == '(') {
  5177. syntax_error(">(process) not supported");
  5178. goto parse_error;
  5179. }
  5180. #endif
  5181. if (parse_redirect(&ctx, redir_fd, redir_style, input))
  5182. goto parse_error;
  5183. continue; /* get next char */
  5184. case '<':
  5185. redir_fd = redirect_opt_num(&ctx.word);
  5186. if (done_word(&ctx)) {
  5187. goto parse_error;
  5188. }
  5189. redir_style = REDIRECT_INPUT;
  5190. if (next == '<') {
  5191. redir_style = REDIRECT_HEREDOC;
  5192. heredoc_cnt++;
  5193. debug_printf_heredoc("++heredoc_cnt=%d\n", heredoc_cnt);
  5194. ch = i_getch(input);
  5195. nommu_addchr(&ctx.as_string, ch);
  5196. } else if (next == '>') {
  5197. redir_style = REDIRECT_IO;
  5198. ch = i_getch(input);
  5199. nommu_addchr(&ctx.as_string, ch);
  5200. }
  5201. #if 0
  5202. else if (next == '(') {
  5203. syntax_error("<(process) not supported");
  5204. goto parse_error;
  5205. }
  5206. #endif
  5207. if (parse_redirect(&ctx, redir_fd, redir_style, input))
  5208. goto parse_error;
  5209. continue; /* get next char */
  5210. case '#':
  5211. if (ctx.word.length == 0 && !ctx.word.has_quoted_part) {
  5212. /* skip "#comment" */
  5213. /* note: we do not add it to &ctx.as_string */
  5214. /* TODO: in bash:
  5215. * comment inside $() goes to the next \n, even inside quoted string (!):
  5216. * cmd "$(cmd2 #comment)" - syntax error
  5217. * cmd "`cmd2 #comment`" - ok
  5218. * We accept both (comment ends where command subst ends, in both cases).
  5219. */
  5220. while (1) {
  5221. ch = i_peek(input);
  5222. if (ch == '\n') {
  5223. nommu_addchr(&ctx.as_string, '\n');
  5224. break;
  5225. }
  5226. ch = i_getch(input);
  5227. if (ch == EOF)
  5228. break;
  5229. }
  5230. continue; /* get next char */
  5231. }
  5232. break;
  5233. }
  5234. skip_end_trigger:
  5235. if (ctx.is_assignment == MAYBE_ASSIGNMENT
  5236. /* check that we are not in word in "a=1 2>word b=1": */
  5237. && !ctx.pending_redirect
  5238. ) {
  5239. /* ch is a special char and thus this word
  5240. * cannot be an assignment */
  5241. ctx.is_assignment = NOT_ASSIGNMENT;
  5242. debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
  5243. }
  5244. /* Note: nommu_addchr(&ctx.as_string, ch) is already done */
  5245. switch (ch) {
  5246. case SPECIAL_VAR_SYMBOL:
  5247. /* Convert raw ^C to corresponding special variable reference */
  5248. o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
  5249. o_addchr(&ctx.word, SPECIAL_VAR_QUOTED_SVS);
  5250. /* fall through */
  5251. case '#':
  5252. /* non-comment #: "echo a#b" etc */
  5253. o_addchr(&ctx.word, ch);
  5254. continue; /* get next char */
  5255. case '$':
  5256. if (!parse_dollar(&ctx.as_string, &ctx.word, input, /*quote_mask:*/ 0)) {
  5257. debug_printf_parse("parse_stream parse error: "
  5258. "parse_dollar returned 0 (error)\n");
  5259. goto parse_error;
  5260. }
  5261. continue; /* get next char */
  5262. case '"':
  5263. ctx.word.has_quoted_part = 1;
  5264. if (next == '"' && !ctx.pending_redirect) {
  5265. i_getch(input); /* eat second " */
  5266. insert_empty_quoted_str_marker:
  5267. nommu_addchr(&ctx.as_string, next);
  5268. o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
  5269. o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
  5270. continue; /* get next char */
  5271. }
  5272. if (ctx.is_assignment == NOT_ASSIGNMENT)
  5273. ctx.word.o_expflags |= EXP_FLAG_ESC_GLOB_CHARS;
  5274. if (!encode_string(&ctx.as_string, &ctx.word, input, '"'))
  5275. goto parse_error;
  5276. ctx.word.o_expflags &= ~EXP_FLAG_ESC_GLOB_CHARS;
  5277. continue; /* get next char */
  5278. #if ENABLE_HUSH_TICK
  5279. case '`': {
  5280. USE_FOR_NOMMU(unsigned pos;)
  5281. o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
  5282. o_addchr(&ctx.word, '`');
  5283. USE_FOR_NOMMU(pos = ctx.word.length;)
  5284. if (!add_till_backquote(&ctx.word, input, /*in_dquote:*/ 0))
  5285. goto parse_error;
  5286. # if !BB_MMU
  5287. o_addstr(&ctx.as_string, ctx.word.data + pos);
  5288. o_addchr(&ctx.as_string, '`');
  5289. # endif
  5290. o_addchr(&ctx.word, SPECIAL_VAR_SYMBOL);
  5291. //debug_printf_subst("SUBST RES3 '%s'\n", ctx.word.data + pos);
  5292. continue; /* get next char */
  5293. }
  5294. #endif
  5295. case ';':
  5296. #if ENABLE_HUSH_CASE
  5297. case_semi:
  5298. #endif
  5299. if (done_word(&ctx)) {
  5300. goto parse_error;
  5301. }
  5302. done_pipe(&ctx, PIPE_SEQ);
  5303. #if ENABLE_HUSH_CASE
  5304. /* Eat multiple semicolons, detect
  5305. * whether it means something special */
  5306. while (1) {
  5307. ch = i_peek_and_eat_bkslash_nl(input);
  5308. if (ch != ';')
  5309. break;
  5310. ch = i_getch(input);
  5311. nommu_addchr(&ctx.as_string, ch);
  5312. if (ctx.ctx_res_w == RES_CASE_BODY) {
  5313. ctx.ctx_dsemicolon = 1;
  5314. ctx.ctx_res_w = RES_MATCH;
  5315. break;
  5316. }
  5317. }
  5318. #endif
  5319. new_cmd:
  5320. /* We just finished a cmd. New one may start
  5321. * with an assignment */
  5322. ctx.is_assignment = MAYBE_ASSIGNMENT;
  5323. debug_printf_parse("ctx.is_assignment='%s'\n", assignment_flag[ctx.is_assignment]);
  5324. continue; /* get next char */
  5325. case '&':
  5326. if (done_word(&ctx)) {
  5327. goto parse_error;
  5328. }
  5329. if (next == '&') {
  5330. ch = i_getch(input);
  5331. nommu_addchr(&ctx.as_string, ch);
  5332. done_pipe(&ctx, PIPE_AND);
  5333. } else {
  5334. done_pipe(&ctx, PIPE_BG);
  5335. }
  5336. goto new_cmd;
  5337. case '|':
  5338. if (done_word(&ctx)) {
  5339. goto parse_error;
  5340. }
  5341. #if ENABLE_HUSH_CASE
  5342. if (ctx.ctx_res_w == RES_MATCH)
  5343. break; /* we are in case's "word | word)" */
  5344. #endif
  5345. if (next == '|') { /* || */
  5346. ch = i_getch(input);
  5347. nommu_addchr(&ctx.as_string, ch);
  5348. done_pipe(&ctx, PIPE_OR);
  5349. } else {
  5350. /* we could pick up a file descriptor choice here
  5351. * with redirect_opt_num(), but bash doesn't do it.
  5352. * "echo foo 2| cat" yields "foo 2". */
  5353. done_command(&ctx);
  5354. }
  5355. goto new_cmd;
  5356. case '(':
  5357. #if ENABLE_HUSH_CASE
  5358. /* "case... in [(]word)..." - skip '(' */
  5359. if (ctx.ctx_res_w == RES_MATCH
  5360. && ctx.command->argv == NULL /* not (word|(... */
  5361. && ctx.word.length == 0 /* not word(... */
  5362. && ctx.word.has_quoted_part == 0 /* not ""(... */
  5363. ) {
  5364. continue; /* get next char */
  5365. }
  5366. #endif
  5367. /* fall through */
  5368. case '{': {
  5369. int n = parse_group(&ctx, input, ch);
  5370. if (n < 0) {
  5371. goto parse_error;
  5372. }
  5373. debug_printf_heredoc("parse_group done, needs heredocs:%d\n", n);
  5374. heredoc_cnt += n;
  5375. goto new_cmd;
  5376. }
  5377. case ')':
  5378. #if ENABLE_HUSH_CASE
  5379. if (ctx.ctx_res_w == RES_MATCH)
  5380. goto case_semi;
  5381. #endif
  5382. case '}':
  5383. /* proper use of this character is caught by end_trigger:
  5384. * if we see {, we call parse_group(..., end_trigger='}')
  5385. * and it will match } earlier (not here). */
  5386. G.last_exitcode = 2;
  5387. syntax_error_unexpected_ch(ch);
  5388. goto parse_error2;
  5389. default:
  5390. if (HUSH_DEBUG)
  5391. bb_error_msg_and_die("BUG: unexpected %c", ch);
  5392. }
  5393. } /* while (1) */
  5394. parse_error:
  5395. G.last_exitcode = 1;
  5396. parse_error2:
  5397. {
  5398. struct parse_context *pctx;
  5399. IF_HAS_KEYWORDS(struct parse_context *p2;)
  5400. /* Clean up allocated tree.
  5401. * Sample for finding leaks on syntax error recovery path.
  5402. * Run it from interactive shell, watch pmap `pidof hush`.
  5403. * while if false; then false; fi; do break; fi
  5404. * Samples to catch leaks at execution:
  5405. * while if (true | { true;}); then echo ok; fi; do break; done
  5406. * while if (true | { true;}); then echo ok; fi; do (if echo ok; break; then :; fi) | cat; break; done
  5407. */
  5408. pctx = &ctx;
  5409. do {
  5410. /* Update pipe/command counts,
  5411. * otherwise freeing may miss some */
  5412. done_pipe(pctx, PIPE_SEQ);
  5413. debug_printf_clean("freeing list %p from ctx %p\n",
  5414. pctx->list_head, pctx);
  5415. debug_print_tree(pctx->list_head, 0);
  5416. free_pipe_list(pctx->list_head);
  5417. debug_printf_clean("freed list %p\n", pctx->list_head);
  5418. #if !BB_MMU
  5419. o_free(&pctx->as_string);
  5420. #endif
  5421. IF_HAS_KEYWORDS(p2 = pctx->stack;)
  5422. if (pctx != &ctx) {
  5423. free(pctx);
  5424. }
  5425. IF_HAS_KEYWORDS(pctx = p2;)
  5426. } while (HAS_KEYWORDS && pctx);
  5427. o_free(&ctx.word);
  5428. #if !BB_MMU
  5429. if (pstring)
  5430. *pstring = NULL;
  5431. #endif
  5432. debug_leave();
  5433. return ERR_PTR;
  5434. }
  5435. }
  5436. /*** Execution routines ***/
  5437. /* Expansion can recurse, need forward decls: */
  5438. #if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
  5439. #define expand_string_to_string(str, EXP_flags, do_unbackslash) \
  5440. expand_string_to_string(str)
  5441. #endif
  5442. static char *expand_string_to_string(const char *str, int EXP_flags, int do_unbackslash);
  5443. #if ENABLE_HUSH_TICK
  5444. static int process_command_subs(o_string *dest, const char *s);
  5445. #endif
  5446. static int expand_vars_to_list(o_string *output, int n, char *arg);
  5447. /* expand_strvec_to_strvec() takes a list of strings, expands
  5448. * all variable references within and returns a pointer to
  5449. * a list of expanded strings, possibly with larger number
  5450. * of strings. (Think VAR="a b"; echo $VAR).
  5451. * This new list is allocated as a single malloc block.
  5452. * NULL-terminated list of char* pointers is at the beginning of it,
  5453. * followed by strings themselves.
  5454. * Caller can deallocate entire list by single free(list). */
  5455. /* A horde of its helpers come first: */
  5456. static void o_addblock_duplicate_backslash(o_string *o, const char *str, int len)
  5457. {
  5458. while (--len >= 0) {
  5459. char c = *str++;
  5460. #if ENABLE_HUSH_BRACE_EXPANSION
  5461. if (c == '{' || c == '}') {
  5462. /* { -> \{, } -> \} */
  5463. o_addchr(o, '\\');
  5464. /* And now we want to add { or } and continue:
  5465. * o_addchr(o, c);
  5466. * continue;
  5467. * luckily, just falling through achieves this.
  5468. */
  5469. }
  5470. #endif
  5471. o_addchr(o, c);
  5472. if (c == '\\') {
  5473. /* \z -> \\\z; \<eol> -> \\<eol> */
  5474. o_addchr(o, '\\');
  5475. if (len) {
  5476. len--;
  5477. o_addchr(o, '\\');
  5478. o_addchr(o, *str++);
  5479. }
  5480. }
  5481. }
  5482. }
  5483. /* Store given string, finalizing the word and starting new one whenever
  5484. * we encounter IFS char(s). This is used for expanding variable values.
  5485. * End-of-string does NOT finalize word: think about 'echo -$VAR-'.
  5486. * Return in output->ended_in_ifs:
  5487. * 1 - ended with IFS char, else 0 (this includes case of empty str).
  5488. */
  5489. static int expand_on_ifs(o_string *output, int n, const char *str)
  5490. {
  5491. int last_is_ifs = 0;
  5492. while (1) {
  5493. int word_len;
  5494. if (!*str) /* EOL - do not finalize word */
  5495. break;
  5496. word_len = strcspn(str, G.ifs);
  5497. if (word_len) {
  5498. /* We have WORD_LEN leading non-IFS chars */
  5499. if (!(output->o_expflags & EXP_FLAG_GLOB)) {
  5500. o_addblock(output, str, word_len);
  5501. } else {
  5502. /* Protect backslashes against globbing up :)
  5503. * Example: "v='\*'; echo b$v" prints "b\*"
  5504. * (and does not try to glob on "*")
  5505. */
  5506. o_addblock_duplicate_backslash(output, str, word_len);
  5507. /*/ Why can't we do it easier? */
  5508. /*o_addblock(output, str, word_len); - WRONG: "v='\*'; echo Z$v" prints "Z*" instead of "Z\*" */
  5509. /*o_addqblock(output, str, word_len); - WRONG: "v='*'; echo Z$v" prints "Z*" instead of Z* files */
  5510. }
  5511. last_is_ifs = 0;
  5512. str += word_len;
  5513. if (!*str) /* EOL - do not finalize word */
  5514. break;
  5515. }
  5516. /* We know str here points to at least one IFS char */
  5517. last_is_ifs = 1;
  5518. str += strspn(str, G.ifs_whitespace); /* skip IFS whitespace chars */
  5519. if (!*str) /* EOL - do not finalize word */
  5520. break;
  5521. if (G.ifs_whitespace != G.ifs /* usually false ($IFS is usually all whitespace), */
  5522. && strchr(G.ifs, *str) /* the second check would fail */
  5523. ) {
  5524. /* This is a non-whitespace $IFS char */
  5525. /* Skip it and IFS whitespace chars, start new word */
  5526. str++;
  5527. str += strspn(str, G.ifs_whitespace);
  5528. goto new_word;
  5529. }
  5530. /* Start new word... but not always! */
  5531. /* Case "v=' a'; echo ''$v": we do need to finalize empty word: */
  5532. if (output->has_quoted_part
  5533. /*
  5534. * Case "v=' a'; echo $v":
  5535. * here nothing precedes the space in $v expansion,
  5536. * therefore we should not finish the word
  5537. * (IOW: if there *is* word to finalize, only then do it):
  5538. * It's okay if this accesses the byte before first argv[]:
  5539. * past call to o_save_ptr() cleared it to zero byte
  5540. * (grep for -prev-ifs-check-).
  5541. */
  5542. || output->data[output->length - 1]
  5543. ) {
  5544. new_word:
  5545. o_addchr(output, '\0');
  5546. debug_print_list("expand_on_ifs", output, n);
  5547. n = o_save_ptr(output, n);
  5548. }
  5549. }
  5550. output->ended_in_ifs = last_is_ifs;
  5551. debug_print_list("expand_on_ifs[1]", output, n);
  5552. return n;
  5553. }
  5554. /* Helper to expand $((...)) and heredoc body. These act as if
  5555. * they are in double quotes, with the exception that they are not :).
  5556. * Just the rules are similar: "expand only $var and `cmd`"
  5557. *
  5558. * Returns malloced string.
  5559. * As an optimization, we return NULL if expansion is not needed.
  5560. */
  5561. static char *encode_then_expand_string(const char *str)
  5562. {
  5563. char *exp_str;
  5564. struct in_str input;
  5565. o_string dest = NULL_O_STRING;
  5566. const char *cp;
  5567. cp = str;
  5568. for (;;) {
  5569. if (!*cp) return NULL; /* string has no special chars */
  5570. if (*cp == '$') break;
  5571. if (*cp == '\\') break;
  5572. #if ENABLE_HUSH_TICK
  5573. if (*cp == '`') break;
  5574. #endif
  5575. cp++;
  5576. }
  5577. /* We need to expand. Example:
  5578. * echo $(($a + `echo 1`)) $((1 + $((2)) ))
  5579. */
  5580. setup_string_in_str(&input, str);
  5581. encode_string(NULL, &dest, &input, EOF);
  5582. //TODO: error check (encode_string returns 0 on error)?
  5583. //bb_error_msg("'%s' -> '%s'", str, dest.data);
  5584. exp_str = expand_string_to_string(dest.data,
  5585. EXP_FLAG_ESC_GLOB_CHARS,
  5586. /*unbackslash:*/ 1
  5587. );
  5588. //bb_error_msg("'%s' -> '%s'", dest.data, exp_str);
  5589. o_free(&dest);
  5590. return exp_str;
  5591. }
  5592. static const char *first_special_char_in_vararg(const char *cp)
  5593. {
  5594. for (;;) {
  5595. if (!*cp) return NULL; /* string has no special chars */
  5596. if (*cp == '$') return cp;
  5597. if (*cp == '\\') return cp;
  5598. if (*cp == '\'') return cp;
  5599. if (*cp == '"') return cp;
  5600. #if ENABLE_HUSH_TICK
  5601. if (*cp == '`') return cp;
  5602. #endif
  5603. /* dquoted "${x:+ARG}" should not glob, therefore
  5604. * '*' et al require some non-literal processing: */
  5605. if (*cp == '*') return cp;
  5606. if (*cp == '?') return cp;
  5607. if (*cp == '[') return cp;
  5608. cp++;
  5609. }
  5610. }
  5611. /* Expanding ARG in ${var#ARG}, ${var%ARG}, or ${var/ARG/ARG}.
  5612. * These can contain single- and double-quoted strings,
  5613. * and treated as if the ARG string is initially unquoted. IOW:
  5614. * ${var#ARG} and "${var#ARG}" treat ARG the same (ARG can even be
  5615. * a dquoted string: "${var#"zz"}"), the difference only comes later
  5616. * (word splitting and globbing of the ${var...} result).
  5617. */
  5618. #if !BASH_PATTERN_SUBST
  5619. #define encode_then_expand_vararg(str, handle_squotes, do_unbackslash) \
  5620. encode_then_expand_vararg(str, handle_squotes)
  5621. #endif
  5622. static char *encode_then_expand_vararg(const char *str, int handle_squotes, int do_unbackslash)
  5623. {
  5624. #if !BASH_PATTERN_SUBST && ENABLE_HUSH_CASE
  5625. const int do_unbackslash = 0;
  5626. #endif
  5627. char *exp_str;
  5628. struct in_str input;
  5629. o_string dest = NULL_O_STRING;
  5630. if (!first_special_char_in_vararg(str)) {
  5631. /* string has no special chars */
  5632. return NULL;
  5633. }
  5634. setup_string_in_str(&input, str);
  5635. dest.data = xzalloc(1); /* start as "", not as NULL */
  5636. exp_str = NULL;
  5637. for (;;) {
  5638. int ch;
  5639. ch = i_getch(&input);
  5640. debug_printf_parse("%s: ch=%c (%d) escape=%d\n",
  5641. __func__, ch, ch, !!dest.o_expflags);
  5642. if (!dest.o_expflags) {
  5643. if (ch == EOF)
  5644. break;
  5645. if (handle_squotes && ch == '\'') {
  5646. if (!add_till_single_quote_dquoted(&dest, &input))
  5647. goto ret; /* error */
  5648. continue;
  5649. }
  5650. }
  5651. if (ch == EOF) {
  5652. syntax_error_unterm_ch('"');
  5653. goto ret; /* error */
  5654. }
  5655. if (ch == '"') {
  5656. dest.o_expflags ^= EXP_FLAG_ESC_GLOB_CHARS;
  5657. continue;
  5658. }
  5659. if (ch == '\\') {
  5660. ch = i_getch(&input);
  5661. if (ch == EOF) {
  5662. //example? error message? syntax_error_unterm_ch('"');
  5663. debug_printf_parse("%s: error: \\<eof>\n", __func__);
  5664. goto ret;
  5665. }
  5666. o_addqchr(&dest, ch);
  5667. continue;
  5668. }
  5669. if (ch == '$') {
  5670. if (!parse_dollar(NULL, &dest, &input, /*quote_mask:*/ 0x80)) {
  5671. debug_printf_parse("%s: error: parse_dollar returned 0 (error)\n", __func__);
  5672. goto ret;
  5673. }
  5674. continue;
  5675. }
  5676. #if ENABLE_HUSH_TICK
  5677. if (ch == '`') {
  5678. //unsigned pos = dest->length;
  5679. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  5680. o_addchr(&dest, 0x80 | '`');
  5681. if (!add_till_backquote(&dest, &input,
  5682. /*in_dquote:*/ dest.o_expflags /* nonzero if EXP_FLAG_ESC_GLOB_CHARS set */
  5683. )
  5684. ) {
  5685. goto ret; /* error */
  5686. }
  5687. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  5688. //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
  5689. continue;
  5690. }
  5691. #endif
  5692. o_addQchr(&dest, ch);
  5693. } /* for (;;) */
  5694. debug_printf_parse("encode: '%s' -> '%s'\n", str, dest.data);
  5695. exp_str = expand_string_to_string(dest.data,
  5696. do_unbackslash ? EXP_FLAG_ESC_GLOB_CHARS : 0,
  5697. do_unbackslash
  5698. );
  5699. ret:
  5700. debug_printf_parse("expand: '%s' -> '%s'\n", dest.data, exp_str);
  5701. o_free(&dest);
  5702. return exp_str;
  5703. }
  5704. /* Expanding ARG in ${var+ARG}, ${var-ARG}
  5705. */
  5706. static int encode_then_append_var_plusminus(o_string *output, int n,
  5707. char *str, int dquoted)
  5708. {
  5709. struct in_str input;
  5710. o_string dest = NULL_O_STRING;
  5711. if (!first_special_char_in_vararg(str)
  5712. && '\0' == str[strcspn(str, G.ifs)]
  5713. ) {
  5714. /* string has no special chars
  5715. * && string has no $IFS chars
  5716. */
  5717. if (dquoted) {
  5718. /* Prints 1 (quoted expansion is a "" word, not nothing):
  5719. * set -- "${notexist-}"; echo $#
  5720. */
  5721. output->has_quoted_part = 1;
  5722. }
  5723. return expand_vars_to_list(output, n, str);
  5724. }
  5725. setup_string_in_str(&input, str);
  5726. for (;;) {
  5727. int ch;
  5728. ch = i_getch(&input);
  5729. debug_printf_parse("%s: ch=%c (%d) escape=%x\n",
  5730. __func__, ch, ch, dest.o_expflags);
  5731. if (!dest.o_expflags) {
  5732. if (ch == EOF)
  5733. break;
  5734. if (!dquoted && strchr(G.ifs, ch)) {
  5735. /* PREFIX${x:d${e}f ...} and we met space: expand "d${e}f" and start new word.
  5736. * do not assume we are at the start of the word (PREFIX above).
  5737. */
  5738. if (dest.data) {
  5739. n = expand_vars_to_list(output, n, dest.data);
  5740. o_free_and_set_NULL(&dest);
  5741. o_addchr(output, '\0');
  5742. n = o_save_ptr(output, n); /* create next word */
  5743. } else
  5744. if (output->length != o_get_last_ptr(output, n)
  5745. || output->has_quoted_part
  5746. ) {
  5747. /* For these cases:
  5748. * f() { for i; do echo "|$i|"; done; }; x=x
  5749. * f a${x:+ }b # 1st condition
  5750. * |a|
  5751. * |b|
  5752. * f ""${x:+ }b # 2nd condition
  5753. * ||
  5754. * |b|
  5755. */
  5756. o_addchr(output, '\0');
  5757. n = o_save_ptr(output, n); /* create next word */
  5758. }
  5759. continue;
  5760. }
  5761. if (!dquoted && ch == '\'') {
  5762. if (!add_till_single_quote_dquoted(&dest, &input))
  5763. goto ret; /* error */
  5764. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  5765. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  5766. continue;
  5767. }
  5768. }
  5769. if (ch == EOF) {
  5770. syntax_error_unterm_ch('"');
  5771. goto ret; /* error */
  5772. }
  5773. if (ch == '"') {
  5774. dest.o_expflags ^= EXP_FLAG_ESC_GLOB_CHARS;
  5775. if (dest.o_expflags) {
  5776. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  5777. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  5778. }
  5779. continue;
  5780. }
  5781. if (ch == '\\') {
  5782. ch = i_getch(&input);
  5783. if (ch == EOF) {
  5784. //example? error message? syntax_error_unterm_ch('"');
  5785. debug_printf_parse("%s: error: \\<eof>\n", __func__);
  5786. goto ret;
  5787. }
  5788. o_addqchr(&dest, ch);
  5789. continue;
  5790. }
  5791. if (ch == '$') {
  5792. if (!parse_dollar(NULL, &dest, &input, /*quote_mask:*/ (dest.o_expflags || dquoted) ? 0x80 : 0)) {
  5793. debug_printf_parse("%s: error: parse_dollar returned 0 (error)\n", __func__);
  5794. goto ret;
  5795. }
  5796. continue;
  5797. }
  5798. #if ENABLE_HUSH_TICK
  5799. if (ch == '`') {
  5800. //unsigned pos = dest->length;
  5801. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  5802. o_addchr(&dest, (dest.o_expflags || dquoted) ? 0x80 | '`' : '`');
  5803. if (!add_till_backquote(&dest, &input,
  5804. /*in_dquote:*/ dest.o_expflags /* nonzero if EXP_FLAG_ESC_GLOB_CHARS set */
  5805. )
  5806. ) {
  5807. goto ret; /* error */
  5808. }
  5809. o_addchr(&dest, SPECIAL_VAR_SYMBOL);
  5810. //debug_printf_subst("SUBST RES3 '%s'\n", dest->data + pos);
  5811. continue;
  5812. }
  5813. #endif
  5814. if (dquoted) {
  5815. /* Always glob-protect if in dquotes:
  5816. * x=x; echo "${x:+/bin/c*}" - prints: /bin/c*
  5817. * x=x; echo "${x:+"/bin/c*"}" - prints: /bin/c*
  5818. */
  5819. o_addqchr(&dest, ch);
  5820. } else {
  5821. /* Glob-protect only if char is quoted:
  5822. * x=x; echo ${x:+/bin/c*} - prints many filenames
  5823. * x=x; echo ${x:+"/bin/c*"} - prints: /bin/c*
  5824. */
  5825. o_addQchr(&dest, ch);
  5826. }
  5827. } /* for (;;) */
  5828. if (dest.data) {
  5829. n = expand_vars_to_list(output, n, dest.data);
  5830. }
  5831. ret:
  5832. o_free(&dest);
  5833. return n;
  5834. }
  5835. #if ENABLE_FEATURE_SH_MATH
  5836. static arith_t expand_and_evaluate_arith(const char *arg, const char **errmsg_p)
  5837. {
  5838. arith_state_t math_state;
  5839. arith_t res;
  5840. char *exp_str;
  5841. math_state.lookupvar = get_local_var_value;
  5842. math_state.setvar = set_local_var_from_halves;
  5843. //math_state.endofname = endofname;
  5844. exp_str = encode_then_expand_string(arg);
  5845. res = arith(&math_state, exp_str ? exp_str : arg);
  5846. free(exp_str);
  5847. if (errmsg_p)
  5848. *errmsg_p = math_state.errmsg;
  5849. if (math_state.errmsg)
  5850. msg_and_die_if_script(math_state.errmsg);
  5851. return res;
  5852. }
  5853. #endif
  5854. #if BASH_PATTERN_SUBST
  5855. /* ${var/[/]pattern[/repl]} helpers */
  5856. static char *strstr_pattern(char *val, const char *pattern, int *size)
  5857. {
  5858. while (1) {
  5859. char *end = scan_and_match(val, pattern, SCAN_MOVE_FROM_RIGHT + SCAN_MATCH_LEFT_HALF);
  5860. debug_printf_varexp("val:'%s' pattern:'%s' end:'%s'\n", val, pattern, end);
  5861. if (end) {
  5862. *size = end - val;
  5863. return val;
  5864. }
  5865. if (*val == '\0')
  5866. return NULL;
  5867. /* Optimization: if "*pat" did not match the start of "string",
  5868. * we know that "tring", "ring" etc will not match too:
  5869. */
  5870. if (pattern[0] == '*')
  5871. return NULL;
  5872. val++;
  5873. }
  5874. }
  5875. static char *replace_pattern(char *val, const char *pattern, const char *repl, char exp_op)
  5876. {
  5877. char *result = NULL;
  5878. unsigned res_len = 0;
  5879. unsigned repl_len = strlen(repl);
  5880. /* Null pattern never matches, including if "var" is empty */
  5881. if (!pattern[0])
  5882. return result; /* NULL, no replaces happened */
  5883. while (1) {
  5884. int size;
  5885. char *s = strstr_pattern(val, pattern, &size);
  5886. if (!s)
  5887. break;
  5888. result = xrealloc(result, res_len + (s - val) + repl_len + 1);
  5889. strcpy(mempcpy(result + res_len, val, s - val), repl);
  5890. res_len += (s - val) + repl_len;
  5891. debug_printf_varexp("val:'%s' s:'%s' result:'%s'\n", val, s, result);
  5892. val = s + size;
  5893. if (exp_op == '/')
  5894. break;
  5895. }
  5896. if (*val && result) {
  5897. result = xrealloc(result, res_len + strlen(val) + 1);
  5898. strcpy(result + res_len, val);
  5899. debug_printf_varexp("val:'%s' result:'%s'\n", val, result);
  5900. }
  5901. debug_printf_varexp("result:'%s'\n", result);
  5902. return result;
  5903. }
  5904. #endif /* BASH_PATTERN_SUBST */
  5905. static int append_str_maybe_ifs_split(o_string *output, int n,
  5906. int first_ch, const char *val)
  5907. {
  5908. if (!(first_ch & 0x80)) { /* unquoted $VAR */
  5909. debug_printf_expand("unquoted '%s', output->o_escape:%d\n", val,
  5910. !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
  5911. if (val && val[0])
  5912. n = expand_on_ifs(output, n, val);
  5913. } else { /* quoted "$VAR" */
  5914. output->has_quoted_part = 1;
  5915. debug_printf_expand("quoted '%s', output->o_escape:%d\n", val,
  5916. !!(output->o_expflags & EXP_FLAG_ESC_GLOB_CHARS));
  5917. if (val && val[0])
  5918. o_addQstr(output, val);
  5919. }
  5920. return n;
  5921. }
  5922. /* Handle <SPECIAL_VAR_SYMBOL>varname...<SPECIAL_VAR_SYMBOL> construct.
  5923. */
  5924. static NOINLINE int expand_one_var(o_string *output, int n,
  5925. int first_ch, char *arg, char **pp)
  5926. {
  5927. const char *val;
  5928. char *to_be_freed;
  5929. char *p;
  5930. char *var;
  5931. char exp_op;
  5932. char exp_save = exp_save; /* for compiler */
  5933. char *exp_saveptr; /* points to expansion operator */
  5934. char *exp_word = exp_word; /* for compiler */
  5935. char arg0;
  5936. val = NULL;
  5937. to_be_freed = NULL;
  5938. p = *pp;
  5939. *p = '\0'; /* replace trailing SPECIAL_VAR_SYMBOL */
  5940. var = arg;
  5941. exp_saveptr = arg[1] ? strchr(VAR_ENCODED_SUBST_OPS, arg[1]) : NULL;
  5942. arg0 = arg[0];
  5943. arg[0] = (arg0 & 0x7f);
  5944. exp_op = 0;
  5945. if (arg[0] == '#' && arg[1] /* ${#...} but not ${#} */
  5946. && (!exp_saveptr /* and ( not(${#<op_char>...}) */
  5947. || (arg[2] == '\0' && strchr(SPECIAL_VARS_STR, arg[1])) /* or ${#C} "len of $C" ) */
  5948. ) /* NB: skipping ^^^specvar check mishandles ${#::2} */
  5949. ) {
  5950. /* It must be length operator: ${#var} */
  5951. var++;
  5952. exp_op = 'L';
  5953. } else {
  5954. /* Maybe handle parameter expansion */
  5955. if (exp_saveptr /* if 2nd char is one of expansion operators */
  5956. && strchr(NUMERIC_SPECVARS_STR, arg[0]) /* 1st char is special variable */
  5957. ) {
  5958. /* ${?:0}, ${#[:]%0} etc */
  5959. exp_saveptr = var + 1;
  5960. } else {
  5961. /* ${?}, ${var}, ${var:0}, ${var[:]%0} etc */
  5962. exp_saveptr = var+1 + strcspn(var+1, VAR_ENCODED_SUBST_OPS);
  5963. }
  5964. exp_op = exp_save = *exp_saveptr;
  5965. if (exp_op) {
  5966. exp_word = exp_saveptr + 1;
  5967. if (exp_op == ':') {
  5968. exp_op = *exp_word++;
  5969. //TODO: try ${var:} and ${var:bogus} in non-bash config
  5970. if (BASH_SUBSTR
  5971. && (!exp_op || !strchr(MINUS_PLUS_EQUAL_QUESTION, exp_op))
  5972. ) {
  5973. /* oops... it's ${var:N[:M]}, not ${var:?xxx} or some such */
  5974. exp_op = ':';
  5975. exp_word--;
  5976. }
  5977. }
  5978. *exp_saveptr = '\0';
  5979. } /* else: it's not an expansion op, but bare ${var} */
  5980. }
  5981. /* Look up the variable in question */
  5982. if (isdigit(var[0])) {
  5983. /* parse_dollar should have vetted var for us */
  5984. int nn = xatoi_positive(var);
  5985. if (nn < G.global_argc)
  5986. val = G.global_argv[nn];
  5987. /* else val remains NULL: $N with too big N */
  5988. } else {
  5989. switch (var[0]) {
  5990. case '$': /* pid */
  5991. val = utoa(G.root_pid);
  5992. break;
  5993. case '!': /* bg pid */
  5994. val = G.last_bg_pid ? utoa(G.last_bg_pid) : "";
  5995. break;
  5996. case '?': /* exitcode */
  5997. val = utoa(G.last_exitcode);
  5998. break;
  5999. case '#': /* argc */
  6000. val = utoa(G.global_argc ? G.global_argc-1 : 0);
  6001. break;
  6002. case '-': { /* active options */
  6003. /* Check set_mode() to see what option chars we support */
  6004. char *cp;
  6005. val = cp = G.optstring_buf;
  6006. if (G.o_opt[OPT_O_ERREXIT])
  6007. *cp++ = 'e';
  6008. if (G_interactive_fd)
  6009. *cp++ = 'i';
  6010. if (G_x_mode)
  6011. *cp++ = 'x';
  6012. /* If G.o_opt[OPT_O_NOEXEC] is true,
  6013. * commands read but are not executed,
  6014. * so $- can not execute too, 'n' is never seen in $-.
  6015. */
  6016. if (G.opt_c)
  6017. *cp++ = 'c';
  6018. if (G.opt_s)
  6019. *cp++ = 's';
  6020. *cp = '\0';
  6021. break;
  6022. }
  6023. default:
  6024. val = get_local_var_value(var);
  6025. }
  6026. }
  6027. /* Handle any expansions */
  6028. if (exp_op == 'L') {
  6029. reinit_unicode_for_hush();
  6030. debug_printf_expand("expand: length(%s)=", val);
  6031. val = utoa(val ? unicode_strlen(val) : 0);
  6032. debug_printf_expand("%s\n", val);
  6033. } else if (exp_op) {
  6034. if (exp_op == '%' || exp_op == '#') {
  6035. /* Standard-mandated substring removal ops:
  6036. * ${parameter%word} - remove smallest suffix pattern
  6037. * ${parameter%%word} - remove largest suffix pattern
  6038. * ${parameter#word} - remove smallest prefix pattern
  6039. * ${parameter##word} - remove largest prefix pattern
  6040. *
  6041. * Word is expanded to produce a glob pattern.
  6042. * Then var's value is matched to it and matching part removed.
  6043. */
  6044. //FIXME: ${x#...${...}...}
  6045. //should evaluate inner ${...} even if x is "" and no shrinking of it is possible -
  6046. //inner ${...} may have side effects!
  6047. if (val && val[0]) {
  6048. char *t;
  6049. char *exp_exp_word;
  6050. char *loc;
  6051. unsigned scan_flags = pick_scan(exp_op, *exp_word);
  6052. if (exp_op == *exp_word) /* ## or %% */
  6053. exp_word++;
  6054. debug_printf_expand("expand: exp_word:'%s'\n", exp_word);
  6055. exp_exp_word = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 0);
  6056. if (exp_exp_word)
  6057. exp_word = exp_exp_word;
  6058. debug_printf_expand("expand: exp_word:'%s'\n", exp_word);
  6059. /*
  6060. * HACK ALERT. We depend here on the fact that
  6061. * G.global_argv and results of utoa and get_local_var_value
  6062. * are actually in writable memory:
  6063. * scan_and_match momentarily stores NULs there.
  6064. */
  6065. t = (char*)val;
  6066. loc = scan_and_match(t, exp_word, scan_flags);
  6067. debug_printf_expand("op:%c str:'%s' pat:'%s' res:'%s'\n", exp_op, t, exp_word, loc);
  6068. free(exp_exp_word);
  6069. if (loc) { /* match was found */
  6070. if (scan_flags & SCAN_MATCH_LEFT_HALF) /* #[#] */
  6071. val = loc; /* take right part */
  6072. else /* %[%] */
  6073. val = to_be_freed = xstrndup(val, loc - val); /* left */
  6074. }
  6075. }
  6076. }
  6077. #if BASH_PATTERN_SUBST
  6078. else if (exp_op == '/' || exp_op == '\\') {
  6079. /* It's ${var/[/]pattern[/repl]} thing.
  6080. * Note that in encoded form it has TWO parts:
  6081. * var/pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
  6082. * and if // is used, it is encoded as \:
  6083. * var\pattern<SPECIAL_VAR_SYMBOL>repl<SPECIAL_VAR_SYMBOL>
  6084. */
  6085. if (val && val[0]) {
  6086. /* pattern uses non-standard expansion.
  6087. * repl should be unbackslashed and globbed
  6088. * by the usual expansion rules:
  6089. * >az >bz
  6090. * v='a bz'; echo "${v/a*z/a*z}" #prints "a*z"
  6091. * v='a bz'; echo "${v/a*z/\z}" #prints "z"
  6092. * v='a bz'; echo ${v/a*z/a*z} #prints "az"
  6093. * v='a bz'; echo ${v/a*z/\z} #prints "z"
  6094. * (note that a*z _pattern_ is never globbed!)
  6095. */
  6096. char *pattern, *repl, *t;
  6097. pattern = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 0);
  6098. if (!pattern)
  6099. pattern = xstrdup(exp_word);
  6100. debug_printf_varexp("pattern:'%s'->'%s'\n", exp_word, pattern);
  6101. *p++ = SPECIAL_VAR_SYMBOL;
  6102. exp_word = p;
  6103. p = strchr(p, SPECIAL_VAR_SYMBOL);
  6104. *p = '\0';
  6105. repl = encode_then_expand_vararg(exp_word, /*handle_squotes:*/ 1, /*unbackslash:*/ 1);
  6106. debug_printf_varexp("repl:'%s'->'%s'\n", exp_word, repl);
  6107. /* HACK ALERT. We depend here on the fact that
  6108. * G.global_argv and results of utoa and get_local_var_value
  6109. * are actually in writable memory:
  6110. * replace_pattern momentarily stores NULs there. */
  6111. t = (char*)val;
  6112. to_be_freed = replace_pattern(t,
  6113. pattern,
  6114. (repl ? repl : exp_word),
  6115. exp_op);
  6116. if (to_be_freed) /* at least one replace happened */
  6117. val = to_be_freed;
  6118. free(pattern);
  6119. free(repl);
  6120. } else {
  6121. /* Empty variable always gives nothing */
  6122. // "v=''; echo ${v/*/w}" prints "", not "w"
  6123. /* Just skip "replace" part */
  6124. *p++ = SPECIAL_VAR_SYMBOL;
  6125. p = strchr(p, SPECIAL_VAR_SYMBOL);
  6126. *p = '\0';
  6127. }
  6128. }
  6129. #endif /* BASH_PATTERN_SUBST */
  6130. else if (exp_op == ':') {
  6131. #if BASH_SUBSTR && ENABLE_FEATURE_SH_MATH
  6132. /* It's ${var:N[:M]} bashism.
  6133. * Note that in encoded form it has TWO parts:
  6134. * var:N<SPECIAL_VAR_SYMBOL>M<SPECIAL_VAR_SYMBOL>
  6135. */
  6136. arith_t beg, len;
  6137. const char *errmsg;
  6138. beg = expand_and_evaluate_arith(exp_word, &errmsg);
  6139. if (errmsg)
  6140. goto arith_err;
  6141. debug_printf_varexp("beg:'%s'=%lld\n", exp_word, (long long)beg);
  6142. *p++ = SPECIAL_VAR_SYMBOL;
  6143. exp_word = p;
  6144. p = strchr(p, SPECIAL_VAR_SYMBOL);
  6145. *p = '\0';
  6146. len = expand_and_evaluate_arith(exp_word, &errmsg);
  6147. if (errmsg)
  6148. goto arith_err;
  6149. debug_printf_varexp("len:'%s'=%lld\n", exp_word, (long long)len);
  6150. if (beg < 0) {
  6151. /* negative beg counts from the end */
  6152. beg = (arith_t)strlen(val) + beg;
  6153. if (beg < 0) /* ${v: -999999} is "" */
  6154. beg = len = 0;
  6155. }
  6156. debug_printf_varexp("from val:'%s'\n", val);
  6157. if (len < 0) {
  6158. /* in bash, len=-n means strlen()-n */
  6159. len = (arith_t)strlen(val) - beg + len;
  6160. if (len < 0) /* bash compat */
  6161. msg_and_die_if_script("%s: substring expression < 0", var);
  6162. }
  6163. if (len <= 0 || !val || beg >= strlen(val)) {
  6164. arith_err:
  6165. val = NULL;
  6166. } else {
  6167. /* Paranoia. What if user entered 9999999999999
  6168. * which fits in arith_t but not int? */
  6169. if (len >= INT_MAX)
  6170. len = INT_MAX;
  6171. val = to_be_freed = xstrndup(val + beg, len);
  6172. }
  6173. debug_printf_varexp("val:'%s'\n", val);
  6174. #else /* not (HUSH_SUBSTR_EXPANSION && FEATURE_SH_MATH) */
  6175. msg_and_die_if_script("malformed ${%s:...}", var);
  6176. val = NULL;
  6177. #endif
  6178. } else { /* one of "-=+?" */
  6179. /* Standard-mandated substitution ops:
  6180. * ${var?word} - indicate error if unset
  6181. * If var is unset, word (or a message indicating it is unset
  6182. * if word is null) is written to standard error
  6183. * and the shell exits with a non-zero exit status.
  6184. * Otherwise, the value of var is substituted.
  6185. * ${var-word} - use default value
  6186. * If var is unset, word is substituted.
  6187. * ${var=word} - assign and use default value
  6188. * If var is unset, word is assigned to var.
  6189. * In all cases, final value of var is substituted.
  6190. * ${var+word} - use alternative value
  6191. * If var is unset, null is substituted.
  6192. * Otherwise, word is substituted.
  6193. *
  6194. * Word is subjected to tilde expansion, parameter expansion,
  6195. * command substitution, and arithmetic expansion.
  6196. * If word is not needed, it is not expanded.
  6197. *
  6198. * Colon forms (${var:-word}, ${var:=word} etc) do the same,
  6199. * but also treat null var as if it is unset.
  6200. *
  6201. * Word-splitting and single quote behavior:
  6202. *
  6203. * $ f() { for i; do echo "|$i|"; done; };
  6204. *
  6205. * $ x=; f ${x:?'x y' z}
  6206. * bash: x: x y z #BUG: does not abort, ${} results in empty expansion
  6207. * $ x=; f "${x:?'x y' z}"
  6208. * bash: x: x y z # dash prints: dash: x: 'x y' z #BUG: does not abort, ${} results in ""
  6209. *
  6210. * $ x=; f ${x:='x y' z}
  6211. * |x|
  6212. * |y|
  6213. * |z|
  6214. * $ x=; f "${x:='x y' z}"
  6215. * |'x y' z|
  6216. *
  6217. * $ x=x; f ${x:+'x y' z}
  6218. * |x y|
  6219. * |z|
  6220. * $ x=x; f "${x:+'x y' z}"
  6221. * |'x y' z|
  6222. *
  6223. * $ x=; f ${x:-'x y' z}
  6224. * |x y|
  6225. * |z|
  6226. * $ x=; f "${x:-'x y' z}"
  6227. * |'x y' z|
  6228. */
  6229. int use_word = (!val || ((exp_save == ':') && !val[0]));
  6230. if (exp_op == '+')
  6231. use_word = !use_word;
  6232. debug_printf_expand("expand: op:%c (null:%s) test:%i\n", exp_op,
  6233. (exp_save == ':') ? "true" : "false", use_word);
  6234. if (use_word) {
  6235. if (exp_op == '+' || exp_op == '-') {
  6236. /* ${var+word} - use alternative value */
  6237. /* ${var-word} - use default value */
  6238. n = encode_then_append_var_plusminus(output, n, exp_word,
  6239. /*dquoted:*/ (arg0 & 0x80)
  6240. );
  6241. val = NULL;
  6242. } else {
  6243. /* ${var?word} - indicate error if unset */
  6244. /* ${var=word} - assign and use default value */
  6245. to_be_freed = encode_then_expand_vararg(exp_word,
  6246. /*handle_squotes:*/ !(arg0 & 0x80),
  6247. /*unbackslash:*/ 0
  6248. );
  6249. if (to_be_freed)
  6250. exp_word = to_be_freed;
  6251. if (exp_op == '?') {
  6252. /* mimic bash message */
  6253. msg_and_die_if_script("%s: %s",
  6254. var,
  6255. exp_word[0]
  6256. ? exp_word
  6257. : "parameter null or not set"
  6258. /* ash has more specific messages, a-la: */
  6259. /*: (exp_save == ':' ? "parameter null or not set" : "parameter not set")*/
  6260. );
  6261. //TODO: how interactive bash aborts expansion mid-command?
  6262. //It aborts the entire line, returns to prompt:
  6263. // $ f() { for i; do echo "|$i|"; done; }; x=; f "${x:?'x y' z}"; echo YO
  6264. // bash: x: x y z
  6265. // $
  6266. // ("echo YO" is not executed, neither the f function call)
  6267. } else {
  6268. val = exp_word;
  6269. }
  6270. if (exp_op == '=') {
  6271. /* ${var=[word]} or ${var:=[word]} */
  6272. if (isdigit(var[0]) || var[0] == '#') {
  6273. /* mimic bash message */
  6274. msg_and_die_if_script("$%s: cannot assign in this way", var);
  6275. val = NULL;
  6276. } else {
  6277. char *new_var = xasprintf("%s=%s", var, val);
  6278. set_local_var(new_var, /*flag:*/ 0);
  6279. }
  6280. }
  6281. }
  6282. }
  6283. } /* one of "-=+?" */
  6284. *exp_saveptr = exp_save;
  6285. } /* if (exp_op) */
  6286. arg[0] = arg0;
  6287. *pp = p;
  6288. n = append_str_maybe_ifs_split(output, n, first_ch, val);
  6289. free(to_be_freed);
  6290. return n;
  6291. }
  6292. /* Expand all variable references in given string, adding words to list[]
  6293. * at n, n+1,... positions. Return updated n (so that list[n] is next one
  6294. * to be filled). This routine is extremely tricky: has to deal with
  6295. * variables/parameters with whitespace, $* and $@, and constructs like
  6296. * 'echo -$*-'. If you play here, you must run testsuite afterwards! */
  6297. static NOINLINE int expand_vars_to_list(o_string *output, int n, char *arg)
  6298. {
  6299. /* output->o_expflags & EXP_FLAG_SINGLEWORD (0x80) if we are in
  6300. * expansion of right-hand side of assignment == 1-element expand.
  6301. */
  6302. char cant_be_null = 0; /* only bit 0x80 matters */
  6303. char *p;
  6304. debug_printf_expand("expand_vars_to_list: arg:'%s' singleword:%x\n", arg,
  6305. !!(output->o_expflags & EXP_FLAG_SINGLEWORD));
  6306. debug_print_list("expand_vars_to_list[0]", output, n);
  6307. while ((p = strchr(arg, SPECIAL_VAR_SYMBOL)) != NULL) {
  6308. char first_ch;
  6309. #if ENABLE_FEATURE_SH_MATH
  6310. char arith_buf[sizeof(arith_t)*3 + 2];
  6311. #endif
  6312. if (output->ended_in_ifs) {
  6313. o_addchr(output, '\0');
  6314. n = o_save_ptr(output, n);
  6315. output->ended_in_ifs = 0;
  6316. }
  6317. o_addblock(output, arg, p - arg);
  6318. debug_print_list("expand_vars_to_list[1]", output, n);
  6319. arg = ++p;
  6320. p = strchr(p, SPECIAL_VAR_SYMBOL);
  6321. /* Fetch special var name (if it is indeed one of them)
  6322. * and quote bit, force the bit on if singleword expansion -
  6323. * important for not getting v=$@ expand to many words. */
  6324. first_ch = arg[0] | (output->o_expflags & EXP_FLAG_SINGLEWORD);
  6325. /* Is this variable quoted and thus expansion can't be null?
  6326. * "$@" is special. Even if quoted, it can still
  6327. * expand to nothing (not even an empty string),
  6328. * thus it is excluded. */
  6329. if ((first_ch & 0x7f) != '@')
  6330. cant_be_null |= first_ch;
  6331. switch (first_ch & 0x7f) {
  6332. /* Highest bit in first_ch indicates that var is double-quoted */
  6333. case '*':
  6334. case '@': {
  6335. int i;
  6336. if (!G.global_argv[1])
  6337. break;
  6338. i = 1;
  6339. cant_be_null |= first_ch; /* do it for "$@" _now_, when we know it's not empty */
  6340. if (!(first_ch & 0x80)) { /* unquoted $* or $@ */
  6341. while (G.global_argv[i]) {
  6342. n = expand_on_ifs(output, n, G.global_argv[i]);
  6343. debug_printf_expand("expand_vars_to_list: argv %d (last %d)\n", i, G.global_argc - 1);
  6344. if (G.global_argv[i++][0] && G.global_argv[i]) {
  6345. /* this argv[] is not empty and not last:
  6346. * put terminating NUL, start new word */
  6347. o_addchr(output, '\0');
  6348. debug_print_list("expand_vars_to_list[2]", output, n);
  6349. n = o_save_ptr(output, n);
  6350. debug_print_list("expand_vars_to_list[3]", output, n);
  6351. }
  6352. }
  6353. } else
  6354. /* If EXP_FLAG_SINGLEWORD, we handle assignment 'a=....$@.....'
  6355. * and in this case should treat it like '$*' - see 'else...' below */
  6356. if (first_ch == (char)('@'|0x80) /* quoted $@ */
  6357. && !(output->o_expflags & EXP_FLAG_SINGLEWORD) /* not v="$@" case */
  6358. ) {
  6359. while (1) {
  6360. o_addQstr(output, G.global_argv[i]);
  6361. if (++i >= G.global_argc)
  6362. break;
  6363. o_addchr(output, '\0');
  6364. debug_print_list("expand_vars_to_list[4]", output, n);
  6365. n = o_save_ptr(output, n);
  6366. }
  6367. } else { /* quoted $* (or v="$@" case): add as one word */
  6368. while (1) {
  6369. o_addQstr(output, G.global_argv[i]);
  6370. if (!G.global_argv[++i])
  6371. break;
  6372. if (G.ifs[0])
  6373. o_addchr(output, G.ifs[0]);
  6374. }
  6375. output->has_quoted_part = 1;
  6376. }
  6377. break;
  6378. }
  6379. case SPECIAL_VAR_SYMBOL: {
  6380. /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_SYMBOL> */
  6381. /* "Empty variable", used to make "" etc to not disappear */
  6382. output->has_quoted_part = 1;
  6383. cant_be_null = 0x80;
  6384. arg++;
  6385. break;
  6386. }
  6387. case SPECIAL_VAR_QUOTED_SVS:
  6388. /* <SPECIAL_VAR_SYMBOL><SPECIAL_VAR_QUOTED_SVS><SPECIAL_VAR_SYMBOL> */
  6389. /* "^C variable", represents literal ^C char (possible in scripts) */
  6390. o_addchr(output, SPECIAL_VAR_SYMBOL);
  6391. arg++;
  6392. break;
  6393. #if ENABLE_HUSH_TICK
  6394. case '`': {
  6395. /* <SPECIAL_VAR_SYMBOL>`cmd<SPECIAL_VAR_SYMBOL> */
  6396. o_string subst_result = NULL_O_STRING;
  6397. *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
  6398. arg++;
  6399. /* Can't just stuff it into output o_string,
  6400. * expanded result may need to be globbed
  6401. * and $IFS-split */
  6402. debug_printf_subst("SUBST '%s' first_ch %x\n", arg, first_ch);
  6403. G.last_exitcode = process_command_subs(&subst_result, arg);
  6404. G.expand_exitcode = G.last_exitcode;
  6405. debug_printf_subst("SUBST RES:%d '%s'\n", G.last_exitcode, subst_result.data);
  6406. n = append_str_maybe_ifs_split(output, n, first_ch, subst_result.data);
  6407. o_free(&subst_result);
  6408. break;
  6409. }
  6410. #endif
  6411. #if ENABLE_FEATURE_SH_MATH
  6412. case '+': {
  6413. /* <SPECIAL_VAR_SYMBOL>+arith<SPECIAL_VAR_SYMBOL> */
  6414. arith_t res;
  6415. arg++; /* skip '+' */
  6416. *p = '\0'; /* replace trailing <SPECIAL_VAR_SYMBOL> */
  6417. debug_printf_subst("ARITH '%s' first_ch %x\n", arg, first_ch);
  6418. res = expand_and_evaluate_arith(arg, NULL);
  6419. debug_printf_subst("ARITH RES '"ARITH_FMT"'\n", res);
  6420. sprintf(arith_buf, ARITH_FMT, res);
  6421. o_addstr(output, arith_buf);
  6422. break;
  6423. }
  6424. #endif
  6425. default:
  6426. /* <SPECIAL_VAR_SYMBOL>varname[ops]<SPECIAL_VAR_SYMBOL> */
  6427. n = expand_one_var(output, n, first_ch, arg, &p);
  6428. break;
  6429. } /* switch (char after <SPECIAL_VAR_SYMBOL>) */
  6430. /* Restore NULL'ed SPECIAL_VAR_SYMBOL.
  6431. * Do the check to avoid writing to a const string. */
  6432. if (*p != SPECIAL_VAR_SYMBOL)
  6433. *p = SPECIAL_VAR_SYMBOL;
  6434. arg = ++p;
  6435. } /* end of "while (SPECIAL_VAR_SYMBOL is found) ..." */
  6436. if (*arg) {
  6437. /* handle trailing string */
  6438. if (output->ended_in_ifs) {
  6439. o_addchr(output, '\0');
  6440. n = o_save_ptr(output, n);
  6441. }
  6442. debug_print_list("expand_vars_to_list[a]", output, n);
  6443. /* this part is literal, and it was already pre-quoted
  6444. * if needed (much earlier), do not use o_addQstr here!
  6445. */
  6446. o_addstr(output, arg);
  6447. debug_print_list("expand_vars_to_list[b]", output, n);
  6448. } else
  6449. if (output->length == o_get_last_ptr(output, n) /* expansion is empty */
  6450. && !(cant_be_null & 0x80) /* and all vars were not quoted */
  6451. && !output->has_quoted_part
  6452. ) {
  6453. n--;
  6454. /* allow to reuse list[n] later without re-growth */
  6455. output->has_empty_slot = 1;
  6456. }
  6457. return n;
  6458. }
  6459. static char **expand_variables(char **argv, unsigned expflags)
  6460. {
  6461. int n;
  6462. char **list;
  6463. o_string output = NULL_O_STRING;
  6464. output.o_expflags = expflags;
  6465. n = 0;
  6466. for (;;) {
  6467. /* go to next list[n] */
  6468. output.ended_in_ifs = 0;
  6469. n = o_save_ptr(&output, n);
  6470. if (!*argv)
  6471. break;
  6472. /* expand argv[i] */
  6473. n = expand_vars_to_list(&output, n, *argv++);
  6474. /* if (!output->has_empty_slot) -- need this?? */
  6475. o_addchr(&output, '\0');
  6476. }
  6477. debug_print_list("expand_variables", &output, n);
  6478. /* output.data (malloced in one block) gets returned in "list" */
  6479. list = o_finalize_list(&output, n);
  6480. debug_print_strings("expand_variables[1]", list);
  6481. return list;
  6482. }
  6483. static char **expand_strvec_to_strvec(char **argv)
  6484. {
  6485. return expand_variables(argv, EXP_FLAG_GLOB | EXP_FLAG_ESC_GLOB_CHARS);
  6486. }
  6487. #if defined(CMD_SINGLEWORD_NOGLOB)
  6488. static char **expand_strvec_to_strvec_singleword_noglob(char **argv)
  6489. {
  6490. return expand_variables(argv, EXP_FLAG_SINGLEWORD);
  6491. }
  6492. #endif
  6493. /* Used for expansion of right hand of assignments,
  6494. * $((...)), heredocs, variable expansion parts.
  6495. *
  6496. * NB: should NOT do globbing!
  6497. * "export v=/bin/c*; env | grep ^v=" outputs "v=/bin/c*"
  6498. */
  6499. static char *expand_string_to_string(const char *str, int EXP_flags, int do_unbackslash)
  6500. {
  6501. #if !BASH_PATTERN_SUBST && !ENABLE_HUSH_CASE
  6502. const int do_unbackslash = 1;
  6503. const int EXP_flags = EXP_FLAG_ESC_GLOB_CHARS;
  6504. #endif
  6505. char *argv[2], **list;
  6506. debug_printf_expand("string_to_string<='%s'\n", str);
  6507. /* This is generally an optimization, but it also
  6508. * handles "", which otherwise trips over !list[0] check below.
  6509. * (is this ever happens that we actually get str="" here?)
  6510. */
  6511. if (!strchr(str, SPECIAL_VAR_SYMBOL) && !strchr(str, '\\')) {
  6512. //TODO: Can use on strings with \ too, just unbackslash() them?
  6513. debug_printf_expand("string_to_string(fast)=>'%s'\n", str);
  6514. return xstrdup(str);
  6515. }
  6516. argv[0] = (char*)str;
  6517. argv[1] = NULL;
  6518. list = expand_variables(argv, EXP_flags | EXP_FLAG_SINGLEWORD);
  6519. if (!list[0]) {
  6520. /* Example where it happens:
  6521. * x=; echo ${x:-"$@"}
  6522. */
  6523. ((char*)list)[0] = '\0';
  6524. } else {
  6525. if (HUSH_DEBUG)
  6526. if (list[1])
  6527. bb_error_msg_and_die("BUG in varexp2");
  6528. /* actually, just move string 2*sizeof(char*) bytes back */
  6529. overlapping_strcpy((char*)list, list[0]);
  6530. if (do_unbackslash)
  6531. unbackslash((char*)list);
  6532. }
  6533. debug_printf_expand("string_to_string=>'%s'\n", (char*)list);
  6534. return (char*)list;
  6535. }
  6536. #if 0
  6537. static char* expand_strvec_to_string(char **argv)
  6538. {
  6539. char **list;
  6540. list = expand_variables(argv, EXP_FLAG_SINGLEWORD);
  6541. /* Convert all NULs to spaces */
  6542. if (list[0]) {
  6543. int n = 1;
  6544. while (list[n]) {
  6545. if (HUSH_DEBUG)
  6546. if (list[n-1] + strlen(list[n-1]) + 1 != list[n])
  6547. bb_error_msg_and_die("BUG in varexp3");
  6548. /* bash uses ' ' regardless of $IFS contents */
  6549. list[n][-1] = ' ';
  6550. n++;
  6551. }
  6552. }
  6553. overlapping_strcpy((char*)list, list[0] ? list[0] : "");
  6554. debug_printf_expand("strvec_to_string='%s'\n", (char*)list);
  6555. return (char*)list;
  6556. }
  6557. #endif
  6558. static char **expand_assignments(char **argv, int count)
  6559. {
  6560. int i;
  6561. char **p;
  6562. G.expanded_assignments = p = NULL;
  6563. /* Expand assignments into one string each */
  6564. for (i = 0; i < count; i++) {
  6565. p = add_string_to_strings(p,
  6566. expand_string_to_string(argv[i],
  6567. EXP_FLAG_ESC_GLOB_CHARS,
  6568. /*unbackslash:*/ 1
  6569. )
  6570. );
  6571. G.expanded_assignments = p;
  6572. }
  6573. G.expanded_assignments = NULL;
  6574. return p;
  6575. }
  6576. static void switch_off_special_sigs(unsigned mask)
  6577. {
  6578. unsigned sig = 0;
  6579. while ((mask >>= 1) != 0) {
  6580. sig++;
  6581. if (!(mask & 1))
  6582. continue;
  6583. #if ENABLE_HUSH_TRAP
  6584. if (G_traps) {
  6585. if (G_traps[sig] && !G_traps[sig][0])
  6586. /* trap is '', has to remain SIG_IGN */
  6587. continue;
  6588. free(G_traps[sig]);
  6589. G_traps[sig] = NULL;
  6590. }
  6591. #endif
  6592. /* We are here only if no trap or trap was not '' */
  6593. install_sighandler(sig, SIG_DFL);
  6594. }
  6595. }
  6596. #if BB_MMU
  6597. /* never called */
  6598. void re_execute_shell(char ***to_free, const char *s,
  6599. char *g_argv0, char **g_argv,
  6600. char **builtin_argv) NORETURN;
  6601. static void reset_traps_to_defaults(void)
  6602. {
  6603. /* This function is always called in a child shell
  6604. * after fork (not vfork, NOMMU doesn't use this function).
  6605. */
  6606. IF_HUSH_TRAP(unsigned sig;)
  6607. unsigned mask;
  6608. /* Child shells are not interactive.
  6609. * SIGTTIN/SIGTTOU/SIGTSTP should not have special handling.
  6610. * Testcase: (while :; do :; done) + ^Z should background.
  6611. * Same goes for SIGTERM, SIGHUP, SIGINT.
  6612. */
  6613. mask = (G.special_sig_mask & SPECIAL_INTERACTIVE_SIGS) | G_fatal_sig_mask;
  6614. if (!G_traps && !mask)
  6615. return; /* already no traps and no special sigs */
  6616. /* Switch off special sigs */
  6617. switch_off_special_sigs(mask);
  6618. # if ENABLE_HUSH_JOB
  6619. G_fatal_sig_mask = 0;
  6620. # endif
  6621. G.special_sig_mask &= ~SPECIAL_INTERACTIVE_SIGS;
  6622. /* SIGQUIT,SIGCHLD and maybe SPECIAL_JOBSTOP_SIGS
  6623. * remain set in G.special_sig_mask */
  6624. # if ENABLE_HUSH_TRAP
  6625. if (!G_traps)
  6626. return;
  6627. /* Reset all sigs to default except ones with empty traps */
  6628. for (sig = 0; sig < NSIG; sig++) {
  6629. if (!G_traps[sig])
  6630. continue; /* no trap: nothing to do */
  6631. if (!G_traps[sig][0])
  6632. continue; /* empty trap: has to remain SIG_IGN */
  6633. /* sig has non-empty trap, reset it: */
  6634. free(G_traps[sig]);
  6635. G_traps[sig] = NULL;
  6636. /* There is no signal for trap 0 (EXIT) */
  6637. if (sig == 0)
  6638. continue;
  6639. install_sighandler(sig, pick_sighandler(sig));
  6640. }
  6641. # endif
  6642. }
  6643. #else /* !BB_MMU */
  6644. static void re_execute_shell(char ***to_free, const char *s,
  6645. char *g_argv0, char **g_argv,
  6646. char **builtin_argv) NORETURN;
  6647. static void re_execute_shell(char ***to_free, const char *s,
  6648. char *g_argv0, char **g_argv,
  6649. char **builtin_argv)
  6650. {
  6651. # define NOMMU_HACK_FMT ("-$%x:%x:%x:%x:%x:%llx" IF_HUSH_LOOPS(":%x"))
  6652. /* delims + 2 * (number of bytes in printed hex numbers) */
  6653. char param_buf[sizeof(NOMMU_HACK_FMT) + 2 * (sizeof(int)*6 + sizeof(long long)*1)];
  6654. char *heredoc_argv[4];
  6655. struct variable *cur;
  6656. # if ENABLE_HUSH_FUNCTIONS
  6657. struct function *funcp;
  6658. # endif
  6659. char **argv, **pp;
  6660. unsigned cnt;
  6661. unsigned long long empty_trap_mask;
  6662. if (!g_argv0) { /* heredoc */
  6663. argv = heredoc_argv;
  6664. argv[0] = (char *) G.argv0_for_re_execing;
  6665. argv[1] = (char *) "-<";
  6666. argv[2] = (char *) s;
  6667. argv[3] = NULL;
  6668. pp = &argv[3]; /* used as pointer to empty environment */
  6669. goto do_exec;
  6670. }
  6671. cnt = 0;
  6672. pp = builtin_argv;
  6673. if (pp) while (*pp++)
  6674. cnt++;
  6675. empty_trap_mask = 0;
  6676. if (G_traps) {
  6677. int sig;
  6678. for (sig = 1; sig < NSIG; sig++) {
  6679. if (G_traps[sig] && !G_traps[sig][0])
  6680. empty_trap_mask |= 1LL << sig;
  6681. }
  6682. }
  6683. sprintf(param_buf, NOMMU_HACK_FMT
  6684. , (unsigned) G.root_pid
  6685. , (unsigned) G.root_ppid
  6686. , (unsigned) G.last_bg_pid
  6687. , (unsigned) G.last_exitcode
  6688. , cnt
  6689. , empty_trap_mask
  6690. IF_HUSH_LOOPS(, G.depth_of_loop)
  6691. );
  6692. # undef NOMMU_HACK_FMT
  6693. /* 1:hush 2:-$<pid>:<pid>:<exitcode>:<etc...> <vars...> <funcs...>
  6694. * 3:-c 4:<cmd> 5:<arg0> <argN...> 6:NULL
  6695. */
  6696. cnt += 6;
  6697. for (cur = G.top_var; cur; cur = cur->next) {
  6698. if (!cur->flg_export || cur->flg_read_only)
  6699. cnt += 2;
  6700. }
  6701. # if ENABLE_HUSH_FUNCTIONS
  6702. for (funcp = G.top_func; funcp; funcp = funcp->next)
  6703. cnt += 3;
  6704. # endif
  6705. pp = g_argv;
  6706. while (*pp++)
  6707. cnt++;
  6708. *to_free = argv = pp = xzalloc(sizeof(argv[0]) * cnt);
  6709. *pp++ = (char *) G.argv0_for_re_execing;
  6710. *pp++ = param_buf;
  6711. for (cur = G.top_var; cur; cur = cur->next) {
  6712. if (strcmp(cur->varstr, hush_version_str) == 0)
  6713. continue;
  6714. if (cur->flg_read_only) {
  6715. *pp++ = (char *) "-R";
  6716. *pp++ = cur->varstr;
  6717. } else if (!cur->flg_export) {
  6718. *pp++ = (char *) "-V";
  6719. *pp++ = cur->varstr;
  6720. }
  6721. }
  6722. # if ENABLE_HUSH_FUNCTIONS
  6723. for (funcp = G.top_func; funcp; funcp = funcp->next) {
  6724. *pp++ = (char *) "-F";
  6725. *pp++ = funcp->name;
  6726. *pp++ = funcp->body_as_string;
  6727. }
  6728. # endif
  6729. /* We can pass activated traps here. Say, -Tnn:trap_string
  6730. *
  6731. * However, POSIX says that subshells reset signals with traps
  6732. * to SIG_DFL.
  6733. * I tested bash-3.2 and it not only does that with true subshells
  6734. * of the form ( list ), but with any forked children shells.
  6735. * I set trap "echo W" WINCH; and then tried:
  6736. *
  6737. * { echo 1; sleep 20; echo 2; } &
  6738. * while true; do echo 1; sleep 20; echo 2; break; done &
  6739. * true | { echo 1; sleep 20; echo 2; } | cat
  6740. *
  6741. * In all these cases sending SIGWINCH to the child shell
  6742. * did not run the trap. If I add trap "echo V" WINCH;
  6743. * _inside_ group (just before echo 1), it works.
  6744. *
  6745. * I conclude it means we don't need to pass active traps here.
  6746. */
  6747. *pp++ = (char *) "-c";
  6748. *pp++ = (char *) s;
  6749. if (builtin_argv) {
  6750. while (*++builtin_argv)
  6751. *pp++ = *builtin_argv;
  6752. *pp++ = (char *) "";
  6753. }
  6754. *pp++ = g_argv0;
  6755. while (*g_argv)
  6756. *pp++ = *g_argv++;
  6757. /* *pp = NULL; - is already there */
  6758. pp = environ;
  6759. do_exec:
  6760. debug_printf_exec("re_execute_shell pid:%d cmd:'%s'\n", getpid(), s);
  6761. /* Don't propagate SIG_IGN to the child */
  6762. if (SPECIAL_JOBSTOP_SIGS != 0)
  6763. switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
  6764. execve(bb_busybox_exec_path, argv, pp);
  6765. /* Fallback. Useful for init=/bin/hush usage etc */
  6766. if (argv[0][0] == '/')
  6767. execve(argv[0], argv, pp);
  6768. xfunc_error_retval = 127;
  6769. bb_error_msg_and_die("can't re-execute the shell");
  6770. }
  6771. #endif /* !BB_MMU */
  6772. static int run_and_free_list(struct pipe *pi);
  6773. /* Executing from string: eval, sh -c '...'
  6774. * or from file: /etc/profile, . file, sh <script>, sh (intereactive)
  6775. * end_trigger controls how often we stop parsing
  6776. * NUL: parse all, execute, return
  6777. * ';': parse till ';' or newline, execute, repeat till EOF
  6778. */
  6779. static void parse_and_run_stream(struct in_str *inp, int end_trigger)
  6780. {
  6781. /* Why we need empty flag?
  6782. * An obscure corner case "false; ``; echo $?":
  6783. * empty command in `` should still set $? to 0.
  6784. * But we can't just set $? to 0 at the start,
  6785. * this breaks "false; echo `echo $?`" case.
  6786. */
  6787. bool empty = 1;
  6788. while (1) {
  6789. struct pipe *pipe_list;
  6790. #if ENABLE_HUSH_INTERACTIVE
  6791. if (end_trigger == ';') {
  6792. G.promptmode = 0; /* PS1 */
  6793. debug_printf_prompt("%s promptmode=%d\n", __func__, G.promptmode);
  6794. }
  6795. #endif
  6796. pipe_list = parse_stream(NULL, NULL, inp, end_trigger);
  6797. if (!pipe_list || pipe_list == ERR_PTR) { /* EOF/error */
  6798. /* If we are in "big" script
  6799. * (not in `cmd` or something similar)...
  6800. */
  6801. if (pipe_list == ERR_PTR && end_trigger == ';') {
  6802. /* Discard cached input (rest of line) */
  6803. int ch = inp->last_char;
  6804. while (ch != EOF && ch != '\n') {
  6805. //bb_error_msg("Discarded:'%c'", ch);
  6806. ch = i_getch(inp);
  6807. }
  6808. /* Force prompt */
  6809. inp->p = NULL;
  6810. /* This stream isn't empty */
  6811. empty = 0;
  6812. continue;
  6813. }
  6814. if (!pipe_list && empty)
  6815. G.last_exitcode = 0;
  6816. break;
  6817. }
  6818. debug_print_tree(pipe_list, 0);
  6819. debug_printf_exec("parse_and_run_stream: run_and_free_list\n");
  6820. run_and_free_list(pipe_list);
  6821. empty = 0;
  6822. if (G_flag_return_in_progress == 1)
  6823. break;
  6824. }
  6825. }
  6826. static void parse_and_run_string(const char *s)
  6827. {
  6828. struct in_str input;
  6829. //IF_HUSH_LINENO_VAR(unsigned sv = G.parse_lineno;)
  6830. setup_string_in_str(&input, s);
  6831. parse_and_run_stream(&input, '\0');
  6832. //IF_HUSH_LINENO_VAR(G.parse_lineno = sv;)
  6833. }
  6834. static void parse_and_run_file(HFILE *fp)
  6835. {
  6836. struct in_str input;
  6837. IF_HUSH_LINENO_VAR(unsigned sv = G.parse_lineno;)
  6838. IF_HUSH_LINENO_VAR(G.parse_lineno = 1;)
  6839. setup_file_in_str(&input, fp);
  6840. parse_and_run_stream(&input, ';');
  6841. IF_HUSH_LINENO_VAR(G.parse_lineno = sv;)
  6842. }
  6843. #if ENABLE_HUSH_TICK
  6844. static int generate_stream_from_string(const char *s, pid_t *pid_p)
  6845. {
  6846. pid_t pid;
  6847. int channel[2];
  6848. # if !BB_MMU
  6849. char **to_free = NULL;
  6850. # endif
  6851. xpipe(channel);
  6852. pid = BB_MMU ? xfork() : xvfork();
  6853. if (pid == 0) { /* child */
  6854. disable_restore_tty_pgrp_on_exit();
  6855. /* Process substitution is not considered to be usual
  6856. * 'command execution'.
  6857. * SUSv3 says ctrl-Z should be ignored, ctrl-C should not.
  6858. */
  6859. bb_signals(0
  6860. + (1 << SIGTSTP)
  6861. + (1 << SIGTTIN)
  6862. + (1 << SIGTTOU)
  6863. , SIG_IGN);
  6864. close(channel[0]); /* NB: close _first_, then move fd! */
  6865. xmove_fd(channel[1], 1);
  6866. # if ENABLE_HUSH_TRAP
  6867. /* Awful hack for `trap` or $(trap).
  6868. *
  6869. * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
  6870. * contains an example where "trap" is executed in a subshell:
  6871. *
  6872. * save_traps=$(trap)
  6873. * ...
  6874. * eval "$save_traps"
  6875. *
  6876. * Standard does not say that "trap" in subshell shall print
  6877. * parent shell's traps. It only says that its output
  6878. * must have suitable form, but then, in the above example
  6879. * (which is not supposed to be normative), it implies that.
  6880. *
  6881. * bash (and probably other shell) does implement it
  6882. * (traps are reset to defaults, but "trap" still shows them),
  6883. * but as a result, "trap" logic is hopelessly messed up:
  6884. *
  6885. * # trap
  6886. * trap -- 'echo Ho' SIGWINCH <--- we have a handler
  6887. * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
  6888. * # true | trap <--- trap is in subshell - no output (ditto)
  6889. * # echo `true | trap` <--- in subshell - output (but traps are reset!)
  6890. * trap -- 'echo Ho' SIGWINCH
  6891. * # echo `(trap)` <--- in subshell in subshell - output
  6892. * trap -- 'echo Ho' SIGWINCH
  6893. * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
  6894. * trap -- 'echo Ho' SIGWINCH
  6895. *
  6896. * The rules when to forget and when to not forget traps
  6897. * get really complex and nonsensical.
  6898. *
  6899. * Our solution: ONLY bare $(trap) or `trap` is special.
  6900. */
  6901. s = skip_whitespace(s);
  6902. if (is_prefixed_with(s, "trap")
  6903. && skip_whitespace(s + 4)[0] == '\0'
  6904. ) {
  6905. static const char *const argv[] = { NULL, NULL };
  6906. builtin_trap((char**)argv);
  6907. fflush_all(); /* important */
  6908. _exit(0);
  6909. }
  6910. # endif
  6911. # if BB_MMU
  6912. /* Prevent it from trying to handle ctrl-z etc */
  6913. IF_HUSH_JOB(G.run_list_level = 1;)
  6914. CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
  6915. reset_traps_to_defaults();
  6916. IF_HUSH_MODE_X(G.x_mode_depth++;)
  6917. //bb_error_msg("%s: ++x_mode_depth=%d", __func__, G.x_mode_depth);
  6918. parse_and_run_string(s);
  6919. _exit(G.last_exitcode);
  6920. # else
  6921. /* We re-execute after vfork on NOMMU. This makes this script safe:
  6922. * yes "0123456789012345678901234567890" | dd bs=32 count=64k >BIG
  6923. * huge=`cat BIG` # was blocking here forever
  6924. * echo OK
  6925. */
  6926. re_execute_shell(&to_free,
  6927. s,
  6928. G.global_argv[0],
  6929. G.global_argv + 1,
  6930. NULL);
  6931. # endif
  6932. }
  6933. /* parent */
  6934. *pid_p = pid;
  6935. # if ENABLE_HUSH_FAST
  6936. G.count_SIGCHLD++;
  6937. //bb_error_msg("[%d] fork in generate_stream_from_string:"
  6938. // " G.count_SIGCHLD:%d G.handled_SIGCHLD:%d",
  6939. // getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
  6940. # endif
  6941. enable_restore_tty_pgrp_on_exit();
  6942. # if !BB_MMU
  6943. free(to_free);
  6944. # endif
  6945. close(channel[1]);
  6946. return channel[0];
  6947. }
  6948. /* Return code is exit status of the process that is run. */
  6949. static int process_command_subs(o_string *dest, const char *s)
  6950. {
  6951. FILE *fp;
  6952. pid_t pid;
  6953. int status, ch, eol_cnt;
  6954. fp = xfdopen_for_read(generate_stream_from_string(s, &pid));
  6955. /* Now send results of command back into original context */
  6956. eol_cnt = 0;
  6957. while ((ch = getc(fp)) != EOF) {
  6958. if (ch == '\0')
  6959. continue;
  6960. if (ch == '\n') {
  6961. eol_cnt++;
  6962. continue;
  6963. }
  6964. while (eol_cnt) {
  6965. o_addchr(dest, '\n');
  6966. eol_cnt--;
  6967. }
  6968. o_addQchr(dest, ch);
  6969. }
  6970. debug_printf("done reading from `cmd` pipe, closing it\n");
  6971. fclose(fp);
  6972. /* We need to extract exitcode. Test case
  6973. * "true; echo `sleep 1; false` $?"
  6974. * should print 1 */
  6975. safe_waitpid(pid, &status, 0);
  6976. debug_printf("child exited. returning its exitcode:%d\n", WEXITSTATUS(status));
  6977. return WEXITSTATUS(status);
  6978. }
  6979. #endif /* ENABLE_HUSH_TICK */
  6980. static void setup_heredoc(struct redir_struct *redir)
  6981. {
  6982. struct fd_pair pair;
  6983. pid_t pid;
  6984. int len, written;
  6985. /* the _body_ of heredoc (misleading field name) */
  6986. const char *heredoc = redir->rd_filename;
  6987. char *expanded;
  6988. #if !BB_MMU
  6989. char **to_free;
  6990. #endif
  6991. expanded = NULL;
  6992. if (!(redir->rd_dup & HEREDOC_QUOTED)) {
  6993. expanded = encode_then_expand_string(heredoc);
  6994. if (expanded)
  6995. heredoc = expanded;
  6996. }
  6997. len = strlen(heredoc);
  6998. close(redir->rd_fd); /* often saves dup2+close in xmove_fd */
  6999. xpiped_pair(pair);
  7000. xmove_fd(pair.rd, redir->rd_fd);
  7001. /* Try writing without forking. Newer kernels have
  7002. * dynamically growing pipes. Must use non-blocking write! */
  7003. ndelay_on(pair.wr);
  7004. while (1) {
  7005. written = write(pair.wr, heredoc, len);
  7006. if (written <= 0)
  7007. break;
  7008. len -= written;
  7009. if (len == 0) {
  7010. close(pair.wr);
  7011. free(expanded);
  7012. return;
  7013. }
  7014. heredoc += written;
  7015. }
  7016. ndelay_off(pair.wr);
  7017. /* Okay, pipe buffer was not big enough */
  7018. /* Note: we must not create a stray child (bastard? :)
  7019. * for the unsuspecting parent process. Child creates a grandchild
  7020. * and exits before parent execs the process which consumes heredoc
  7021. * (that exec happens after we return from this function) */
  7022. #if !BB_MMU
  7023. to_free = NULL;
  7024. #endif
  7025. pid = xvfork();
  7026. if (pid == 0) {
  7027. /* child */
  7028. disable_restore_tty_pgrp_on_exit();
  7029. pid = BB_MMU ? xfork() : xvfork();
  7030. if (pid != 0)
  7031. _exit(0);
  7032. /* grandchild */
  7033. close(redir->rd_fd); /* read side of the pipe */
  7034. #if BB_MMU
  7035. full_write(pair.wr, heredoc, len); /* may loop or block */
  7036. _exit(0);
  7037. #else
  7038. /* Delegate blocking writes to another process */
  7039. xmove_fd(pair.wr, STDOUT_FILENO);
  7040. re_execute_shell(&to_free, heredoc, NULL, NULL, NULL);
  7041. #endif
  7042. }
  7043. /* parent */
  7044. #if ENABLE_HUSH_FAST
  7045. G.count_SIGCHLD++;
  7046. //bb_error_msg("[%d] fork in setup_heredoc: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
  7047. #endif
  7048. enable_restore_tty_pgrp_on_exit();
  7049. #if !BB_MMU
  7050. free(to_free);
  7051. #endif
  7052. close(pair.wr);
  7053. free(expanded);
  7054. wait(NULL); /* wait till child has died */
  7055. }
  7056. struct squirrel {
  7057. int orig_fd;
  7058. int moved_to;
  7059. /* moved_to = n: fd was moved to n; restore back to orig_fd after redir */
  7060. /* moved_to = -1: fd was opened by redirect; close orig_fd after redir */
  7061. };
  7062. static struct squirrel *append_squirrel(struct squirrel *sq, int i, int orig, int moved)
  7063. {
  7064. sq = xrealloc(sq, (i + 2) * sizeof(sq[0]));
  7065. sq[i].orig_fd = orig;
  7066. sq[i].moved_to = moved;
  7067. sq[i+1].orig_fd = -1; /* end marker */
  7068. return sq;
  7069. }
  7070. static struct squirrel *add_squirrel(struct squirrel *sq, int fd, int avoid_fd)
  7071. {
  7072. int moved_to;
  7073. int i;
  7074. i = 0;
  7075. if (sq) for (; sq[i].orig_fd >= 0; i++) {
  7076. /* If we collide with an already moved fd... */
  7077. if (fd == sq[i].moved_to) {
  7078. sq[i].moved_to = dup_CLOEXEC(sq[i].moved_to, avoid_fd);
  7079. debug_printf_redir("redirect_fd %d: already busy, moving to %d\n", fd, sq[i].moved_to);
  7080. if (sq[i].moved_to < 0) /* what? */
  7081. xfunc_die();
  7082. return sq;
  7083. }
  7084. if (fd == sq[i].orig_fd) {
  7085. /* Example: echo Hello >/dev/null 1>&2 */
  7086. debug_printf_redir("redirect_fd %d: already moved\n", fd);
  7087. return sq;
  7088. }
  7089. }
  7090. /* If this fd is open, we move and remember it; if it's closed, moved_to = -1 */
  7091. moved_to = dup_CLOEXEC(fd, avoid_fd);
  7092. debug_printf_redir("redirect_fd %d: previous fd is moved to %d (-1 if it was closed)\n", fd, moved_to);
  7093. if (moved_to < 0 && errno != EBADF)
  7094. xfunc_die();
  7095. return append_squirrel(sq, i, fd, moved_to);
  7096. }
  7097. static struct squirrel *add_squirrel_closed(struct squirrel *sq, int fd)
  7098. {
  7099. int i;
  7100. i = 0;
  7101. if (sq) for (; sq[i].orig_fd >= 0; i++) {
  7102. /* If we collide with an already moved fd... */
  7103. if (fd == sq[i].orig_fd) {
  7104. /* Examples:
  7105. * "echo 3>FILE 3>&- 3>FILE"
  7106. * "echo 3>&- 3>FILE"
  7107. * No need for last redirect to insert
  7108. * another "need to close 3" indicator.
  7109. */
  7110. debug_printf_redir("redirect_fd %d: already moved or closed\n", fd);
  7111. return sq;
  7112. }
  7113. }
  7114. debug_printf_redir("redirect_fd %d: previous fd was closed\n", fd);
  7115. return append_squirrel(sq, i, fd, -1);
  7116. }
  7117. /* fd: redirect wants this fd to be used (e.g. 3>file).
  7118. * Move all conflicting internally used fds,
  7119. * and remember them so that we can restore them later.
  7120. */
  7121. static int save_fd_on_redirect(int fd, int avoid_fd, struct squirrel **sqp)
  7122. {
  7123. if (avoid_fd < 9) /* the important case here is that it can be -1 */
  7124. avoid_fd = 9;
  7125. #if ENABLE_HUSH_INTERACTIVE
  7126. if (fd == G_interactive_fd) {
  7127. /* Testcase: "ls -l /proc/$$/fd 255>&-" should work */
  7128. G_interactive_fd = xdup_CLOEXEC_and_close(G_interactive_fd, avoid_fd);
  7129. debug_printf_redir("redirect_fd %d: matches interactive_fd, moving it to %d\n", fd, G_interactive_fd);
  7130. return 1; /* "we closed fd" */
  7131. }
  7132. #endif
  7133. /* Are we called from setup_redirects(squirrel==NULL)
  7134. * in redirect in a [v]forked child?
  7135. */
  7136. if (sqp == NULL) {
  7137. /* No need to move script fds.
  7138. * For NOMMU case, it's actively wrong: we'd change ->fd
  7139. * fields in memory for the parent, but parent's fds
  7140. * aren't be moved, it would use wrong fd!
  7141. * Reproducer: "cmd 3>FILE" in script.
  7142. * If we would call move_HFILEs_on_redirect(), child would:
  7143. * fcntl64(3, F_DUPFD_CLOEXEC, 10) = 10
  7144. * close(3) = 0
  7145. * and change ->fd to 10 if fd#3 is a script fd. WRONG.
  7146. */
  7147. //bb_error_msg("sqp == NULL: [v]forked child");
  7148. return 0;
  7149. }
  7150. /* If this one of script's fds? */
  7151. if (move_HFILEs_on_redirect(fd, avoid_fd))
  7152. return 1; /* yes. "we closed fd" (actually moved it) */
  7153. /* Are we called for "exec 3>FILE"? Came through
  7154. * redirect_and_varexp_helper(squirrel=ERR_PTR) -> setup_redirects(ERR_PTR)
  7155. * This case used to fail for this script:
  7156. * exec 3>FILE
  7157. * echo Ok
  7158. * ...100000 more lines...
  7159. * echo Ok
  7160. * as follows:
  7161. * read(3, "exec 3>FILE\necho Ok\necho Ok"..., 1024) = 1024
  7162. * open("FILE", O_WRONLY|O_CREAT|O_TRUNC|O_LARGEFILE, 0666) = 4
  7163. * dup2(4, 3) = 3
  7164. * ^^^^^^^^ oops, we lost fd#3 opened to our script!
  7165. * close(4) = 0
  7166. * write(1, "Ok\n", 3) = 3
  7167. * ... = 3
  7168. * write(1, "Ok\n", 3) = 3
  7169. * read(3, 0x94fbc08, 1024) = -1 EBADF (Bad file descriptor)
  7170. * ^^^^^^^^ oops, wrong fd!!!
  7171. * With this case separate from sqp == NULL and *after* move_HFILEs,
  7172. * it now works:
  7173. */
  7174. if (sqp == ERR_PTR) {
  7175. /* Don't preserve redirected fds: exec is _meant_ to change these */
  7176. //bb_error_msg("sqp == ERR_PTR: exec >FILE");
  7177. return 0;
  7178. }
  7179. /* Check whether it collides with any open fds (e.g. stdio), save fds as needed */
  7180. *sqp = add_squirrel(*sqp, fd, avoid_fd);
  7181. return 0; /* "we did not close fd" */
  7182. }
  7183. static void restore_redirects(struct squirrel *sq)
  7184. {
  7185. if (sq) {
  7186. int i;
  7187. for (i = 0; sq[i].orig_fd >= 0; i++) {
  7188. if (sq[i].moved_to >= 0) {
  7189. /* We simply die on error */
  7190. debug_printf_redir("restoring redirected fd from %d to %d\n", sq[i].moved_to, sq[i].orig_fd);
  7191. xmove_fd(sq[i].moved_to, sq[i].orig_fd);
  7192. } else {
  7193. /* cmd1 9>FILE; cmd2_should_see_fd9_closed */
  7194. debug_printf_redir("restoring redirected fd %d: closing it\n", sq[i].orig_fd);
  7195. close(sq[i].orig_fd);
  7196. }
  7197. }
  7198. free(sq);
  7199. }
  7200. /* If moved, G_interactive_fd stays on new fd, not restoring it */
  7201. }
  7202. #if ENABLE_FEATURE_SH_STANDALONE && BB_MMU
  7203. static void close_saved_fds_and_FILE_fds(void)
  7204. {
  7205. if (G_interactive_fd)
  7206. close(G_interactive_fd);
  7207. close_all_HFILE_list();
  7208. }
  7209. #endif
  7210. static int internally_opened_fd(int fd, struct squirrel *sq)
  7211. {
  7212. int i;
  7213. #if ENABLE_HUSH_INTERACTIVE
  7214. if (fd == G_interactive_fd)
  7215. return 1;
  7216. #endif
  7217. /* If this one of script's fds? */
  7218. if (fd_in_HFILEs(fd))
  7219. return 1;
  7220. if (sq) for (i = 0; sq[i].orig_fd >= 0; i++) {
  7221. if (fd == sq[i].moved_to)
  7222. return 1;
  7223. }
  7224. return 0;
  7225. }
  7226. /* squirrel != NULL means we squirrel away copies of stdin, stdout,
  7227. * and stderr if they are redirected. */
  7228. static int setup_redirects(struct command *prog, struct squirrel **sqp)
  7229. {
  7230. struct redir_struct *redir;
  7231. for (redir = prog->redirects; redir; redir = redir->next) {
  7232. int newfd;
  7233. int closed;
  7234. if (redir->rd_type == REDIRECT_HEREDOC2) {
  7235. /* "rd_fd<<HERE" case */
  7236. save_fd_on_redirect(redir->rd_fd, /*avoid:*/ 0, sqp);
  7237. /* for REDIRECT_HEREDOC2, rd_filename holds _contents_
  7238. * of the heredoc */
  7239. debug_printf_redir("set heredoc '%s'\n",
  7240. redir->rd_filename);
  7241. setup_heredoc(redir);
  7242. continue;
  7243. }
  7244. if (redir->rd_dup == REDIRFD_TO_FILE) {
  7245. /* "rd_fd<*>file" case (<*> is <,>,>>,<>) */
  7246. char *p;
  7247. int mode;
  7248. if (redir->rd_filename == NULL) {
  7249. /* Examples:
  7250. * "cmd >" (no filename)
  7251. * "cmd > <file" (2nd redirect starts too early)
  7252. */
  7253. syntax_error("invalid redirect");
  7254. continue;
  7255. }
  7256. mode = redir_table[redir->rd_type].mode;
  7257. p = expand_string_to_string(redir->rd_filename,
  7258. EXP_FLAG_ESC_GLOB_CHARS, /*unbackslash:*/ 1);
  7259. newfd = open_or_warn(p, mode);
  7260. free(p);
  7261. if (newfd < 0) {
  7262. /* Error message from open_or_warn can be lost
  7263. * if stderr has been redirected, but bash
  7264. * and ash both lose it as well
  7265. * (though zsh doesn't!)
  7266. */
  7267. return 1;
  7268. }
  7269. if (newfd == redir->rd_fd && sqp) {
  7270. /* open() gave us precisely the fd we wanted.
  7271. * This means that this fd was not busy
  7272. * (not opened to anywhere).
  7273. * Remember to close it on restore:
  7274. */
  7275. *sqp = add_squirrel_closed(*sqp, newfd);
  7276. debug_printf_redir("redir to previously closed fd %d\n", newfd);
  7277. }
  7278. } else {
  7279. /* "rd_fd>&rd_dup" or "rd_fd>&-" case */
  7280. newfd = redir->rd_dup;
  7281. }
  7282. if (newfd == redir->rd_fd)
  7283. continue;
  7284. /* if "N>FILE": move newfd to redir->rd_fd */
  7285. /* if "N>&M": dup newfd to redir->rd_fd */
  7286. /* if "N>&-": close redir->rd_fd (newfd is REDIRFD_CLOSE) */
  7287. closed = save_fd_on_redirect(redir->rd_fd, /*avoid:*/ newfd, sqp);
  7288. if (newfd == REDIRFD_CLOSE) {
  7289. /* "N>&-" means "close me" */
  7290. if (!closed) {
  7291. /* ^^^ optimization: saving may already
  7292. * have closed it. If not... */
  7293. close(redir->rd_fd);
  7294. }
  7295. /* Sometimes we do another close on restore, getting EBADF.
  7296. * Consider "echo 3>FILE 3>&-"
  7297. * first redirect remembers "need to close 3",
  7298. * and second redirect closes 3! Restore code then closes 3 again.
  7299. */
  7300. } else {
  7301. /* if newfd is a script fd or saved fd, simulate EBADF */
  7302. if (internally_opened_fd(newfd, sqp && sqp != ERR_PTR ? *sqp : NULL)) {
  7303. //errno = EBADF;
  7304. //bb_perror_msg_and_die("can't duplicate file descriptor");
  7305. newfd = -1; /* same effect as code above */
  7306. }
  7307. xdup2(newfd, redir->rd_fd);
  7308. if (redir->rd_dup == REDIRFD_TO_FILE)
  7309. /* "rd_fd > FILE" */
  7310. close(newfd);
  7311. /* else: "rd_fd > rd_dup" */
  7312. }
  7313. }
  7314. return 0;
  7315. }
  7316. static char *find_in_path(const char *arg)
  7317. {
  7318. char *ret = NULL;
  7319. const char *PATH = get_local_var_value("PATH");
  7320. if (!PATH)
  7321. return NULL;
  7322. while (1) {
  7323. const char *end = strchrnul(PATH, ':');
  7324. int sz = end - PATH; /* must be int! */
  7325. free(ret);
  7326. if (sz != 0) {
  7327. ret = xasprintf("%.*s/%s", sz, PATH, arg);
  7328. } else {
  7329. /* We have xxx::yyyy in $PATH,
  7330. * it means "use current dir" */
  7331. ret = xstrdup(arg);
  7332. }
  7333. if (access(ret, F_OK) == 0)
  7334. break;
  7335. if (*end == '\0') {
  7336. free(ret);
  7337. return NULL;
  7338. }
  7339. PATH = end + 1;
  7340. }
  7341. return ret;
  7342. }
  7343. static const struct built_in_command *find_builtin_helper(const char *name,
  7344. const struct built_in_command *x,
  7345. const struct built_in_command *end)
  7346. {
  7347. while (x != end) {
  7348. if (strcmp(name, x->b_cmd) != 0) {
  7349. x++;
  7350. continue;
  7351. }
  7352. debug_printf_exec("found builtin '%s'\n", name);
  7353. return x;
  7354. }
  7355. return NULL;
  7356. }
  7357. static const struct built_in_command *find_builtin1(const char *name)
  7358. {
  7359. return find_builtin_helper(name, bltins1, &bltins1[ARRAY_SIZE(bltins1)]);
  7360. }
  7361. static const struct built_in_command *find_builtin(const char *name)
  7362. {
  7363. const struct built_in_command *x = find_builtin1(name);
  7364. if (x)
  7365. return x;
  7366. return find_builtin_helper(name, bltins2, &bltins2[ARRAY_SIZE(bltins2)]);
  7367. }
  7368. static void remove_nested_vars(void)
  7369. {
  7370. struct variable *cur;
  7371. struct variable **cur_pp;
  7372. cur_pp = &G.top_var;
  7373. while ((cur = *cur_pp) != NULL) {
  7374. if (cur->var_nest_level <= G.var_nest_level) {
  7375. cur_pp = &cur->next;
  7376. continue;
  7377. }
  7378. /* Unexport */
  7379. if (cur->flg_export) {
  7380. debug_printf_env("unexporting nested '%s'/%u\n", cur->varstr, cur->var_nest_level);
  7381. bb_unsetenv(cur->varstr);
  7382. }
  7383. /* Remove from global list */
  7384. *cur_pp = cur->next;
  7385. /* Free */
  7386. if (!cur->max_len) {
  7387. debug_printf_env("freeing nested '%s'/%u\n", cur->varstr, cur->var_nest_level);
  7388. free(cur->varstr);
  7389. }
  7390. free(cur);
  7391. }
  7392. }
  7393. static void enter_var_nest_level(void)
  7394. {
  7395. G.var_nest_level++;
  7396. debug_printf_env("var_nest_level++ %u\n", G.var_nest_level);
  7397. /* Try: f() { echo -n .; f; }; f
  7398. * struct variable::var_nest_level is uint16_t,
  7399. * thus limiting recursion to < 2^16.
  7400. * In any case, with 8 Mbyte stack SEGV happens
  7401. * not too long after 2^16 recursions anyway.
  7402. */
  7403. if (G.var_nest_level > 0xff00)
  7404. bb_error_msg_and_die("fatal recursion (depth %u)", G.var_nest_level);
  7405. }
  7406. static void leave_var_nest_level(void)
  7407. {
  7408. G.var_nest_level--;
  7409. debug_printf_env("var_nest_level-- %u\n", G.var_nest_level);
  7410. if (HUSH_DEBUG && (int)G.var_nest_level < 0)
  7411. bb_error_msg_and_die("BUG: nesting underflow");
  7412. remove_nested_vars();
  7413. }
  7414. #if ENABLE_HUSH_FUNCTIONS
  7415. static struct function **find_function_slot(const char *name)
  7416. {
  7417. struct function *funcp;
  7418. struct function **funcpp = &G.top_func;
  7419. while ((funcp = *funcpp) != NULL) {
  7420. if (strcmp(name, funcp->name) == 0) {
  7421. debug_printf_exec("found function '%s'\n", name);
  7422. break;
  7423. }
  7424. funcpp = &funcp->next;
  7425. }
  7426. return funcpp;
  7427. }
  7428. static ALWAYS_INLINE const struct function *find_function(const char *name)
  7429. {
  7430. const struct function *funcp = *find_function_slot(name);
  7431. return funcp;
  7432. }
  7433. /* Note: takes ownership on name ptr */
  7434. static struct function *new_function(char *name)
  7435. {
  7436. struct function **funcpp = find_function_slot(name);
  7437. struct function *funcp = *funcpp;
  7438. if (funcp != NULL) {
  7439. struct command *cmd = funcp->parent_cmd;
  7440. debug_printf_exec("func %p parent_cmd %p\n", funcp, cmd);
  7441. if (!cmd) {
  7442. debug_printf_exec("freeing & replacing function '%s'\n", funcp->name);
  7443. free(funcp->name);
  7444. /* Note: if !funcp->body, do not free body_as_string!
  7445. * This is a special case of "-F name body" function:
  7446. * body_as_string was not malloced! */
  7447. if (funcp->body) {
  7448. free_pipe_list(funcp->body);
  7449. # if !BB_MMU
  7450. free(funcp->body_as_string);
  7451. # endif
  7452. }
  7453. } else {
  7454. debug_printf_exec("reinserting in tree & replacing function '%s'\n", funcp->name);
  7455. cmd->argv[0] = funcp->name;
  7456. cmd->group = funcp->body;
  7457. # if !BB_MMU
  7458. cmd->group_as_string = funcp->body_as_string;
  7459. # endif
  7460. }
  7461. } else {
  7462. debug_printf_exec("remembering new function '%s'\n", name);
  7463. funcp = *funcpp = xzalloc(sizeof(*funcp));
  7464. /*funcp->next = NULL;*/
  7465. }
  7466. funcp->name = name;
  7467. return funcp;
  7468. }
  7469. # if ENABLE_HUSH_UNSET
  7470. static void unset_func(const char *name)
  7471. {
  7472. struct function **funcpp = find_function_slot(name);
  7473. struct function *funcp = *funcpp;
  7474. if (funcp != NULL) {
  7475. debug_printf_exec("freeing function '%s'\n", funcp->name);
  7476. *funcpp = funcp->next;
  7477. /* funcp is unlinked now, deleting it.
  7478. * Note: if !funcp->body, the function was created by
  7479. * "-F name body", do not free ->body_as_string
  7480. * and ->name as they were not malloced. */
  7481. if (funcp->body) {
  7482. free_pipe_list(funcp->body);
  7483. free(funcp->name);
  7484. # if !BB_MMU
  7485. free(funcp->body_as_string);
  7486. # endif
  7487. }
  7488. free(funcp);
  7489. }
  7490. }
  7491. # endif
  7492. # if BB_MMU
  7493. #define exec_function(to_free, funcp, argv) \
  7494. exec_function(funcp, argv)
  7495. # endif
  7496. static void exec_function(char ***to_free,
  7497. const struct function *funcp,
  7498. char **argv) NORETURN;
  7499. static void exec_function(char ***to_free,
  7500. const struct function *funcp,
  7501. char **argv)
  7502. {
  7503. # if BB_MMU
  7504. int n;
  7505. argv[0] = G.global_argv[0];
  7506. G.global_argv = argv;
  7507. G.global_argc = n = 1 + string_array_len(argv + 1);
  7508. // Example when we are here: "cmd | func"
  7509. // func will run with saved-redirect fds open.
  7510. // $ f() { echo /proc/self/fd/*; }
  7511. // $ true | f
  7512. // /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3
  7513. // stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ DIR fd for glob
  7514. // Same in script:
  7515. // $ . ./SCRIPT
  7516. // /proc/self/fd/0 /proc/self/fd/1 /proc/self/fd/2 /proc/self/fd/255 /proc/self/fd/3 /proc/self/fd/4
  7517. // stdio^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ G_interactive_fd^ opened ./SCRIPT DIR fd for glob
  7518. // They are CLOEXEC so external programs won't see them, but
  7519. // for "more correctness" we might want to close those extra fds here:
  7520. //? close_saved_fds_and_FILE_fds();
  7521. /* "we are in a function, ok to use return" */
  7522. G_flag_return_in_progress = -1;
  7523. enter_var_nest_level();
  7524. IF_HUSH_LOCAL(G.func_nest_level++;)
  7525. /* On MMU, funcp->body is always non-NULL */
  7526. n = run_list(funcp->body);
  7527. fflush_all();
  7528. _exit(n);
  7529. # else
  7530. //? close_saved_fds_and_FILE_fds();
  7531. //TODO: check whether "true | func_with_return" works
  7532. re_execute_shell(to_free,
  7533. funcp->body_as_string,
  7534. G.global_argv[0],
  7535. argv + 1,
  7536. NULL);
  7537. # endif
  7538. }
  7539. static int run_function(const struct function *funcp, char **argv)
  7540. {
  7541. int rc;
  7542. save_arg_t sv;
  7543. smallint sv_flg;
  7544. save_and_replace_G_args(&sv, argv);
  7545. /* "We are in function, ok to use return" */
  7546. sv_flg = G_flag_return_in_progress;
  7547. G_flag_return_in_progress = -1;
  7548. /* Make "local" variables properly shadow previous ones */
  7549. IF_HUSH_LOCAL(enter_var_nest_level();)
  7550. IF_HUSH_LOCAL(G.func_nest_level++;)
  7551. /* On MMU, funcp->body is always non-NULL */
  7552. # if !BB_MMU
  7553. if (!funcp->body) {
  7554. /* Function defined by -F */
  7555. parse_and_run_string(funcp->body_as_string);
  7556. rc = G.last_exitcode;
  7557. } else
  7558. # endif
  7559. {
  7560. rc = run_list(funcp->body);
  7561. }
  7562. IF_HUSH_LOCAL(G.func_nest_level--;)
  7563. IF_HUSH_LOCAL(leave_var_nest_level();)
  7564. G_flag_return_in_progress = sv_flg;
  7565. restore_G_args(&sv, argv);
  7566. return rc;
  7567. }
  7568. #endif /* ENABLE_HUSH_FUNCTIONS */
  7569. #if BB_MMU
  7570. #define exec_builtin(to_free, x, argv) \
  7571. exec_builtin(x, argv)
  7572. #else
  7573. #define exec_builtin(to_free, x, argv) \
  7574. exec_builtin(to_free, argv)
  7575. #endif
  7576. static void exec_builtin(char ***to_free,
  7577. const struct built_in_command *x,
  7578. char **argv) NORETURN;
  7579. static void exec_builtin(char ***to_free,
  7580. const struct built_in_command *x,
  7581. char **argv)
  7582. {
  7583. #if BB_MMU
  7584. int rcode;
  7585. fflush_all();
  7586. //? close_saved_fds_and_FILE_fds();
  7587. rcode = x->b_function(argv);
  7588. fflush_all();
  7589. _exit(rcode);
  7590. #else
  7591. fflush_all();
  7592. /* On NOMMU, we must never block!
  7593. * Example: { sleep 99 | read line; } & echo Ok
  7594. */
  7595. re_execute_shell(to_free,
  7596. argv[0],
  7597. G.global_argv[0],
  7598. G.global_argv + 1,
  7599. argv);
  7600. #endif
  7601. }
  7602. static void execvp_or_die(char **argv) NORETURN;
  7603. static void execvp_or_die(char **argv)
  7604. {
  7605. int e;
  7606. debug_printf_exec("execing '%s'\n", argv[0]);
  7607. /* Don't propagate SIG_IGN to the child */
  7608. if (SPECIAL_JOBSTOP_SIGS != 0)
  7609. switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
  7610. execvp(argv[0], argv);
  7611. e = 2;
  7612. if (errno == EACCES) e = 126;
  7613. if (errno == ENOENT) e = 127;
  7614. bb_perror_msg("can't execute '%s'", argv[0]);
  7615. _exit(e);
  7616. }
  7617. #if ENABLE_HUSH_MODE_X
  7618. static void x_mode_print_optionally_squoted(const char *str)
  7619. {
  7620. unsigned len;
  7621. const char *cp;
  7622. cp = str;
  7623. /* the set of chars which-cause-string-to-be-squoted mimics bash */
  7624. /* test a char with: bash -c 'set -x; echo "CH"' */
  7625. if (str[strcspn(str, "\\\"'`$(){}[]<>;#&|~*?!^"
  7626. " " "\001\002\003\004\005\006\007"
  7627. "\010\011\012\013\014\015\016\017"
  7628. "\020\021\022\023\024\025\026\027"
  7629. "\030\031\032\033\034\035\036\037"
  7630. )
  7631. ] == '\0'
  7632. ) {
  7633. /* string has no special chars */
  7634. x_mode_addstr(str);
  7635. return;
  7636. }
  7637. cp = str;
  7638. for (;;) {
  7639. /* print '....' up to EOL or first squote */
  7640. len = (int)(strchrnul(cp, '\'') - cp);
  7641. if (len != 0) {
  7642. x_mode_addchr('\'');
  7643. x_mode_addblock(cp, len);
  7644. x_mode_addchr('\'');
  7645. cp += len;
  7646. }
  7647. if (*cp == '\0')
  7648. break;
  7649. /* string contains squote(s), print them as \' */
  7650. x_mode_addchr('\\');
  7651. x_mode_addchr('\'');
  7652. cp++;
  7653. }
  7654. }
  7655. static void dump_cmd_in_x_mode(char **argv)
  7656. {
  7657. if (G_x_mode && argv) {
  7658. unsigned n;
  7659. /* "+[+++...][ cmd...]\n\0" */
  7660. x_mode_prefix();
  7661. n = 0;
  7662. while (argv[n]) {
  7663. x_mode_addchr(' ');
  7664. if (argv[n][0] == '\0') {
  7665. x_mode_addchr('\'');
  7666. x_mode_addchr('\'');
  7667. } else {
  7668. x_mode_print_optionally_squoted(argv[n]);
  7669. }
  7670. n++;
  7671. }
  7672. x_mode_flush();
  7673. }
  7674. }
  7675. #else
  7676. # define dump_cmd_in_x_mode(argv) ((void)0)
  7677. #endif
  7678. #if ENABLE_HUSH_COMMAND
  7679. static void if_command_vV_print_and_exit(char opt_vV, char *cmd, const char *explanation)
  7680. {
  7681. char *to_free;
  7682. if (!opt_vV)
  7683. return;
  7684. to_free = NULL;
  7685. if (!explanation) {
  7686. char *path = getenv("PATH");
  7687. explanation = to_free = find_executable(cmd, &path); /* path == NULL is ok */
  7688. if (!explanation)
  7689. _exit(1); /* PROG was not found */
  7690. if (opt_vV != 'V')
  7691. cmd = to_free; /* -v PROG prints "/path/to/PROG" */
  7692. }
  7693. printf((opt_vV == 'V') ? "%s is %s\n" : "%s\n", cmd, explanation);
  7694. free(to_free);
  7695. fflush_all();
  7696. _exit(0);
  7697. }
  7698. #else
  7699. # define if_command_vV_print_and_exit(a,b,c) ((void)0)
  7700. #endif
  7701. #if BB_MMU
  7702. #define pseudo_exec_argv(nommu_save, argv, assignment_cnt, argv_expanded) \
  7703. pseudo_exec_argv(argv, assignment_cnt, argv_expanded)
  7704. #define pseudo_exec(nommu_save, command, argv_expanded) \
  7705. pseudo_exec(command, argv_expanded)
  7706. #endif
  7707. /* Called after [v]fork() in run_pipe, or from builtin_exec.
  7708. * Never returns.
  7709. * Don't exit() here. If you don't exec, use _exit instead.
  7710. * The at_exit handlers apparently confuse the calling process,
  7711. * in particular stdin handling. Not sure why? -- because of vfork! (vda)
  7712. */
  7713. static void pseudo_exec_argv(nommu_save_t *nommu_save,
  7714. char **argv, int assignment_cnt,
  7715. char **argv_expanded) NORETURN;
  7716. static NOINLINE void pseudo_exec_argv(nommu_save_t *nommu_save,
  7717. char **argv, int assignment_cnt,
  7718. char **argv_expanded)
  7719. {
  7720. const struct built_in_command *x;
  7721. struct variable **sv_shadowed;
  7722. char **new_env;
  7723. IF_HUSH_COMMAND(char opt_vV = 0;)
  7724. IF_HUSH_FUNCTIONS(const struct function *funcp;)
  7725. new_env = expand_assignments(argv, assignment_cnt);
  7726. dump_cmd_in_x_mode(new_env);
  7727. if (!argv[assignment_cnt]) {
  7728. /* Case when we are here: ... | var=val | ...
  7729. * (note that we do not exit early, i.e., do not optimize out
  7730. * expand_assignments(): think about ... | var=`sleep 1` | ...
  7731. */
  7732. free_strings(new_env);
  7733. _exit(EXIT_SUCCESS);
  7734. }
  7735. sv_shadowed = G.shadowed_vars_pp;
  7736. #if BB_MMU
  7737. G.shadowed_vars_pp = NULL; /* "don't save, free them instead" */
  7738. #else
  7739. G.shadowed_vars_pp = &nommu_save->old_vars;
  7740. G.var_nest_level++;
  7741. #endif
  7742. set_vars_and_save_old(new_env);
  7743. G.shadowed_vars_pp = sv_shadowed;
  7744. if (argv_expanded) {
  7745. argv = argv_expanded;
  7746. } else {
  7747. argv = expand_strvec_to_strvec(argv + assignment_cnt);
  7748. #if !BB_MMU
  7749. nommu_save->argv = argv;
  7750. #endif
  7751. }
  7752. dump_cmd_in_x_mode(argv);
  7753. #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
  7754. if (strchr(argv[0], '/') != NULL)
  7755. goto skip;
  7756. #endif
  7757. #if ENABLE_HUSH_FUNCTIONS
  7758. /* Check if the command matches any functions (this goes before bltins) */
  7759. funcp = find_function(argv[0]);
  7760. if (funcp)
  7761. exec_function(&nommu_save->argv_from_re_execing, funcp, argv);
  7762. #endif
  7763. #if ENABLE_HUSH_COMMAND
  7764. /* "command BAR": run BAR without looking it up among functions
  7765. * "command -v BAR": print "BAR" or "/path/to/BAR"; or exit 1
  7766. * "command -V BAR": print "BAR is {a function,a shell builtin,/path/to/BAR}"
  7767. */
  7768. while (strcmp(argv[0], "command") == 0 && argv[1]) {
  7769. char *p;
  7770. argv++;
  7771. p = *argv;
  7772. if (p[0] != '-' || !p[1])
  7773. continue; /* bash allows "command command command [-OPT] BAR" */
  7774. for (;;) {
  7775. p++;
  7776. switch (*p) {
  7777. case '\0':
  7778. argv++;
  7779. p = *argv;
  7780. if (p[0] != '-' || !p[1])
  7781. goto after_opts;
  7782. continue; /* next arg is also -opts, process it too */
  7783. case 'v':
  7784. case 'V':
  7785. opt_vV = *p;
  7786. continue;
  7787. default:
  7788. bb_error_msg_and_die("%s: %s: invalid option", "command", argv[0]);
  7789. }
  7790. }
  7791. }
  7792. after_opts:
  7793. # if ENABLE_HUSH_FUNCTIONS
  7794. if (opt_vV && find_function(argv[0]))
  7795. if_command_vV_print_and_exit(opt_vV, argv[0], "a function");
  7796. # endif
  7797. #endif
  7798. /* Check if the command matches any of the builtins.
  7799. * Depending on context, this might be redundant. But it's
  7800. * easier to waste a few CPU cycles than it is to figure out
  7801. * if this is one of those cases.
  7802. */
  7803. /* Why "BB_MMU ? :" difference in logic? -
  7804. * On NOMMU, it is more expensive to re-execute shell
  7805. * just in order to run echo or test builtin.
  7806. * It's better to skip it here and run corresponding
  7807. * non-builtin later. */
  7808. x = BB_MMU ? find_builtin(argv[0]) : find_builtin1(argv[0]);
  7809. if (x) {
  7810. if_command_vV_print_and_exit(opt_vV, argv[0], "a shell builtin");
  7811. exec_builtin(&nommu_save->argv_from_re_execing, x, argv);
  7812. }
  7813. #if ENABLE_FEATURE_SH_STANDALONE
  7814. /* Check if the command matches any busybox applets */
  7815. {
  7816. int a = find_applet_by_name(argv[0]);
  7817. if (a >= 0) {
  7818. if_command_vV_print_and_exit(opt_vV, argv[0], "an applet");
  7819. # if BB_MMU /* see above why on NOMMU it is not allowed */
  7820. if (APPLET_IS_NOEXEC(a)) {
  7821. /* Do not leak open fds from opened script files etc.
  7822. * Testcase: interactive "ls -l /proc/self/fd"
  7823. * should not show tty fd open.
  7824. */
  7825. close_saved_fds_and_FILE_fds();
  7826. //FIXME: should also close saved redir fds
  7827. //This casuses test failures in
  7828. //redir_children_should_not_see_saved_fd_2.tests
  7829. //redir_children_should_not_see_saved_fd_3.tests
  7830. //if you replace "busybox find" with just "find" in them
  7831. /* Without this, "rm -i FILE" can't be ^C'ed: */
  7832. switch_off_special_sigs(G.special_sig_mask);
  7833. debug_printf_exec("running applet '%s'\n", argv[0]);
  7834. run_noexec_applet_and_exit(a, argv[0], argv);
  7835. }
  7836. # endif
  7837. /* Re-exec ourselves */
  7838. debug_printf_exec("re-execing applet '%s'\n", argv[0]);
  7839. /* Don't propagate SIG_IGN to the child */
  7840. if (SPECIAL_JOBSTOP_SIGS != 0)
  7841. switch_off_special_sigs(G.special_sig_mask & SPECIAL_JOBSTOP_SIGS);
  7842. execv(bb_busybox_exec_path, argv);
  7843. /* If they called chroot or otherwise made the binary no longer
  7844. * executable, fall through */
  7845. }
  7846. }
  7847. #endif
  7848. #if ENABLE_FEATURE_SH_STANDALONE || BB_MMU
  7849. skip:
  7850. #endif
  7851. if_command_vV_print_and_exit(opt_vV, argv[0], NULL);
  7852. execvp_or_die(argv);
  7853. }
  7854. /* Called after [v]fork() in run_pipe
  7855. */
  7856. static void pseudo_exec(nommu_save_t *nommu_save,
  7857. struct command *command,
  7858. char **argv_expanded) NORETURN;
  7859. static void pseudo_exec(nommu_save_t *nommu_save,
  7860. struct command *command,
  7861. char **argv_expanded)
  7862. {
  7863. #if ENABLE_HUSH_FUNCTIONS
  7864. if (command->cmd_type == CMD_FUNCDEF) {
  7865. /* Ignore funcdefs in pipes:
  7866. * true | f() { cmd }
  7867. */
  7868. _exit(0);
  7869. }
  7870. #endif
  7871. if (command->argv) {
  7872. pseudo_exec_argv(nommu_save, command->argv,
  7873. command->assignment_cnt, argv_expanded);
  7874. }
  7875. if (command->group) {
  7876. /* Cases when we are here:
  7877. * ( list )
  7878. * { list } &
  7879. * ... | ( list ) | ...
  7880. * ... | { list } | ...
  7881. */
  7882. #if BB_MMU
  7883. int rcode;
  7884. debug_printf_exec("pseudo_exec: run_list\n");
  7885. reset_traps_to_defaults();
  7886. rcode = run_list(command->group);
  7887. /* OK to leak memory by not calling free_pipe_list,
  7888. * since this process is about to exit */
  7889. _exit(rcode);
  7890. #else
  7891. re_execute_shell(&nommu_save->argv_from_re_execing,
  7892. command->group_as_string,
  7893. G.global_argv[0],
  7894. G.global_argv + 1,
  7895. NULL);
  7896. #endif
  7897. }
  7898. /* Case when we are here: ... | >file */
  7899. debug_printf_exec("pseudo_exec'ed null command\n");
  7900. _exit(EXIT_SUCCESS);
  7901. }
  7902. #if ENABLE_HUSH_JOB
  7903. static const char *get_cmdtext(struct pipe *pi)
  7904. {
  7905. char **argv;
  7906. char *p;
  7907. int len;
  7908. /* This is subtle. ->cmdtext is created only on first backgrounding.
  7909. * (Think "cat, <ctrl-z>, fg, <ctrl-z>, fg, <ctrl-z>...." here...)
  7910. * On subsequent bg argv is trashed, but we won't use it */
  7911. if (pi->cmdtext)
  7912. return pi->cmdtext;
  7913. argv = pi->cmds[0].argv;
  7914. if (!argv) {
  7915. pi->cmdtext = xzalloc(1);
  7916. return pi->cmdtext;
  7917. }
  7918. len = 0;
  7919. do {
  7920. len += strlen(*argv) + 1;
  7921. } while (*++argv);
  7922. p = xmalloc(len);
  7923. pi->cmdtext = p;
  7924. argv = pi->cmds[0].argv;
  7925. do {
  7926. p = stpcpy(p, *argv);
  7927. *p++ = ' ';
  7928. } while (*++argv);
  7929. p[-1] = '\0';
  7930. return pi->cmdtext;
  7931. }
  7932. static void remove_job_from_table(struct pipe *pi)
  7933. {
  7934. struct pipe *prev_pipe;
  7935. if (pi == G.job_list) {
  7936. G.job_list = pi->next;
  7937. } else {
  7938. prev_pipe = G.job_list;
  7939. while (prev_pipe->next != pi)
  7940. prev_pipe = prev_pipe->next;
  7941. prev_pipe->next = pi->next;
  7942. }
  7943. G.last_jobid = 0;
  7944. if (G.job_list)
  7945. G.last_jobid = G.job_list->jobid;
  7946. }
  7947. static void delete_finished_job(struct pipe *pi)
  7948. {
  7949. remove_job_from_table(pi);
  7950. free_pipe(pi);
  7951. }
  7952. static void clean_up_last_dead_job(void)
  7953. {
  7954. if (G.job_list && !G.job_list->alive_cmds)
  7955. delete_finished_job(G.job_list);
  7956. }
  7957. static void insert_job_into_table(struct pipe *pi)
  7958. {
  7959. struct pipe *job, **jobp;
  7960. int i;
  7961. clean_up_last_dead_job();
  7962. /* Find the end of the list, and find next job ID to use */
  7963. i = 0;
  7964. jobp = &G.job_list;
  7965. while ((job = *jobp) != NULL) {
  7966. if (job->jobid > i)
  7967. i = job->jobid;
  7968. jobp = &job->next;
  7969. }
  7970. pi->jobid = i + 1;
  7971. /* Create a new job struct at the end */
  7972. job = *jobp = xmemdup(pi, sizeof(*pi));
  7973. job->next = NULL;
  7974. job->cmds = xzalloc(sizeof(pi->cmds[0]) * pi->num_cmds);
  7975. /* Cannot copy entire pi->cmds[] vector! This causes double frees */
  7976. for (i = 0; i < pi->num_cmds; i++) {
  7977. job->cmds[i].pid = pi->cmds[i].pid;
  7978. /* all other fields are not used and stay zero */
  7979. }
  7980. job->cmdtext = xstrdup(get_cmdtext(pi));
  7981. if (G_interactive_fd)
  7982. printf("[%u] %u %s\n", job->jobid, (unsigned)job->cmds[0].pid, job->cmdtext);
  7983. G.last_jobid = job->jobid;
  7984. }
  7985. #endif /* JOB */
  7986. static int job_exited_or_stopped(struct pipe *pi)
  7987. {
  7988. int rcode, i;
  7989. if (pi->alive_cmds != pi->stopped_cmds)
  7990. return -1;
  7991. /* All processes in fg pipe have exited or stopped */
  7992. rcode = 0;
  7993. i = pi->num_cmds;
  7994. while (--i >= 0) {
  7995. rcode = pi->cmds[i].cmd_exitcode;
  7996. /* usually last process gives overall exitstatus,
  7997. * but with "set -o pipefail", last *failed* process does */
  7998. if (G.o_opt[OPT_O_PIPEFAIL] == 0 || rcode != 0)
  7999. break;
  8000. }
  8001. IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
  8002. return rcode;
  8003. }
  8004. static int process_wait_result(struct pipe *fg_pipe, pid_t childpid, int status)
  8005. {
  8006. #if ENABLE_HUSH_JOB
  8007. struct pipe *pi;
  8008. #endif
  8009. int i, dead;
  8010. dead = WIFEXITED(status) || WIFSIGNALED(status);
  8011. #if DEBUG_JOBS
  8012. if (WIFSTOPPED(status))
  8013. debug_printf_jobs("pid %d stopped by sig %d (exitcode %d)\n",
  8014. childpid, WSTOPSIG(status), WEXITSTATUS(status));
  8015. if (WIFSIGNALED(status))
  8016. debug_printf_jobs("pid %d killed by sig %d (exitcode %d)\n",
  8017. childpid, WTERMSIG(status), WEXITSTATUS(status));
  8018. if (WIFEXITED(status))
  8019. debug_printf_jobs("pid %d exited, exitcode %d\n",
  8020. childpid, WEXITSTATUS(status));
  8021. #endif
  8022. /* Were we asked to wait for a fg pipe? */
  8023. if (fg_pipe) {
  8024. i = fg_pipe->num_cmds;
  8025. while (--i >= 0) {
  8026. int rcode;
  8027. debug_printf_jobs("check pid %d\n", fg_pipe->cmds[i].pid);
  8028. if (fg_pipe->cmds[i].pid != childpid)
  8029. continue;
  8030. if (dead) {
  8031. int ex;
  8032. fg_pipe->cmds[i].pid = 0;
  8033. fg_pipe->alive_cmds--;
  8034. ex = WEXITSTATUS(status);
  8035. /* bash prints killer signal's name for *last*
  8036. * process in pipe (prints just newline for SIGINT/SIGPIPE).
  8037. * Mimic this. Example: "sleep 5" + (^\ or kill -QUIT)
  8038. */
  8039. if (WIFSIGNALED(status)) {
  8040. int sig = WTERMSIG(status);
  8041. if (i == fg_pipe->num_cmds-1)
  8042. /* TODO: use strsignal() instead for bash compat? but that's bloat... */
  8043. puts(sig == SIGINT || sig == SIGPIPE ? "" : get_signame(sig));
  8044. /* TODO: if (WCOREDUMP(status)) + " (core dumped)"; */
  8045. /* TODO: MIPS has 128 sigs (1..128), what if sig==128 here?
  8046. * Maybe we need to use sig | 128? */
  8047. ex = sig + 128;
  8048. }
  8049. fg_pipe->cmds[i].cmd_exitcode = ex;
  8050. } else {
  8051. fg_pipe->stopped_cmds++;
  8052. }
  8053. debug_printf_jobs("fg_pipe: alive_cmds %d stopped_cmds %d\n",
  8054. fg_pipe->alive_cmds, fg_pipe->stopped_cmds);
  8055. rcode = job_exited_or_stopped(fg_pipe);
  8056. if (rcode >= 0) {
  8057. /* Note: *non-interactive* bash does not continue if all processes in fg pipe
  8058. * are stopped. Testcase: "cat | cat" in a script (not on command line!)
  8059. * and "killall -STOP cat" */
  8060. if (G_interactive_fd) {
  8061. #if ENABLE_HUSH_JOB
  8062. if (fg_pipe->alive_cmds != 0)
  8063. insert_job_into_table(fg_pipe);
  8064. #endif
  8065. return rcode;
  8066. }
  8067. if (fg_pipe->alive_cmds == 0)
  8068. return rcode;
  8069. }
  8070. /* There are still running processes in the fg_pipe */
  8071. return -1;
  8072. }
  8073. /* It wasn't in fg_pipe, look for process in bg pipes */
  8074. }
  8075. #if ENABLE_HUSH_JOB
  8076. /* We were asked to wait for bg or orphaned children */
  8077. /* No need to remember exitcode in this case */
  8078. for (pi = G.job_list; pi; pi = pi->next) {
  8079. for (i = 0; i < pi->num_cmds; i++) {
  8080. if (pi->cmds[i].pid == childpid)
  8081. goto found_pi_and_prognum;
  8082. }
  8083. }
  8084. /* Happens when shell is used as init process (init=/bin/sh) */
  8085. debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
  8086. return -1; /* this wasn't a process from fg_pipe */
  8087. found_pi_and_prognum:
  8088. if (dead) {
  8089. /* child exited */
  8090. int rcode = WEXITSTATUS(status);
  8091. if (WIFSIGNALED(status))
  8092. rcode = 128 + WTERMSIG(status);
  8093. pi->cmds[i].cmd_exitcode = rcode;
  8094. if (G.last_bg_pid == pi->cmds[i].pid)
  8095. G.last_bg_pid_exitcode = rcode;
  8096. pi->cmds[i].pid = 0;
  8097. pi->alive_cmds--;
  8098. if (!pi->alive_cmds) {
  8099. #if ENABLE_HUSH_BASH_COMPAT
  8100. G.dead_job_exitcode = job_exited_or_stopped(pi);
  8101. #endif
  8102. if (G_interactive_fd) {
  8103. printf(JOB_STATUS_FORMAT, pi->jobid,
  8104. "Done", pi->cmdtext);
  8105. delete_finished_job(pi);
  8106. } else {
  8107. /*
  8108. * bash deletes finished jobs from job table only in interactive mode,
  8109. * after "jobs" cmd, or if pid of a new process matches one of the old ones
  8110. * (see cleanup_dead_jobs(), delete_old_job(), J_NOTIFIED in bash source).
  8111. * Testcase script: "(exit 3) & sleep 1; wait %1; echo $?" prints 3 in bash.
  8112. * We only retain one "dead" job, if it's the single job on the list.
  8113. * This covers most of real-world scenarios where this is useful.
  8114. */
  8115. if (pi != G.job_list)
  8116. delete_finished_job(pi);
  8117. }
  8118. }
  8119. } else {
  8120. /* child stopped */
  8121. pi->stopped_cmds++;
  8122. }
  8123. #endif
  8124. return -1; /* this wasn't a process from fg_pipe */
  8125. }
  8126. /* Check to see if any processes have exited -- if they have,
  8127. * figure out why and see if a job has completed.
  8128. *
  8129. * If non-NULL fg_pipe: wait for its completion or stop.
  8130. * Return its exitcode or zero if stopped.
  8131. *
  8132. * Alternatively (fg_pipe == NULL, waitfor_pid != 0):
  8133. * waitpid(WNOHANG), if waitfor_pid exits or stops, return exitcode+1,
  8134. * else return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
  8135. * or 0 if no children changed status.
  8136. *
  8137. * Alternatively (fg_pipe == NULL, waitfor_pid == 0),
  8138. * return <0 if waitpid errors out (e.g. ECHILD: nothing to wait for)
  8139. * or 0 if no children changed status.
  8140. */
  8141. static int checkjobs(struct pipe *fg_pipe, pid_t waitfor_pid)
  8142. {
  8143. int attributes;
  8144. int status;
  8145. int rcode = 0;
  8146. debug_printf_jobs("checkjobs %p\n", fg_pipe);
  8147. attributes = WUNTRACED;
  8148. if (fg_pipe == NULL)
  8149. attributes |= WNOHANG;
  8150. errno = 0;
  8151. #if ENABLE_HUSH_FAST
  8152. if (G.handled_SIGCHLD == G.count_SIGCHLD) {
  8153. //bb_error_msg("[%d] checkjobs: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d children?:%d fg_pipe:%p",
  8154. //getpid(), G.count_SIGCHLD, G.handled_SIGCHLD, G.we_have_children, fg_pipe);
  8155. /* There was neither fork nor SIGCHLD since last waitpid */
  8156. /* Avoid doing waitpid syscall if possible */
  8157. if (!G.we_have_children) {
  8158. errno = ECHILD;
  8159. return -1;
  8160. }
  8161. if (fg_pipe == NULL) { /* is WNOHANG set? */
  8162. /* We have children, but they did not exit
  8163. * or stop yet (we saw no SIGCHLD) */
  8164. return 0;
  8165. }
  8166. /* else: !WNOHANG, waitpid will block, can't short-circuit */
  8167. }
  8168. #endif
  8169. /* Do we do this right?
  8170. * bash-3.00# sleep 20 | false
  8171. * <ctrl-Z pressed>
  8172. * [3]+ Stopped sleep 20 | false
  8173. * bash-3.00# echo $?
  8174. * 1 <========== bg pipe is not fully done, but exitcode is already known!
  8175. * [hush 1.14.0: yes we do it right]
  8176. */
  8177. while (1) {
  8178. pid_t childpid;
  8179. #if ENABLE_HUSH_FAST
  8180. int i;
  8181. i = G.count_SIGCHLD;
  8182. #endif
  8183. childpid = waitpid(-1, &status, attributes);
  8184. if (childpid <= 0) {
  8185. if (childpid && errno != ECHILD)
  8186. bb_perror_msg("waitpid");
  8187. #if ENABLE_HUSH_FAST
  8188. else { /* Until next SIGCHLD, waitpid's are useless */
  8189. G.we_have_children = (childpid == 0);
  8190. G.handled_SIGCHLD = i;
  8191. //bb_error_msg("[%d] checkjobs: waitpid returned <= 0, G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
  8192. }
  8193. #endif
  8194. /* ECHILD (no children), or 0 (no change in children status) */
  8195. rcode = childpid;
  8196. break;
  8197. }
  8198. rcode = process_wait_result(fg_pipe, childpid, status);
  8199. if (rcode >= 0) {
  8200. /* fg_pipe exited or stopped */
  8201. break;
  8202. }
  8203. if (childpid == waitfor_pid) { /* "wait PID" */
  8204. debug_printf_exec("childpid==waitfor_pid:%d status:0x%08x\n", childpid, status);
  8205. rcode = WEXITSTATUS(status);
  8206. if (WIFSIGNALED(status))
  8207. rcode = 128 + WTERMSIG(status);
  8208. if (WIFSTOPPED(status))
  8209. /* bash: "cmd & wait $!" and cmd stops: $? = 128 + stopsig */
  8210. rcode = 128 + WSTOPSIG(status);
  8211. rcode++;
  8212. break; /* "wait PID" called us, give it exitcode+1 */
  8213. }
  8214. #if ENABLE_HUSH_BASH_COMPAT
  8215. if (-1 == waitfor_pid /* "wait -n" (wait for any one job) */
  8216. && G.dead_job_exitcode >= 0 /* some job did finish */
  8217. ) {
  8218. debug_printf_exec("waitfor_pid:-1\n");
  8219. rcode = G.dead_job_exitcode + 1;
  8220. break;
  8221. }
  8222. #endif
  8223. /* This wasn't one of our processes, or */
  8224. /* fg_pipe still has running processes, do waitpid again */
  8225. } /* while (waitpid succeeds)... */
  8226. return rcode;
  8227. }
  8228. #if ENABLE_HUSH_JOB
  8229. static int checkjobs_and_fg_shell(struct pipe *fg_pipe)
  8230. {
  8231. pid_t p;
  8232. int rcode = checkjobs(fg_pipe, 0 /*(no pid to wait for)*/);
  8233. if (G_saved_tty_pgrp) {
  8234. /* Job finished, move the shell to the foreground */
  8235. p = getpgrp(); /* our process group id */
  8236. debug_printf_jobs("fg'ing ourself: getpgrp()=%d\n", (int)p);
  8237. tcsetpgrp(G_interactive_fd, p);
  8238. }
  8239. return rcode;
  8240. }
  8241. #endif
  8242. /* Start all the jobs, but don't wait for anything to finish.
  8243. * See checkjobs().
  8244. *
  8245. * Return code is normally -1, when the caller has to wait for children
  8246. * to finish to determine the exit status of the pipe. If the pipe
  8247. * is a simple builtin command, however, the action is done by the
  8248. * time run_pipe returns, and the exit code is provided as the
  8249. * return value.
  8250. *
  8251. * Returns -1 only if started some children. IOW: we have to
  8252. * mask out retvals of builtins etc with 0xff!
  8253. *
  8254. * The only case when we do not need to [v]fork is when the pipe
  8255. * is single, non-backgrounded, non-subshell command. Examples:
  8256. * cmd ; ... { list } ; ...
  8257. * cmd && ... { list } && ...
  8258. * cmd || ... { list } || ...
  8259. * If it is, then we can run cmd as a builtin, NOFORK,
  8260. * or (if SH_STANDALONE) an applet, and we can run the { list }
  8261. * with run_list. If it isn't one of these, we fork and exec cmd.
  8262. *
  8263. * Cases when we must fork:
  8264. * non-single: cmd | cmd
  8265. * backgrounded: cmd & { list } &
  8266. * subshell: ( list ) [&]
  8267. */
  8268. #if !ENABLE_HUSH_MODE_X
  8269. #define redirect_and_varexp_helper(command, sqp, argv_expanded) \
  8270. redirect_and_varexp_helper(command, sqp)
  8271. #endif
  8272. static int redirect_and_varexp_helper(
  8273. struct command *command,
  8274. struct squirrel **sqp,
  8275. char **argv_expanded)
  8276. {
  8277. /* Assignments occur before redirects. Try:
  8278. * a=`sleep 1` sleep 2 3>/qwe/rty
  8279. */
  8280. char **new_env = expand_assignments(command->argv, command->assignment_cnt);
  8281. dump_cmd_in_x_mode(new_env);
  8282. dump_cmd_in_x_mode(argv_expanded);
  8283. /* this takes ownership of new_env[i] elements, and frees new_env: */
  8284. set_vars_and_save_old(new_env);
  8285. return setup_redirects(command, sqp);
  8286. }
  8287. static NOINLINE int run_pipe(struct pipe *pi)
  8288. {
  8289. static const char *const null_ptr = NULL;
  8290. int cmd_no;
  8291. int next_infd;
  8292. struct command *command;
  8293. char **argv_expanded;
  8294. char **argv;
  8295. struct squirrel *squirrel = NULL;
  8296. int rcode;
  8297. debug_printf_exec("run_pipe start: members:%d\n", pi->num_cmds);
  8298. debug_enter();
  8299. /* Testcase: set -- q w e; (IFS='' echo "$*"; IFS=''; echo "$*"); echo "$*"
  8300. * Result should be 3 lines: q w e, qwe, q w e
  8301. */
  8302. if (G.ifs_whitespace != G.ifs)
  8303. free(G.ifs_whitespace);
  8304. G.ifs = get_local_var_value("IFS");
  8305. if (G.ifs) {
  8306. char *p;
  8307. G.ifs_whitespace = (char*)G.ifs;
  8308. p = skip_whitespace(G.ifs);
  8309. if (*p) {
  8310. /* Not all $IFS is whitespace */
  8311. char *d;
  8312. int len = p - G.ifs;
  8313. p = skip_non_whitespace(p);
  8314. G.ifs_whitespace = xmalloc(len + strlen(p) + 1); /* can overestimate */
  8315. d = mempcpy(G.ifs_whitespace, G.ifs, len);
  8316. while (*p) {
  8317. if (isspace(*p))
  8318. *d++ = *p;
  8319. p++;
  8320. }
  8321. *d = '\0';
  8322. }
  8323. } else {
  8324. G.ifs = defifs;
  8325. G.ifs_whitespace = (char*)G.ifs;
  8326. }
  8327. IF_HUSH_JOB(pi->pgrp = -1;)
  8328. pi->stopped_cmds = 0;
  8329. command = &pi->cmds[0];
  8330. argv_expanded = NULL;
  8331. if (pi->num_cmds != 1
  8332. || pi->followup == PIPE_BG
  8333. || command->cmd_type == CMD_SUBSHELL
  8334. ) {
  8335. goto must_fork;
  8336. }
  8337. pi->alive_cmds = 1;
  8338. debug_printf_exec(": group:%p argv:'%s'\n",
  8339. command->group, command->argv ? command->argv[0] : "NONE");
  8340. if (command->group) {
  8341. #if ENABLE_HUSH_FUNCTIONS
  8342. if (command->cmd_type == CMD_FUNCDEF) {
  8343. /* "executing" func () { list } */
  8344. struct function *funcp;
  8345. funcp = new_function(command->argv[0]);
  8346. /* funcp->name is already set to argv[0] */
  8347. funcp->body = command->group;
  8348. # if !BB_MMU
  8349. funcp->body_as_string = command->group_as_string;
  8350. command->group_as_string = NULL;
  8351. # endif
  8352. command->group = NULL;
  8353. command->argv[0] = NULL;
  8354. debug_printf_exec("cmd %p has child func at %p\n", command, funcp);
  8355. funcp->parent_cmd = command;
  8356. command->child_func = funcp;
  8357. debug_printf_exec("run_pipe: return EXIT_SUCCESS\n");
  8358. debug_leave();
  8359. return EXIT_SUCCESS;
  8360. }
  8361. #endif
  8362. /* { list } */
  8363. debug_printf_exec("non-subshell group\n");
  8364. rcode = 1; /* exitcode if redir failed */
  8365. if (setup_redirects(command, &squirrel) == 0) {
  8366. debug_printf_exec(": run_list\n");
  8367. //FIXME: we need to pass squirrel down into run_list()
  8368. //for SH_STANDALONE case, or else this construct:
  8369. // { find /proc/self/fd; true; } >FILE; cmd2
  8370. //has no way of closing saved fd#1 for "find",
  8371. //and in SH_STANDALONE mode, "find" is not execed,
  8372. //therefore CLOEXEC on saved fd does not help.
  8373. rcode = run_list(command->group) & 0xff;
  8374. }
  8375. restore_redirects(squirrel);
  8376. IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
  8377. debug_leave();
  8378. debug_printf_exec("run_pipe: return %d\n", rcode);
  8379. return rcode;
  8380. }
  8381. argv = command->argv ? command->argv : (char **) &null_ptr;
  8382. {
  8383. const struct built_in_command *x;
  8384. IF_HUSH_FUNCTIONS(const struct function *funcp;)
  8385. IF_NOT_HUSH_FUNCTIONS(enum { funcp = 0 };)
  8386. struct variable **sv_shadowed;
  8387. struct variable *old_vars;
  8388. #if ENABLE_HUSH_LINENO_VAR
  8389. G.execute_lineno = command->lineno;
  8390. #endif
  8391. if (argv[command->assignment_cnt] == NULL) {
  8392. /* Assignments, but no command.
  8393. * Ensure redirects take effect (that is, create files).
  8394. * Try "a=t >file"
  8395. */
  8396. unsigned i;
  8397. G.expand_exitcode = 0;
  8398. only_assignments:
  8399. rcode = setup_redirects(command, &squirrel);
  8400. restore_redirects(squirrel);
  8401. /* Set shell variables */
  8402. i = 0;
  8403. while (i < command->assignment_cnt) {
  8404. char *p = expand_string_to_string(argv[i],
  8405. EXP_FLAG_ESC_GLOB_CHARS,
  8406. /*unbackslash:*/ 1
  8407. );
  8408. #if ENABLE_HUSH_MODE_X
  8409. if (G_x_mode) {
  8410. char *eq;
  8411. if (i == 0)
  8412. x_mode_prefix();
  8413. x_mode_addchr(' ');
  8414. eq = strchrnul(p, '=');
  8415. if (*eq) eq++;
  8416. x_mode_addblock(p, (eq - p));
  8417. x_mode_print_optionally_squoted(eq);
  8418. x_mode_flush();
  8419. }
  8420. #endif
  8421. debug_printf_env("set shell var:'%s'->'%s'\n", *argv, p);
  8422. if (set_local_var(p, /*flag:*/ 0)) {
  8423. /* assignment to readonly var / putenv error? */
  8424. rcode = 1;
  8425. }
  8426. i++;
  8427. }
  8428. /* Redirect error sets $? to 1. Otherwise,
  8429. * if evaluating assignment value set $?, retain it.
  8430. * Else, clear $?:
  8431. * false; q=`exit 2`; echo $? - should print 2
  8432. * false; x=1; echo $? - should print 0
  8433. * Because of the 2nd case, we can't just use G.last_exitcode.
  8434. */
  8435. if (rcode == 0)
  8436. rcode = G.expand_exitcode;
  8437. IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
  8438. debug_leave();
  8439. debug_printf_exec("run_pipe: return %d\n", rcode);
  8440. return rcode;
  8441. }
  8442. /* Expand the rest into (possibly) many strings each */
  8443. #if defined(CMD_SINGLEWORD_NOGLOB)
  8444. if (command->cmd_type == CMD_SINGLEWORD_NOGLOB)
  8445. argv_expanded = expand_strvec_to_strvec_singleword_noglob(argv + command->assignment_cnt);
  8446. else
  8447. #endif
  8448. argv_expanded = expand_strvec_to_strvec(argv + command->assignment_cnt);
  8449. /* If someone gives us an empty string: `cmd with empty output` */
  8450. if (!argv_expanded[0]) {
  8451. free(argv_expanded);
  8452. /* `false` still has to set exitcode 1 */
  8453. G.expand_exitcode = G.last_exitcode;
  8454. goto only_assignments;
  8455. }
  8456. old_vars = NULL;
  8457. sv_shadowed = G.shadowed_vars_pp;
  8458. /* Check if argv[0] matches any functions (this goes before bltins) */
  8459. IF_HUSH_FUNCTIONS(funcp = find_function(argv_expanded[0]);)
  8460. IF_HUSH_FUNCTIONS(x = NULL;)
  8461. IF_HUSH_FUNCTIONS(if (!funcp))
  8462. x = find_builtin(argv_expanded[0]);
  8463. if (x || funcp) {
  8464. if (x && x->b_function == builtin_exec && argv_expanded[1] == NULL) {
  8465. debug_printf("exec with redirects only\n");
  8466. /*
  8467. * Variable assignments are executed, but then "forgotten":
  8468. * a=`sleep 1;echo A` exec 3>&-; echo $a
  8469. * sleeps, but prints nothing.
  8470. */
  8471. enter_var_nest_level();
  8472. G.shadowed_vars_pp = &old_vars;
  8473. rcode = redirect_and_varexp_helper(command,
  8474. /*squirrel:*/ ERR_PTR,
  8475. argv_expanded
  8476. );
  8477. G.shadowed_vars_pp = sv_shadowed;
  8478. /* rcode=1 can be if redir file can't be opened */
  8479. goto clean_up_and_ret1;
  8480. }
  8481. /* Bump var nesting, or this will leak exported $a:
  8482. * a=b true; env | grep ^a=
  8483. */
  8484. enter_var_nest_level();
  8485. /* Collect all variables "shadowed" by helper
  8486. * (IOW: old vars overridden by "var1=val1 var2=val2 cmd..." syntax)
  8487. * into old_vars list:
  8488. */
  8489. G.shadowed_vars_pp = &old_vars;
  8490. rcode = redirect_and_varexp_helper(command, &squirrel, argv_expanded);
  8491. if (rcode == 0) {
  8492. if (!funcp) {
  8493. /* Do not collect *to old_vars list* vars shadowed
  8494. * by e.g. "local VAR" builtin (collect them
  8495. * in the previously nested list instead):
  8496. * don't want them to be restored immediately
  8497. * after "local" completes.
  8498. */
  8499. G.shadowed_vars_pp = sv_shadowed;
  8500. debug_printf_exec(": builtin '%s' '%s'...\n",
  8501. x->b_cmd, argv_expanded[1]);
  8502. fflush_all();
  8503. rcode = x->b_function(argv_expanded) & 0xff;
  8504. fflush_all();
  8505. }
  8506. #if ENABLE_HUSH_FUNCTIONS
  8507. else {
  8508. debug_printf_exec(": function '%s' '%s'...\n",
  8509. funcp->name, argv_expanded[1]);
  8510. rcode = run_function(funcp, argv_expanded) & 0xff;
  8511. /*
  8512. * But do collect *to old_vars list* vars shadowed
  8513. * within function execution. To that end, restore
  8514. * this pointer _after_ function run:
  8515. */
  8516. G.shadowed_vars_pp = sv_shadowed;
  8517. }
  8518. #endif
  8519. }
  8520. } else
  8521. if (ENABLE_FEATURE_SH_NOFORK && NUM_APPLETS > 1) {
  8522. int n = find_applet_by_name(argv_expanded[0]);
  8523. if (n < 0 || !APPLET_IS_NOFORK(n))
  8524. goto must_fork;
  8525. enter_var_nest_level();
  8526. /* Collect all variables "shadowed" by helper into old_vars list */
  8527. G.shadowed_vars_pp = &old_vars;
  8528. rcode = redirect_and_varexp_helper(command, &squirrel, argv_expanded);
  8529. G.shadowed_vars_pp = sv_shadowed;
  8530. if (rcode == 0) {
  8531. debug_printf_exec(": run_nofork_applet '%s' '%s'...\n",
  8532. argv_expanded[0], argv_expanded[1]);
  8533. /*
  8534. * Note: signals (^C) can't interrupt here.
  8535. * We remember them and they will be acted upon
  8536. * after applet returns.
  8537. * This makes applets which can run for a long time
  8538. * and/or wait for user input ineligible for NOFORK:
  8539. * for example, "yes" or "rm" (rm -i waits for input).
  8540. */
  8541. rcode = run_nofork_applet(n, argv_expanded);
  8542. }
  8543. } else
  8544. goto must_fork;
  8545. restore_redirects(squirrel);
  8546. clean_up_and_ret1:
  8547. leave_var_nest_level();
  8548. add_vars(old_vars);
  8549. /*
  8550. * Try "usleep 99999999" + ^C + "echo $?"
  8551. * with FEATURE_SH_NOFORK=y.
  8552. */
  8553. if (!funcp) {
  8554. /* It was builtin or nofork.
  8555. * if this would be a real fork/execed program,
  8556. * it should have died if a fatal sig was received.
  8557. * But OTOH, there was no separate process,
  8558. * the sig was sent to _shell_, not to non-existing
  8559. * child.
  8560. * Let's just handle ^C only, this one is obvious:
  8561. * we aren't ok with exitcode 0 when ^C was pressed
  8562. * during builtin/nofork.
  8563. */
  8564. if (sigismember(&G.pending_set, SIGINT))
  8565. rcode = 128 + SIGINT;
  8566. }
  8567. free(argv_expanded);
  8568. IF_HAS_KEYWORDS(if (pi->pi_inverted) rcode = !rcode;)
  8569. debug_leave();
  8570. debug_printf_exec("run_pipe return %d\n", rcode);
  8571. return rcode;
  8572. }
  8573. must_fork:
  8574. /* NB: argv_expanded may already be created, and that
  8575. * might include `cmd` runs! Do not rerun it! We *must*
  8576. * use argv_expanded if it's non-NULL */
  8577. /* Going to fork a child per each pipe member */
  8578. pi->alive_cmds = 0;
  8579. next_infd = 0;
  8580. cmd_no = 0;
  8581. while (cmd_no < pi->num_cmds) {
  8582. struct fd_pair pipefds;
  8583. #if !BB_MMU
  8584. int sv_var_nest_level = G.var_nest_level;
  8585. volatile nommu_save_t nommu_save;
  8586. nommu_save.old_vars = NULL;
  8587. nommu_save.argv = NULL;
  8588. nommu_save.argv_from_re_execing = NULL;
  8589. #endif
  8590. command = &pi->cmds[cmd_no];
  8591. cmd_no++;
  8592. if (command->argv) {
  8593. debug_printf_exec(": pipe member '%s' '%s'...\n",
  8594. command->argv[0], command->argv[1]);
  8595. } else {
  8596. debug_printf_exec(": pipe member with no argv\n");
  8597. }
  8598. /* pipes are inserted between pairs of commands */
  8599. pipefds.rd = 0;
  8600. pipefds.wr = 1;
  8601. if (cmd_no < pi->num_cmds)
  8602. xpiped_pair(pipefds);
  8603. #if ENABLE_HUSH_LINENO_VAR
  8604. G.execute_lineno = command->lineno;
  8605. #endif
  8606. command->pid = BB_MMU ? fork() : vfork();
  8607. if (!command->pid) { /* child */
  8608. #if ENABLE_HUSH_JOB
  8609. disable_restore_tty_pgrp_on_exit();
  8610. CLEAR_RANDOM_T(&G.random_gen); /* or else $RANDOM repeats in child */
  8611. /* Every child adds itself to new process group
  8612. * with pgid == pid_of_first_child_in_pipe */
  8613. if (G.run_list_level == 1 && G_interactive_fd) {
  8614. pid_t pgrp;
  8615. pgrp = pi->pgrp;
  8616. if (pgrp < 0) /* true for 1st process only */
  8617. pgrp = getpid();
  8618. if (setpgid(0, pgrp) == 0
  8619. && pi->followup != PIPE_BG
  8620. && G_saved_tty_pgrp /* we have ctty */
  8621. ) {
  8622. /* We do it in *every* child, not just first,
  8623. * to avoid races */
  8624. tcsetpgrp(G_interactive_fd, pgrp);
  8625. }
  8626. }
  8627. #endif
  8628. if (pi->alive_cmds == 0 && pi->followup == PIPE_BG) {
  8629. /* 1st cmd in backgrounded pipe
  8630. * should have its stdin /dev/null'ed */
  8631. close(0);
  8632. if (open(bb_dev_null, O_RDONLY))
  8633. xopen("/", O_RDONLY);
  8634. } else {
  8635. xmove_fd(next_infd, 0);
  8636. }
  8637. xmove_fd(pipefds.wr, 1);
  8638. if (pipefds.rd > 1)
  8639. close(pipefds.rd);
  8640. /* Like bash, explicit redirects override pipes,
  8641. * and the pipe fd (fd#1) is available for dup'ing:
  8642. * "cmd1 2>&1 | cmd2": fd#1 is duped to fd#2, thus stderr
  8643. * of cmd1 goes into pipe.
  8644. */
  8645. if (setup_redirects(command, NULL)) {
  8646. /* Happens when redir file can't be opened:
  8647. * $ hush -c 'echo FOO >&2 | echo BAR 3>/qwe/rty; echo BAZ'
  8648. * FOO
  8649. * hush: can't open '/qwe/rty': No such file or directory
  8650. * BAZ
  8651. * (echo BAR is not executed, it hits _exit(1) below)
  8652. */
  8653. _exit(1);
  8654. }
  8655. /* Stores to nommu_save list of env vars putenv'ed
  8656. * (NOMMU, on MMU we don't need that) */
  8657. /* cast away volatility... */
  8658. pseudo_exec((nommu_save_t*) &nommu_save, command, argv_expanded);
  8659. /* pseudo_exec() does not return */
  8660. }
  8661. /* parent or error */
  8662. #if ENABLE_HUSH_FAST
  8663. G.count_SIGCHLD++;
  8664. //bb_error_msg("[%d] fork in run_pipe: G.count_SIGCHLD:%d G.handled_SIGCHLD:%d", getpid(), G.count_SIGCHLD, G.handled_SIGCHLD);
  8665. #endif
  8666. enable_restore_tty_pgrp_on_exit();
  8667. #if !BB_MMU
  8668. /* Clean up after vforked child */
  8669. free(nommu_save.argv);
  8670. free(nommu_save.argv_from_re_execing);
  8671. G.var_nest_level = sv_var_nest_level;
  8672. remove_nested_vars();
  8673. add_vars(nommu_save.old_vars);
  8674. #endif
  8675. free(argv_expanded);
  8676. argv_expanded = NULL;
  8677. if (command->pid < 0) { /* [v]fork failed */
  8678. /* Clearly indicate, was it fork or vfork */
  8679. bb_perror_msg(BB_MMU ? "vfork"+1 : "vfork");
  8680. } else {
  8681. pi->alive_cmds++;
  8682. #if ENABLE_HUSH_JOB
  8683. /* Second and next children need to know pid of first one */
  8684. if (pi->pgrp < 0)
  8685. pi->pgrp = command->pid;
  8686. #endif
  8687. }
  8688. if (cmd_no > 1)
  8689. close(next_infd);
  8690. if (cmd_no < pi->num_cmds)
  8691. close(pipefds.wr);
  8692. /* Pass read (output) pipe end to next iteration */
  8693. next_infd = pipefds.rd;
  8694. }
  8695. if (!pi->alive_cmds) {
  8696. debug_leave();
  8697. debug_printf_exec("run_pipe return 1 (all forks failed, no children)\n");
  8698. return 1;
  8699. }
  8700. debug_leave();
  8701. debug_printf_exec("run_pipe return -1 (%u children started)\n", pi->alive_cmds);
  8702. return -1;
  8703. }
  8704. /* NB: called by pseudo_exec, and therefore must not modify any
  8705. * global data until exec/_exit (we can be a child after vfork!) */
  8706. static int run_list(struct pipe *pi)
  8707. {
  8708. #if ENABLE_HUSH_CASE
  8709. char *case_word = NULL;
  8710. #endif
  8711. #if ENABLE_HUSH_LOOPS
  8712. struct pipe *loop_top = NULL;
  8713. char **for_lcur = NULL;
  8714. char **for_list = NULL;
  8715. #endif
  8716. smallint last_followup;
  8717. smalluint rcode;
  8718. #if ENABLE_HUSH_IF || ENABLE_HUSH_CASE
  8719. smalluint cond_code = 0;
  8720. #else
  8721. enum { cond_code = 0 };
  8722. #endif
  8723. #if HAS_KEYWORDS
  8724. smallint rword; /* RES_foo */
  8725. smallint last_rword; /* ditto */
  8726. #endif
  8727. debug_printf_exec("run_list start lvl %d\n", G.run_list_level);
  8728. debug_enter();
  8729. #if ENABLE_HUSH_LOOPS
  8730. /* Check syntax for "for" */
  8731. {
  8732. struct pipe *cpipe;
  8733. for (cpipe = pi; cpipe; cpipe = cpipe->next) {
  8734. if (cpipe->res_word != RES_FOR && cpipe->res_word != RES_IN)
  8735. continue;
  8736. /* current word is FOR or IN (BOLD in comments below) */
  8737. if (cpipe->next == NULL) {
  8738. syntax_error("malformed for");
  8739. debug_leave();
  8740. debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
  8741. return 1;
  8742. }
  8743. /* "FOR v; do ..." and "for v IN a b; do..." are ok */
  8744. if (cpipe->next->res_word == RES_DO)
  8745. continue;
  8746. /* next word is not "do". It must be "in" then ("FOR v in ...") */
  8747. if (cpipe->res_word == RES_IN /* "for v IN a b; not_do..."? */
  8748. || cpipe->next->res_word != RES_IN /* FOR v not_do_and_not_in..."? */
  8749. ) {
  8750. syntax_error("malformed for");
  8751. debug_leave();
  8752. debug_printf_exec("run_list lvl %d return 1\n", G.run_list_level);
  8753. return 1;
  8754. }
  8755. }
  8756. }
  8757. #endif
  8758. /* Past this point, all code paths should jump to ret: label
  8759. * in order to return, no direct "return" statements please.
  8760. * This helps to ensure that no memory is leaked. */
  8761. #if ENABLE_HUSH_JOB
  8762. G.run_list_level++;
  8763. #endif
  8764. #if HAS_KEYWORDS
  8765. rword = RES_NONE;
  8766. last_rword = RES_XXXX;
  8767. #endif
  8768. last_followup = PIPE_SEQ;
  8769. rcode = G.last_exitcode;
  8770. /* Go through list of pipes, (maybe) executing them. */
  8771. for (; pi; pi = IF_HUSH_LOOPS(rword == RES_DONE ? loop_top : ) pi->next) {
  8772. int r;
  8773. int sv_errexit_depth;
  8774. if (G.flag_SIGINT)
  8775. break;
  8776. if (G_flag_return_in_progress == 1)
  8777. break;
  8778. IF_HAS_KEYWORDS(rword = pi->res_word;)
  8779. debug_printf_exec(": rword=%d cond_code=%d last_rword=%d\n",
  8780. rword, cond_code, last_rword);
  8781. sv_errexit_depth = G.errexit_depth;
  8782. if (
  8783. #if ENABLE_HUSH_IF
  8784. rword == RES_IF || rword == RES_ELIF ||
  8785. #endif
  8786. pi->followup != PIPE_SEQ
  8787. ) {
  8788. G.errexit_depth++;
  8789. }
  8790. #if ENABLE_HUSH_LOOPS
  8791. if ((rword == RES_WHILE || rword == RES_UNTIL || rword == RES_FOR)
  8792. && loop_top == NULL /* avoid bumping G.depth_of_loop twice */
  8793. ) {
  8794. /* start of a loop: remember where loop starts */
  8795. loop_top = pi;
  8796. G.depth_of_loop++;
  8797. }
  8798. #endif
  8799. /* Still in the same "if...", "then..." or "do..." branch? */
  8800. if (IF_HAS_KEYWORDS(rword == last_rword &&) 1) {
  8801. if ((rcode == 0 && last_followup == PIPE_OR)
  8802. || (rcode != 0 && last_followup == PIPE_AND)
  8803. ) {
  8804. /* It is "<true> || CMD" or "<false> && CMD"
  8805. * and we should not execute CMD */
  8806. debug_printf_exec("skipped cmd because of || or &&\n");
  8807. last_followup = pi->followup;
  8808. goto dont_check_jobs_but_continue;
  8809. }
  8810. }
  8811. last_followup = pi->followup;
  8812. IF_HAS_KEYWORDS(last_rword = rword;)
  8813. #if ENABLE_HUSH_IF
  8814. if (cond_code) {
  8815. if (rword == RES_THEN) {
  8816. /* if false; then ... fi has exitcode 0! */
  8817. G.last_exitcode = rcode = EXIT_SUCCESS;
  8818. /* "if <false> THEN cmd": skip cmd */
  8819. continue;
  8820. }
  8821. } else {
  8822. if (rword == RES_ELSE || rword == RES_ELIF) {
  8823. /* "if <true> then ... ELSE/ELIF cmd":
  8824. * skip cmd and all following ones */
  8825. break;
  8826. }
  8827. }
  8828. #endif
  8829. #if ENABLE_HUSH_LOOPS
  8830. if (rword == RES_FOR) { /* && pi->num_cmds - always == 1 */
  8831. if (!for_lcur) {
  8832. /* first loop through for */
  8833. static const char encoded_dollar_at[] ALIGN1 = {
  8834. SPECIAL_VAR_SYMBOL, '@' | 0x80, SPECIAL_VAR_SYMBOL, '\0'
  8835. }; /* encoded representation of "$@" */
  8836. static const char *const encoded_dollar_at_argv[] = {
  8837. encoded_dollar_at, NULL
  8838. }; /* argv list with one element: "$@" */
  8839. char **vals;
  8840. G.last_exitcode = rcode = EXIT_SUCCESS;
  8841. vals = (char**)encoded_dollar_at_argv;
  8842. if (pi->next->res_word == RES_IN) {
  8843. /* if no variable values after "in" we skip "for" */
  8844. if (!pi->next->cmds[0].argv) {
  8845. debug_printf_exec(": null FOR: exitcode EXIT_SUCCESS\n");
  8846. break;
  8847. }
  8848. vals = pi->next->cmds[0].argv;
  8849. } /* else: "for var; do..." -> assume "$@" list */
  8850. /* create list of variable values */
  8851. debug_print_strings("for_list made from", vals);
  8852. for_list = expand_strvec_to_strvec(vals);
  8853. for_lcur = for_list;
  8854. debug_print_strings("for_list", for_list);
  8855. }
  8856. if (!*for_lcur) {
  8857. /* "for" loop is over, clean up */
  8858. free(for_list);
  8859. for_list = NULL;
  8860. for_lcur = NULL;
  8861. break;
  8862. }
  8863. /* Insert next value from for_lcur */
  8864. /* note: *for_lcur already has quotes removed, $var expanded, etc */
  8865. set_local_var(xasprintf("%s=%s", pi->cmds[0].argv[0], *for_lcur++), /*flag:*/ 0);
  8866. continue;
  8867. }
  8868. if (rword == RES_IN) {
  8869. continue; /* "for v IN list;..." - "in" has no cmds anyway */
  8870. }
  8871. if (rword == RES_DONE) {
  8872. continue; /* "done" has no cmds too */
  8873. }
  8874. #endif
  8875. #if ENABLE_HUSH_CASE
  8876. if (rword == RES_CASE) {
  8877. debug_printf_exec("CASE cond_code:%d\n", cond_code);
  8878. case_word = expand_string_to_string(pi->cmds->argv[0],
  8879. EXP_FLAG_ESC_GLOB_CHARS, /*unbackslash:*/ 1);
  8880. debug_printf_exec("CASE word1:'%s'\n", case_word);
  8881. //unbackslash(case_word);
  8882. //debug_printf_exec("CASE word2:'%s'\n", case_word);
  8883. continue;
  8884. }
  8885. if (rword == RES_MATCH) {
  8886. char **argv;
  8887. debug_printf_exec("MATCH cond_code:%d\n", cond_code);
  8888. if (!case_word) /* "case ... matched_word) ... WORD)": we executed selected branch, stop */
  8889. break;
  8890. /* all prev words didn't match, does this one match? */
  8891. argv = pi->cmds->argv;
  8892. while (*argv) {
  8893. char *pattern;
  8894. debug_printf_exec("expand_string_to_string('%s')\n", *argv);
  8895. pattern = expand_string_to_string(*argv,
  8896. EXP_FLAG_ESC_GLOB_CHARS,
  8897. /*unbackslash:*/ 0
  8898. );
  8899. /* TODO: which FNM_xxx flags to use? */
  8900. cond_code = (fnmatch(pattern, case_word, /*flags:*/ 0) != 0);
  8901. debug_printf_exec("fnmatch(pattern:'%s',str:'%s'):%d\n",
  8902. pattern, case_word, cond_code);
  8903. free(pattern);
  8904. if (cond_code == 0) {
  8905. /* match! we will execute this branch */
  8906. free(case_word);
  8907. case_word = NULL; /* make future "word)" stop */
  8908. break;
  8909. }
  8910. argv++;
  8911. }
  8912. continue;
  8913. }
  8914. if (rword == RES_CASE_BODY) { /* inside of a case branch */
  8915. debug_printf_exec("CASE_BODY cond_code:%d\n", cond_code);
  8916. if (cond_code != 0)
  8917. continue; /* not matched yet, skip this pipe */
  8918. }
  8919. if (rword == RES_ESAC) {
  8920. debug_printf_exec("ESAC cond_code:%d\n", cond_code);
  8921. if (case_word) {
  8922. /* "case" did not match anything: still set $? (to 0) */
  8923. G.last_exitcode = rcode = EXIT_SUCCESS;
  8924. }
  8925. }
  8926. #endif
  8927. /* Just pressing <enter> in shell should check for jobs.
  8928. * OTOH, in non-interactive shell this is useless
  8929. * and only leads to extra job checks */
  8930. if (pi->num_cmds == 0) {
  8931. if (G_interactive_fd)
  8932. goto check_jobs_and_continue;
  8933. continue;
  8934. }
  8935. /* After analyzing all keywords and conditions, we decided
  8936. * to execute this pipe. NB: have to do checkjobs(NULL)
  8937. * after run_pipe to collect any background children,
  8938. * even if list execution is to be stopped. */
  8939. debug_printf_exec(": run_pipe with %d members\n", pi->num_cmds);
  8940. #if ENABLE_HUSH_LOOPS
  8941. G.flag_break_continue = 0;
  8942. #endif
  8943. rcode = r = run_pipe(pi); /* NB: rcode is a smalluint, r is int */
  8944. if (r != -1) {
  8945. /* We ran a builtin, function, or group.
  8946. * rcode is already known
  8947. * and we don't need to wait for anything. */
  8948. debug_printf_exec(": builtin/func exitcode %d\n", rcode);
  8949. G.last_exitcode = rcode;
  8950. check_and_run_traps();
  8951. #if ENABLE_HUSH_LOOPS
  8952. /* Was it "break" or "continue"? */
  8953. if (G.flag_break_continue) {
  8954. smallint fbc = G.flag_break_continue;
  8955. /* We might fall into outer *loop*,
  8956. * don't want to break it too */
  8957. if (loop_top) {
  8958. G.depth_break_continue--;
  8959. if (G.depth_break_continue == 0)
  8960. G.flag_break_continue = 0;
  8961. /* else: e.g. "continue 2" should *break* once, *then* continue */
  8962. } /* else: "while... do... { we are here (innermost list is not a loop!) };...done" */
  8963. if (G.depth_break_continue != 0 || fbc == BC_BREAK) {
  8964. checkjobs(NULL, 0 /*(no pid to wait for)*/);
  8965. break;
  8966. }
  8967. /* "continue": simulate end of loop */
  8968. rword = RES_DONE;
  8969. continue;
  8970. }
  8971. #endif
  8972. if (G_flag_return_in_progress == 1) {
  8973. checkjobs(NULL, 0 /*(no pid to wait for)*/);
  8974. break;
  8975. }
  8976. } else if (pi->followup == PIPE_BG) {
  8977. /* What does bash do with attempts to background builtins? */
  8978. /* even bash 3.2 doesn't do that well with nested bg:
  8979. * try "{ { sleep 10; echo DEEP; } & echo HERE; } &".
  8980. * I'm NOT treating inner &'s as jobs */
  8981. #if ENABLE_HUSH_JOB
  8982. if (G.run_list_level == 1)
  8983. insert_job_into_table(pi);
  8984. #endif
  8985. /* Last command's pid goes to $! */
  8986. G.last_bg_pid = pi->cmds[pi->num_cmds - 1].pid;
  8987. G.last_bg_pid_exitcode = 0;
  8988. debug_printf_exec(": cmd&: exitcode EXIT_SUCCESS\n");
  8989. /* Check pi->pi_inverted? "! sleep 1 & echo $?": bash says 1. dash and ash say 0 */
  8990. rcode = EXIT_SUCCESS;
  8991. goto check_traps;
  8992. } else {
  8993. #if ENABLE_HUSH_JOB
  8994. if (G.run_list_level == 1 && G_interactive_fd) {
  8995. /* Waits for completion, then fg's main shell */
  8996. rcode = checkjobs_and_fg_shell(pi);
  8997. debug_printf_exec(": checkjobs_and_fg_shell exitcode %d\n", rcode);
  8998. goto check_traps;
  8999. }
  9000. #endif
  9001. /* This one just waits for completion */
  9002. rcode = checkjobs(pi, 0 /*(no pid to wait for)*/);
  9003. debug_printf_exec(": checkjobs exitcode %d\n", rcode);
  9004. check_traps:
  9005. G.last_exitcode = rcode;
  9006. check_and_run_traps();
  9007. }
  9008. /* Handle "set -e" */
  9009. if (rcode != 0 && G.o_opt[OPT_O_ERREXIT]) {
  9010. debug_printf_exec("ERREXIT:1 errexit_depth:%d\n", G.errexit_depth);
  9011. if (G.errexit_depth == 0)
  9012. hush_exit(rcode);
  9013. }
  9014. G.errexit_depth = sv_errexit_depth;
  9015. /* Analyze how result affects subsequent commands */
  9016. #if ENABLE_HUSH_IF
  9017. if (rword == RES_IF || rword == RES_ELIF)
  9018. cond_code = rcode;
  9019. #endif
  9020. check_jobs_and_continue:
  9021. checkjobs(NULL, 0 /*(no pid to wait for)*/);
  9022. dont_check_jobs_but_continue: ;
  9023. #if ENABLE_HUSH_LOOPS
  9024. /* Beware of "while false; true; do ..."! */
  9025. if (pi->next
  9026. && (pi->next->res_word == RES_DO || pi->next->res_word == RES_DONE)
  9027. /* check for RES_DONE is needed for "while ...; do \n done" case */
  9028. ) {
  9029. if (rword == RES_WHILE) {
  9030. if (rcode) {
  9031. /* "while false; do...done" - exitcode 0 */
  9032. G.last_exitcode = rcode = EXIT_SUCCESS;
  9033. debug_printf_exec(": while expr is false: breaking (exitcode:EXIT_SUCCESS)\n");
  9034. break;
  9035. }
  9036. }
  9037. if (rword == RES_UNTIL) {
  9038. if (!rcode) {
  9039. debug_printf_exec(": until expr is true: breaking\n");
  9040. break;
  9041. }
  9042. }
  9043. }
  9044. #endif
  9045. } /* for (pi) */
  9046. #if ENABLE_HUSH_JOB
  9047. G.run_list_level--;
  9048. #endif
  9049. #if ENABLE_HUSH_LOOPS
  9050. if (loop_top)
  9051. G.depth_of_loop--;
  9052. free(for_list);
  9053. #endif
  9054. #if ENABLE_HUSH_CASE
  9055. free(case_word);
  9056. #endif
  9057. debug_leave();
  9058. debug_printf_exec("run_list lvl %d return %d\n", G.run_list_level + 1, rcode);
  9059. return rcode;
  9060. }
  9061. /* Select which version we will use */
  9062. static int run_and_free_list(struct pipe *pi)
  9063. {
  9064. int rcode = 0;
  9065. debug_printf_exec("run_and_free_list entered\n");
  9066. if (!G.o_opt[OPT_O_NOEXEC]) {
  9067. debug_printf_exec(": run_list: 1st pipe with %d cmds\n", pi->num_cmds);
  9068. rcode = run_list(pi);
  9069. }
  9070. /* free_pipe_list has the side effect of clearing memory.
  9071. * In the long run that function can be merged with run_list,
  9072. * but doing that now would hobble the debugging effort. */
  9073. free_pipe_list(pi);
  9074. debug_printf_exec("run_and_free_list return %d\n", rcode);
  9075. return rcode;
  9076. }
  9077. static void install_sighandlers(unsigned mask)
  9078. {
  9079. sighandler_t old_handler;
  9080. unsigned sig = 0;
  9081. while ((mask >>= 1) != 0) {
  9082. sig++;
  9083. if (!(mask & 1))
  9084. continue;
  9085. old_handler = install_sighandler(sig, pick_sighandler(sig));
  9086. /* POSIX allows shell to re-enable SIGCHLD
  9087. * even if it was SIG_IGN on entry.
  9088. * Therefore we skip IGN check for it:
  9089. */
  9090. if (sig == SIGCHLD)
  9091. continue;
  9092. /* bash re-enables SIGHUP which is SIG_IGNed on entry.
  9093. * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
  9094. */
  9095. //if (sig == SIGHUP) continue; - TODO?
  9096. if (old_handler == SIG_IGN) {
  9097. /* oops... restore back to IGN, and record this fact */
  9098. install_sighandler(sig, old_handler);
  9099. #if ENABLE_HUSH_TRAP
  9100. if (!G_traps)
  9101. G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
  9102. free(G_traps[sig]);
  9103. G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
  9104. #endif
  9105. }
  9106. }
  9107. }
  9108. /* Called a few times only (or even once if "sh -c") */
  9109. static void install_special_sighandlers(void)
  9110. {
  9111. unsigned mask;
  9112. /* Which signals are shell-special? */
  9113. mask = (1 << SIGQUIT) | (1 << SIGCHLD);
  9114. if (G_interactive_fd) {
  9115. mask |= SPECIAL_INTERACTIVE_SIGS;
  9116. if (G_saved_tty_pgrp) /* we have ctty, job control sigs work */
  9117. mask |= SPECIAL_JOBSTOP_SIGS;
  9118. }
  9119. /* Careful, do not re-install handlers we already installed */
  9120. if (G.special_sig_mask != mask) {
  9121. unsigned diff = mask & ~G.special_sig_mask;
  9122. G.special_sig_mask = mask;
  9123. install_sighandlers(diff);
  9124. }
  9125. }
  9126. #if ENABLE_HUSH_JOB
  9127. /* helper */
  9128. /* Set handlers to restore tty pgrp and exit */
  9129. static void install_fatal_sighandlers(void)
  9130. {
  9131. unsigned mask;
  9132. /* We will restore tty pgrp on these signals */
  9133. mask = 0
  9134. /*+ (1 << SIGILL ) * HUSH_DEBUG*/
  9135. /*+ (1 << SIGFPE ) * HUSH_DEBUG*/
  9136. + (1 << SIGBUS ) * HUSH_DEBUG
  9137. + (1 << SIGSEGV) * HUSH_DEBUG
  9138. /*+ (1 << SIGTRAP) * HUSH_DEBUG*/
  9139. + (1 << SIGABRT)
  9140. /* bash 3.2 seems to handle these just like 'fatal' ones */
  9141. + (1 << SIGPIPE)
  9142. + (1 << SIGALRM)
  9143. /* if we are interactive, SIGHUP, SIGTERM and SIGINT are special sigs.
  9144. * if we aren't interactive... but in this case
  9145. * we never want to restore pgrp on exit, and this fn is not called
  9146. */
  9147. /*+ (1 << SIGHUP )*/
  9148. /*+ (1 << SIGTERM)*/
  9149. /*+ (1 << SIGINT )*/
  9150. ;
  9151. G_fatal_sig_mask = mask;
  9152. install_sighandlers(mask);
  9153. }
  9154. #endif
  9155. static int set_mode(int state, char mode, const char *o_opt)
  9156. {
  9157. int idx;
  9158. switch (mode) {
  9159. case 'n':
  9160. G.o_opt[OPT_O_NOEXEC] = state;
  9161. break;
  9162. case 'x':
  9163. IF_HUSH_MODE_X(G_x_mode = state;)
  9164. IF_HUSH_MODE_X(if (G.x_mode_fd <= 0) G.x_mode_fd = dup_CLOEXEC(2, 10);)
  9165. break;
  9166. case 'o':
  9167. if (!o_opt) {
  9168. /* "set -+o" without parameter.
  9169. * in bash, set -o produces this output:
  9170. * pipefail off
  9171. * and set +o:
  9172. * set +o pipefail
  9173. * We always use the second form.
  9174. */
  9175. const char *p = o_opt_strings;
  9176. idx = 0;
  9177. while (*p) {
  9178. printf("set %co %s\n", (G.o_opt[idx] ? '-' : '+'), p);
  9179. idx++;
  9180. p += strlen(p) + 1;
  9181. }
  9182. break;
  9183. }
  9184. idx = index_in_strings(o_opt_strings, o_opt);
  9185. if (idx >= 0) {
  9186. G.o_opt[idx] = state;
  9187. break;
  9188. }
  9189. case 'e':
  9190. G.o_opt[OPT_O_ERREXIT] = state;
  9191. break;
  9192. default:
  9193. return EXIT_FAILURE;
  9194. }
  9195. return EXIT_SUCCESS;
  9196. }
  9197. int hush_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  9198. int hush_main(int argc, char **argv)
  9199. {
  9200. enum {
  9201. OPT_login = (1 << 0),
  9202. };
  9203. unsigned flags;
  9204. unsigned builtin_argc;
  9205. char **e;
  9206. struct variable *cur_var;
  9207. struct variable *shell_ver;
  9208. INIT_G();
  9209. if (EXIT_SUCCESS != 0) /* if EXIT_SUCCESS == 0, it is already done */
  9210. G.last_exitcode = EXIT_SUCCESS;
  9211. #if ENABLE_HUSH_FAST
  9212. G.count_SIGCHLD++; /* ensure it is != G.handled_SIGCHLD */
  9213. #endif
  9214. #if !BB_MMU
  9215. G.argv0_for_re_execing = argv[0];
  9216. #endif
  9217. /* Deal with HUSH_VERSION */
  9218. debug_printf_env("unsetenv '%s'\n", "HUSH_VERSION");
  9219. unsetenv("HUSH_VERSION"); /* in case it exists in initial env */
  9220. shell_ver = xzalloc(sizeof(*shell_ver));
  9221. shell_ver->flg_export = 1;
  9222. shell_ver->flg_read_only = 1;
  9223. /* Code which handles ${var<op>...} needs writable values for all variables,
  9224. * therefore we xstrdup: */
  9225. shell_ver->varstr = xstrdup(hush_version_str);
  9226. /* Create shell local variables from the values
  9227. * currently living in the environment */
  9228. G.top_var = shell_ver;
  9229. cur_var = G.top_var;
  9230. e = environ;
  9231. if (e) while (*e) {
  9232. char *value = strchr(*e, '=');
  9233. if (value) { /* paranoia */
  9234. cur_var->next = xzalloc(sizeof(*cur_var));
  9235. cur_var = cur_var->next;
  9236. cur_var->varstr = *e;
  9237. cur_var->max_len = strlen(*e);
  9238. cur_var->flg_export = 1;
  9239. }
  9240. e++;
  9241. }
  9242. /* (Re)insert HUSH_VERSION into env (AFTER we scanned the env!) */
  9243. debug_printf_env("putenv '%s'\n", shell_ver->varstr);
  9244. putenv(shell_ver->varstr);
  9245. /* Export PWD */
  9246. set_pwd_var(SETFLAG_EXPORT);
  9247. #if BASH_HOSTNAME_VAR
  9248. /* Set (but not export) HOSTNAME unless already set */
  9249. if (!get_local_var_value("HOSTNAME")) {
  9250. struct utsname uts;
  9251. uname(&uts);
  9252. set_local_var_from_halves("HOSTNAME", uts.nodename);
  9253. }
  9254. #endif
  9255. /* IFS is not inherited from the parent environment */
  9256. set_local_var_from_halves("IFS", defifs);
  9257. if (!get_local_var_value("PATH"))
  9258. set_local_var_from_halves("PATH", bb_default_root_path);
  9259. /* PS1/PS2 are set later, if we determine that we are interactive */
  9260. /* bash also exports SHLVL and _,
  9261. * and sets (but doesn't export) the following variables:
  9262. * BASH=/bin/bash
  9263. * BASH_VERSINFO=([0]="3" [1]="2" [2]="0" [3]="1" [4]="release" [5]="i386-pc-linux-gnu")
  9264. * BASH_VERSION='3.2.0(1)-release'
  9265. * HOSTTYPE=i386
  9266. * MACHTYPE=i386-pc-linux-gnu
  9267. * OSTYPE=linux-gnu
  9268. * PPID=<NNNNN> - we also do it elsewhere
  9269. * EUID=<NNNNN>
  9270. * UID=<NNNNN>
  9271. * GROUPS=()
  9272. * LINES=<NNN>
  9273. * COLUMNS=<NNN>
  9274. * BASH_ARGC=()
  9275. * BASH_ARGV=()
  9276. * BASH_LINENO=()
  9277. * BASH_SOURCE=()
  9278. * DIRSTACK=()
  9279. * PIPESTATUS=([0]="0")
  9280. * HISTFILE=/<xxx>/.bash_history
  9281. * HISTFILESIZE=500
  9282. * HISTSIZE=500
  9283. * MAILCHECK=60
  9284. * PATH=/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:.
  9285. * SHELL=/bin/bash
  9286. * SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
  9287. * TERM=dumb
  9288. * OPTERR=1
  9289. * OPTIND=1
  9290. * PS4='+ '
  9291. */
  9292. /* Initialize some more globals to non-zero values */
  9293. die_func = restore_ttypgrp_and__exit;
  9294. /* Shell is non-interactive at first. We need to call
  9295. * install_special_sighandlers() if we are going to execute "sh <script>",
  9296. * "sh -c <cmds>" or login shell's /etc/profile and friends.
  9297. * If we later decide that we are interactive, we run install_special_sighandlers()
  9298. * in order to intercept (more) signals.
  9299. */
  9300. /* Parse options */
  9301. /* http://www.opengroup.org/onlinepubs/9699919799/utilities/sh.html */
  9302. flags = (argv[0] && argv[0][0] == '-') ? OPT_login : 0;
  9303. builtin_argc = 0;
  9304. #if NUM_SCRIPTS > 0
  9305. if (argc < 0) {
  9306. optarg = get_script_content(-argc - 1);
  9307. optind = 0;
  9308. argc = string_array_len(argv);
  9309. goto run_script;
  9310. }
  9311. #endif
  9312. while (1) {
  9313. int opt = getopt(argc, argv, "+c:exinsl"
  9314. #if !BB_MMU
  9315. "<:$:R:V:"
  9316. # if ENABLE_HUSH_FUNCTIONS
  9317. "F:"
  9318. # endif
  9319. #endif
  9320. );
  9321. if (opt <= 0)
  9322. break;
  9323. switch (opt) {
  9324. case 'c':
  9325. /* Possibilities:
  9326. * sh ... -c 'script'
  9327. * sh ... -c 'script' ARG0 [ARG1...]
  9328. * On NOMMU, if builtin_argc != 0,
  9329. * sh ... -c 'builtin' BARGV... "" ARG0 [ARG1...]
  9330. * "" needs to be replaced with NULL
  9331. * and BARGV vector fed to builtin function.
  9332. * Note: the form without ARG0 never happens:
  9333. * sh ... -c 'builtin' BARGV... ""
  9334. */
  9335. #if NUM_SCRIPTS > 0
  9336. run_script:
  9337. #endif
  9338. if (!G.root_pid) {
  9339. G.root_pid = getpid();
  9340. G.root_ppid = getppid();
  9341. }
  9342. G.global_argv = argv + optind;
  9343. G.global_argc = argc - optind;
  9344. if (builtin_argc) {
  9345. /* -c 'builtin' [BARGV...] "" ARG0 [ARG1...] */
  9346. const struct built_in_command *x;
  9347. install_special_sighandlers();
  9348. x = find_builtin(optarg);
  9349. if (x) { /* paranoia */
  9350. G.global_argc -= builtin_argc; /* skip [BARGV...] "" */
  9351. G.global_argv += builtin_argc;
  9352. G.global_argv[-1] = NULL; /* replace "" */
  9353. fflush_all();
  9354. G.last_exitcode = x->b_function(argv + optind - 1);
  9355. }
  9356. goto final_return;
  9357. }
  9358. G.opt_c = 1;
  9359. if (!G.global_argv[0]) {
  9360. /* -c 'script' (no params): prevent empty $0 */
  9361. G.global_argv--; /* points to argv[i] of 'script' */
  9362. G.global_argv[0] = argv[0];
  9363. G.global_argc++;
  9364. } /* else -c 'script' ARG0 [ARG1...]: $0 is ARG0 */
  9365. install_special_sighandlers();
  9366. parse_and_run_string(optarg);
  9367. goto final_return;
  9368. case 'i':
  9369. /* Well, we cannot just declare interactiveness,
  9370. * we have to have some stuff (ctty, etc) */
  9371. /* G_interactive_fd++; */
  9372. break;
  9373. case 's':
  9374. G.opt_s = 1;
  9375. break;
  9376. case 'l':
  9377. flags |= OPT_login;
  9378. break;
  9379. #if !BB_MMU
  9380. case '<': /* "big heredoc" support */
  9381. full_write1_str(optarg);
  9382. _exit(0);
  9383. case '$': {
  9384. unsigned long long empty_trap_mask;
  9385. G.root_pid = bb_strtou(optarg, &optarg, 16);
  9386. optarg++;
  9387. G.root_ppid = bb_strtou(optarg, &optarg, 16);
  9388. optarg++;
  9389. G.last_bg_pid = bb_strtou(optarg, &optarg, 16);
  9390. optarg++;
  9391. G.last_exitcode = bb_strtou(optarg, &optarg, 16);
  9392. optarg++;
  9393. builtin_argc = bb_strtou(optarg, &optarg, 16);
  9394. optarg++;
  9395. empty_trap_mask = bb_strtoull(optarg, &optarg, 16);
  9396. if (empty_trap_mask != 0) {
  9397. IF_HUSH_TRAP(int sig;)
  9398. install_special_sighandlers();
  9399. # if ENABLE_HUSH_TRAP
  9400. G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
  9401. for (sig = 1; sig < NSIG; sig++) {
  9402. if (empty_trap_mask & (1LL << sig)) {
  9403. G_traps[sig] = xzalloc(1); /* == xstrdup(""); */
  9404. install_sighandler(sig, SIG_IGN);
  9405. }
  9406. }
  9407. # endif
  9408. }
  9409. # if ENABLE_HUSH_LOOPS
  9410. optarg++;
  9411. G.depth_of_loop = bb_strtou(optarg, &optarg, 16);
  9412. # endif
  9413. # if ENABLE_HUSH_FUNCTIONS
  9414. /* nommu uses re-exec trick for "... | func | ...",
  9415. * should allow "return".
  9416. * This accidentally allows returns in subshells.
  9417. */
  9418. G_flag_return_in_progress = -1;
  9419. # endif
  9420. break;
  9421. }
  9422. case 'R':
  9423. case 'V':
  9424. set_local_var(xstrdup(optarg), opt == 'R' ? SETFLAG_MAKE_RO : 0);
  9425. break;
  9426. # if ENABLE_HUSH_FUNCTIONS
  9427. case 'F': {
  9428. struct function *funcp = new_function(optarg);
  9429. /* funcp->name is already set to optarg */
  9430. /* funcp->body is set to NULL. It's a special case. */
  9431. funcp->body_as_string = argv[optind];
  9432. optind++;
  9433. break;
  9434. }
  9435. # endif
  9436. #endif
  9437. case 'n':
  9438. case 'x':
  9439. case 'e':
  9440. if (set_mode(1, opt, NULL) == 0) /* no error */
  9441. break;
  9442. default:
  9443. #ifndef BB_VER
  9444. fprintf(stderr, "Usage: sh [FILE]...\n"
  9445. " or: sh -c command [args]...\n\n");
  9446. exit(EXIT_FAILURE);
  9447. #else
  9448. bb_show_usage();
  9449. #endif
  9450. }
  9451. } /* option parsing loop */
  9452. /* Skip options. Try "hush -l": $1 should not be "-l"! */
  9453. G.global_argc = argc - (optind - 1);
  9454. G.global_argv = argv + (optind - 1);
  9455. G.global_argv[0] = argv[0];
  9456. if (!G.root_pid) {
  9457. G.root_pid = getpid();
  9458. G.root_ppid = getppid();
  9459. }
  9460. /* If we are login shell... */
  9461. if (flags & OPT_login) {
  9462. HFILE *input;
  9463. debug_printf("sourcing /etc/profile\n");
  9464. input = hfopen("/etc/profile");
  9465. if (input != NULL) {
  9466. install_special_sighandlers();
  9467. parse_and_run_file(input);
  9468. hfclose(input);
  9469. }
  9470. /* bash: after sourcing /etc/profile,
  9471. * tries to source (in the given order):
  9472. * ~/.bash_profile, ~/.bash_login, ~/.profile,
  9473. * stopping on first found. --noprofile turns this off.
  9474. * bash also sources ~/.bash_logout on exit.
  9475. * If called as sh, skips .bash_XXX files.
  9476. */
  9477. }
  9478. /* -s is: hush -s ARGV1 ARGV2 (no SCRIPT) */
  9479. if (!G.opt_s && G.global_argv[1]) {
  9480. HFILE *input;
  9481. /*
  9482. * "bash <script>" (which is never interactive (unless -i?))
  9483. * sources $BASH_ENV here (without scanning $PATH).
  9484. * If called as sh, does the same but with $ENV.
  9485. * Also NB, per POSIX, $ENV should undergo parameter expansion.
  9486. */
  9487. G.global_argc--;
  9488. G.global_argv++;
  9489. debug_printf("running script '%s'\n", G.global_argv[0]);
  9490. xfunc_error_retval = 127; /* for "hush /does/not/exist" case */
  9491. input = hfopen(G.global_argv[0]);
  9492. if (!input) {
  9493. bb_simple_perror_msg_and_die(G.global_argv[0]);
  9494. }
  9495. xfunc_error_retval = 1;
  9496. install_special_sighandlers();
  9497. parse_and_run_file(input);
  9498. #if ENABLE_FEATURE_CLEAN_UP
  9499. hfclose(input);
  9500. #endif
  9501. goto final_return;
  9502. }
  9503. /* "implicit" -s: bare interactive hush shows 's' in $- */
  9504. G.opt_s = 1;
  9505. /* Up to here, shell was non-interactive. Now it may become one.
  9506. * NB: don't forget to (re)run install_special_sighandlers() as needed.
  9507. */
  9508. /* A shell is interactive if the '-i' flag was given,
  9509. * or if all of the following conditions are met:
  9510. * no -c command
  9511. * no arguments remaining or the -s flag given
  9512. * standard input is a terminal
  9513. * standard output is a terminal
  9514. * Refer to Posix.2, the description of the 'sh' utility.
  9515. */
  9516. #if ENABLE_HUSH_JOB
  9517. if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
  9518. G_saved_tty_pgrp = tcgetpgrp(STDIN_FILENO);
  9519. debug_printf("saved_tty_pgrp:%d\n", G_saved_tty_pgrp);
  9520. if (G_saved_tty_pgrp < 0)
  9521. G_saved_tty_pgrp = 0;
  9522. /* try to dup stdin to high fd#, >= 255 */
  9523. G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, 254);
  9524. if (G_interactive_fd < 0) {
  9525. /* try to dup to any fd */
  9526. G_interactive_fd = dup(STDIN_FILENO);
  9527. if (G_interactive_fd < 0) {
  9528. /* give up */
  9529. G_interactive_fd = 0;
  9530. G_saved_tty_pgrp = 0;
  9531. }
  9532. }
  9533. // TODO: track & disallow any attempts of user
  9534. // to (inadvertently) close/redirect G_interactive_fd
  9535. }
  9536. debug_printf("interactive_fd:%d\n", G_interactive_fd);
  9537. if (G_interactive_fd) {
  9538. close_on_exec_on(G_interactive_fd);
  9539. if (G_saved_tty_pgrp) {
  9540. /* If we were run as 'hush &', sleep until we are
  9541. * in the foreground (tty pgrp == our pgrp).
  9542. * If we get started under a job aware app (like bash),
  9543. * make sure we are now in charge so we don't fight over
  9544. * who gets the foreground */
  9545. while (1) {
  9546. pid_t shell_pgrp = getpgrp();
  9547. G_saved_tty_pgrp = tcgetpgrp(G_interactive_fd);
  9548. if (G_saved_tty_pgrp == shell_pgrp)
  9549. break;
  9550. /* send TTIN to ourself (should stop us) */
  9551. kill(- shell_pgrp, SIGTTIN);
  9552. }
  9553. }
  9554. /* Install more signal handlers */
  9555. install_special_sighandlers();
  9556. if (G_saved_tty_pgrp) {
  9557. /* Set other signals to restore saved_tty_pgrp */
  9558. install_fatal_sighandlers();
  9559. /* Put ourselves in our own process group
  9560. * (bash, too, does this only if ctty is available) */
  9561. bb_setpgrp(); /* is the same as setpgid(our_pid, our_pid); */
  9562. /* Grab control of the terminal */
  9563. tcsetpgrp(G_interactive_fd, getpid());
  9564. }
  9565. enable_restore_tty_pgrp_on_exit();
  9566. # if ENABLE_FEATURE_EDITING
  9567. G.line_input_state = new_line_input_t(FOR_SHELL);
  9568. # endif
  9569. # if ENABLE_HUSH_SAVEHISTORY && MAX_HISTORY > 0
  9570. {
  9571. const char *hp = get_local_var_value("HISTFILE");
  9572. if (!hp) {
  9573. hp = get_local_var_value("HOME");
  9574. if (hp)
  9575. hp = concat_path_file(hp, ".hush_history");
  9576. } else {
  9577. hp = xstrdup(hp);
  9578. }
  9579. if (hp) {
  9580. G.line_input_state->hist_file = hp;
  9581. //set_local_var(xasprintf("HISTFILE=%s", ...));
  9582. }
  9583. # if ENABLE_FEATURE_SH_HISTFILESIZE
  9584. hp = get_local_var_value("HISTFILESIZE");
  9585. G.line_input_state->max_history = size_from_HISTFILESIZE(hp);
  9586. # endif
  9587. }
  9588. # endif
  9589. } else {
  9590. install_special_sighandlers();
  9591. }
  9592. #elif ENABLE_HUSH_INTERACTIVE
  9593. /* No job control compiled in, only prompt/line editing */
  9594. if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
  9595. G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, 254);
  9596. if (G_interactive_fd < 0) {
  9597. /* try to dup to any fd */
  9598. G_interactive_fd = dup_CLOEXEC(STDIN_FILENO, -1);
  9599. if (G_interactive_fd < 0)
  9600. /* give up */
  9601. G_interactive_fd = 0;
  9602. }
  9603. }
  9604. if (G_interactive_fd) {
  9605. close_on_exec_on(G_interactive_fd);
  9606. }
  9607. install_special_sighandlers();
  9608. #else
  9609. /* We have interactiveness code disabled */
  9610. install_special_sighandlers();
  9611. #endif
  9612. /* bash:
  9613. * if interactive but not a login shell, sources ~/.bashrc
  9614. * (--norc turns this off, --rcfile <file> overrides)
  9615. */
  9616. if (G_interactive_fd) {
  9617. #if ENABLE_HUSH_INTERACTIVE && ENABLE_FEATURE_EDITING_FANCY_PROMPT
  9618. /* Set (but not export) PS1/2 unless already set */
  9619. if (!get_local_var_value("PS1"))
  9620. set_local_var_from_halves("PS1", "\\w \\$ ");
  9621. if (!get_local_var_value("PS2"))
  9622. set_local_var_from_halves("PS2", "> ");
  9623. #endif
  9624. if (!ENABLE_FEATURE_SH_EXTRA_QUIET) {
  9625. /* note: ash and hush share this string */
  9626. printf("\n\n%s %s\n"
  9627. IF_HUSH_HELP("Enter 'help' for a list of built-in commands.\n")
  9628. "\n",
  9629. bb_banner,
  9630. "hush - the humble shell"
  9631. );
  9632. }
  9633. }
  9634. parse_and_run_file(hfopen(NULL)); /* stdin */
  9635. final_return:
  9636. hush_exit(G.last_exitcode);
  9637. }
  9638. /*
  9639. * Built-ins
  9640. */
  9641. static int FAST_FUNC builtin_true(char **argv UNUSED_PARAM)
  9642. {
  9643. return 0;
  9644. }
  9645. #if ENABLE_HUSH_TEST || ENABLE_HUSH_ECHO || ENABLE_HUSH_PRINTF || ENABLE_HUSH_KILL
  9646. static int run_applet_main(char **argv, int (*applet_main_func)(int argc, char **argv))
  9647. {
  9648. int argc = string_array_len(argv);
  9649. return applet_main_func(argc, argv);
  9650. }
  9651. #endif
  9652. #if ENABLE_HUSH_TEST || BASH_TEST2
  9653. static int FAST_FUNC builtin_test(char **argv)
  9654. {
  9655. return run_applet_main(argv, test_main);
  9656. }
  9657. #endif
  9658. #if ENABLE_HUSH_ECHO
  9659. static int FAST_FUNC builtin_echo(char **argv)
  9660. {
  9661. return run_applet_main(argv, echo_main);
  9662. }
  9663. #endif
  9664. #if ENABLE_HUSH_PRINTF
  9665. static int FAST_FUNC builtin_printf(char **argv)
  9666. {
  9667. return run_applet_main(argv, printf_main);
  9668. }
  9669. #endif
  9670. #if ENABLE_HUSH_HELP
  9671. static int FAST_FUNC builtin_help(char **argv UNUSED_PARAM)
  9672. {
  9673. const struct built_in_command *x;
  9674. printf(
  9675. "Built-in commands:\n"
  9676. "------------------\n");
  9677. for (x = bltins1; x != &bltins1[ARRAY_SIZE(bltins1)]; x++) {
  9678. if (x->b_descr)
  9679. printf("%-10s%s\n", x->b_cmd, x->b_descr);
  9680. }
  9681. return EXIT_SUCCESS;
  9682. }
  9683. #endif
  9684. #if MAX_HISTORY && ENABLE_FEATURE_EDITING
  9685. static int FAST_FUNC builtin_history(char **argv UNUSED_PARAM)
  9686. {
  9687. if (G.line_input_state)
  9688. show_history(G.line_input_state);
  9689. return EXIT_SUCCESS;
  9690. }
  9691. #endif
  9692. static char **skip_dash_dash(char **argv)
  9693. {
  9694. argv++;
  9695. if (argv[0] && argv[0][0] == '-' && argv[0][1] == '-' && argv[0][2] == '\0')
  9696. argv++;
  9697. return argv;
  9698. }
  9699. static int FAST_FUNC builtin_cd(char **argv)
  9700. {
  9701. const char *newdir;
  9702. argv = skip_dash_dash(argv);
  9703. newdir = argv[0];
  9704. if (newdir == NULL) {
  9705. /* bash does nothing (exitcode 0) if HOME is ""; if it's unset,
  9706. * bash says "bash: cd: HOME not set" and does nothing
  9707. * (exitcode 1)
  9708. */
  9709. const char *home = get_local_var_value("HOME");
  9710. newdir = home ? home : "/";
  9711. }
  9712. if (chdir(newdir)) {
  9713. /* Mimic bash message exactly */
  9714. bb_perror_msg("cd: %s", newdir);
  9715. return EXIT_FAILURE;
  9716. }
  9717. /* Read current dir (get_cwd(1) is inside) and set PWD.
  9718. * Note: do not enforce exporting. If PWD was unset or unexported,
  9719. * set it again, but do not export. bash does the same.
  9720. */
  9721. set_pwd_var(/*flag:*/ 0);
  9722. return EXIT_SUCCESS;
  9723. }
  9724. static int FAST_FUNC builtin_pwd(char **argv UNUSED_PARAM)
  9725. {
  9726. puts(get_cwd(0));
  9727. return EXIT_SUCCESS;
  9728. }
  9729. static int FAST_FUNC builtin_eval(char **argv)
  9730. {
  9731. argv = skip_dash_dash(argv);
  9732. if (!argv[0])
  9733. return EXIT_SUCCESS;
  9734. IF_HUSH_MODE_X(G.x_mode_depth++;)
  9735. //bb_error_msg("%s: ++x_mode_depth=%d", __func__, G.x_mode_depth);
  9736. if (!argv[1]) {
  9737. /* bash:
  9738. * eval "echo Hi; done" ("done" is syntax error):
  9739. * "echo Hi" will not execute too.
  9740. */
  9741. parse_and_run_string(argv[0]);
  9742. } else {
  9743. /* "The eval utility shall construct a command by
  9744. * concatenating arguments together, separating
  9745. * each with a <space> character."
  9746. */
  9747. char *str, *p;
  9748. unsigned len = 0;
  9749. char **pp = argv;
  9750. do
  9751. len += strlen(*pp) + 1;
  9752. while (*++pp);
  9753. str = p = xmalloc(len);
  9754. pp = argv;
  9755. for (;;) {
  9756. p = stpcpy(p, *pp);
  9757. pp++;
  9758. if (!*pp)
  9759. break;
  9760. *p++ = ' ';
  9761. }
  9762. parse_and_run_string(str);
  9763. free(str);
  9764. }
  9765. IF_HUSH_MODE_X(G.x_mode_depth--;)
  9766. //bb_error_msg("%s: --x_mode_depth=%d", __func__, G.x_mode_depth);
  9767. return G.last_exitcode;
  9768. }
  9769. static int FAST_FUNC builtin_exec(char **argv)
  9770. {
  9771. argv = skip_dash_dash(argv);
  9772. if (argv[0] == NULL)
  9773. return EXIT_SUCCESS; /* bash does this */
  9774. /* Careful: we can end up here after [v]fork. Do not restore
  9775. * tty pgrp then, only top-level shell process does that */
  9776. if (G_saved_tty_pgrp && getpid() == G.root_pid)
  9777. tcsetpgrp(G_interactive_fd, G_saved_tty_pgrp);
  9778. /* Saved-redirect fds, script fds and G_interactive_fd are still
  9779. * open here. However, they are all CLOEXEC, and execv below
  9780. * closes them. Try interactive "exec ls -l /proc/self/fd",
  9781. * it should show no extra open fds in the "ls" process.
  9782. * If we'd try to run builtins/NOEXECs, this would need improving.
  9783. */
  9784. //close_saved_fds_and_FILE_fds();
  9785. /* TODO: if exec fails, bash does NOT exit! We do.
  9786. * We'll need to undo trap cleanup (it's inside execvp_or_die)
  9787. * and tcsetpgrp, and this is inherently racy.
  9788. */
  9789. execvp_or_die(argv);
  9790. }
  9791. static int FAST_FUNC builtin_exit(char **argv)
  9792. {
  9793. debug_printf_exec("%s()\n", __func__);
  9794. /* interactive bash:
  9795. * # trap "echo EEE" EXIT
  9796. * # exit
  9797. * exit
  9798. * There are stopped jobs.
  9799. * (if there are _stopped_ jobs, running ones don't count)
  9800. * # exit
  9801. * exit
  9802. * EEE (then bash exits)
  9803. *
  9804. * TODO: we can use G.exiting = -1 as indicator "last cmd was exit"
  9805. */
  9806. /* note: EXIT trap is run by hush_exit */
  9807. argv = skip_dash_dash(argv);
  9808. if (argv[0] == NULL)
  9809. hush_exit(G.last_exitcode);
  9810. /* mimic bash: exit 123abc == exit 255 + error msg */
  9811. xfunc_error_retval = 255;
  9812. /* bash: exit -2 == exit 254, no error msg */
  9813. hush_exit(xatoi(argv[0]) & 0xff);
  9814. }
  9815. #if ENABLE_HUSH_TYPE
  9816. /* http://www.opengroup.org/onlinepubs/9699919799/utilities/type.html */
  9817. static int FAST_FUNC builtin_type(char **argv)
  9818. {
  9819. int ret = EXIT_SUCCESS;
  9820. while (*++argv) {
  9821. const char *type;
  9822. char *path = NULL;
  9823. if (0) {} /* make conditional compile easier below */
  9824. /*else if (find_alias(*argv))
  9825. type = "an alias";*/
  9826. #if ENABLE_HUSH_FUNCTIONS
  9827. else if (find_function(*argv))
  9828. type = "a function";
  9829. #endif
  9830. else if (find_builtin(*argv))
  9831. type = "a shell builtin";
  9832. else if ((path = find_in_path(*argv)) != NULL)
  9833. type = path;
  9834. else {
  9835. bb_error_msg("type: %s: not found", *argv);
  9836. ret = EXIT_FAILURE;
  9837. continue;
  9838. }
  9839. printf("%s is %s\n", *argv, type);
  9840. free(path);
  9841. }
  9842. return ret;
  9843. }
  9844. #endif
  9845. #if ENABLE_HUSH_READ
  9846. /* Interruptibility of read builtin in bash
  9847. * (tested on bash-4.2.8 by sending signals (not by ^C)):
  9848. *
  9849. * Empty trap makes read ignore corresponding signal, for any signal.
  9850. *
  9851. * SIGINT:
  9852. * - terminates non-interactive shell;
  9853. * - interrupts read in interactive shell;
  9854. * if it has non-empty trap:
  9855. * - executes trap and returns to command prompt in interactive shell;
  9856. * - executes trap and returns to read in non-interactive shell;
  9857. * SIGTERM:
  9858. * - is ignored (does not interrupt) read in interactive shell;
  9859. * - terminates non-interactive shell;
  9860. * if it has non-empty trap:
  9861. * - executes trap and returns to read;
  9862. * SIGHUP:
  9863. * - terminates shell (regardless of interactivity);
  9864. * if it has non-empty trap:
  9865. * - executes trap and returns to read;
  9866. * SIGCHLD from children:
  9867. * - does not interrupt read regardless of interactivity:
  9868. * try: sleep 1 & read x; echo $x
  9869. */
  9870. static int FAST_FUNC builtin_read(char **argv)
  9871. {
  9872. const char *r;
  9873. struct builtin_read_params params;
  9874. memset(&params, 0, sizeof(params));
  9875. /* "!": do not abort on errors.
  9876. * Option string must start with "sr" to match BUILTIN_READ_xxx
  9877. */
  9878. params.read_flags = getopt32(argv,
  9879. #if BASH_READ_D
  9880. "!srn:p:t:u:d:", &params.opt_n, &params.opt_p, &params.opt_t, &params.opt_u, &params.opt_d
  9881. #else
  9882. "!srn:p:t:u:", &params.opt_n, &params.opt_p, &params.opt_t, &params.opt_u
  9883. #endif
  9884. );
  9885. if ((uint32_t)params.read_flags == (uint32_t)-1)
  9886. return EXIT_FAILURE;
  9887. argv += optind;
  9888. params.argv = argv;
  9889. params.setvar = set_local_var_from_halves;
  9890. params.ifs = get_local_var_value("IFS"); /* can be NULL */
  9891. again:
  9892. r = shell_builtin_read(&params);
  9893. if ((uintptr_t)r == 1 && errno == EINTR) {
  9894. unsigned sig = check_and_run_traps();
  9895. if (sig != SIGINT)
  9896. goto again;
  9897. }
  9898. if ((uintptr_t)r > 1) {
  9899. bb_error_msg("%s", r);
  9900. r = (char*)(uintptr_t)1;
  9901. }
  9902. return (uintptr_t)r;
  9903. }
  9904. #endif
  9905. #if ENABLE_HUSH_UMASK
  9906. static int FAST_FUNC builtin_umask(char **argv)
  9907. {
  9908. int rc;
  9909. mode_t mask;
  9910. rc = 1;
  9911. mask = umask(0);
  9912. argv = skip_dash_dash(argv);
  9913. if (argv[0]) {
  9914. mode_t old_mask = mask;
  9915. /* numeric umasks are taken as-is */
  9916. /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
  9917. if (!isdigit(argv[0][0]))
  9918. mask ^= 0777;
  9919. mask = bb_parse_mode(argv[0], mask);
  9920. if (!isdigit(argv[0][0]))
  9921. mask ^= 0777;
  9922. if ((unsigned)mask > 0777) {
  9923. mask = old_mask;
  9924. /* bash messages:
  9925. * bash: umask: 'q': invalid symbolic mode operator
  9926. * bash: umask: 999: octal number out of range
  9927. */
  9928. bb_error_msg("%s: invalid mode '%s'", "umask", argv[0]);
  9929. rc = 0;
  9930. }
  9931. } else {
  9932. /* Mimic bash */
  9933. printf("%04o\n", (unsigned) mask);
  9934. /* fall through and restore mask which we set to 0 */
  9935. }
  9936. umask(mask);
  9937. return !rc; /* rc != 0 - success */
  9938. }
  9939. #endif
  9940. #if ENABLE_HUSH_EXPORT || ENABLE_HUSH_TRAP
  9941. static void print_escaped(const char *s)
  9942. {
  9943. if (*s == '\'')
  9944. goto squote;
  9945. do {
  9946. const char *p = strchrnul(s, '\'');
  9947. /* print 'xxxx', possibly just '' */
  9948. printf("'%.*s'", (int)(p - s), s);
  9949. if (*p == '\0')
  9950. break;
  9951. s = p;
  9952. squote:
  9953. /* s points to '; print "'''...'''" */
  9954. putchar('"');
  9955. do putchar('\''); while (*++s == '\'');
  9956. putchar('"');
  9957. } while (*s);
  9958. }
  9959. #endif
  9960. #if ENABLE_HUSH_EXPORT || ENABLE_HUSH_LOCAL || ENABLE_HUSH_READONLY
  9961. static int helper_export_local(char **argv, unsigned flags)
  9962. {
  9963. do {
  9964. char *name = *argv;
  9965. const char *name_end = endofname(name);
  9966. if (*name_end == '\0') {
  9967. struct variable *var, **vpp;
  9968. vpp = get_ptr_to_local_var(name, name_end - name);
  9969. var = vpp ? *vpp : NULL;
  9970. if (flags & SETFLAG_UNEXPORT) {
  9971. /* export -n NAME (without =VALUE) */
  9972. if (var) {
  9973. var->flg_export = 0;
  9974. debug_printf_env("%s: unsetenv '%s'\n", __func__, name);
  9975. unsetenv(name);
  9976. } /* else: export -n NOT_EXISTING_VAR: no-op */
  9977. continue;
  9978. }
  9979. if (flags & SETFLAG_EXPORT) {
  9980. /* export NAME (without =VALUE) */
  9981. if (var) {
  9982. var->flg_export = 1;
  9983. debug_printf_env("%s: putenv '%s'\n", __func__, var->varstr);
  9984. putenv(var->varstr);
  9985. continue;
  9986. }
  9987. }
  9988. if (flags & SETFLAG_MAKE_RO) {
  9989. /* readonly NAME (without =VALUE) */
  9990. if (var) {
  9991. var->flg_read_only = 1;
  9992. continue;
  9993. }
  9994. }
  9995. # if ENABLE_HUSH_LOCAL
  9996. /* Is this "local" bltin? */
  9997. if (!(flags & (SETFLAG_EXPORT|SETFLAG_UNEXPORT|SETFLAG_MAKE_RO))) {
  9998. unsigned lvl = flags >> SETFLAG_VARLVL_SHIFT;
  9999. if (var && var->var_nest_level == lvl) {
  10000. /* "local x=abc; ...; local x" - ignore second local decl */
  10001. continue;
  10002. }
  10003. }
  10004. # endif
  10005. /* Exporting non-existing variable.
  10006. * bash does not put it in environment,
  10007. * but remembers that it is exported,
  10008. * and does put it in env when it is set later.
  10009. * We just set it to "" and export.
  10010. */
  10011. /* Or, it's "local NAME" (without =VALUE).
  10012. * bash sets the value to "".
  10013. */
  10014. /* Or, it's "readonly NAME" (without =VALUE).
  10015. * bash remembers NAME and disallows its creation
  10016. * in the future.
  10017. */
  10018. name = xasprintf("%s=", name);
  10019. } else {
  10020. if (*name_end != '=') {
  10021. bb_error_msg("'%s': bad variable name", name);
  10022. /* do not parse following argv[]s: */
  10023. return 1;
  10024. }
  10025. /* (Un)exporting/making local NAME=VALUE */
  10026. name = xstrdup(name);
  10027. /* Testcase: export PS1='\w \$ ' */
  10028. unbackslash(name);
  10029. }
  10030. debug_printf_env("%s: set_local_var('%s')\n", __func__, name);
  10031. if (set_local_var(name, flags))
  10032. return EXIT_FAILURE;
  10033. } while (*++argv);
  10034. return EXIT_SUCCESS;
  10035. }
  10036. #endif
  10037. #if ENABLE_HUSH_EXPORT
  10038. static int FAST_FUNC builtin_export(char **argv)
  10039. {
  10040. unsigned opt_unexport;
  10041. #if ENABLE_HUSH_EXPORT_N
  10042. /* "!": do not abort on errors */
  10043. opt_unexport = getopt32(argv, "!n");
  10044. if (opt_unexport == (uint32_t)-1)
  10045. return EXIT_FAILURE;
  10046. argv += optind;
  10047. #else
  10048. opt_unexport = 0;
  10049. argv++;
  10050. #endif
  10051. if (argv[0] == NULL) {
  10052. char **e = environ;
  10053. if (e) {
  10054. while (*e) {
  10055. #if 0
  10056. puts(*e++);
  10057. #else
  10058. /* ash emits: export VAR='VAL'
  10059. * bash: declare -x VAR="VAL"
  10060. * we follow ash example */
  10061. const char *s = *e++;
  10062. const char *p = strchr(s, '=');
  10063. if (!p) /* wtf? take next variable */
  10064. continue;
  10065. /* export var= */
  10066. printf("export %.*s", (int)(p - s) + 1, s);
  10067. print_escaped(p + 1);
  10068. putchar('\n');
  10069. #endif
  10070. }
  10071. /*fflush_all(); - done after each builtin anyway */
  10072. }
  10073. return EXIT_SUCCESS;
  10074. }
  10075. return helper_export_local(argv, opt_unexport ? SETFLAG_UNEXPORT : SETFLAG_EXPORT);
  10076. }
  10077. #endif
  10078. #if ENABLE_HUSH_LOCAL
  10079. static int FAST_FUNC builtin_local(char **argv)
  10080. {
  10081. if (G.func_nest_level == 0) {
  10082. bb_error_msg("%s: not in a function", argv[0]);
  10083. return EXIT_FAILURE; /* bash compat */
  10084. }
  10085. argv++;
  10086. /* Since all builtins run in a nested variable level,
  10087. * need to use level - 1 here. Or else the variable will be removed at once
  10088. * after builtin returns.
  10089. */
  10090. return helper_export_local(argv, (G.var_nest_level - 1) << SETFLAG_VARLVL_SHIFT);
  10091. }
  10092. #endif
  10093. #if ENABLE_HUSH_READONLY
  10094. static int FAST_FUNC builtin_readonly(char **argv)
  10095. {
  10096. argv++;
  10097. if (*argv == NULL) {
  10098. /* bash: readonly [-p]: list all readonly VARs
  10099. * (-p has no effect in bash)
  10100. */
  10101. struct variable *e;
  10102. for (e = G.top_var; e; e = e->next) {
  10103. if (e->flg_read_only) {
  10104. //TODO: quote value: readonly VAR='VAL'
  10105. printf("readonly %s\n", e->varstr);
  10106. }
  10107. }
  10108. return EXIT_SUCCESS;
  10109. }
  10110. return helper_export_local(argv, SETFLAG_MAKE_RO);
  10111. }
  10112. #endif
  10113. #if ENABLE_HUSH_UNSET
  10114. /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#unset */
  10115. static int FAST_FUNC builtin_unset(char **argv)
  10116. {
  10117. int ret;
  10118. unsigned opts;
  10119. /* "!": do not abort on errors */
  10120. /* "+": stop at 1st non-option */
  10121. opts = getopt32(argv, "!+vf");
  10122. if (opts == (unsigned)-1)
  10123. return EXIT_FAILURE;
  10124. if (opts == 3) {
  10125. bb_error_msg("unset: -v and -f are exclusive");
  10126. return EXIT_FAILURE;
  10127. }
  10128. argv += optind;
  10129. ret = EXIT_SUCCESS;
  10130. while (*argv) {
  10131. if (!(opts & 2)) { /* not -f */
  10132. if (unset_local_var(*argv)) {
  10133. /* unset <nonexistent_var> doesn't fail.
  10134. * Error is when one tries to unset RO var.
  10135. * Message was printed by unset_local_var. */
  10136. ret = EXIT_FAILURE;
  10137. }
  10138. }
  10139. # if ENABLE_HUSH_FUNCTIONS
  10140. else {
  10141. unset_func(*argv);
  10142. }
  10143. # endif
  10144. argv++;
  10145. }
  10146. return ret;
  10147. }
  10148. #endif
  10149. #if ENABLE_HUSH_SET
  10150. /* http://www.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#set
  10151. * built-in 'set' handler
  10152. * SUSv3 says:
  10153. * set [-abCefhmnuvx] [-o option] [argument...]
  10154. * set [+abCefhmnuvx] [+o option] [argument...]
  10155. * set -- [argument...]
  10156. * set -o
  10157. * set +o
  10158. * Implementations shall support the options in both their hyphen and
  10159. * plus-sign forms. These options can also be specified as options to sh.
  10160. * Examples:
  10161. * Write out all variables and their values: set
  10162. * Set $1, $2, and $3 and set "$#" to 3: set c a b
  10163. * Turn on the -x and -v options: set -xv
  10164. * Unset all positional parameters: set --
  10165. * Set $1 to the value of x, even if it begins with '-' or '+': set -- "$x"
  10166. * Set the positional parameters to the expansion of x, even if x expands
  10167. * with a leading '-' or '+': set -- $x
  10168. *
  10169. * So far, we only support "set -- [argument...]" and some of the short names.
  10170. */
  10171. static int FAST_FUNC builtin_set(char **argv)
  10172. {
  10173. int n;
  10174. char **pp, **g_argv;
  10175. char *arg = *++argv;
  10176. if (arg == NULL) {
  10177. struct variable *e;
  10178. for (e = G.top_var; e; e = e->next)
  10179. puts(e->varstr);
  10180. return EXIT_SUCCESS;
  10181. }
  10182. do {
  10183. if (strcmp(arg, "--") == 0) {
  10184. ++argv;
  10185. goto set_argv;
  10186. }
  10187. if (arg[0] != '+' && arg[0] != '-')
  10188. break;
  10189. for (n = 1; arg[n]; ++n) {
  10190. if (set_mode((arg[0] == '-'), arg[n], argv[1]))
  10191. goto error;
  10192. if (arg[n] == 'o' && argv[1])
  10193. argv++;
  10194. }
  10195. } while ((arg = *++argv) != NULL);
  10196. /* Now argv[0] is 1st argument */
  10197. if (arg == NULL)
  10198. return EXIT_SUCCESS;
  10199. set_argv:
  10200. /* NB: G.global_argv[0] ($0) is never freed/changed */
  10201. g_argv = G.global_argv;
  10202. if (G.global_args_malloced) {
  10203. pp = g_argv;
  10204. while (*++pp)
  10205. free(*pp);
  10206. g_argv[1] = NULL;
  10207. } else {
  10208. G.global_args_malloced = 1;
  10209. pp = xzalloc(sizeof(pp[0]) * 2);
  10210. pp[0] = g_argv[0]; /* retain $0 */
  10211. g_argv = pp;
  10212. }
  10213. /* This realloc's G.global_argv */
  10214. G.global_argv = pp = add_strings_to_strings(g_argv, argv, /*dup:*/ 1);
  10215. G.global_argc = 1 + string_array_len(pp + 1);
  10216. return EXIT_SUCCESS;
  10217. /* Nothing known, so abort */
  10218. error:
  10219. bb_error_msg("%s: %s: invalid option", "set", arg);
  10220. return EXIT_FAILURE;
  10221. }
  10222. #endif
  10223. static int FAST_FUNC builtin_shift(char **argv)
  10224. {
  10225. int n = 1;
  10226. argv = skip_dash_dash(argv);
  10227. if (argv[0]) {
  10228. n = bb_strtou(argv[0], NULL, 10);
  10229. if (errno || n < 0) {
  10230. /* shared string with ash.c */
  10231. bb_error_msg("Illegal number: %s", argv[0]);
  10232. /*
  10233. * ash aborts in this case.
  10234. * bash prints error message and set $? to 1.
  10235. * Interestingly, for "shift 99999" bash does not
  10236. * print error message, but does set $? to 1
  10237. * (and does no shifting at all).
  10238. */
  10239. }
  10240. }
  10241. if (n >= 0 && n < G.global_argc) {
  10242. if (G_global_args_malloced) {
  10243. int m = 1;
  10244. while (m <= n)
  10245. free(G.global_argv[m++]);
  10246. }
  10247. G.global_argc -= n;
  10248. memmove(&G.global_argv[1], &G.global_argv[n+1],
  10249. G.global_argc * sizeof(G.global_argv[0]));
  10250. return EXIT_SUCCESS;
  10251. }
  10252. return EXIT_FAILURE;
  10253. }
  10254. #if ENABLE_HUSH_GETOPTS
  10255. static int FAST_FUNC builtin_getopts(char **argv)
  10256. {
  10257. /* http://pubs.opengroup.org/onlinepubs/9699919799/utilities/getopts.html
  10258. TODO:
  10259. If a required argument is not found, and getopts is not silent,
  10260. a question mark (?) is placed in VAR, OPTARG is unset, and a
  10261. diagnostic message is printed. If getopts is silent, then a
  10262. colon (:) is placed in VAR and OPTARG is set to the option
  10263. character found.
  10264. Test that VAR is a valid variable name?
  10265. "Whenever the shell is invoked, OPTIND shall be initialized to 1"
  10266. */
  10267. char cbuf[2];
  10268. const char *cp, *optstring, *var;
  10269. int c, n, exitcode, my_opterr;
  10270. unsigned count;
  10271. optstring = *++argv;
  10272. if (!optstring || !(var = *++argv)) {
  10273. bb_error_msg("usage: getopts OPTSTRING VAR [ARGS]");
  10274. return EXIT_FAILURE;
  10275. }
  10276. if (argv[1])
  10277. argv[0] = G.global_argv[0]; /* for error messages in getopt() */
  10278. else
  10279. argv = G.global_argv;
  10280. cbuf[1] = '\0';
  10281. my_opterr = 0;
  10282. if (optstring[0] != ':') {
  10283. cp = get_local_var_value("OPTERR");
  10284. /* 0 if "OPTERR=0", 1 otherwise */
  10285. my_opterr = (!cp || NOT_LONE_CHAR(cp, '0'));
  10286. }
  10287. /* getopts stops on first non-option. Add "+" to force that */
  10288. /*if (optstring[0] != '+')*/ {
  10289. char *s = alloca(strlen(optstring) + 2);
  10290. sprintf(s, "+%s", optstring);
  10291. optstring = s;
  10292. }
  10293. /* Naively, now we should just
  10294. * cp = get_local_var_value("OPTIND");
  10295. * optind = cp ? atoi(cp) : 0;
  10296. * optarg = NULL;
  10297. * opterr = my_opterr;
  10298. * c = getopt(string_array_len(argv), argv, optstring);
  10299. * and be done? Not so fast...
  10300. * Unlike normal getopt() usage in C programs, here
  10301. * each successive call will (usually) have the same argv[] CONTENTS,
  10302. * but not the ADDRESSES. Worse yet, it's possible that between
  10303. * invocations of "getopts", there will be calls to shell builtins
  10304. * which use getopt() internally. Example:
  10305. * while getopts "abc" RES -a -bc -abc de; do
  10306. * unset -ff func
  10307. * done
  10308. * This would not work correctly: getopt() call inside "unset"
  10309. * modifies internal libc state which is tracking position in
  10310. * multi-option strings ("-abc"). At best, it can skip options
  10311. * or return the same option infinitely. With glibc implementation
  10312. * of getopt(), it would use outright invalid pointers and return
  10313. * garbage even _without_ "unset" mangling internal state.
  10314. *
  10315. * We resort to resetting getopt() state and calling it N times,
  10316. * until we get Nth result (or failure).
  10317. * (N == G.getopt_count is reset to 0 whenever OPTIND is [un]set).
  10318. */
  10319. GETOPT_RESET();
  10320. count = 0;
  10321. n = string_array_len(argv);
  10322. do {
  10323. optarg = NULL;
  10324. opterr = (count < G.getopt_count) ? 0 : my_opterr;
  10325. c = getopt(n, argv, optstring);
  10326. if (c < 0)
  10327. break;
  10328. count++;
  10329. } while (count <= G.getopt_count);
  10330. /* Set OPTIND. Prevent resetting of the magic counter! */
  10331. set_local_var_from_halves("OPTIND", utoa(optind));
  10332. G.getopt_count = count; /* "next time, give me N+1'th result" */
  10333. GETOPT_RESET(); /* just in case */
  10334. /* Set OPTARG */
  10335. /* Always set or unset, never left as-is, even on exit/error:
  10336. * "If no option was found, or if the option that was found
  10337. * does not have an option-argument, OPTARG shall be unset."
  10338. */
  10339. cp = optarg;
  10340. if (c == '?') {
  10341. /* If ":optstring" and unknown option is seen,
  10342. * it is stored to OPTARG.
  10343. */
  10344. if (optstring[1] == ':') {
  10345. cbuf[0] = optopt;
  10346. cp = cbuf;
  10347. }
  10348. }
  10349. if (cp)
  10350. set_local_var_from_halves("OPTARG", cp);
  10351. else
  10352. unset_local_var("OPTARG");
  10353. /* Convert -1 to "?" */
  10354. exitcode = EXIT_SUCCESS;
  10355. if (c < 0) { /* -1: end of options */
  10356. exitcode = EXIT_FAILURE;
  10357. c = '?';
  10358. }
  10359. /* Set VAR */
  10360. cbuf[0] = c;
  10361. set_local_var_from_halves(var, cbuf);
  10362. return exitcode;
  10363. }
  10364. #endif
  10365. static int FAST_FUNC builtin_source(char **argv)
  10366. {
  10367. char *arg_path, *filename;
  10368. HFILE *input;
  10369. save_arg_t sv;
  10370. char *args_need_save;
  10371. #if ENABLE_HUSH_FUNCTIONS
  10372. smallint sv_flg;
  10373. #endif
  10374. argv = skip_dash_dash(argv);
  10375. filename = argv[0];
  10376. if (!filename) {
  10377. /* bash says: "bash: .: filename argument required" */
  10378. return 2; /* bash compat */
  10379. }
  10380. arg_path = NULL;
  10381. if (!strchr(filename, '/')) {
  10382. arg_path = find_in_path(filename);
  10383. if (arg_path)
  10384. filename = arg_path;
  10385. else if (!ENABLE_HUSH_BASH_SOURCE_CURDIR) {
  10386. errno = ENOENT;
  10387. bb_simple_perror_msg(filename);
  10388. return EXIT_FAILURE;
  10389. }
  10390. }
  10391. input = hfopen(filename);
  10392. free(arg_path);
  10393. if (!input) {
  10394. bb_perror_msg("%s", filename);
  10395. /* POSIX: non-interactive shell should abort here,
  10396. * not merely fail. So far no one complained :)
  10397. */
  10398. return EXIT_FAILURE;
  10399. }
  10400. #if ENABLE_HUSH_FUNCTIONS
  10401. sv_flg = G_flag_return_in_progress;
  10402. /* "we are inside sourced file, ok to use return" */
  10403. G_flag_return_in_progress = -1;
  10404. #endif
  10405. args_need_save = argv[1]; /* used as a boolean variable */
  10406. if (args_need_save)
  10407. save_and_replace_G_args(&sv, argv);
  10408. /* "false; . ./empty_line; echo Zero:$?" should print 0 */
  10409. G.last_exitcode = 0;
  10410. parse_and_run_file(input);
  10411. hfclose(input);
  10412. if (args_need_save) /* can't use argv[1] instead: "shift" can mangle it */
  10413. restore_G_args(&sv, argv);
  10414. #if ENABLE_HUSH_FUNCTIONS
  10415. G_flag_return_in_progress = sv_flg;
  10416. #endif
  10417. return G.last_exitcode;
  10418. }
  10419. #if ENABLE_HUSH_TRAP
  10420. static int FAST_FUNC builtin_trap(char **argv)
  10421. {
  10422. int sig;
  10423. char *new_cmd;
  10424. if (!G_traps)
  10425. G_traps = xzalloc(sizeof(G_traps[0]) * NSIG);
  10426. argv++;
  10427. if (!*argv) {
  10428. int i;
  10429. /* No args: print all trapped */
  10430. for (i = 0; i < NSIG; ++i) {
  10431. if (G_traps[i]) {
  10432. printf("trap -- ");
  10433. print_escaped(G_traps[i]);
  10434. /* note: bash adds "SIG", but only if invoked
  10435. * as "bash". If called as "sh", or if set -o posix,
  10436. * then it prints short signal names.
  10437. * We are printing short names: */
  10438. printf(" %s\n", get_signame(i));
  10439. }
  10440. }
  10441. /*fflush_all(); - done after each builtin anyway */
  10442. return EXIT_SUCCESS;
  10443. }
  10444. new_cmd = NULL;
  10445. /* If first arg is a number: reset all specified signals */
  10446. sig = bb_strtou(*argv, NULL, 10);
  10447. if (errno == 0) {
  10448. int ret;
  10449. process_sig_list:
  10450. ret = EXIT_SUCCESS;
  10451. while (*argv) {
  10452. sighandler_t handler;
  10453. sig = get_signum(*argv++);
  10454. if (sig < 0) {
  10455. ret = EXIT_FAILURE;
  10456. /* Mimic bash message exactly */
  10457. bb_error_msg("trap: %s: invalid signal specification", argv[-1]);
  10458. continue;
  10459. }
  10460. free(G_traps[sig]);
  10461. G_traps[sig] = xstrdup(new_cmd);
  10462. debug_printf("trap: setting SIG%s (%i) to '%s'\n",
  10463. get_signame(sig), sig, G_traps[sig]);
  10464. /* There is no signal for 0 (EXIT) */
  10465. if (sig == 0)
  10466. continue;
  10467. if (new_cmd)
  10468. handler = (new_cmd[0] ? record_pending_signo : SIG_IGN);
  10469. else
  10470. /* We are removing trap handler */
  10471. handler = pick_sighandler(sig);
  10472. install_sighandler(sig, handler);
  10473. }
  10474. return ret;
  10475. }
  10476. if (!argv[1]) { /* no second arg */
  10477. bb_error_msg("trap: invalid arguments");
  10478. return EXIT_FAILURE;
  10479. }
  10480. /* First arg is "-": reset all specified to default */
  10481. /* First arg is "--": skip it, the rest is "handler SIGs..." */
  10482. /* Everything else: set arg as signal handler
  10483. * (includes "" case, which ignores signal) */
  10484. if (argv[0][0] == '-') {
  10485. if (argv[0][1] == '\0') { /* "-" */
  10486. /* new_cmd remains NULL: "reset these sigs" */
  10487. goto reset_traps;
  10488. }
  10489. if (argv[0][1] == '-' && argv[0][2] == '\0') { /* "--" */
  10490. argv++;
  10491. }
  10492. /* else: "-something", no special meaning */
  10493. }
  10494. new_cmd = *argv;
  10495. reset_traps:
  10496. argv++;
  10497. goto process_sig_list;
  10498. }
  10499. #endif
  10500. #if ENABLE_HUSH_JOB
  10501. static struct pipe *parse_jobspec(const char *str)
  10502. {
  10503. struct pipe *pi;
  10504. unsigned jobnum;
  10505. if (sscanf(str, "%%%u", &jobnum) != 1) {
  10506. if (str[0] != '%'
  10507. || (str[1] != '%' && str[1] != '+' && str[1] != '\0')
  10508. ) {
  10509. bb_error_msg("bad argument '%s'", str);
  10510. return NULL;
  10511. }
  10512. /* It is "%%", "%+" or "%" - current job */
  10513. jobnum = G.last_jobid;
  10514. if (jobnum == 0) {
  10515. bb_error_msg("no current job");
  10516. return NULL;
  10517. }
  10518. }
  10519. for (pi = G.job_list; pi; pi = pi->next) {
  10520. if (pi->jobid == jobnum) {
  10521. return pi;
  10522. }
  10523. }
  10524. bb_error_msg("%u: no such job", jobnum);
  10525. return NULL;
  10526. }
  10527. static int FAST_FUNC builtin_jobs(char **argv UNUSED_PARAM)
  10528. {
  10529. struct pipe *job;
  10530. const char *status_string;
  10531. checkjobs(NULL, 0 /*(no pid to wait for)*/);
  10532. for (job = G.job_list; job; job = job->next) {
  10533. if (job->alive_cmds == job->stopped_cmds)
  10534. status_string = "Stopped";
  10535. else
  10536. status_string = "Running";
  10537. printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->cmdtext);
  10538. }
  10539. clean_up_last_dead_job();
  10540. return EXIT_SUCCESS;
  10541. }
  10542. /* built-in 'fg' and 'bg' handler */
  10543. static int FAST_FUNC builtin_fg_bg(char **argv)
  10544. {
  10545. int i;
  10546. struct pipe *pi;
  10547. if (!G_interactive_fd)
  10548. return EXIT_FAILURE;
  10549. /* If they gave us no args, assume they want the last backgrounded task */
  10550. if (!argv[1]) {
  10551. for (pi = G.job_list; pi; pi = pi->next) {
  10552. if (pi->jobid == G.last_jobid) {
  10553. goto found;
  10554. }
  10555. }
  10556. bb_error_msg("%s: no current job", argv[0]);
  10557. return EXIT_FAILURE;
  10558. }
  10559. pi = parse_jobspec(argv[1]);
  10560. if (!pi)
  10561. return EXIT_FAILURE;
  10562. found:
  10563. /* TODO: bash prints a string representation
  10564. * of job being foregrounded (like "sleep 1 | cat") */
  10565. if (argv[0][0] == 'f' && G_saved_tty_pgrp) {
  10566. /* Put the job into the foreground. */
  10567. tcsetpgrp(G_interactive_fd, pi->pgrp);
  10568. }
  10569. /* Restart the processes in the job */
  10570. debug_printf_jobs("reviving %d procs, pgrp %d\n", pi->num_cmds, pi->pgrp);
  10571. for (i = 0; i < pi->num_cmds; i++) {
  10572. debug_printf_jobs("reviving pid %d\n", pi->cmds[i].pid);
  10573. }
  10574. pi->stopped_cmds = 0;
  10575. i = kill(- pi->pgrp, SIGCONT);
  10576. if (i < 0) {
  10577. if (errno == ESRCH) {
  10578. delete_finished_job(pi);
  10579. return EXIT_SUCCESS;
  10580. }
  10581. bb_perror_msg("kill (SIGCONT)");
  10582. }
  10583. if (argv[0][0] == 'f') {
  10584. remove_job_from_table(pi); /* FG job shouldn't be in job table */
  10585. return checkjobs_and_fg_shell(pi);
  10586. }
  10587. return EXIT_SUCCESS;
  10588. }
  10589. #endif
  10590. #if ENABLE_HUSH_KILL
  10591. static int FAST_FUNC builtin_kill(char **argv)
  10592. {
  10593. int ret = 0;
  10594. # if ENABLE_HUSH_JOB
  10595. if (argv[1] && strcmp(argv[1], "-l") != 0) {
  10596. int i = 1;
  10597. do {
  10598. struct pipe *pi;
  10599. char *dst;
  10600. int j, n;
  10601. if (argv[i][0] != '%')
  10602. continue;
  10603. /*
  10604. * "kill %N" - job kill
  10605. * Converting to pgrp / pid kill
  10606. */
  10607. pi = parse_jobspec(argv[i]);
  10608. if (!pi) {
  10609. /* Eat bad jobspec */
  10610. j = i;
  10611. do {
  10612. j++;
  10613. argv[j - 1] = argv[j];
  10614. } while (argv[j]);
  10615. ret = 1;
  10616. i--;
  10617. continue;
  10618. }
  10619. /*
  10620. * In jobs started under job control, we signal
  10621. * entire process group by kill -PGRP_ID.
  10622. * This happens, f.e., in interactive shell.
  10623. *
  10624. * Otherwise, we signal each child via
  10625. * kill PID1 PID2 PID3.
  10626. * Testcases:
  10627. * sh -c 'sleep 1|sleep 1 & kill %1'
  10628. * sh -c 'true|sleep 2 & sleep 1; kill %1'
  10629. * sh -c 'true|sleep 1 & sleep 2; kill %1'
  10630. */
  10631. n = G_interactive_fd ? 1 : pi->num_cmds;
  10632. dst = alloca(n * sizeof(int)*4);
  10633. argv[i] = dst;
  10634. if (G_interactive_fd)
  10635. dst += sprintf(dst, " -%u", (int)pi->pgrp);
  10636. else for (j = 0; j < n; j++) {
  10637. struct command *cmd = &pi->cmds[j];
  10638. /* Skip exited members of the job */
  10639. if (cmd->pid == 0)
  10640. continue;
  10641. /*
  10642. * kill_main has matching code to expect
  10643. * leading space. Needed to not confuse
  10644. * negative pids with "kill -SIGNAL_NO" syntax
  10645. */
  10646. dst += sprintf(dst, " %u", (int)cmd->pid);
  10647. }
  10648. *dst = '\0';
  10649. } while (argv[++i]);
  10650. }
  10651. # endif
  10652. if (argv[1] || ret == 0) {
  10653. ret = run_applet_main(argv, kill_main);
  10654. }
  10655. /* else: ret = 1, "kill %bad_jobspec" case */
  10656. return ret;
  10657. }
  10658. #endif
  10659. #if ENABLE_HUSH_WAIT
  10660. /* http://www.opengroup.org/onlinepubs/9699919799/utilities/wait.html */
  10661. #if !ENABLE_HUSH_JOB
  10662. # define wait_for_child_or_signal(pipe,pid) wait_for_child_or_signal(pid)
  10663. #endif
  10664. static int wait_for_child_or_signal(struct pipe *waitfor_pipe, pid_t waitfor_pid)
  10665. {
  10666. int ret = 0;
  10667. for (;;) {
  10668. int sig;
  10669. sigset_t oldset;
  10670. if (!sigisemptyset(&G.pending_set))
  10671. goto check_sig;
  10672. /* waitpid is not interruptible by SA_RESTARTed
  10673. * signals which we use. Thus, this ugly dance:
  10674. */
  10675. /* Make sure possible SIGCHLD is stored in kernel's
  10676. * pending signal mask before we call waitpid.
  10677. * Or else we may race with SIGCHLD, lose it,
  10678. * and get stuck in sigsuspend...
  10679. */
  10680. sigfillset(&oldset); /* block all signals, remember old set */
  10681. sigprocmask2(SIG_SETMASK, &oldset);
  10682. if (!sigisemptyset(&G.pending_set)) {
  10683. /* Crap! we raced with some signal! */
  10684. goto restore;
  10685. }
  10686. /*errno = 0; - checkjobs does this */
  10687. /* Can't pass waitfor_pipe into checkjobs(): it won't be interruptible */
  10688. ret = checkjobs(NULL, waitfor_pid); /* waitpid(WNOHANG) inside */
  10689. debug_printf_exec("checkjobs:%d\n", ret);
  10690. #if ENABLE_HUSH_JOB
  10691. if (waitfor_pipe) {
  10692. int rcode = job_exited_or_stopped(waitfor_pipe);
  10693. debug_printf_exec("job_exited_or_stopped:%d\n", rcode);
  10694. if (rcode >= 0) {
  10695. ret = rcode;
  10696. sigprocmask(SIG_SETMASK, &oldset, NULL);
  10697. break;
  10698. }
  10699. }
  10700. #endif
  10701. /* if ECHILD, there are no children (ret is -1 or 0) */
  10702. /* if ret == 0, no children changed state */
  10703. /* if ret != 0, it's exitcode+1 of exited waitfor_pid child */
  10704. if (errno == ECHILD || ret) {
  10705. ret--;
  10706. if (ret < 0) /* if ECHILD, may need to fix "ret" */
  10707. ret = 0;
  10708. #if ENABLE_HUSH_BASH_COMPAT
  10709. if (waitfor_pid == -1 && errno == ECHILD) {
  10710. /* exitcode of "wait -n" with no children is 127, not 0 */
  10711. ret = 127;
  10712. }
  10713. #endif
  10714. sigprocmask(SIG_SETMASK, &oldset, NULL);
  10715. break;
  10716. }
  10717. /* Wait for SIGCHLD or any other signal */
  10718. /* It is vitally important for sigsuspend that SIGCHLD has non-DFL handler! */
  10719. /* Note: sigsuspend invokes signal handler */
  10720. sigsuspend(&oldset);
  10721. restore:
  10722. sigprocmask(SIG_SETMASK, &oldset, NULL);
  10723. check_sig:
  10724. /* So, did we get a signal? */
  10725. sig = check_and_run_traps();
  10726. if (sig /*&& sig != SIGCHLD - always true */) {
  10727. /* Do this for any (non-ignored) signal, not only for ^C */
  10728. ret = 128 + sig;
  10729. break;
  10730. }
  10731. /* SIGCHLD, or no signal, or ignored one, such as SIGQUIT. Repeat */
  10732. }
  10733. return ret;
  10734. }
  10735. static int FAST_FUNC builtin_wait(char **argv)
  10736. {
  10737. int ret;
  10738. int status;
  10739. argv = skip_dash_dash(argv);
  10740. #if ENABLE_HUSH_BASH_COMPAT
  10741. if (argv[0] && strcmp(argv[0], "-n") == 0) {
  10742. /* wait -n */
  10743. /* (bash accepts "wait -n PID" too and ignores PID) */
  10744. G.dead_job_exitcode = -1;
  10745. return wait_for_child_or_signal(NULL, -1 /*no job, wait for one job*/);
  10746. }
  10747. #endif
  10748. if (argv[0] == NULL) {
  10749. /* Don't care about wait results */
  10750. /* Note 1: must wait until there are no more children */
  10751. /* Note 2: must be interruptible */
  10752. /* Examples:
  10753. * $ sleep 3 & sleep 6 & wait
  10754. * [1] 30934 sleep 3
  10755. * [2] 30935 sleep 6
  10756. * [1] Done sleep 3
  10757. * [2] Done sleep 6
  10758. * $ sleep 3 & sleep 6 & wait
  10759. * [1] 30936 sleep 3
  10760. * [2] 30937 sleep 6
  10761. * [1] Done sleep 3
  10762. * ^C <-- after ~4 sec from keyboard
  10763. * $
  10764. */
  10765. return wait_for_child_or_signal(NULL, 0 /*no job and no pid to wait for*/);
  10766. }
  10767. do {
  10768. pid_t pid = bb_strtou(*argv, NULL, 10);
  10769. if (errno || pid <= 0) {
  10770. #if ENABLE_HUSH_JOB
  10771. if (argv[0][0] == '%') {
  10772. struct pipe *wait_pipe;
  10773. ret = 127; /* bash compat for bad jobspecs */
  10774. wait_pipe = parse_jobspec(*argv);
  10775. if (wait_pipe) {
  10776. ret = job_exited_or_stopped(wait_pipe);
  10777. if (ret < 0) {
  10778. ret = wait_for_child_or_signal(wait_pipe, 0);
  10779. } else {
  10780. /* waiting on "last dead job" removes it */
  10781. clean_up_last_dead_job();
  10782. }
  10783. }
  10784. /* else: parse_jobspec() already emitted error msg */
  10785. continue;
  10786. }
  10787. #endif
  10788. /* mimic bash message */
  10789. bb_error_msg("wait: '%s': not a pid or valid job spec", *argv);
  10790. ret = EXIT_FAILURE;
  10791. continue; /* bash checks all argv[] */
  10792. }
  10793. /* Do we have such child? */
  10794. ret = waitpid(pid, &status, WNOHANG);
  10795. if (ret < 0) {
  10796. /* No */
  10797. ret = 127;
  10798. if (errno == ECHILD) {
  10799. if (pid == G.last_bg_pid) {
  10800. /* "wait $!" but last bg task has already exited. Try:
  10801. * (sleep 1; exit 3) & sleep 2; echo $?; wait $!; echo $?
  10802. * In bash it prints exitcode 0, then 3.
  10803. * In dash, it is 127.
  10804. */
  10805. ret = G.last_bg_pid_exitcode;
  10806. } else {
  10807. /* Example: "wait 1". mimic bash message */
  10808. bb_error_msg("wait: pid %d is not a child of this shell", (int)pid);
  10809. }
  10810. } else {
  10811. /* ??? */
  10812. bb_perror_msg("wait %s", *argv);
  10813. }
  10814. continue; /* bash checks all argv[] */
  10815. }
  10816. if (ret == 0) {
  10817. /* Yes, and it still runs */
  10818. ret = wait_for_child_or_signal(NULL, pid);
  10819. } else {
  10820. /* Yes, and it just exited */
  10821. process_wait_result(NULL, pid, status);
  10822. ret = WEXITSTATUS(status);
  10823. if (WIFSIGNALED(status))
  10824. ret = 128 + WTERMSIG(status);
  10825. }
  10826. } while (*++argv);
  10827. return ret;
  10828. }
  10829. #endif
  10830. #if ENABLE_HUSH_LOOPS || ENABLE_HUSH_FUNCTIONS
  10831. static unsigned parse_numeric_argv1(char **argv, unsigned def, unsigned def_min)
  10832. {
  10833. if (argv[1]) {
  10834. def = bb_strtou(argv[1], NULL, 10);
  10835. if (errno || def < def_min || argv[2]) {
  10836. bb_error_msg("%s: bad arguments", argv[0]);
  10837. def = UINT_MAX;
  10838. }
  10839. }
  10840. return def;
  10841. }
  10842. #endif
  10843. #if ENABLE_HUSH_LOOPS
  10844. static int FAST_FUNC builtin_break(char **argv)
  10845. {
  10846. unsigned depth;
  10847. if (G.depth_of_loop == 0) {
  10848. bb_error_msg("%s: only meaningful in a loop", argv[0]);
  10849. /* if we came from builtin_continue(), need to undo "= 1" */
  10850. G.flag_break_continue = 0;
  10851. return EXIT_SUCCESS; /* bash compat */
  10852. }
  10853. G.flag_break_continue++; /* BC_BREAK = 1, or BC_CONTINUE = 2 */
  10854. G.depth_break_continue = depth = parse_numeric_argv1(argv, 1, 1);
  10855. if (depth == UINT_MAX)
  10856. G.flag_break_continue = BC_BREAK;
  10857. if (G.depth_of_loop < depth)
  10858. G.depth_break_continue = G.depth_of_loop;
  10859. return EXIT_SUCCESS;
  10860. }
  10861. static int FAST_FUNC builtin_continue(char **argv)
  10862. {
  10863. G.flag_break_continue = 1; /* BC_CONTINUE = 2 = 1+1 */
  10864. return builtin_break(argv);
  10865. }
  10866. #endif
  10867. #if ENABLE_HUSH_FUNCTIONS
  10868. static int FAST_FUNC builtin_return(char **argv)
  10869. {
  10870. int rc;
  10871. if (G_flag_return_in_progress != -1) {
  10872. bb_error_msg("%s: not in a function or sourced script", argv[0]);
  10873. return EXIT_FAILURE; /* bash compat */
  10874. }
  10875. G_flag_return_in_progress = 1;
  10876. /* bash:
  10877. * out of range: wraps around at 256, does not error out
  10878. * non-numeric param:
  10879. * f() { false; return qwe; }; f; echo $?
  10880. * bash: return: qwe: numeric argument required <== we do this
  10881. * 255 <== we also do this
  10882. */
  10883. rc = parse_numeric_argv1(argv, G.last_exitcode, 0);
  10884. return rc;
  10885. }
  10886. #endif
  10887. #if ENABLE_HUSH_TIMES
  10888. static int FAST_FUNC builtin_times(char **argv UNUSED_PARAM)
  10889. {
  10890. static const uint8_t times_tbl[] ALIGN1 = {
  10891. ' ', offsetof(struct tms, tms_utime),
  10892. '\n', offsetof(struct tms, tms_stime),
  10893. ' ', offsetof(struct tms, tms_cutime),
  10894. '\n', offsetof(struct tms, tms_cstime),
  10895. 0
  10896. };
  10897. const uint8_t *p;
  10898. unsigned clk_tck;
  10899. struct tms buf;
  10900. clk_tck = bb_clk_tck();
  10901. times(&buf);
  10902. p = times_tbl;
  10903. do {
  10904. unsigned sec, frac;
  10905. unsigned long t;
  10906. t = *(clock_t *)(((char *) &buf) + p[1]);
  10907. sec = t / clk_tck;
  10908. frac = t % clk_tck;
  10909. printf("%um%u.%03us%c",
  10910. sec / 60, sec % 60,
  10911. (frac * 1000) / clk_tck,
  10912. p[0]);
  10913. p += 2;
  10914. } while (*p);
  10915. return EXIT_SUCCESS;
  10916. }
  10917. #endif
  10918. #if ENABLE_HUSH_MEMLEAK
  10919. static int FAST_FUNC builtin_memleak(char **argv UNUSED_PARAM)
  10920. {
  10921. void *p;
  10922. unsigned long l;
  10923. # ifdef M_TRIM_THRESHOLD
  10924. /* Optional. Reduces probability of false positives */
  10925. malloc_trim(0);
  10926. # endif
  10927. /* Crude attempt to find where "free memory" starts,
  10928. * sans fragmentation. */
  10929. p = malloc(240);
  10930. l = (unsigned long)p;
  10931. free(p);
  10932. p = malloc(3400);
  10933. if (l < (unsigned long)p) l = (unsigned long)p;
  10934. free(p);
  10935. # if 0 /* debug */
  10936. {
  10937. struct mallinfo mi = mallinfo();
  10938. printf("top alloc:0x%lx malloced:%d+%d=%d\n", l,
  10939. mi.arena, mi.hblkhd, mi.arena + mi.hblkhd);
  10940. }
  10941. # endif
  10942. if (!G.memleak_value)
  10943. G.memleak_value = l;
  10944. l -= G.memleak_value;
  10945. if ((long)l < 0)
  10946. l = 0;
  10947. l /= 1024;
  10948. if (l > 127)
  10949. l = 127;
  10950. /* Exitcode is "how many kilobytes we leaked since 1st call" */
  10951. return l;
  10952. }
  10953. #endif