ash.c 326 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * ash shell port for busybox
  4. *
  5. * This code is derived from software contributed to Berkeley by
  6. * Kenneth Almquist.
  7. *
  8. * Original BSD copyright notice is retained at the end of this file.
  9. *
  10. * Copyright (c) 1989, 1991, 1993, 1994
  11. * The Regents of the University of California. All rights reserved.
  12. *
  13. * Copyright (c) 1997-2005 Herbert Xu <herbert@gondor.apana.org.au>
  14. * was re-ported from NetBSD and debianized.
  15. *
  16. * Licensed under GPLv2 or later, see file LICENSE in this source tree.
  17. */
  18. //config:config ASH
  19. //config: bool "ash (78 kb)"
  20. //config: default y
  21. //config: depends on !NOMMU
  22. //config: help
  23. //config: The most complete and most pedantically correct shell included with
  24. //config: busybox. This shell is actually a derivative of the Debian 'dash'
  25. //config: shell (by Herbert Xu), which was created by porting the 'ash' shell
  26. //config: (written by Kenneth Almquist) from NetBSD.
  27. //config:
  28. //config:# ash options
  29. //config:# note: Don't remove !NOMMU part in the next line; it would break
  30. //config:# menuconfig's indenting.
  31. //config:if !NOMMU && (ASH || SH_IS_ASH || BASH_IS_ASH)
  32. //config:
  33. //config:config ASH_OPTIMIZE_FOR_SIZE
  34. //config: bool "Optimize for size instead of speed"
  35. //config: default y
  36. //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
  37. //config:
  38. //config:config ASH_INTERNAL_GLOB
  39. //config: bool "Use internal glob() implementation"
  40. //config: default y # Y is bigger, but because of uclibc glob() bug, let Y be default for now
  41. //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
  42. //config: help
  43. //config: Do not use glob() function from libc, use internal implementation.
  44. //config: Use this if you are getting "glob.h: No such file or directory"
  45. //config: or similar build errors.
  46. //config: Note that as of now (2017-01), uclibc and musl glob() both have bugs
  47. //config: which would break ash if you select N here.
  48. //config:
  49. //config:config ASH_BASH_COMPAT
  50. //config: bool "bash-compatible extensions"
  51. //config: default y
  52. //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
  53. //config:
  54. //config:config ASH_BASH_SOURCE_CURDIR
  55. //config: bool "'source' and '.' builtins search current directory after $PATH"
  56. //config: default n # do not encourage non-standard behavior
  57. //config: depends on ASH_BASH_COMPAT
  58. //config: help
  59. //config: This is not compliant with standards. Avoid if possible.
  60. //config:
  61. //config:config ASH_BASH_NOT_FOUND_HOOK
  62. //config: bool "command_not_found_handle hook support"
  63. //config: default y
  64. //config: depends on ASH_BASH_COMPAT
  65. //config: help
  66. //config: Enable support for the 'command_not_found_handle' hook function,
  67. //config: from GNU bash, which allows for alternative command not found
  68. //config: handling.
  69. //config:
  70. //config:config ASH_JOB_CONTROL
  71. //config: bool "Job control"
  72. //config: default y
  73. //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
  74. //config:
  75. //config:config ASH_ALIAS
  76. //config: bool "Alias support"
  77. //config: default y
  78. //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
  79. //config:
  80. //config:config ASH_RANDOM_SUPPORT
  81. //config: bool "Pseudorandom generator and $RANDOM variable"
  82. //config: default y
  83. //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
  84. //config: help
  85. //config: Enable pseudorandom generator and dynamic variable "$RANDOM".
  86. //config: Each read of "$RANDOM" will generate a new pseudorandom value.
  87. //config: You can reset the generator by using a specified start value.
  88. //config: After "unset RANDOM" the generator will switch off and this
  89. //config: variable will no longer have special treatment.
  90. //config:
  91. //config:config ASH_EXPAND_PRMT
  92. //config: bool "Expand prompt string"
  93. //config: default y
  94. //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
  95. //config: help
  96. //config: $PS# may contain volatile content, such as backquote commands.
  97. //config: This option recreates the prompt string from the environment
  98. //config: variable each time it is displayed.
  99. //config:
  100. //config:config ASH_IDLE_TIMEOUT
  101. //config: bool "Idle timeout variable $TMOUT"
  102. //config: default y
  103. //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
  104. //config: help
  105. //config: Enable bash-like auto-logout after $TMOUT seconds of idle time.
  106. //config:
  107. //config:config ASH_MAIL
  108. //config: bool "Check for new mail in interactive shell"
  109. //config: default y
  110. //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
  111. //config: help
  112. //config: Enable "check for new mail" function:
  113. //config: if set, $MAIL file and $MAILPATH list of files
  114. //config: are checked for mtime changes, and "you have mail"
  115. //config: message is printed if change is detected.
  116. //config:
  117. //config:config ASH_ECHO
  118. //config: bool "echo builtin"
  119. //config: default y
  120. //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
  121. //config:
  122. //config:config ASH_PRINTF
  123. //config: bool "printf builtin"
  124. //config: default y
  125. //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
  126. //config:
  127. //config:config ASH_TEST
  128. //config: bool "test builtin"
  129. //config: default y
  130. //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
  131. //config:
  132. //config:config ASH_HELP
  133. //config: bool "help builtin"
  134. //config: default y
  135. //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
  136. //config:
  137. //config:config ASH_GETOPTS
  138. //config: bool "getopts builtin"
  139. //config: default y
  140. //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
  141. //config:
  142. //config:config ASH_CMDCMD
  143. //config: bool "command builtin"
  144. //config: default y
  145. //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
  146. //config: help
  147. //config: Enable support for the 'command' builtin, which allows
  148. //config: you to run the specified command or builtin,
  149. //config: even when there is a function with the same name.
  150. //config:
  151. //config:endif # ash options
  152. //applet:IF_ASH(APPLET(ash, BB_DIR_BIN, BB_SUID_DROP))
  153. // APPLET_ODDNAME:name main location suid_type help
  154. //applet:IF_SH_IS_ASH( APPLET_ODDNAME(sh, ash, BB_DIR_BIN, BB_SUID_DROP, ash))
  155. //applet:IF_BASH_IS_ASH(APPLET_ODDNAME(bash, ash, BB_DIR_BIN, BB_SUID_DROP, ash))
  156. //kbuild:lib-$(CONFIG_ASH) += ash.o ash_ptr_hack.o shell_common.o
  157. //kbuild:lib-$(CONFIG_SH_IS_ASH) += ash.o ash_ptr_hack.o shell_common.o
  158. //kbuild:lib-$(CONFIG_BASH_IS_ASH) += ash.o ash_ptr_hack.o shell_common.o
  159. //kbuild:lib-$(CONFIG_ASH_RANDOM_SUPPORT) += random.o
  160. /*
  161. * DEBUG=1 to compile in debugging ('set -o debug' turns on)
  162. * DEBUG=2 to compile in and turn on debugging.
  163. * When debugging is on ("set -o debug" was executed, or DEBUG=2),
  164. * debugging info is written to ./trace, quit signal generates core dump.
  165. */
  166. #define DEBUG 0
  167. /* Tweak debug output verbosity here */
  168. #define DEBUG_TIME 0
  169. #define DEBUG_PID 1
  170. #define DEBUG_SIG 1
  171. #define DEBUG_INTONOFF 0
  172. #define PROFILE 0
  173. #define JOBS ENABLE_ASH_JOB_CONTROL
  174. #include <fnmatch.h>
  175. #include <sys/times.h>
  176. #include <sys/utsname.h> /* for setting $HOSTNAME */
  177. #include "busybox.h" /* for applet_names */
  178. #if ENABLE_FEATURE_SH_EMBEDDED_SCRIPTS
  179. # include "embedded_scripts.h"
  180. #else
  181. # define NUM_SCRIPTS 0
  182. #endif
  183. /* So far, all bash compat is controlled by one config option */
  184. /* Separate defines document which part of code implements what */
  185. /* function keyword */
  186. #define BASH_FUNCTION ENABLE_ASH_BASH_COMPAT
  187. #define IF_BASH_FUNCTION IF_ASH_BASH_COMPAT
  188. /* &>file */
  189. #define BASH_REDIR_OUTPUT ENABLE_ASH_BASH_COMPAT
  190. #define IF_BASH_REDIR_OUTPUT IF_ASH_BASH_COMPAT
  191. /* $'...' */
  192. #define BASH_DOLLAR_SQUOTE ENABLE_ASH_BASH_COMPAT
  193. #define IF_BASH_DOLLAR_SQUOTE IF_ASH_BASH_COMPAT
  194. #define BASH_PATTERN_SUBST ENABLE_ASH_BASH_COMPAT
  195. #define IF_BASH_PATTERN_SUBST IF_ASH_BASH_COMPAT
  196. #define BASH_SUBSTR ENABLE_ASH_BASH_COMPAT
  197. #define IF_BASH_SUBSTR IF_ASH_BASH_COMPAT
  198. /* BASH_TEST2: [[ EXPR ]]
  199. * Status of [[ support:
  200. * We replace && and || with -a and -o
  201. * TODO:
  202. * singleword+noglob expansion:
  203. * v='a b'; [[ $v = 'a b' ]]; echo 0:$?
  204. * [[ /bin/n* ]]; echo 0:$?
  205. * -a/-o are not AND/OR ops! (they are just strings)
  206. * quoting needs to be considered (-f is an operator, "-f" and ""-f are not; etc)
  207. * = is glob match operator, not equality operator: STR = GLOB
  208. * (in GLOB, quoting is significant on char-by-char basis: a*cd"*")
  209. * == same as =
  210. * add =~ regex match operator: STR =~ REGEX
  211. */
  212. #define BASH_TEST2 (ENABLE_ASH_BASH_COMPAT * ENABLE_ASH_TEST)
  213. #define BASH_SOURCE ENABLE_ASH_BASH_COMPAT
  214. #define BASH_PIPEFAIL ENABLE_ASH_BASH_COMPAT
  215. #define BASH_HOSTNAME_VAR ENABLE_ASH_BASH_COMPAT
  216. #define BASH_EPOCH_VARS ENABLE_ASH_BASH_COMPAT
  217. #define BASH_SHLVL_VAR ENABLE_ASH_BASH_COMPAT
  218. #define BASH_XTRACEFD ENABLE_ASH_BASH_COMPAT
  219. #define BASH_READ_D ENABLE_ASH_BASH_COMPAT
  220. #define IF_BASH_READ_D IF_ASH_BASH_COMPAT
  221. #define BASH_WAIT_N ENABLE_ASH_BASH_COMPAT
  222. #if defined(__ANDROID_API__) && __ANDROID_API__ <= 24
  223. /* Bionic at least up to version 24 has no glob() */
  224. # undef ENABLE_ASH_INTERNAL_GLOB
  225. # define ENABLE_ASH_INTERNAL_GLOB 1
  226. #endif
  227. #if !ENABLE_ASH_INTERNAL_GLOB && defined(__UCLIBC__)
  228. # error uClibc glob() is buggy, use ASH_INTERNAL_GLOB.
  229. # error The bug is: for "$PWD"/<pattern> ash will escape e.g. dashes in "$PWD"
  230. # error with backslash, even ones which do not need to be: "/a-b" -> "/a\-b"
  231. # error glob() should unbackslash them and match. uClibc does not unbackslash,
  232. # error fails to match dirname, subsequently not expanding <pattern> in it.
  233. // Testcase:
  234. // if (glob("/etc/polkit\\-1", 0, NULL, &pglob)) - this returns 0 on uclibc, no bug
  235. // if (glob("/etc/polkit\\-1/*", 0, NULL, &pglob)) printf("uclibc bug!\n");
  236. #endif
  237. #if !ENABLE_ASH_INTERNAL_GLOB
  238. # include <glob.h>
  239. #endif
  240. #include "unicode.h"
  241. #include "shell_common.h"
  242. #if ENABLE_FEATURE_SH_MATH
  243. # include "math.h"
  244. #else
  245. typedef long arith_t;
  246. # define ARITH_FMT "%ld"
  247. #endif
  248. #if ENABLE_ASH_RANDOM_SUPPORT
  249. # include "random.h"
  250. #else
  251. # define CLEAR_RANDOM_T(rnd) ((void)0)
  252. #endif
  253. #include "NUM_APPLETS.h"
  254. #if NUM_APPLETS == 1
  255. /* STANDALONE does not make sense, and won't compile */
  256. # undef CONFIG_FEATURE_SH_STANDALONE
  257. # undef ENABLE_FEATURE_SH_STANDALONE
  258. # undef IF_FEATURE_SH_STANDALONE
  259. # undef IF_NOT_FEATURE_SH_STANDALONE
  260. # define ENABLE_FEATURE_SH_STANDALONE 0
  261. # define IF_FEATURE_SH_STANDALONE(...)
  262. # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
  263. #endif
  264. #ifndef F_DUPFD_CLOEXEC
  265. # define F_DUPFD_CLOEXEC F_DUPFD
  266. #endif
  267. #ifndef O_CLOEXEC
  268. # define O_CLOEXEC 0
  269. #endif
  270. #ifndef PIPE_BUF
  271. # define PIPE_BUF 4096 /* amount of buffering in a pipe */
  272. #endif
  273. #if !BB_MMU
  274. # error "Do not even bother, ash will not run on NOMMU machine"
  275. #endif
  276. /* We use a trick to have more optimized code (fewer pointer reloads):
  277. * ash.c: extern struct globals *const ash_ptr_to_globals;
  278. * ash_ptr_hack.c: struct globals *ash_ptr_to_globals;
  279. * This way, compiler in ash.c knows the pointer can not change.
  280. *
  281. * However, this may break on weird arches or toolchains. In this case,
  282. * set "-DBB_GLOBAL_CONST=''" in CONFIG_EXTRA_CFLAGS to disable
  283. * this optimization.
  284. */
  285. #ifndef BB_GLOBAL_CONST
  286. # define BB_GLOBAL_CONST const
  287. #endif
  288. /* ============ Hash table sizes. Configurable. */
  289. #define VTABSIZE 39
  290. #define ATABSIZE 39
  291. #define CMDTABLESIZE 31 /* should be prime */
  292. /* ============ Shell options */
  293. static const char *const optletters_optnames[] = {
  294. "e" "errexit",
  295. "f" "noglob",
  296. "I" "ignoreeof",
  297. /* The below allowed this invocation:
  298. * ash -c 'set -i; echo $-; sleep 5; echo $-'
  299. * to be ^C-ed and get to interactive ash prompt.
  300. * bash does not support such "set -i".
  301. * In our code, this is denoted by empty long name:
  302. */
  303. "i" "",
  304. "m" "monitor",
  305. "n" "noexec",
  306. /* Ditto: bash has no "set -s" */
  307. "s" "",
  308. "c" "",
  309. "x" "xtrace",
  310. "v" "verbose",
  311. "C" "noclobber",
  312. "a" "allexport",
  313. "b" "notify",
  314. "u" "nounset",
  315. "\0" "vi"
  316. #if BASH_PIPEFAIL
  317. ,"\0" "pipefail"
  318. #endif
  319. #if DEBUG
  320. ,"\0" "nolog"
  321. ,"\0" "debug"
  322. #endif
  323. };
  324. //bash 4.4.23 also has these opts (with these defaults):
  325. //braceexpand on
  326. //emacs on
  327. //errtrace off
  328. //functrace off
  329. //hashall on
  330. //histexpand off
  331. //history on
  332. //interactive-comments on
  333. //keyword off
  334. //onecmd off
  335. //physical off
  336. //posix off
  337. //privileged off
  338. #define optletters(n) optletters_optnames[n][0]
  339. #define optnames(n) (optletters_optnames[n] + 1)
  340. enum { NOPTS = ARRAY_SIZE(optletters_optnames) };
  341. /* ============ Misc data */
  342. #define msg_illnum "Illegal number: %s"
  343. /*
  344. * We enclose jmp_buf in a structure so that we can declare pointers to
  345. * jump locations. The global variable handler contains the location to
  346. * jump to when an exception occurs, and the global variable exception_type
  347. * contains a code identifying the exception. To implement nested
  348. * exception handlers, the user should save the value of handler on entry
  349. * to an inner scope, set handler to point to a jmploc structure for the
  350. * inner scope, and restore handler on exit from the scope.
  351. */
  352. struct jmploc {
  353. jmp_buf loc;
  354. };
  355. struct globals_misc {
  356. uint8_t exitstatus; /* exit status of last command */
  357. uint8_t back_exitstatus;/* exit status of backquoted command */
  358. smallint job_warning; /* user was warned about stopped jobs (can be 2, 1 or 0). */
  359. int savestatus; /* exit status of last command outside traps */
  360. int rootpid; /* pid of main shell */
  361. /* shell level: 0 for the main shell, 1 for its children, and so on */
  362. int shlvl;
  363. #define rootshell (!shlvl)
  364. int errlinno;
  365. char *minusc; /* argument to -c option */
  366. char *curdir; // = nullstr; /* current working directory */
  367. char *physdir; // = nullstr; /* physical working directory */
  368. char *arg0; /* value of $0 */
  369. struct jmploc *exception_handler;
  370. volatile int suppress_int; /* counter */
  371. volatile /*sig_atomic_t*/ smallint pending_int; /* 1 = got SIGINT */
  372. volatile /*sig_atomic_t*/ smallint got_sigchld; /* 1 = got SIGCHLD */
  373. volatile /*sig_atomic_t*/ smallint pending_sig; /* last pending signal */
  374. smallint exception_type; /* kind of exception: */
  375. #define EXINT 0 /* SIGINT received */
  376. #define EXERROR 1 /* a generic error */
  377. #define EXEND 3 /* exit the shell */
  378. #define EXEXIT 4 /* exit the shell via exitcmd */
  379. char nullstr[1]; /* zero length string */
  380. char optlist[NOPTS];
  381. #define eflag optlist[0]
  382. #define fflag optlist[1]
  383. #define Iflag optlist[2]
  384. #define iflag optlist[3]
  385. #define mflag optlist[4]
  386. #define nflag optlist[5]
  387. #define sflag optlist[6]
  388. #define cflag optlist[7]
  389. #define xflag optlist[8]
  390. #define vflag optlist[9]
  391. #define Cflag optlist[10]
  392. #define aflag optlist[11]
  393. #define bflag optlist[12]
  394. #define uflag optlist[13]
  395. #define viflag optlist[14]
  396. #if BASH_PIPEFAIL
  397. # define pipefail optlist[15]
  398. #else
  399. # define pipefail 0
  400. #endif
  401. #if DEBUG
  402. # define nolog optlist[15 + BASH_PIPEFAIL]
  403. # define debug optlist[16 + BASH_PIPEFAIL]
  404. #endif
  405. /* trap handler commands */
  406. /*
  407. * Sigmode records the current value of the signal handlers for the various
  408. * modes. A value of zero means that the current handler is not known.
  409. * S_HARD_IGN indicates that the signal was ignored on entry to the shell.
  410. */
  411. char sigmode[NSIG - 1];
  412. #define S_DFL 1 /* default signal handling (SIG_DFL) */
  413. #define S_CATCH 2 /* signal is caught */
  414. #define S_IGN 3 /* signal is ignored (SIG_IGN) */
  415. #define S_HARD_IGN 4 /* signal is ignored permanently (it was SIG_IGN on entry to shell) */
  416. /* indicates specified signal received */
  417. uint8_t gotsig[NSIG - 1]; /* offset by 1: "signal" 0 is meaningless */
  418. uint8_t may_have_traps; /* 0: definitely no traps are set, 1: some traps may be set */
  419. char *trap[NSIG];
  420. char **trap_ptr; /* used only by "trap hack" */
  421. /* Rarely referenced stuff */
  422. #if ENABLE_ASH_RANDOM_SUPPORT
  423. random_t random_gen;
  424. #endif
  425. pid_t backgndpid; /* pid of last background process */
  426. };
  427. extern struct globals_misc *BB_GLOBAL_CONST ash_ptr_to_globals_misc;
  428. #define G_misc (*ash_ptr_to_globals_misc)
  429. #define exitstatus (G_misc.exitstatus )
  430. #define back_exitstatus (G_misc.back_exitstatus )
  431. #define job_warning (G_misc.job_warning)
  432. #define savestatus (G_misc.savestatus )
  433. #define rootpid (G_misc.rootpid )
  434. #define shlvl (G_misc.shlvl )
  435. #define errlinno (G_misc.errlinno )
  436. #define minusc (G_misc.minusc )
  437. #define curdir (G_misc.curdir )
  438. #define physdir (G_misc.physdir )
  439. #define arg0 (G_misc.arg0 )
  440. #define exception_handler (G_misc.exception_handler)
  441. #define exception_type (G_misc.exception_type )
  442. #define suppress_int (G_misc.suppress_int )
  443. #define pending_int (G_misc.pending_int )
  444. #define got_sigchld (G_misc.got_sigchld )
  445. #define pending_sig (G_misc.pending_sig )
  446. #define nullstr (G_misc.nullstr )
  447. #define optlist (G_misc.optlist )
  448. #define sigmode (G_misc.sigmode )
  449. #define gotsig (G_misc.gotsig )
  450. #define may_have_traps (G_misc.may_have_traps )
  451. #define trap (G_misc.trap )
  452. #define trap_ptr (G_misc.trap_ptr )
  453. #define random_gen (G_misc.random_gen )
  454. #define backgndpid (G_misc.backgndpid )
  455. #define INIT_G_misc() do { \
  456. (*(struct globals_misc**)not_const_pp(&ash_ptr_to_globals_misc)) = xzalloc(sizeof(G_misc)); \
  457. barrier(); \
  458. savestatus = -1; \
  459. curdir = nullstr; \
  460. physdir = nullstr; \
  461. trap_ptr = trap; \
  462. } while (0)
  463. /* ============ DEBUG */
  464. #if DEBUG
  465. static void trace_printf(const char *fmt, ...);
  466. static void trace_vprintf(const char *fmt, va_list va);
  467. # define TRACE(param) trace_printf param
  468. # define TRACEV(param) trace_vprintf param
  469. # define close(fd) do { \
  470. int dfd = (fd); \
  471. if (close(dfd) < 0) \
  472. bb_error_msg("bug on %d: closing %d(0x%x)", \
  473. __LINE__, dfd, dfd); \
  474. } while (0)
  475. #else
  476. # define TRACE(param)
  477. # define TRACEV(param)
  478. #endif
  479. /* ============ Utility functions */
  480. #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
  481. #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
  482. static int
  483. isdigit_str9(const char *str)
  484. {
  485. int maxlen = 9 + 1; /* max 9 digits: 999999999 */
  486. while (--maxlen && isdigit(*str))
  487. str++;
  488. return (*str == '\0');
  489. }
  490. static const char *
  491. var_end(const char *var)
  492. {
  493. while (*var)
  494. if (*var++ == '=')
  495. break;
  496. return var;
  497. }
  498. /* ============ Interrupts / exceptions */
  499. static void exitshell(void) NORETURN;
  500. /*
  501. * These macros allow the user to suspend the handling of interrupt signals
  502. * over a period of time. This is similar to SIGHOLD or to sigblock, but
  503. * much more efficient and portable. (But hacking the kernel is so much
  504. * more fun than worrying about efficiency and portability. :-))
  505. */
  506. #if DEBUG_INTONOFF
  507. # define INT_OFF do { \
  508. TRACE(("%s:%d INT_OFF(%d)\n", __func__, __LINE__, suppress_int)); \
  509. suppress_int++; \
  510. barrier(); \
  511. } while (0)
  512. #else
  513. # define INT_OFF do { \
  514. suppress_int++; \
  515. barrier(); \
  516. } while (0)
  517. #endif
  518. /*
  519. * Called to raise an exception. Since C doesn't include exceptions, we
  520. * just do a longjmp to the exception handler. The type of exception is
  521. * stored in the global variable "exception_type".
  522. */
  523. static void raise_exception(int) NORETURN;
  524. static void
  525. raise_exception(int e)
  526. {
  527. #if DEBUG
  528. if (exception_handler == NULL)
  529. abort();
  530. #endif
  531. INT_OFF;
  532. exception_type = e;
  533. longjmp(exception_handler->loc, 1);
  534. }
  535. #if DEBUG
  536. #define raise_exception(e) do { \
  537. TRACE(("raising exception %d on line %d\n", (e), __LINE__)); \
  538. raise_exception(e); \
  539. } while (0)
  540. #endif
  541. /*
  542. * Called when a SIGINT is received. (If the user specifies
  543. * that SIGINT is to be trapped or ignored using the trap builtin, then
  544. * this routine is not called.) Suppressint is nonzero when interrupts
  545. * are held using the INT_OFF macro. (The test for iflag is just
  546. * defensive programming.)
  547. */
  548. static void raise_interrupt(void) NORETURN;
  549. static void
  550. raise_interrupt(void)
  551. {
  552. pending_int = 0;
  553. /* Signal is not automatically unmasked after it is raised,
  554. * do it ourself - unmask all signals */
  555. sigprocmask_allsigs(SIG_UNBLOCK);
  556. /* pending_sig = 0; - now done in signal_handler() */
  557. if (!(rootshell && iflag)) {
  558. /* Kill ourself with SIGINT */
  559. signal(SIGINT, SIG_DFL);
  560. raise(SIGINT);
  561. }
  562. /* bash: ^C even on empty command line sets $? */
  563. exitstatus = SIGINT + 128;
  564. raise_exception(EXINT);
  565. /* NOTREACHED */
  566. }
  567. #if DEBUG
  568. #define raise_interrupt() do { \
  569. TRACE(("raising interrupt on line %d\n", __LINE__)); \
  570. raise_interrupt(); \
  571. } while (0)
  572. #endif
  573. static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
  574. int_on(void)
  575. {
  576. barrier();
  577. if (--suppress_int == 0 && pending_int) {
  578. raise_interrupt();
  579. }
  580. }
  581. #if DEBUG_INTONOFF
  582. # define INT_ON do { \
  583. TRACE(("%s:%d INT_ON(%d)\n", __func__, __LINE__, suppress_int-1)); \
  584. int_on(); \
  585. } while (0)
  586. #else
  587. # define INT_ON int_on()
  588. #endif
  589. static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
  590. force_int_on(void)
  591. {
  592. barrier();
  593. suppress_int = 0;
  594. if (pending_int)
  595. raise_interrupt();
  596. }
  597. #define FORCE_INT_ON force_int_on()
  598. #define SAVE_INT(v) ((v) = suppress_int)
  599. #define RESTORE_INT(v) do { \
  600. barrier(); \
  601. suppress_int = (v); \
  602. if (suppress_int == 0 && pending_int) \
  603. raise_interrupt(); \
  604. } while (0)
  605. /* ============ Stdout/stderr output */
  606. static void
  607. outstr(const char *p, FILE *file)
  608. {
  609. INT_OFF;
  610. fputs(p, file);
  611. INT_ON;
  612. }
  613. static void
  614. flush_stdout_stderr(void)
  615. {
  616. INT_OFF;
  617. fflush_all();
  618. INT_ON;
  619. }
  620. /* Was called outcslow(c,FILE*), but c was always '\n' */
  621. static void
  622. newline_and_flush(FILE *dest)
  623. {
  624. INT_OFF;
  625. putc('\n', dest);
  626. fflush(dest);
  627. INT_ON;
  628. }
  629. static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
  630. static int
  631. out1fmt(const char *fmt, ...)
  632. {
  633. va_list ap;
  634. int r;
  635. INT_OFF;
  636. va_start(ap, fmt);
  637. r = vprintf(fmt, ap);
  638. va_end(ap);
  639. INT_ON;
  640. return r;
  641. }
  642. static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
  643. static int
  644. fmtstr(char *outbuf, size_t length, const char *fmt, ...)
  645. {
  646. va_list ap;
  647. int ret;
  648. INT_OFF;
  649. va_start(ap, fmt);
  650. ret = vsnprintf(outbuf, length, fmt, ap);
  651. va_end(ap);
  652. INT_ON;
  653. return ret > (int)length ? length : ret;
  654. }
  655. static void
  656. out1str(const char *p)
  657. {
  658. outstr(p, stdout);
  659. }
  660. static void
  661. out2str(const char *p)
  662. {
  663. outstr(p, stderr);
  664. flush_stdout_stderr();
  665. }
  666. /* ============ Parser structures */
  667. /* control characters in argument strings */
  668. #define CTL_FIRST CTLESC
  669. #define CTLESC ((unsigned char)'\201') /* escape next character */
  670. #define CTLVAR ((unsigned char)'\202') /* variable defn */
  671. #define CTLENDVAR ((unsigned char)'\203')
  672. #define CTLBACKQ ((unsigned char)'\204')
  673. #define CTLARI ((unsigned char)'\206') /* arithmetic expression */
  674. #define CTLENDARI ((unsigned char)'\207')
  675. #define CTLQUOTEMARK ((unsigned char)'\210')
  676. #define CTL_LAST CTLQUOTEMARK
  677. /* variable substitution byte (follows CTLVAR) */
  678. #define VSTYPE 0x0f /* type of variable substitution */
  679. #define VSNUL 0x10 /* colon--treat the empty string as unset */
  680. /* values of VSTYPE field */
  681. #define VSNORMAL 0x1 /* normal variable: $var or ${var} */
  682. #define VSMINUS 0x2 /* ${var-text} */
  683. #define VSPLUS 0x3 /* ${var+text} */
  684. #define VSQUESTION 0x4 /* ${var?message} */
  685. #define VSASSIGN 0x5 /* ${var=text} */
  686. #define VSTRIMRIGHT 0x6 /* ${var%pattern} */
  687. #define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
  688. #define VSTRIMLEFT 0x8 /* ${var#pattern} */
  689. #define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
  690. #define VSLENGTH 0xa /* ${#var} */
  691. #if BASH_SUBSTR
  692. #define VSSUBSTR 0xc /* ${var:position:length} */
  693. #endif
  694. #if BASH_PATTERN_SUBST
  695. #define VSREPLACE 0xd /* ${var/pattern/replacement} */
  696. #define VSREPLACEALL 0xe /* ${var//pattern/replacement} */
  697. #endif
  698. static const char dolatstr[] ALIGN1 = {
  699. CTLQUOTEMARK, CTLVAR, VSNORMAL, '@', '=', CTLQUOTEMARK, '\0'
  700. };
  701. #define DOLATSTRLEN 6
  702. #define NCMD 0
  703. #define NPIPE 1
  704. #define NREDIR 2
  705. #define NBACKGND 3
  706. #define NSUBSHELL 4
  707. #define NAND 5
  708. #define NOR 6
  709. #define NSEMI 7
  710. #define NIF 8
  711. #define NWHILE 9
  712. #define NUNTIL 10
  713. #define NFOR 11
  714. #define NCASE 12
  715. #define NCLIST 13
  716. #define NDEFUN 14
  717. #define NARG 15
  718. #define NTO 16
  719. #if BASH_REDIR_OUTPUT
  720. #define NTO2 17
  721. #endif
  722. #define NCLOBBER 18
  723. #define NFROM 19
  724. #define NFROMTO 20
  725. #define NAPPEND 21
  726. #define NTOFD 22
  727. #define NFROMFD 23
  728. #define NHERE 24
  729. #define NXHERE 25
  730. #define NNOT 26
  731. #define N_NUMBER 27
  732. union node;
  733. struct ncmd {
  734. smallint type; /* Nxxxx */
  735. int linno;
  736. union node *assign;
  737. union node *args;
  738. union node *redirect;
  739. };
  740. struct npipe {
  741. smallint type;
  742. smallint pipe_backgnd;
  743. struct nodelist *cmdlist;
  744. };
  745. struct nredir {
  746. smallint type;
  747. int linno;
  748. union node *n;
  749. union node *redirect;
  750. };
  751. struct nbinary {
  752. smallint type;
  753. union node *ch1;
  754. union node *ch2;
  755. };
  756. struct nif {
  757. smallint type;
  758. union node *test;
  759. union node *ifpart;
  760. union node *elsepart;
  761. };
  762. struct nfor {
  763. smallint type;
  764. int linno;
  765. union node *args;
  766. union node *body;
  767. char *var;
  768. };
  769. struct ncase {
  770. smallint type;
  771. int linno;
  772. union node *expr;
  773. union node *cases;
  774. };
  775. struct nclist {
  776. smallint type;
  777. union node *next;
  778. union node *pattern;
  779. union node *body;
  780. };
  781. struct ndefun {
  782. smallint type;
  783. int linno;
  784. char *text;
  785. union node *body;
  786. };
  787. struct narg {
  788. smallint type;
  789. union node *next;
  790. char *text;
  791. struct nodelist *backquote;
  792. };
  793. /* nfile and ndup layout must match!
  794. * NTOFD (>&fdnum) uses ndup structure, but we may discover mid-flight
  795. * that it is actually NTO2 (>&file), and change its type.
  796. */
  797. struct nfile {
  798. smallint type;
  799. union node *next;
  800. int fd;
  801. int _unused_dupfd;
  802. union node *fname;
  803. char *expfname;
  804. };
  805. struct ndup {
  806. smallint type;
  807. union node *next;
  808. int fd;
  809. int dupfd;
  810. union node *vname;
  811. char *_unused_expfname;
  812. };
  813. struct nhere {
  814. smallint type;
  815. union node *next;
  816. int fd;
  817. union node *doc;
  818. };
  819. struct nnot {
  820. smallint type;
  821. union node *com;
  822. };
  823. union node {
  824. smallint type;
  825. struct ncmd ncmd;
  826. struct npipe npipe;
  827. struct nredir nredir;
  828. struct nbinary nbinary;
  829. struct nif nif;
  830. struct nfor nfor;
  831. struct ncase ncase;
  832. struct nclist nclist;
  833. struct ndefun ndefun;
  834. struct narg narg;
  835. struct nfile nfile;
  836. struct ndup ndup;
  837. struct nhere nhere;
  838. struct nnot nnot;
  839. };
  840. /*
  841. * NODE_EOF is returned by parsecmd when it encounters an end of file.
  842. * It must be distinct from NULL.
  843. */
  844. #define NODE_EOF ((union node *) -1L)
  845. struct nodelist {
  846. struct nodelist *next;
  847. union node *n;
  848. };
  849. struct funcnode {
  850. int count;
  851. union node n;
  852. };
  853. /*
  854. * Free a parse tree.
  855. */
  856. static void
  857. freefunc(struct funcnode *f)
  858. {
  859. if (f && --f->count < 0)
  860. free(f);
  861. }
  862. /* ============ Debugging output */
  863. #if DEBUG
  864. static FILE *tracefile;
  865. static void
  866. trace_printf(const char *fmt, ...)
  867. {
  868. va_list va;
  869. if (debug != 1)
  870. return;
  871. if (DEBUG_TIME)
  872. fprintf(tracefile, "%u ", (int) time(NULL));
  873. if (DEBUG_PID)
  874. fprintf(tracefile, "[%u] ", (int) getpid());
  875. if (DEBUG_SIG)
  876. fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
  877. va_start(va, fmt);
  878. vfprintf(tracefile, fmt, va);
  879. va_end(va);
  880. }
  881. static void
  882. trace_vprintf(const char *fmt, va_list va)
  883. {
  884. if (debug != 1)
  885. return;
  886. vfprintf(tracefile, fmt, va);
  887. fprintf(tracefile, "\n");
  888. }
  889. static void
  890. trace_puts(const char *s)
  891. {
  892. if (debug != 1)
  893. return;
  894. fputs(s, tracefile);
  895. }
  896. static void
  897. trace_puts_quoted(char *s)
  898. {
  899. char *p;
  900. char c;
  901. if (debug != 1)
  902. return;
  903. putc('"', tracefile);
  904. for (p = s; *p; p++) {
  905. switch ((unsigned char)*p) {
  906. case '\n': c = 'n'; goto backslash;
  907. case '\t': c = 't'; goto backslash;
  908. case '\r': c = 'r'; goto backslash;
  909. case '\"': c = '\"'; goto backslash;
  910. case '\\': c = '\\'; goto backslash;
  911. case CTLESC: c = 'e'; goto backslash;
  912. case CTLVAR: c = 'v'; goto backslash;
  913. case CTLBACKQ: c = 'q'; goto backslash;
  914. backslash:
  915. putc('\\', tracefile);
  916. putc(c, tracefile);
  917. break;
  918. default:
  919. if (*p >= ' ' && *p <= '~')
  920. putc(*p, tracefile);
  921. else {
  922. putc('\\', tracefile);
  923. putc((*p >> 6) & 03, tracefile);
  924. putc((*p >> 3) & 07, tracefile);
  925. putc(*p & 07, tracefile);
  926. }
  927. break;
  928. }
  929. }
  930. putc('"', tracefile);
  931. }
  932. static void
  933. trace_puts_args(char **ap)
  934. {
  935. if (debug != 1)
  936. return;
  937. if (!*ap)
  938. return;
  939. while (1) {
  940. trace_puts_quoted(*ap);
  941. if (!*++ap) {
  942. putc('\n', tracefile);
  943. break;
  944. }
  945. putc(' ', tracefile);
  946. }
  947. }
  948. static void
  949. opentrace(void)
  950. {
  951. char s[100];
  952. #ifdef O_APPEND
  953. int flags;
  954. #endif
  955. if (debug != 1) {
  956. if (tracefile)
  957. fflush(tracefile);
  958. /* leave open because libedit might be using it */
  959. return;
  960. }
  961. strcpy(s, "./trace");
  962. if (tracefile) {
  963. if (!freopen(s, "a", tracefile)) {
  964. fprintf(stderr, "Can't re-open %s\n", s);
  965. debug = 0;
  966. return;
  967. }
  968. } else {
  969. tracefile = fopen(s, "a");
  970. if (tracefile == NULL) {
  971. fprintf(stderr, "Can't open %s\n", s);
  972. debug = 0;
  973. return;
  974. }
  975. }
  976. #ifdef O_APPEND
  977. flags = fcntl(fileno(tracefile), F_GETFL);
  978. if (flags >= 0)
  979. fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
  980. #endif
  981. setlinebuf(tracefile);
  982. fputs("\nTracing started.\n", tracefile);
  983. }
  984. static void
  985. indent(int amount, char *pfx, FILE *fp)
  986. {
  987. int i;
  988. for (i = 0; i < amount; i++) {
  989. if (pfx && i == amount - 1)
  990. fputs(pfx, fp);
  991. putc('\t', fp);
  992. }
  993. }
  994. /* little circular references here... */
  995. static void shtree(union node *n, int ind, char *pfx, FILE *fp);
  996. static void
  997. sharg(union node *arg, FILE *fp)
  998. {
  999. char *p;
  1000. struct nodelist *bqlist;
  1001. unsigned char subtype;
  1002. if (arg->type != NARG) {
  1003. out1fmt("<node type %d>\n", arg->type);
  1004. abort();
  1005. }
  1006. bqlist = arg->narg.backquote;
  1007. for (p = arg->narg.text; *p; p++) {
  1008. switch ((unsigned char)*p) {
  1009. case CTLESC:
  1010. p++;
  1011. putc(*p, fp);
  1012. break;
  1013. case CTLVAR:
  1014. putc('$', fp);
  1015. putc('{', fp);
  1016. subtype = *++p;
  1017. if (subtype == VSLENGTH)
  1018. putc('#', fp);
  1019. while (*p != '=') {
  1020. putc(*p, fp);
  1021. p++;
  1022. }
  1023. if (subtype & VSNUL)
  1024. putc(':', fp);
  1025. switch (subtype & VSTYPE) {
  1026. case VSNORMAL:
  1027. putc('}', fp);
  1028. break;
  1029. case VSMINUS:
  1030. putc('-', fp);
  1031. break;
  1032. case VSPLUS:
  1033. putc('+', fp);
  1034. break;
  1035. case VSQUESTION:
  1036. putc('?', fp);
  1037. break;
  1038. case VSASSIGN:
  1039. putc('=', fp);
  1040. break;
  1041. case VSTRIMLEFT:
  1042. putc('#', fp);
  1043. break;
  1044. case VSTRIMLEFTMAX:
  1045. putc('#', fp);
  1046. putc('#', fp);
  1047. break;
  1048. case VSTRIMRIGHT:
  1049. putc('%', fp);
  1050. break;
  1051. case VSTRIMRIGHTMAX:
  1052. putc('%', fp);
  1053. putc('%', fp);
  1054. break;
  1055. case VSLENGTH:
  1056. break;
  1057. default:
  1058. out1fmt("<subtype %d>", subtype);
  1059. }
  1060. break;
  1061. case CTLENDVAR:
  1062. putc('}', fp);
  1063. break;
  1064. case CTLBACKQ:
  1065. putc('$', fp);
  1066. putc('(', fp);
  1067. shtree(bqlist->n, -1, NULL, fp);
  1068. putc(')', fp);
  1069. break;
  1070. default:
  1071. putc(*p, fp);
  1072. break;
  1073. }
  1074. }
  1075. }
  1076. static void
  1077. shcmd(union node *cmd, FILE *fp)
  1078. {
  1079. union node *np;
  1080. int first;
  1081. const char *s;
  1082. int dftfd;
  1083. first = 1;
  1084. for (np = cmd->ncmd.args; np; np = np->narg.next) {
  1085. if (!first)
  1086. putc(' ', fp);
  1087. sharg(np, fp);
  1088. first = 0;
  1089. }
  1090. for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
  1091. if (!first)
  1092. putc(' ', fp);
  1093. dftfd = 0;
  1094. switch (np->nfile.type) {
  1095. case NTO: s = ">>"+1; dftfd = 1; break;
  1096. case NCLOBBER: s = ">|"; dftfd = 1; break;
  1097. case NAPPEND: s = ">>"; dftfd = 1; break;
  1098. #if BASH_REDIR_OUTPUT
  1099. case NTO2:
  1100. #endif
  1101. case NTOFD: s = ">&"; dftfd = 1; break;
  1102. case NFROM: s = "<"; break;
  1103. case NFROMFD: s = "<&"; break;
  1104. case NFROMTO: s = "<>"; break;
  1105. default: s = "*error*"; break;
  1106. }
  1107. if (np->nfile.fd != dftfd)
  1108. fprintf(fp, "%d", np->nfile.fd);
  1109. fputs(s, fp);
  1110. if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
  1111. fprintf(fp, "%d", np->ndup.dupfd);
  1112. } else {
  1113. sharg(np->nfile.fname, fp);
  1114. }
  1115. first = 0;
  1116. }
  1117. }
  1118. static void
  1119. shtree(union node *n, int ind, char *pfx, FILE *fp)
  1120. {
  1121. struct nodelist *lp;
  1122. const char *s;
  1123. if (n == NULL)
  1124. return;
  1125. indent(ind, pfx, fp);
  1126. if (n == NODE_EOF) {
  1127. fputs("<EOF>", fp);
  1128. return;
  1129. }
  1130. switch (n->type) {
  1131. case NSEMI:
  1132. s = "; ";
  1133. goto binop;
  1134. case NAND:
  1135. s = " && ";
  1136. goto binop;
  1137. case NOR:
  1138. s = " || ";
  1139. binop:
  1140. shtree(n->nbinary.ch1, ind, NULL, fp);
  1141. /* if (ind < 0) */
  1142. fputs(s, fp);
  1143. shtree(n->nbinary.ch2, ind, NULL, fp);
  1144. break;
  1145. case NCMD:
  1146. shcmd(n, fp);
  1147. if (ind >= 0)
  1148. putc('\n', fp);
  1149. break;
  1150. case NPIPE:
  1151. for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
  1152. shtree(lp->n, 0, NULL, fp);
  1153. if (lp->next)
  1154. fputs(" | ", fp);
  1155. }
  1156. if (n->npipe.pipe_backgnd)
  1157. fputs(" &", fp);
  1158. if (ind >= 0)
  1159. putc('\n', fp);
  1160. break;
  1161. default:
  1162. fprintf(fp, "<node type %d>", n->type);
  1163. if (ind >= 0)
  1164. putc('\n', fp);
  1165. break;
  1166. }
  1167. }
  1168. static void
  1169. showtree(union node *n)
  1170. {
  1171. trace_puts("showtree called\n");
  1172. shtree(n, 1, NULL, stderr);
  1173. }
  1174. #endif /* DEBUG */
  1175. /* ============ Parser data */
  1176. /*
  1177. * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
  1178. */
  1179. struct strlist {
  1180. struct strlist *next;
  1181. char *text;
  1182. };
  1183. struct alias;
  1184. struct strpush {
  1185. struct strpush *prev; /* preceding string on stack */
  1186. char *prev_string;
  1187. int prev_left_in_line;
  1188. #if ENABLE_ASH_ALIAS
  1189. struct alias *ap; /* if push was associated with an alias */
  1190. #endif
  1191. char *string; /* remember the string since it may change */
  1192. /* Remember last two characters for pungetc. */
  1193. int lastc[2];
  1194. /* Number of outstanding calls to pungetc. */
  1195. int unget;
  1196. };
  1197. /*
  1198. * The parsefile structure pointed to by the global variable parsefile
  1199. * contains information about the current file being read.
  1200. */
  1201. struct parsefile {
  1202. struct parsefile *prev; /* preceding file on stack */
  1203. int linno; /* current line */
  1204. int pf_fd; /* file descriptor (or -1 if string) */
  1205. int left_in_line; /* number of chars left in this line */
  1206. int left_in_buffer; /* number of chars left in this buffer past the line */
  1207. char *next_to_pgetc; /* next char in buffer */
  1208. char *buf; /* input buffer */
  1209. struct strpush *strpush; /* for pushing strings at this level */
  1210. struct strpush basestrpush; /* so pushing one is fast */
  1211. /* Remember last two characters for pungetc. */
  1212. int lastc[2];
  1213. /* Number of outstanding calls to pungetc. */
  1214. int unget;
  1215. };
  1216. static struct parsefile basepf; /* top level input file */
  1217. static struct parsefile *g_parsefile = &basepf; /* current input file */
  1218. static char *commandname; /* currently executing command */
  1219. /* ============ Message printing */
  1220. static void
  1221. ash_vmsg(const char *msg, va_list ap)
  1222. {
  1223. fprintf(stderr, "%s: ", arg0);
  1224. if (commandname) {
  1225. if (strcmp(arg0, commandname))
  1226. fprintf(stderr, "%s: ", commandname);
  1227. if (!iflag || g_parsefile->pf_fd > 0)
  1228. fprintf(stderr, "line %d: ", errlinno);
  1229. }
  1230. vfprintf(stderr, msg, ap);
  1231. newline_and_flush(stderr);
  1232. }
  1233. /*
  1234. * Exverror is called to raise the error exception. If the second argument
  1235. * is not NULL then error prints an error message using printf style
  1236. * formatting. It then raises the error exception.
  1237. */
  1238. static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
  1239. static void
  1240. ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
  1241. {
  1242. #if DEBUG
  1243. if (msg) {
  1244. TRACE(("ash_vmsg_and_raise(%d):", cond));
  1245. TRACEV((msg, ap));
  1246. } else
  1247. TRACE(("ash_vmsg_and_raise(%d):NULL\n", cond));
  1248. if (msg)
  1249. #endif
  1250. ash_vmsg(msg, ap);
  1251. flush_stdout_stderr();
  1252. raise_exception(cond);
  1253. /* NOTREACHED */
  1254. }
  1255. static void ash_msg_and_raise_error(const char *, ...) NORETURN;
  1256. static void
  1257. ash_msg_and_raise_error(const char *msg, ...)
  1258. {
  1259. va_list ap;
  1260. exitstatus = 2;
  1261. va_start(ap, msg);
  1262. ash_vmsg_and_raise(EXERROR, msg, ap);
  1263. /* NOTREACHED */
  1264. va_end(ap);
  1265. }
  1266. /*
  1267. * 'fmt' must be a string literal.
  1268. */
  1269. #define ash_msg_and_raise_perror(fmt, ...) ash_msg_and_raise_error(fmt ": "STRERROR_FMT, ##__VA_ARGS__ STRERROR_ERRNO)
  1270. static void raise_error_syntax(const char *) NORETURN;
  1271. static void
  1272. raise_error_syntax(const char *msg)
  1273. {
  1274. errlinno = g_parsefile->linno;
  1275. ash_msg_and_raise_error("syntax error: %s", msg);
  1276. /* NOTREACHED */
  1277. }
  1278. static void ash_msg_and_raise(int, const char *, ...) NORETURN;
  1279. static void
  1280. ash_msg_and_raise(int cond, const char *msg, ...)
  1281. {
  1282. va_list ap;
  1283. va_start(ap, msg);
  1284. ash_vmsg_and_raise(cond, msg, ap);
  1285. /* NOTREACHED */
  1286. va_end(ap);
  1287. }
  1288. /*
  1289. * error/warning routines for external builtins
  1290. */
  1291. static void
  1292. ash_msg(const char *fmt, ...)
  1293. {
  1294. va_list ap;
  1295. va_start(ap, fmt);
  1296. ash_vmsg(fmt, ap);
  1297. va_end(ap);
  1298. }
  1299. /*
  1300. * Return a string describing an error. The returned string may be a
  1301. * pointer to a static buffer that will be overwritten on the next call.
  1302. * Action describes the operation that got the error.
  1303. */
  1304. static const char *
  1305. errmsg(int e, const char *em)
  1306. {
  1307. if (e == ENOENT || e == ENOTDIR) {
  1308. return em;
  1309. }
  1310. return strerror(e);
  1311. }
  1312. /* ============ Memory allocation */
  1313. #if 0
  1314. /* I consider these wrappers nearly useless:
  1315. * ok, they return you to nearest exception handler, but
  1316. * how much memory do you leak in the process, making
  1317. * memory starvation worse?
  1318. */
  1319. static void *
  1320. ckrealloc(void * p, size_t nbytes)
  1321. {
  1322. p = realloc(p, nbytes);
  1323. if (!p)
  1324. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  1325. return p;
  1326. }
  1327. static void *
  1328. ckmalloc(size_t nbytes)
  1329. {
  1330. return ckrealloc(NULL, nbytes);
  1331. }
  1332. static void *
  1333. ckzalloc(size_t nbytes)
  1334. {
  1335. return memset(ckmalloc(nbytes), 0, nbytes);
  1336. }
  1337. static char *
  1338. ckstrdup(const char *s)
  1339. {
  1340. char *p = strdup(s);
  1341. if (!p)
  1342. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  1343. return p;
  1344. }
  1345. #else
  1346. /* Using bbox equivalents. They exit if out of memory */
  1347. # define ckrealloc xrealloc
  1348. # define ckmalloc xmalloc
  1349. # define ckzalloc xzalloc
  1350. # define ckstrdup xstrdup
  1351. #endif
  1352. /*
  1353. * It appears that grabstackstr() will barf with such alignments
  1354. * because stalloc() will return a string allocated in a new stackblock.
  1355. */
  1356. #define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
  1357. enum {
  1358. /* Most machines require the value returned from malloc to be aligned
  1359. * in some way. The following macro will get this right
  1360. * on many machines. */
  1361. SHELL_SIZE = sizeof(union { int i; char *cp; double d; }) - 1,
  1362. /* Minimum size of a block */
  1363. MINSIZE = SHELL_ALIGN(504),
  1364. };
  1365. struct stack_block {
  1366. struct stack_block *prev;
  1367. char space[MINSIZE];
  1368. };
  1369. struct stackmark {
  1370. struct stack_block *stackp;
  1371. char *stacknxt;
  1372. size_t stacknleft;
  1373. };
  1374. struct globals_memstack {
  1375. struct stack_block *g_stackp; // = &stackbase;
  1376. char *g_stacknxt; // = stackbase.space;
  1377. char *sstrend; // = stackbase.space + MINSIZE;
  1378. size_t g_stacknleft; // = MINSIZE;
  1379. struct stack_block stackbase;
  1380. };
  1381. extern struct globals_memstack *BB_GLOBAL_CONST ash_ptr_to_globals_memstack;
  1382. #define G_memstack (*ash_ptr_to_globals_memstack)
  1383. #define g_stackp (G_memstack.g_stackp )
  1384. #define g_stacknxt (G_memstack.g_stacknxt )
  1385. #define sstrend (G_memstack.sstrend )
  1386. #define g_stacknleft (G_memstack.g_stacknleft)
  1387. #define stackbase (G_memstack.stackbase )
  1388. #define INIT_G_memstack() do { \
  1389. (*(struct globals_memstack**)not_const_pp(&ash_ptr_to_globals_memstack)) = xzalloc(sizeof(G_memstack)); \
  1390. barrier(); \
  1391. g_stackp = &stackbase; \
  1392. g_stacknxt = stackbase.space; \
  1393. g_stacknleft = MINSIZE; \
  1394. sstrend = stackbase.space + MINSIZE; \
  1395. } while (0)
  1396. #define stackblock() ((void *)g_stacknxt)
  1397. #define stackblocksize() g_stacknleft
  1398. /*
  1399. * Parse trees for commands are allocated in lifo order, so we use a stack
  1400. * to make this more efficient, and also to avoid all sorts of exception
  1401. * handling code to handle interrupts in the middle of a parse.
  1402. *
  1403. * The size 504 was chosen because the Ultrix malloc handles that size
  1404. * well.
  1405. */
  1406. static void *
  1407. stalloc(size_t nbytes)
  1408. {
  1409. char *p;
  1410. size_t aligned;
  1411. aligned = SHELL_ALIGN(nbytes);
  1412. if (aligned > g_stacknleft) {
  1413. size_t len;
  1414. size_t blocksize;
  1415. struct stack_block *sp;
  1416. blocksize = aligned;
  1417. if (blocksize < MINSIZE)
  1418. blocksize = MINSIZE;
  1419. len = sizeof(struct stack_block) - MINSIZE + blocksize;
  1420. if (len < blocksize)
  1421. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  1422. INT_OFF;
  1423. sp = ckmalloc(len);
  1424. sp->prev = g_stackp;
  1425. g_stacknxt = sp->space;
  1426. g_stacknleft = blocksize;
  1427. sstrend = g_stacknxt + blocksize;
  1428. g_stackp = sp;
  1429. INT_ON;
  1430. }
  1431. p = g_stacknxt;
  1432. g_stacknxt += aligned;
  1433. g_stacknleft -= aligned;
  1434. return p;
  1435. }
  1436. static void *
  1437. stzalloc(size_t nbytes)
  1438. {
  1439. return memset(stalloc(nbytes), 0, nbytes);
  1440. }
  1441. static void
  1442. stunalloc(void *p)
  1443. {
  1444. #if DEBUG
  1445. if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
  1446. write(STDERR_FILENO, "stunalloc\n", 10);
  1447. abort();
  1448. }
  1449. #endif
  1450. g_stacknleft += g_stacknxt - (char *)p;
  1451. g_stacknxt = p;
  1452. }
  1453. /*
  1454. * Like strdup but works with the ash stack.
  1455. */
  1456. static char *
  1457. sstrdup(const char *p)
  1458. {
  1459. size_t len = strlen(p) + 1;
  1460. return memcpy(stalloc(len), p, len);
  1461. }
  1462. static ALWAYS_INLINE void
  1463. grabstackblock(size_t len)
  1464. {
  1465. stalloc(len);
  1466. }
  1467. static void
  1468. pushstackmark(struct stackmark *mark, size_t len)
  1469. {
  1470. mark->stackp = g_stackp;
  1471. mark->stacknxt = g_stacknxt;
  1472. mark->stacknleft = g_stacknleft;
  1473. grabstackblock(len);
  1474. }
  1475. static void
  1476. setstackmark(struct stackmark *mark)
  1477. {
  1478. pushstackmark(mark, g_stacknxt == g_stackp->space && g_stackp != &stackbase);
  1479. }
  1480. static void
  1481. popstackmark(struct stackmark *mark)
  1482. {
  1483. struct stack_block *sp;
  1484. if (!mark->stackp)
  1485. return;
  1486. INT_OFF;
  1487. while (g_stackp != mark->stackp) {
  1488. sp = g_stackp;
  1489. g_stackp = sp->prev;
  1490. free(sp);
  1491. }
  1492. g_stacknxt = mark->stacknxt;
  1493. g_stacknleft = mark->stacknleft;
  1494. sstrend = mark->stacknxt + mark->stacknleft;
  1495. INT_ON;
  1496. }
  1497. /*
  1498. * When the parser reads in a string, it wants to stick the string on the
  1499. * stack and only adjust the stack pointer when it knows how big the
  1500. * string is. Stackblock (defined in stack.h) returns a pointer to a block
  1501. * of space on top of the stack and stackblocklen returns the length of
  1502. * this block. Growstackblock will grow this space by at least one byte,
  1503. * possibly moving it (like realloc). Grabstackblock actually allocates the
  1504. * part of the block that has been used.
  1505. */
  1506. static void
  1507. growstackblock(size_t min)
  1508. {
  1509. size_t newlen;
  1510. newlen = g_stacknleft * 2;
  1511. if (newlen < g_stacknleft)
  1512. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  1513. min = SHELL_ALIGN(min | 128);
  1514. if (newlen < min)
  1515. newlen += min;
  1516. if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
  1517. struct stack_block *sp;
  1518. struct stack_block *prevstackp;
  1519. size_t grosslen;
  1520. INT_OFF;
  1521. sp = g_stackp;
  1522. prevstackp = sp->prev;
  1523. grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
  1524. sp = ckrealloc(sp, grosslen);
  1525. sp->prev = prevstackp;
  1526. g_stackp = sp;
  1527. g_stacknxt = sp->space;
  1528. g_stacknleft = newlen;
  1529. sstrend = sp->space + newlen;
  1530. INT_ON;
  1531. } else {
  1532. char *oldspace = g_stacknxt;
  1533. size_t oldlen = g_stacknleft;
  1534. char *p = stalloc(newlen);
  1535. /* free the space we just allocated */
  1536. g_stacknxt = memcpy(p, oldspace, oldlen);
  1537. g_stacknleft += newlen;
  1538. }
  1539. }
  1540. /*
  1541. * The following routines are somewhat easier to use than the above.
  1542. * The user declares a variable of type STACKSTR, which may be declared
  1543. * to be a register. The macro STARTSTACKSTR initializes things. Then
  1544. * the user uses the macro STPUTC to add characters to the string. In
  1545. * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
  1546. * grown as necessary. When the user is done, she can just leave the
  1547. * string there and refer to it using stackblock(). Or she can allocate
  1548. * the space for it using grabstackstr(). If it is necessary to allow
  1549. * someone else to use the stack temporarily and then continue to grow
  1550. * the string, the user should use grabstack to allocate the space, and
  1551. * then call ungrabstr(p) to return to the previous mode of operation.
  1552. *
  1553. * USTPUTC is like STPUTC except that it doesn't check for overflow.
  1554. * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
  1555. * is space for at least one character.
  1556. */
  1557. static void *
  1558. growstackstr(void)
  1559. {
  1560. size_t len = stackblocksize();
  1561. growstackblock(0);
  1562. return (char *)stackblock() + len;
  1563. }
  1564. static char *
  1565. growstackto(size_t len)
  1566. {
  1567. if (stackblocksize() < len)
  1568. growstackblock(len);
  1569. return stackblock();
  1570. }
  1571. /*
  1572. * Called from CHECKSTRSPACE.
  1573. */
  1574. static char *
  1575. makestrspace(size_t newlen, char *p)
  1576. {
  1577. size_t len = p - g_stacknxt;
  1578. return growstackto(len + newlen) + len;
  1579. }
  1580. static char *
  1581. stnputs(const char *s, size_t n, char *p)
  1582. {
  1583. p = makestrspace(n, p);
  1584. p = (char *)mempcpy(p, s, n);
  1585. return p;
  1586. }
  1587. static char *
  1588. stack_putstr(const char *s, char *p)
  1589. {
  1590. return stnputs(s, strlen(s), p);
  1591. }
  1592. static char *
  1593. _STPUTC(int c, char *p)
  1594. {
  1595. if (p == sstrend)
  1596. p = growstackstr();
  1597. *p++ = c;
  1598. return p;
  1599. }
  1600. #define STARTSTACKSTR(p) ((p) = stackblock())
  1601. #define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
  1602. #define CHECKSTRSPACE(n, p) do { \
  1603. char *q = (p); \
  1604. size_t l = (n); \
  1605. size_t m = sstrend - q; \
  1606. if (l > m) \
  1607. (p) = makestrspace(l, q); \
  1608. } while (0)
  1609. #define USTPUTC(c, p) (*(p)++ = (c))
  1610. #define STACKSTRNUL(p) do { \
  1611. if ((p) == sstrend) \
  1612. (p) = growstackstr(); \
  1613. *(p) = '\0'; \
  1614. } while (0)
  1615. #define STUNPUTC(p) (--(p))
  1616. #define STTOPC(p) ((p)[-1])
  1617. #define STADJUST(amount, p) ((p) += (amount))
  1618. #define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
  1619. #define ungrabstackstr(s, p) stunalloc(s)
  1620. #define stackstrend() ((void *)sstrend)
  1621. /* ============ String helpers */
  1622. /*
  1623. * prefix -- see if pfx is a prefix of string.
  1624. */
  1625. static char *
  1626. prefix(const char *string, const char *pfx)
  1627. {
  1628. while (*pfx) {
  1629. if (*pfx++ != *string++)
  1630. return NULL;
  1631. }
  1632. return (char *) string;
  1633. }
  1634. /*
  1635. * Check for a valid number. This should be elsewhere.
  1636. */
  1637. static int
  1638. is_number(const char *p)
  1639. {
  1640. do {
  1641. if (!isdigit(*p))
  1642. return 0;
  1643. } while (*++p != '\0');
  1644. return 1;
  1645. }
  1646. /*
  1647. * Convert a string of digits to an integer, printing an error message on
  1648. * failure.
  1649. */
  1650. static int
  1651. number(const char *s)
  1652. {
  1653. if (!is_number(s))
  1654. ash_msg_and_raise_error(msg_illnum, s);
  1655. return atoi(s);
  1656. }
  1657. /*
  1658. * Produce a single quoted string suitable as input to the shell.
  1659. * The return string is allocated on the stack.
  1660. */
  1661. static char *
  1662. single_quote(const char *s)
  1663. {
  1664. char *p;
  1665. STARTSTACKSTR(p);
  1666. do {
  1667. char *q;
  1668. size_t len;
  1669. len = strchrnul(s, '\'') - s;
  1670. q = p = makestrspace(len + 3, p);
  1671. *q++ = '\'';
  1672. q = (char *)mempcpy(q, s, len);
  1673. *q++ = '\'';
  1674. s += len;
  1675. STADJUST(q - p, p);
  1676. if (*s != '\'')
  1677. break;
  1678. len = 0;
  1679. do len++; while (*++s == '\'');
  1680. q = p = makestrspace(len + 3, p);
  1681. *q++ = '"';
  1682. q = (char *)mempcpy(q, s - len, len);
  1683. *q++ = '"';
  1684. STADJUST(q - p, p);
  1685. } while (*s);
  1686. USTPUTC('\0', p);
  1687. return stackblock();
  1688. }
  1689. /*
  1690. * Produce a possibly single quoted string suitable as input to the shell.
  1691. * If quoting was done, the return string is allocated on the stack,
  1692. * otherwise a pointer to the original string is returned.
  1693. */
  1694. static const char *
  1695. maybe_single_quote(const char *s)
  1696. {
  1697. const char *p = s;
  1698. while (*p) {
  1699. /* Assuming ACSII */
  1700. /* quote ctrl_chars space !"#$%&'()* */
  1701. if (*p < '+')
  1702. goto need_quoting;
  1703. /* quote ;<=>? */
  1704. if (*p >= ';' && *p <= '?')
  1705. goto need_quoting;
  1706. /* quote `[\ */
  1707. if (*p == '`')
  1708. goto need_quoting;
  1709. if (*p == '[')
  1710. goto need_quoting;
  1711. if (*p == '\\')
  1712. goto need_quoting;
  1713. /* quote {|}~ DEL and high bytes */
  1714. if (*p > 'z')
  1715. goto need_quoting;
  1716. /* Not quoting these: +,-./ 0-9 :@ A-Z ]^_ a-z */
  1717. /* TODO: maybe avoid quoting % */
  1718. p++;
  1719. }
  1720. return s;
  1721. need_quoting:
  1722. return single_quote(s);
  1723. }
  1724. /* ============ nextopt */
  1725. static char **argptr; /* argument list for builtin commands */
  1726. static char *optionarg; /* set by nextopt (like getopt) */
  1727. static char *optptr; /* used by nextopt */
  1728. /*
  1729. * XXX - should get rid of. Have all builtins use getopt(3).
  1730. * The library getopt must have the BSD extension static variable
  1731. * "optreset", otherwise it can't be used within the shell safely.
  1732. *
  1733. * Standard option processing (a la getopt) for builtin routines.
  1734. * The only argument that is passed to nextopt is the option string;
  1735. * the other arguments are unnecessary. It returns the character,
  1736. * or '\0' on end of input.
  1737. */
  1738. static int
  1739. nextopt(const char *optstring)
  1740. {
  1741. char *p;
  1742. const char *q;
  1743. char c;
  1744. p = optptr;
  1745. if (p == NULL || *p == '\0') {
  1746. /* We ate entire "-param", take next one */
  1747. p = *argptr;
  1748. if (p == NULL)
  1749. return '\0';
  1750. if (*p != '-')
  1751. return '\0';
  1752. if (*++p == '\0') /* just "-" ? */
  1753. return '\0';
  1754. argptr++;
  1755. if (LONE_DASH(p)) /* "--" ? */
  1756. return '\0';
  1757. /* p => next "-param" */
  1758. }
  1759. /* p => some option char in the middle of a "-param" */
  1760. c = *p++;
  1761. for (q = optstring; *q != c;) {
  1762. if (*q == '\0')
  1763. ash_msg_and_raise_error("illegal option -%c", c);
  1764. if (*++q == ':')
  1765. q++;
  1766. }
  1767. if (*++q == ':') {
  1768. if (*p == '\0') {
  1769. p = *argptr++;
  1770. if (p == NULL)
  1771. ash_msg_and_raise_error("no arg for -%c option", c);
  1772. }
  1773. optionarg = p;
  1774. p = NULL;
  1775. }
  1776. optptr = p;
  1777. return c;
  1778. }
  1779. /* ============ Shell variables */
  1780. struct shparam {
  1781. int nparam; /* # of positional parameters (without $0) */
  1782. #if ENABLE_ASH_GETOPTS
  1783. int optind; /* next parameter to be processed by getopts */
  1784. int optoff; /* used by getopts */
  1785. #endif
  1786. unsigned char malloced; /* if parameter list dynamically allocated */
  1787. char **p; /* parameter list */
  1788. };
  1789. /*
  1790. * Free the list of positional parameters.
  1791. */
  1792. static void
  1793. freeparam(volatile struct shparam *param)
  1794. {
  1795. if (param->malloced) {
  1796. char **ap, **ap1;
  1797. ap = ap1 = param->p;
  1798. while (*ap)
  1799. free(*ap++);
  1800. free(ap1);
  1801. }
  1802. }
  1803. #if ENABLE_ASH_GETOPTS
  1804. static void FAST_FUNC getoptsreset(const char *value);
  1805. #endif
  1806. struct var {
  1807. struct var *next; /* next entry in hash list */
  1808. int flags; /* flags are defined above */
  1809. const char *var_text; /* name=value */
  1810. void (*var_func)(const char *) FAST_FUNC; /* function to be called when */
  1811. /* the variable gets set/unset */
  1812. };
  1813. struct localvar {
  1814. struct localvar *next; /* next local variable in list */
  1815. struct var *vp; /* the variable that was made local */
  1816. int flags; /* saved flags */
  1817. const char *text; /* saved text */
  1818. };
  1819. /* flags */
  1820. #define VEXPORT 0x01 /* variable is exported */
  1821. #define VREADONLY 0x02 /* variable cannot be modified */
  1822. #define VSTRFIXED 0x04 /* variable struct is statically allocated */
  1823. #define VTEXTFIXED 0x08 /* text is statically allocated */
  1824. #define VSTACK 0x10 /* text is allocated on the stack */
  1825. #define VUNSET 0x20 /* the variable is not set */
  1826. #define VNOFUNC 0x40 /* don't call the callback function */
  1827. #define VNOSET 0x80 /* do not set variable - just readonly test */
  1828. #define VNOSAVE 0x100 /* when text is on the heap before setvareq */
  1829. #if ENABLE_ASH_RANDOM_SUPPORT
  1830. # define VDYNAMIC 0x200 /* dynamic variable */
  1831. #else
  1832. # define VDYNAMIC 0
  1833. #endif
  1834. /* Need to be before varinit_data[] */
  1835. #if ENABLE_LOCALE_SUPPORT
  1836. static void FAST_FUNC
  1837. change_lc_all(const char *value)
  1838. {
  1839. if (value && *value != '\0')
  1840. setlocale(LC_ALL, value);
  1841. }
  1842. static void FAST_FUNC
  1843. change_lc_ctype(const char *value)
  1844. {
  1845. if (value && *value != '\0')
  1846. setlocale(LC_CTYPE, value);
  1847. }
  1848. #endif
  1849. #if ENABLE_ASH_MAIL
  1850. static void chkmail(void);
  1851. static void changemail(const char *var_value) FAST_FUNC;
  1852. #else
  1853. # define chkmail() ((void)0)
  1854. #endif
  1855. static void changepath(const char *) FAST_FUNC;
  1856. #if ENABLE_ASH_RANDOM_SUPPORT
  1857. static void change_random(const char *) FAST_FUNC;
  1858. #endif
  1859. #if BASH_EPOCH_VARS
  1860. static void change_seconds(const char *) FAST_FUNC;
  1861. static void change_realtime(const char *) FAST_FUNC;
  1862. #endif
  1863. static const struct {
  1864. int flags;
  1865. const char *var_text;
  1866. void (*var_func)(const char *) FAST_FUNC;
  1867. } varinit_data[] = {
  1868. /*
  1869. * Note: VEXPORT would not work correctly here for NOFORK applets:
  1870. * some environment strings may be constant.
  1871. */
  1872. { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
  1873. #if ENABLE_ASH_MAIL
  1874. { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL" , changemail },
  1875. { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH" , changemail },
  1876. #endif
  1877. { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
  1878. { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
  1879. { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
  1880. { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
  1881. #if ENABLE_ASH_GETOPTS
  1882. { VSTRFIXED|VTEXTFIXED , defoptindvar, getoptsreset },
  1883. #endif
  1884. { VSTRFIXED|VTEXTFIXED , NULL /* inited to linenovar */, NULL },
  1885. #if ENABLE_ASH_RANDOM_SUPPORT
  1886. { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM", change_random },
  1887. #endif
  1888. #if BASH_EPOCH_VARS
  1889. { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "EPOCHSECONDS", change_seconds },
  1890. { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "EPOCHREALTIME", change_realtime },
  1891. #endif
  1892. #if ENABLE_LOCALE_SUPPORT
  1893. { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL" , change_lc_all },
  1894. { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE" , change_lc_ctype },
  1895. #endif
  1896. #if ENABLE_FEATURE_EDITING_SAVEHISTORY
  1897. { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE" , NULL },
  1898. #endif
  1899. };
  1900. struct redirtab;
  1901. struct globals_var {
  1902. struct shparam shellparam; /* $@ current positional parameters */
  1903. struct redirtab *redirlist;
  1904. int preverrout_fd; /* stderr fd: usually 2, unless redirect moved it */
  1905. struct var *vartab[VTABSIZE];
  1906. struct var varinit[ARRAY_SIZE(varinit_data)];
  1907. int lineno;
  1908. char linenovar[sizeof("LINENO=") + sizeof(int)*3];
  1909. };
  1910. extern struct globals_var *BB_GLOBAL_CONST ash_ptr_to_globals_var;
  1911. #define G_var (*ash_ptr_to_globals_var)
  1912. #define shellparam (G_var.shellparam )
  1913. //#define redirlist (G_var.redirlist )
  1914. #define preverrout_fd (G_var.preverrout_fd)
  1915. #define vartab (G_var.vartab )
  1916. #define varinit (G_var.varinit )
  1917. #define lineno (G_var.lineno )
  1918. #define linenovar (G_var.linenovar )
  1919. #define vifs varinit[0]
  1920. #if ENABLE_ASH_MAIL
  1921. # define vmail varinit[1]
  1922. # define vmpath varinit[2]
  1923. #endif
  1924. #define VAR_OFFSET1 (ENABLE_ASH_MAIL*2)
  1925. #define vpath varinit[VAR_OFFSET1 + 1]
  1926. #define vps1 varinit[VAR_OFFSET1 + 2]
  1927. #define vps2 varinit[VAR_OFFSET1 + 3]
  1928. #define vps4 varinit[VAR_OFFSET1 + 4]
  1929. #if ENABLE_ASH_GETOPTS
  1930. # define voptind varinit[VAR_OFFSET1 + 5]
  1931. #endif
  1932. #define VAR_OFFSET2 (VAR_OFFSET1 + ENABLE_ASH_GETOPTS)
  1933. #define vlineno varinit[VAR_OFFSET2 + 5]
  1934. #if ENABLE_ASH_RANDOM_SUPPORT
  1935. # define vrandom varinit[VAR_OFFSET2 + 6]
  1936. #endif
  1937. #define VAR_OFFSET3 (VAR_OFFSET2 + ENABLE_ASH_RANDOM_SUPPORT)
  1938. #if BASH_EPOCH_VARS
  1939. # define vepochs varinit[VAR_OFFSET3 + 6]
  1940. # define vepochr varinit[VAR_OFFSET3 + 7]
  1941. #endif
  1942. #define INIT_G_var() do { \
  1943. unsigned i; \
  1944. (*(struct globals_var**)not_const_pp(&ash_ptr_to_globals_var)) = xzalloc(sizeof(G_var)); \
  1945. barrier(); \
  1946. for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
  1947. varinit[i].flags = varinit_data[i].flags; \
  1948. varinit[i].var_text = varinit_data[i].var_text; \
  1949. varinit[i].var_func = varinit_data[i].var_func; \
  1950. } \
  1951. strcpy(linenovar, "LINENO="); \
  1952. vlineno.var_text = linenovar; \
  1953. } while (0)
  1954. /*
  1955. * The following macros access the values of the above variables.
  1956. * They have to skip over the name. They return the null string
  1957. * for unset variables.
  1958. */
  1959. #define ifsval() (vifs.var_text + 4)
  1960. #define ifsset() ((vifs.flags & VUNSET) == 0)
  1961. #if ENABLE_ASH_MAIL
  1962. # define mailval() (vmail.var_text + 5)
  1963. # define mpathval() (vmpath.var_text + 9)
  1964. # define mpathset() ((vmpath.flags & VUNSET) == 0)
  1965. #endif
  1966. #define pathval() (vpath.var_text + 5)
  1967. #define ps1val() (vps1.var_text + 4)
  1968. #define ps2val() (vps2.var_text + 4)
  1969. #define ps4val() (vps4.var_text + 4)
  1970. #if ENABLE_ASH_GETOPTS
  1971. # define optindval() (voptind.var_text + 7)
  1972. #endif
  1973. #if ENABLE_ASH_GETOPTS
  1974. static void FAST_FUNC
  1975. getoptsreset(const char *value)
  1976. {
  1977. shellparam.optind = 1;
  1978. if (is_number(value))
  1979. shellparam.optind = number(value) ?: 1;
  1980. shellparam.optoff = -1;
  1981. }
  1982. #endif
  1983. /*
  1984. * Compares two strings up to the first = or '\0'. The first
  1985. * string must be terminated by '='; the second may be terminated by
  1986. * either '=' or '\0'.
  1987. */
  1988. static int
  1989. varcmp(const char *p, const char *q)
  1990. {
  1991. int c, d;
  1992. while ((c = *p) == (d = *q)) {
  1993. if (c == '\0' || c == '=')
  1994. goto out;
  1995. p++;
  1996. q++;
  1997. }
  1998. if (c == '=')
  1999. c = '\0';
  2000. if (d == '=')
  2001. d = '\0';
  2002. out:
  2003. return c - d;
  2004. }
  2005. /*
  2006. * Find the appropriate entry in the hash table from the name.
  2007. */
  2008. static struct var **
  2009. hashvar(const char *p)
  2010. {
  2011. unsigned hashval;
  2012. hashval = ((unsigned char) *p) << 4;
  2013. while (*p && *p != '=')
  2014. hashval += (unsigned char) *p++;
  2015. return &vartab[hashval % VTABSIZE];
  2016. }
  2017. static int
  2018. vpcmp(const void *a, const void *b)
  2019. {
  2020. return varcmp(*(const char **)a, *(const char **)b);
  2021. }
  2022. /*
  2023. * This routine initializes the builtin variables.
  2024. */
  2025. static void
  2026. initvar(void)
  2027. {
  2028. struct var *vp;
  2029. struct var *end;
  2030. struct var **vpp;
  2031. /*
  2032. * PS1 depends on uid
  2033. */
  2034. #if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
  2035. vps1.var_text = "PS1=\\w \\$ ";
  2036. #else
  2037. if (!geteuid())
  2038. vps1.var_text = "PS1=# ";
  2039. #endif
  2040. vp = varinit;
  2041. end = vp + ARRAY_SIZE(varinit);
  2042. do {
  2043. vpp = hashvar(vp->var_text);
  2044. vp->next = *vpp;
  2045. *vpp = vp;
  2046. } while (++vp < end);
  2047. }
  2048. static struct var **
  2049. findvar(struct var **vpp, const char *name)
  2050. {
  2051. for (; *vpp; vpp = &(*vpp)->next) {
  2052. if (varcmp((*vpp)->var_text, name) == 0) {
  2053. break;
  2054. }
  2055. }
  2056. return vpp;
  2057. }
  2058. /*
  2059. * Find the value of a variable. Returns NULL if not set.
  2060. */
  2061. static const char* FAST_FUNC
  2062. lookupvar(const char *name)
  2063. {
  2064. struct var *v;
  2065. v = *findvar(hashvar(name), name);
  2066. if (v) {
  2067. #if ENABLE_ASH_RANDOM_SUPPORT || BASH_EPOCH_VARS
  2068. /*
  2069. * Dynamic variables are implemented roughly the same way they are
  2070. * in bash. Namely, they're "special" so long as they aren't unset.
  2071. * As soon as they're unset, they're no longer dynamic, and dynamic
  2072. * lookup will no longer happen at that point. -- PFM.
  2073. */
  2074. if (v->flags & VDYNAMIC)
  2075. v->var_func(NULL);
  2076. #endif
  2077. if (!(v->flags & VUNSET)) {
  2078. if (v == &vlineno && v->var_text == linenovar) {
  2079. fmtstr(linenovar+7, sizeof(linenovar)-7, "%d", lineno);
  2080. }
  2081. return var_end(v->var_text);
  2082. }
  2083. }
  2084. return NULL;
  2085. }
  2086. #if ENABLE_UNICODE_SUPPORT
  2087. static void
  2088. reinit_unicode_for_ash(void)
  2089. {
  2090. /* Unicode support should be activated even if LANG is set
  2091. * _during_ shell execution, not only if it was set when
  2092. * shell was started. Therefore, re-check LANG every time:
  2093. */
  2094. if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
  2095. || ENABLE_UNICODE_USING_LOCALE
  2096. ) {
  2097. const char *s = lookupvar("LC_ALL");
  2098. if (!s) s = lookupvar("LC_CTYPE");
  2099. if (!s) s = lookupvar("LANG");
  2100. reinit_unicode(s);
  2101. }
  2102. }
  2103. #else
  2104. # define reinit_unicode_for_ash() ((void)0)
  2105. #endif
  2106. /*
  2107. * Search the environment of a builtin command.
  2108. */
  2109. static ALWAYS_INLINE const char *
  2110. bltinlookup(const char *name)
  2111. {
  2112. return lookupvar(name);
  2113. }
  2114. /*
  2115. * Same as setvar except that the variable and value are passed in
  2116. * the first argument as name=value. Since the first argument will
  2117. * be actually stored in the table, it should not be a string that
  2118. * will go away.
  2119. * Called with interrupts off.
  2120. */
  2121. static struct var *
  2122. setvareq(char *s, int flags)
  2123. {
  2124. struct var *vp, **vpp;
  2125. vpp = hashvar(s);
  2126. flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
  2127. vpp = findvar(vpp, s);
  2128. vp = *vpp;
  2129. if (vp) {
  2130. if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
  2131. const char *n;
  2132. if (flags & VNOSAVE)
  2133. free(s);
  2134. n = vp->var_text;
  2135. exitstatus = 1;
  2136. ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
  2137. }
  2138. if (flags & VNOSET)
  2139. goto out;
  2140. if (vp->var_func && !(flags & VNOFUNC))
  2141. vp->var_func(var_end(s));
  2142. if (!(vp->flags & (VTEXTFIXED|VSTACK)))
  2143. free((char*)vp->var_text);
  2144. if (((flags & (VEXPORT|VREADONLY|VSTRFIXED|VUNSET)) | (vp->flags & VSTRFIXED)) == VUNSET) {
  2145. *vpp = vp->next;
  2146. free(vp);
  2147. out_free:
  2148. if ((flags & (VTEXTFIXED|VSTACK|VNOSAVE)) == VNOSAVE)
  2149. free(s);
  2150. goto out;
  2151. }
  2152. flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
  2153. #if ENABLE_ASH_RANDOM_SUPPORT || BASH_EPOCH_VARS
  2154. if (flags & VUNSET)
  2155. flags &= ~VDYNAMIC;
  2156. #endif
  2157. } else {
  2158. /* variable s is not found */
  2159. if (flags & VNOSET)
  2160. goto out;
  2161. if ((flags & (VEXPORT|VREADONLY|VSTRFIXED|VUNSET)) == VUNSET)
  2162. goto out_free;
  2163. vp = ckzalloc(sizeof(*vp));
  2164. vp->next = *vpp;
  2165. /*vp->func = NULL; - ckzalloc did it */
  2166. *vpp = vp;
  2167. }
  2168. if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
  2169. s = ckstrdup(s);
  2170. vp->var_text = s;
  2171. vp->flags = flags;
  2172. out:
  2173. return vp;
  2174. }
  2175. /*
  2176. * Set the value of a variable. The flags argument is ored with the
  2177. * flags of the variable. If val is NULL, the variable is unset.
  2178. */
  2179. static struct var *
  2180. setvar(const char *name, const char *val, int flags)
  2181. {
  2182. const char *q;
  2183. char *p;
  2184. char *nameeq;
  2185. size_t namelen;
  2186. size_t vallen;
  2187. struct var *vp;
  2188. q = endofname(name);
  2189. p = strchrnul(q, '=');
  2190. namelen = p - name;
  2191. if (!namelen || p != q)
  2192. ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
  2193. vallen = 0;
  2194. if (val == NULL) {
  2195. flags |= VUNSET;
  2196. } else {
  2197. vallen = strlen(val);
  2198. }
  2199. INT_OFF;
  2200. nameeq = ckzalloc(namelen + vallen + 2);
  2201. p = mempcpy(nameeq, name, namelen);
  2202. if (val) {
  2203. *p++ = '=';
  2204. memcpy(p, val, vallen);
  2205. }
  2206. vp = setvareq(nameeq, flags | VNOSAVE);
  2207. INT_ON;
  2208. return vp;
  2209. }
  2210. static void FAST_FUNC
  2211. setvar0(const char *name, const char *val)
  2212. {
  2213. setvar(name, val, 0);
  2214. }
  2215. /*
  2216. * Unset the specified variable.
  2217. */
  2218. static void
  2219. unsetvar(const char *s)
  2220. {
  2221. setvar(s, NULL, 0);
  2222. }
  2223. /*
  2224. * Generate a list of variables satisfying the given conditions.
  2225. */
  2226. #if !ENABLE_FEATURE_SH_NOFORK
  2227. # define listvars(on, off, lp, end) listvars(on, off, end)
  2228. #endif
  2229. static char **
  2230. listvars(int on, int off, struct strlist *lp, char ***end)
  2231. {
  2232. struct var **vpp;
  2233. struct var *vp;
  2234. char **ep;
  2235. int mask;
  2236. STARTSTACKSTR(ep);
  2237. vpp = vartab;
  2238. mask = on | off;
  2239. do {
  2240. for (vp = *vpp; vp; vp = vp->next) {
  2241. if ((vp->flags & mask) == on) {
  2242. #if ENABLE_FEATURE_SH_NOFORK
  2243. /* If variable with the same name is both
  2244. * exported and temporarily set for a command:
  2245. * export ZVAR=5
  2246. * ZVAR=6 printenv
  2247. * then "ZVAR=6" will be both in vartab and
  2248. * lp lists. Do not pass it twice to printenv.
  2249. */
  2250. struct strlist *lp1 = lp;
  2251. while (lp1) {
  2252. if (strcmp(lp1->text, vp->var_text) == 0)
  2253. goto skip;
  2254. lp1 = lp1->next;
  2255. }
  2256. #endif
  2257. if (ep == stackstrend())
  2258. ep = growstackstr();
  2259. *ep++ = (char*)vp->var_text;
  2260. #if ENABLE_FEATURE_SH_NOFORK
  2261. skip: ;
  2262. #endif
  2263. }
  2264. }
  2265. } while (++vpp < vartab + VTABSIZE);
  2266. #if ENABLE_FEATURE_SH_NOFORK
  2267. while (lp) {
  2268. if (ep == stackstrend())
  2269. ep = growstackstr();
  2270. *ep++ = lp->text;
  2271. lp = lp->next;
  2272. }
  2273. #endif
  2274. if (ep == stackstrend())
  2275. ep = growstackstr();
  2276. if (end)
  2277. *end = ep;
  2278. *ep++ = NULL;
  2279. return grabstackstr(ep);
  2280. }
  2281. /* ============ Path search helper */
  2282. static const char *
  2283. legal_pathopt(const char *opt, const char *term, int magic)
  2284. {
  2285. switch (magic) {
  2286. case 0:
  2287. opt = NULL;
  2288. break;
  2289. case 1:
  2290. opt = prefix(opt, "builtin") ?: prefix(opt, "func");
  2291. break;
  2292. default:
  2293. opt += strcspn(opt, term);
  2294. break;
  2295. }
  2296. if (opt && *opt == '%')
  2297. opt++;
  2298. return opt;
  2299. }
  2300. /*
  2301. * The variable path (passed by reference) should be set to the start
  2302. * of the path before the first call; padvance will update
  2303. * this value as it proceeds. Successive calls to padvance will return
  2304. * the possible path expansions in sequence. If an option (indicated by
  2305. * a percent sign) appears in the path entry then the global variable
  2306. * pathopt will be set to point to it; otherwise pathopt will be set to
  2307. * NULL.
  2308. *
  2309. * If magic is 0 then pathopt recognition will be disabled. If magic is
  2310. * 1 we shall recognise %builtin/%func. Otherwise we shall accept any
  2311. * pathopt.
  2312. */
  2313. static const char *pathopt; /* set by padvance */
  2314. static int
  2315. padvance_magic(const char **path, const char *name, int magic)
  2316. {
  2317. const char *term = "%:";
  2318. const char *lpathopt;
  2319. const char *p;
  2320. char *q;
  2321. const char *start;
  2322. size_t qlen;
  2323. size_t len;
  2324. if (*path == NULL)
  2325. return -1;
  2326. lpathopt = NULL;
  2327. start = *path;
  2328. if (*start == '%' && (p = legal_pathopt(start + 1, term, magic))) {
  2329. lpathopt = start + 1;
  2330. start = p;
  2331. term = ":";
  2332. }
  2333. len = strcspn(start, term);
  2334. p = start + len;
  2335. if (*p == '%') {
  2336. size_t extra = strchrnul(p, ':') - p;
  2337. if (legal_pathopt(p + 1, term, magic))
  2338. lpathopt = p + 1;
  2339. else
  2340. len += extra;
  2341. p += extra;
  2342. }
  2343. pathopt = lpathopt;
  2344. *path = *p == ':' ? p + 1 : NULL;
  2345. /* "2" is for '/' and '\0' */
  2346. qlen = len + strlen(name) + 2;
  2347. q = growstackto(qlen);
  2348. if (len) {
  2349. q = mempcpy(q, start, len);
  2350. *q++ = '/';
  2351. }
  2352. strcpy(q, name);
  2353. return qlen;
  2354. }
  2355. static int
  2356. padvance(const char **path, const char *name)
  2357. {
  2358. return padvance_magic(path, name, 1);
  2359. }
  2360. /* ============ Prompt */
  2361. static smallint doprompt; /* if set, prompt the user */
  2362. static smallint needprompt; /* true if interactive and at start of line */
  2363. #if ENABLE_FEATURE_EDITING
  2364. static line_input_t *line_input_state;
  2365. static const char *cmdedit_prompt;
  2366. static void
  2367. putprompt(const char *s)
  2368. {
  2369. if (ENABLE_ASH_EXPAND_PRMT) {
  2370. free((char*)cmdedit_prompt);
  2371. cmdedit_prompt = ckstrdup(s);
  2372. return;
  2373. }
  2374. cmdedit_prompt = s;
  2375. }
  2376. #else
  2377. static void
  2378. putprompt(const char *s)
  2379. {
  2380. out2str(s);
  2381. }
  2382. #endif
  2383. /* expandstr() needs parsing machinery, so it is far away ahead... */
  2384. static const char *expandstr(const char *ps, int syntax_type);
  2385. /* Values for syntax param */
  2386. #define BASESYNTAX 0 /* not in quotes */
  2387. #define DQSYNTAX 1 /* in double quotes */
  2388. #define SQSYNTAX 2 /* in single quotes */
  2389. #define ARISYNTAX 3 /* in arithmetic */
  2390. #if ENABLE_ASH_EXPAND_PRMT
  2391. # define PSSYNTAX 4 /* prompt. never passed to SIT() */
  2392. #endif
  2393. /* PSSYNTAX expansion is identical to DQSYNTAX, except keeping '\$' as '\$' */
  2394. /*
  2395. * called by editline -- any expansions to the prompt should be added here.
  2396. */
  2397. static void
  2398. setprompt_if(smallint do_set, int whichprompt)
  2399. {
  2400. const char *prompt;
  2401. IF_ASH_EXPAND_PRMT(struct stackmark smark;)
  2402. if (!do_set)
  2403. return;
  2404. needprompt = 0;
  2405. switch (whichprompt) {
  2406. case 1:
  2407. prompt = ps1val();
  2408. break;
  2409. case 2:
  2410. prompt = ps2val();
  2411. break;
  2412. default: /* 0 */
  2413. prompt = nullstr;
  2414. }
  2415. #if ENABLE_ASH_EXPAND_PRMT
  2416. pushstackmark(&smark, stackblocksize());
  2417. putprompt(expandstr(prompt, PSSYNTAX));
  2418. popstackmark(&smark);
  2419. #else
  2420. putprompt(prompt);
  2421. #endif
  2422. }
  2423. /* ============ The cd and pwd commands */
  2424. #define CD_PHYSICAL 1
  2425. #define CD_PRINT 2
  2426. static int
  2427. cdopt(void)
  2428. {
  2429. int flags = 0;
  2430. int i, j;
  2431. j = 'L';
  2432. while ((i = nextopt("LP")) != '\0') {
  2433. if (i != j) {
  2434. flags ^= CD_PHYSICAL;
  2435. j = i;
  2436. }
  2437. }
  2438. return flags;
  2439. }
  2440. /*
  2441. * Update curdir (the name of the current directory) in response to a
  2442. * cd command.
  2443. */
  2444. static const char *
  2445. updatepwd(const char *dir)
  2446. {
  2447. char *new;
  2448. char *p;
  2449. char *cdcomppath;
  2450. const char *lim;
  2451. cdcomppath = sstrdup(dir);
  2452. STARTSTACKSTR(new);
  2453. if (*dir != '/') {
  2454. if (curdir == nullstr)
  2455. return 0;
  2456. new = stack_putstr(curdir, new);
  2457. }
  2458. new = makestrspace(strlen(dir) + 2, new);
  2459. lim = (char *)stackblock() + 1;
  2460. if (*dir != '/') {
  2461. if (new[-1] != '/')
  2462. USTPUTC('/', new);
  2463. if (new > lim && *lim == '/')
  2464. lim++;
  2465. } else {
  2466. USTPUTC('/', new);
  2467. cdcomppath++;
  2468. if (dir[1] == '/' && dir[2] != '/') {
  2469. USTPUTC('/', new);
  2470. cdcomppath++;
  2471. lim++;
  2472. }
  2473. }
  2474. p = strtok(cdcomppath, "/");
  2475. while (p) {
  2476. switch (*p) {
  2477. case '.':
  2478. if (p[1] == '.' && p[2] == '\0') {
  2479. while (new > lim) {
  2480. STUNPUTC(new);
  2481. if (new[-1] == '/')
  2482. break;
  2483. }
  2484. break;
  2485. }
  2486. if (p[1] == '\0')
  2487. break;
  2488. /* fall through */
  2489. default:
  2490. new = stack_putstr(p, new);
  2491. USTPUTC('/', new);
  2492. }
  2493. p = strtok(NULL, "/");
  2494. }
  2495. if (new > lim)
  2496. STUNPUTC(new);
  2497. *new = 0;
  2498. return stackblock();
  2499. }
  2500. /*
  2501. * Find out what the current directory is. If we already know the current
  2502. * directory, this routine returns immediately.
  2503. */
  2504. static char *
  2505. getpwd(void)
  2506. {
  2507. char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
  2508. return dir ? dir : nullstr;
  2509. }
  2510. static void
  2511. setpwd(const char *val, int setold)
  2512. {
  2513. char *oldcur, *dir;
  2514. oldcur = dir = curdir;
  2515. if (setold) {
  2516. setvar("OLDPWD", oldcur, VEXPORT);
  2517. }
  2518. INT_OFF;
  2519. if (physdir != nullstr) {
  2520. if (physdir != oldcur)
  2521. free(physdir);
  2522. physdir = nullstr;
  2523. }
  2524. if (oldcur == val || !val) {
  2525. char *s = getpwd();
  2526. physdir = s;
  2527. if (!val)
  2528. dir = s;
  2529. } else
  2530. dir = ckstrdup(val);
  2531. if (oldcur != dir && oldcur != nullstr) {
  2532. free(oldcur);
  2533. }
  2534. curdir = dir;
  2535. INT_ON;
  2536. setvar("PWD", dir, VEXPORT);
  2537. }
  2538. static void hashcd(void);
  2539. /*
  2540. * Actually do the chdir. We also call hashcd to let other routines
  2541. * know that the current directory has changed.
  2542. */
  2543. static int
  2544. docd(const char *dest, int flags)
  2545. {
  2546. const char *dir = NULL;
  2547. int err;
  2548. TRACE(("docd(\"%s\", %d) called\n", dest, flags));
  2549. INT_OFF;
  2550. if (!(flags & CD_PHYSICAL)) {
  2551. dir = updatepwd(dest);
  2552. if (dir)
  2553. dest = dir;
  2554. }
  2555. err = chdir(dest);
  2556. if (err)
  2557. goto out;
  2558. setpwd(dir, 1);
  2559. hashcd();
  2560. out:
  2561. INT_ON;
  2562. return err;
  2563. }
  2564. static int FAST_FUNC
  2565. cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  2566. {
  2567. const char *dest;
  2568. const char *path;
  2569. const char *p;
  2570. char c;
  2571. struct stat statb;
  2572. int flags;
  2573. int len;
  2574. flags = cdopt();
  2575. dest = *argptr;
  2576. if (!dest)
  2577. dest = bltinlookup("HOME");
  2578. else if (LONE_DASH(dest)) {
  2579. dest = bltinlookup("OLDPWD");
  2580. flags |= CD_PRINT;
  2581. }
  2582. if (!dest)
  2583. dest = nullstr;
  2584. if (*dest == '/')
  2585. goto step6;
  2586. if (*dest == '.') {
  2587. c = dest[1];
  2588. dotdot:
  2589. switch (c) {
  2590. case '\0':
  2591. case '/':
  2592. goto step6;
  2593. case '.':
  2594. c = dest[2];
  2595. if (c != '.')
  2596. goto dotdot;
  2597. }
  2598. }
  2599. if (!*dest)
  2600. dest = ".";
  2601. path = bltinlookup("CDPATH");
  2602. while (p = path, (len = padvance(&path, dest)) >= 0) {
  2603. c = *p;
  2604. p = stalloc(len);
  2605. if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
  2606. if (c && c != ':')
  2607. flags |= CD_PRINT;
  2608. docd:
  2609. if (!docd(p, flags))
  2610. goto out;
  2611. goto err;
  2612. }
  2613. }
  2614. step6:
  2615. p = dest;
  2616. goto docd;
  2617. err:
  2618. ash_msg_and_raise_perror("can't cd to %s", dest);
  2619. /* NOTREACHED */
  2620. out:
  2621. if (flags & CD_PRINT)
  2622. out1fmt("%s\n", curdir);
  2623. return 0;
  2624. }
  2625. static int FAST_FUNC
  2626. pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  2627. {
  2628. int flags;
  2629. const char *dir = curdir;
  2630. flags = cdopt();
  2631. if (flags) {
  2632. if (physdir == nullstr)
  2633. setpwd(dir, 0);
  2634. dir = physdir;
  2635. }
  2636. out1fmt("%s\n", dir);
  2637. return 0;
  2638. }
  2639. /* ============ ... */
  2640. #define IBUFSIZ (ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 1024)
  2641. /* Syntax classes */
  2642. #define CWORD 0 /* character is nothing special */
  2643. #define CNL 1 /* newline character */
  2644. #define CBACK 2 /* a backslash character */
  2645. #define CSQUOTE 3 /* single quote */
  2646. #define CDQUOTE 4 /* double quote */
  2647. #define CENDQUOTE 5 /* a terminating quote */
  2648. #define CBQUOTE 6 /* backwards single quote */
  2649. #define CVAR 7 /* a dollar sign */
  2650. #define CENDVAR 8 /* a '}' character */
  2651. #define CLP 9 /* a left paren in arithmetic */
  2652. #define CRP 10 /* a right paren in arithmetic */
  2653. #define CENDFILE 11 /* end of file */
  2654. #define CCTL 12 /* like CWORD, except it must be escaped */
  2655. #define CSPCL 13 /* these terminate a word */
  2656. #define CIGN 14 /* character should be ignored */
  2657. #define PEOF 256
  2658. #if ENABLE_ASH_ALIAS
  2659. # define PEOA 257
  2660. #endif
  2661. #define USE_SIT_FUNCTION ENABLE_ASH_OPTIMIZE_FOR_SIZE
  2662. #if ENABLE_FEATURE_SH_MATH
  2663. # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8) | (d << 12))
  2664. #else
  2665. # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8))
  2666. #endif
  2667. static const uint16_t S_I_T[] ALIGN2 = {
  2668. #if ENABLE_ASH_ALIAS
  2669. SIT_ITEM(CSPCL , CIGN , CIGN , CIGN ), /* 0, PEOA */
  2670. #endif
  2671. SIT_ITEM(CSPCL , CWORD , CWORD, CWORD ), /* 1, ' ' */
  2672. SIT_ITEM(CNL , CNL , CNL , CNL ), /* 2, \n */
  2673. SIT_ITEM(CWORD , CCTL , CCTL , CWORD ), /* 3, !*-/:=?[]~ */
  2674. SIT_ITEM(CDQUOTE , CENDQUOTE, CWORD, CWORD ), /* 4, '"' */
  2675. SIT_ITEM(CVAR , CVAR , CWORD, CVAR ), /* 5, $ */
  2676. SIT_ITEM(CSQUOTE , CWORD , CENDQUOTE, CWORD), /* 6, "'" */
  2677. SIT_ITEM(CSPCL , CWORD , CWORD, CLP ), /* 7, ( */
  2678. SIT_ITEM(CSPCL , CWORD , CWORD, CRP ), /* 8, ) */
  2679. SIT_ITEM(CBACK , CBACK , CCTL , CBACK ), /* 9, \ */
  2680. SIT_ITEM(CBQUOTE , CBQUOTE , CWORD, CBQUOTE), /* 10, ` */
  2681. SIT_ITEM(CENDVAR , CENDVAR , CWORD, CENDVAR), /* 11, } */
  2682. #if !USE_SIT_FUNCTION
  2683. SIT_ITEM(CENDFILE, CENDFILE , CENDFILE, CENDFILE),/* 12, PEOF */
  2684. SIT_ITEM(CWORD , CWORD , CWORD, CWORD ), /* 13, 0-9A-Za-z */
  2685. SIT_ITEM(CCTL , CCTL , CCTL , CCTL ) /* 14, CTLESC ... */
  2686. #endif
  2687. #undef SIT_ITEM
  2688. };
  2689. /* Constants below must match table above */
  2690. enum {
  2691. #if ENABLE_ASH_ALIAS
  2692. CSPCL_CIGN_CIGN_CIGN , /* 0 */
  2693. #endif
  2694. CSPCL_CWORD_CWORD_CWORD , /* 1 */
  2695. CNL_CNL_CNL_CNL , /* 2 */
  2696. CWORD_CCTL_CCTL_CWORD , /* 3 */
  2697. CDQUOTE_CENDQUOTE_CWORD_CWORD , /* 4 */
  2698. CVAR_CVAR_CWORD_CVAR , /* 5 */
  2699. CSQUOTE_CWORD_CENDQUOTE_CWORD , /* 6 */
  2700. CSPCL_CWORD_CWORD_CLP , /* 7 */
  2701. CSPCL_CWORD_CWORD_CRP , /* 8 */
  2702. CBACK_CBACK_CCTL_CBACK , /* 9 */
  2703. CBQUOTE_CBQUOTE_CWORD_CBQUOTE , /* 10 */
  2704. CENDVAR_CENDVAR_CWORD_CENDVAR , /* 11 */
  2705. CENDFILE_CENDFILE_CENDFILE_CENDFILE, /* 12 */
  2706. CWORD_CWORD_CWORD_CWORD , /* 13 */
  2707. CCTL_CCTL_CCTL_CCTL , /* 14 */
  2708. };
  2709. /* c in SIT(c, syntax) must be an *unsigned char* or PEOA or PEOF,
  2710. * caller must ensure proper cast on it if c is *char_ptr!
  2711. */
  2712. #if USE_SIT_FUNCTION
  2713. static int
  2714. SIT(int c, int syntax)
  2715. {
  2716. /* Used to also have '/' in this string: "\t\n !\"$&'()*-/:;<=>?[\\]`|}~" */
  2717. static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-:;<=>?[\\]`|}~";
  2718. /*
  2719. * This causes '/' to be prepended with CTLESC in dquoted string,
  2720. * making "./file"* treated incorrectly because we feed
  2721. * ".\/file*" string to glob(), confusing it (see expandmeta func).
  2722. * The "homegrown" glob implementation is okay with that,
  2723. * but glibc one isn't. With '/' always treated as CWORD,
  2724. * both work fine.
  2725. */
  2726. # if ENABLE_ASH_ALIAS
  2727. static const uint8_t syntax_index_table[] ALIGN1 = {
  2728. 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
  2729. 7, 8, 3, 3,/*3,*/3, 1, 1, /* "()*-/:;<" */
  2730. 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
  2731. 11, 3 /* "}~" */
  2732. };
  2733. # else
  2734. static const uint8_t syntax_index_table[] ALIGN1 = {
  2735. 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
  2736. 6, 7, 2, 2,/*2,*/2, 0, 0, /* "()*-/:;<" */
  2737. 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
  2738. 10, 2 /* "}~" */
  2739. };
  2740. # endif
  2741. const char *s;
  2742. int indx;
  2743. if (c == PEOF)
  2744. return CENDFILE;
  2745. # if ENABLE_ASH_ALIAS
  2746. if (c == PEOA)
  2747. indx = 0;
  2748. else
  2749. # endif
  2750. {
  2751. /* Cast is purely for paranoia here,
  2752. * just in case someone passed signed char to us */
  2753. if ((unsigned char)c >= CTL_FIRST
  2754. && (unsigned char)c <= CTL_LAST
  2755. ) {
  2756. return CCTL;
  2757. }
  2758. s = strchrnul(spec_symbls, c);
  2759. if (*s == '\0')
  2760. return CWORD;
  2761. indx = syntax_index_table[s - spec_symbls];
  2762. }
  2763. return (S_I_T[indx] >> (syntax*4)) & 0xf;
  2764. }
  2765. #else /* !USE_SIT_FUNCTION */
  2766. static const uint8_t syntax_index_table[] ALIGN1 = {
  2767. /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
  2768. /* 0 */ CWORD_CWORD_CWORD_CWORD,
  2769. /* 1 */ CWORD_CWORD_CWORD_CWORD,
  2770. /* 2 */ CWORD_CWORD_CWORD_CWORD,
  2771. /* 3 */ CWORD_CWORD_CWORD_CWORD,
  2772. /* 4 */ CWORD_CWORD_CWORD_CWORD,
  2773. /* 5 */ CWORD_CWORD_CWORD_CWORD,
  2774. /* 6 */ CWORD_CWORD_CWORD_CWORD,
  2775. /* 7 */ CWORD_CWORD_CWORD_CWORD,
  2776. /* 8 */ CWORD_CWORD_CWORD_CWORD,
  2777. /* 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
  2778. /* 10 "\n" */ CNL_CNL_CNL_CNL,
  2779. /* 11 */ CWORD_CWORD_CWORD_CWORD,
  2780. /* 12 */ CWORD_CWORD_CWORD_CWORD,
  2781. /* 13 */ CWORD_CWORD_CWORD_CWORD,
  2782. /* 14 */ CWORD_CWORD_CWORD_CWORD,
  2783. /* 15 */ CWORD_CWORD_CWORD_CWORD,
  2784. /* 16 */ CWORD_CWORD_CWORD_CWORD,
  2785. /* 17 */ CWORD_CWORD_CWORD_CWORD,
  2786. /* 18 */ CWORD_CWORD_CWORD_CWORD,
  2787. /* 19 */ CWORD_CWORD_CWORD_CWORD,
  2788. /* 20 */ CWORD_CWORD_CWORD_CWORD,
  2789. /* 21 */ CWORD_CWORD_CWORD_CWORD,
  2790. /* 22 */ CWORD_CWORD_CWORD_CWORD,
  2791. /* 23 */ CWORD_CWORD_CWORD_CWORD,
  2792. /* 24 */ CWORD_CWORD_CWORD_CWORD,
  2793. /* 25 */ CWORD_CWORD_CWORD_CWORD,
  2794. /* 26 */ CWORD_CWORD_CWORD_CWORD,
  2795. /* 27 */ CWORD_CWORD_CWORD_CWORD,
  2796. /* 28 */ CWORD_CWORD_CWORD_CWORD,
  2797. /* 29 */ CWORD_CWORD_CWORD_CWORD,
  2798. /* 30 */ CWORD_CWORD_CWORD_CWORD,
  2799. /* 31 */ CWORD_CWORD_CWORD_CWORD,
  2800. /* 32 " " */ CSPCL_CWORD_CWORD_CWORD,
  2801. /* 33 "!" */ CWORD_CCTL_CCTL_CWORD,
  2802. /* 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
  2803. /* 35 "#" */ CWORD_CWORD_CWORD_CWORD,
  2804. /* 36 "$" */ CVAR_CVAR_CWORD_CVAR,
  2805. /* 37 "%" */ CWORD_CWORD_CWORD_CWORD,
  2806. /* 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
  2807. /* 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
  2808. /* 40 "(" */ CSPCL_CWORD_CWORD_CLP,
  2809. /* 41 ")" */ CSPCL_CWORD_CWORD_CRP,
  2810. /* 42 "*" */ CWORD_CCTL_CCTL_CWORD,
  2811. /* 43 "+" */ CWORD_CWORD_CWORD_CWORD,
  2812. /* 44 "," */ CWORD_CWORD_CWORD_CWORD,
  2813. /* 45 "-" */ CWORD_CCTL_CCTL_CWORD,
  2814. /* 46 "." */ CWORD_CWORD_CWORD_CWORD,
  2815. /* "/" was CWORD_CCTL_CCTL_CWORD, see comment in SIT() function why this is changed: */
  2816. /* 47 "/" */ CWORD_CWORD_CWORD_CWORD,
  2817. /* 48 "0" */ CWORD_CWORD_CWORD_CWORD,
  2818. /* 49 "1" */ CWORD_CWORD_CWORD_CWORD,
  2819. /* 50 "2" */ CWORD_CWORD_CWORD_CWORD,
  2820. /* 51 "3" */ CWORD_CWORD_CWORD_CWORD,
  2821. /* 52 "4" */ CWORD_CWORD_CWORD_CWORD,
  2822. /* 53 "5" */ CWORD_CWORD_CWORD_CWORD,
  2823. /* 54 "6" */ CWORD_CWORD_CWORD_CWORD,
  2824. /* 55 "7" */ CWORD_CWORD_CWORD_CWORD,
  2825. /* 56 "8" */ CWORD_CWORD_CWORD_CWORD,
  2826. /* 57 "9" */ CWORD_CWORD_CWORD_CWORD,
  2827. /* 58 ":" */ CWORD_CCTL_CCTL_CWORD,
  2828. /* 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
  2829. /* 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
  2830. /* 61 "=" */ CWORD_CCTL_CCTL_CWORD,
  2831. /* 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
  2832. /* 63 "?" */ CWORD_CCTL_CCTL_CWORD,
  2833. /* 64 "@" */ CWORD_CWORD_CWORD_CWORD,
  2834. /* 65 "A" */ CWORD_CWORD_CWORD_CWORD,
  2835. /* 66 "B" */ CWORD_CWORD_CWORD_CWORD,
  2836. /* 67 "C" */ CWORD_CWORD_CWORD_CWORD,
  2837. /* 68 "D" */ CWORD_CWORD_CWORD_CWORD,
  2838. /* 69 "E" */ CWORD_CWORD_CWORD_CWORD,
  2839. /* 70 "F" */ CWORD_CWORD_CWORD_CWORD,
  2840. /* 71 "G" */ CWORD_CWORD_CWORD_CWORD,
  2841. /* 72 "H" */ CWORD_CWORD_CWORD_CWORD,
  2842. /* 73 "I" */ CWORD_CWORD_CWORD_CWORD,
  2843. /* 74 "J" */ CWORD_CWORD_CWORD_CWORD,
  2844. /* 75 "K" */ CWORD_CWORD_CWORD_CWORD,
  2845. /* 76 "L" */ CWORD_CWORD_CWORD_CWORD,
  2846. /* 77 "M" */ CWORD_CWORD_CWORD_CWORD,
  2847. /* 78 "N" */ CWORD_CWORD_CWORD_CWORD,
  2848. /* 79 "O" */ CWORD_CWORD_CWORD_CWORD,
  2849. /* 80 "P" */ CWORD_CWORD_CWORD_CWORD,
  2850. /* 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
  2851. /* 82 "R" */ CWORD_CWORD_CWORD_CWORD,
  2852. /* 83 "S" */ CWORD_CWORD_CWORD_CWORD,
  2853. /* 84 "T" */ CWORD_CWORD_CWORD_CWORD,
  2854. /* 85 "U" */ CWORD_CWORD_CWORD_CWORD,
  2855. /* 86 "V" */ CWORD_CWORD_CWORD_CWORD,
  2856. /* 87 "W" */ CWORD_CWORD_CWORD_CWORD,
  2857. /* 88 "X" */ CWORD_CWORD_CWORD_CWORD,
  2858. /* 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
  2859. /* 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
  2860. /* 91 "[" */ CWORD_CCTL_CCTL_CWORD,
  2861. /* 92 "\" */ CBACK_CBACK_CCTL_CBACK,
  2862. /* 93 "]" */ CWORD_CCTL_CCTL_CWORD,
  2863. /* 94 "^" */ CWORD_CWORD_CWORD_CWORD,
  2864. /* 95 "_" */ CWORD_CWORD_CWORD_CWORD,
  2865. /* 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
  2866. /* 97 "a" */ CWORD_CWORD_CWORD_CWORD,
  2867. /* 98 "b" */ CWORD_CWORD_CWORD_CWORD,
  2868. /* 99 "c" */ CWORD_CWORD_CWORD_CWORD,
  2869. /* 100 "d" */ CWORD_CWORD_CWORD_CWORD,
  2870. /* 101 "e" */ CWORD_CWORD_CWORD_CWORD,
  2871. /* 102 "f" */ CWORD_CWORD_CWORD_CWORD,
  2872. /* 103 "g" */ CWORD_CWORD_CWORD_CWORD,
  2873. /* 104 "h" */ CWORD_CWORD_CWORD_CWORD,
  2874. /* 105 "i" */ CWORD_CWORD_CWORD_CWORD,
  2875. /* 106 "j" */ CWORD_CWORD_CWORD_CWORD,
  2876. /* 107 "k" */ CWORD_CWORD_CWORD_CWORD,
  2877. /* 108 "l" */ CWORD_CWORD_CWORD_CWORD,
  2878. /* 109 "m" */ CWORD_CWORD_CWORD_CWORD,
  2879. /* 110 "n" */ CWORD_CWORD_CWORD_CWORD,
  2880. /* 111 "o" */ CWORD_CWORD_CWORD_CWORD,
  2881. /* 112 "p" */ CWORD_CWORD_CWORD_CWORD,
  2882. /* 113 "q" */ CWORD_CWORD_CWORD_CWORD,
  2883. /* 114 "r" */ CWORD_CWORD_CWORD_CWORD,
  2884. /* 115 "s" */ CWORD_CWORD_CWORD_CWORD,
  2885. /* 116 "t" */ CWORD_CWORD_CWORD_CWORD,
  2886. /* 117 "u" */ CWORD_CWORD_CWORD_CWORD,
  2887. /* 118 "v" */ CWORD_CWORD_CWORD_CWORD,
  2888. /* 119 "w" */ CWORD_CWORD_CWORD_CWORD,
  2889. /* 120 "x" */ CWORD_CWORD_CWORD_CWORD,
  2890. /* 121 "y" */ CWORD_CWORD_CWORD_CWORD,
  2891. /* 122 "z" */ CWORD_CWORD_CWORD_CWORD,
  2892. /* 123 "{" */ CWORD_CWORD_CWORD_CWORD,
  2893. /* 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
  2894. /* 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
  2895. /* 126 "~" */ CWORD_CCTL_CCTL_CWORD,
  2896. /* 127 del */ CWORD_CWORD_CWORD_CWORD,
  2897. /* 128 0x80 */ CWORD_CWORD_CWORD_CWORD,
  2898. /* 129 CTLESC */ CCTL_CCTL_CCTL_CCTL,
  2899. /* 130 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
  2900. /* 131 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
  2901. /* 132 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
  2902. /* 133 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
  2903. /* 134 CTLARI */ CCTL_CCTL_CCTL_CCTL,
  2904. /* 135 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
  2905. /* 136 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
  2906. /* 137 */ CWORD_CWORD_CWORD_CWORD,
  2907. /* 138 */ CWORD_CWORD_CWORD_CWORD,
  2908. /* 139 */ CWORD_CWORD_CWORD_CWORD,
  2909. /* 140 */ CWORD_CWORD_CWORD_CWORD,
  2910. /* 141 */ CWORD_CWORD_CWORD_CWORD,
  2911. /* 142 */ CWORD_CWORD_CWORD_CWORD,
  2912. /* 143 */ CWORD_CWORD_CWORD_CWORD,
  2913. /* 144 */ CWORD_CWORD_CWORD_CWORD,
  2914. /* 145 */ CWORD_CWORD_CWORD_CWORD,
  2915. /* 146 */ CWORD_CWORD_CWORD_CWORD,
  2916. /* 147 */ CWORD_CWORD_CWORD_CWORD,
  2917. /* 148 */ CWORD_CWORD_CWORD_CWORD,
  2918. /* 149 */ CWORD_CWORD_CWORD_CWORD,
  2919. /* 150 */ CWORD_CWORD_CWORD_CWORD,
  2920. /* 151 */ CWORD_CWORD_CWORD_CWORD,
  2921. /* 152 */ CWORD_CWORD_CWORD_CWORD,
  2922. /* 153 */ CWORD_CWORD_CWORD_CWORD,
  2923. /* 154 */ CWORD_CWORD_CWORD_CWORD,
  2924. /* 155 */ CWORD_CWORD_CWORD_CWORD,
  2925. /* 156 */ CWORD_CWORD_CWORD_CWORD,
  2926. /* 157 */ CWORD_CWORD_CWORD_CWORD,
  2927. /* 158 */ CWORD_CWORD_CWORD_CWORD,
  2928. /* 159 */ CWORD_CWORD_CWORD_CWORD,
  2929. /* 160 */ CWORD_CWORD_CWORD_CWORD,
  2930. /* 161 */ CWORD_CWORD_CWORD_CWORD,
  2931. /* 162 */ CWORD_CWORD_CWORD_CWORD,
  2932. /* 163 */ CWORD_CWORD_CWORD_CWORD,
  2933. /* 164 */ CWORD_CWORD_CWORD_CWORD,
  2934. /* 165 */ CWORD_CWORD_CWORD_CWORD,
  2935. /* 166 */ CWORD_CWORD_CWORD_CWORD,
  2936. /* 167 */ CWORD_CWORD_CWORD_CWORD,
  2937. /* 168 */ CWORD_CWORD_CWORD_CWORD,
  2938. /* 169 */ CWORD_CWORD_CWORD_CWORD,
  2939. /* 170 */ CWORD_CWORD_CWORD_CWORD,
  2940. /* 171 */ CWORD_CWORD_CWORD_CWORD,
  2941. /* 172 */ CWORD_CWORD_CWORD_CWORD,
  2942. /* 173 */ CWORD_CWORD_CWORD_CWORD,
  2943. /* 174 */ CWORD_CWORD_CWORD_CWORD,
  2944. /* 175 */ CWORD_CWORD_CWORD_CWORD,
  2945. /* 176 */ CWORD_CWORD_CWORD_CWORD,
  2946. /* 177 */ CWORD_CWORD_CWORD_CWORD,
  2947. /* 178 */ CWORD_CWORD_CWORD_CWORD,
  2948. /* 179 */ CWORD_CWORD_CWORD_CWORD,
  2949. /* 180 */ CWORD_CWORD_CWORD_CWORD,
  2950. /* 181 */ CWORD_CWORD_CWORD_CWORD,
  2951. /* 182 */ CWORD_CWORD_CWORD_CWORD,
  2952. /* 183 */ CWORD_CWORD_CWORD_CWORD,
  2953. /* 184 */ CWORD_CWORD_CWORD_CWORD,
  2954. /* 185 */ CWORD_CWORD_CWORD_CWORD,
  2955. /* 186 */ CWORD_CWORD_CWORD_CWORD,
  2956. /* 187 */ CWORD_CWORD_CWORD_CWORD,
  2957. /* 188 */ CWORD_CWORD_CWORD_CWORD,
  2958. /* 189 */ CWORD_CWORD_CWORD_CWORD,
  2959. /* 190 */ CWORD_CWORD_CWORD_CWORD,
  2960. /* 191 */ CWORD_CWORD_CWORD_CWORD,
  2961. /* 192 */ CWORD_CWORD_CWORD_CWORD,
  2962. /* 193 */ CWORD_CWORD_CWORD_CWORD,
  2963. /* 194 */ CWORD_CWORD_CWORD_CWORD,
  2964. /* 195 */ CWORD_CWORD_CWORD_CWORD,
  2965. /* 196 */ CWORD_CWORD_CWORD_CWORD,
  2966. /* 197 */ CWORD_CWORD_CWORD_CWORD,
  2967. /* 198 */ CWORD_CWORD_CWORD_CWORD,
  2968. /* 199 */ CWORD_CWORD_CWORD_CWORD,
  2969. /* 200 */ CWORD_CWORD_CWORD_CWORD,
  2970. /* 201 */ CWORD_CWORD_CWORD_CWORD,
  2971. /* 202 */ CWORD_CWORD_CWORD_CWORD,
  2972. /* 203 */ CWORD_CWORD_CWORD_CWORD,
  2973. /* 204 */ CWORD_CWORD_CWORD_CWORD,
  2974. /* 205 */ CWORD_CWORD_CWORD_CWORD,
  2975. /* 206 */ CWORD_CWORD_CWORD_CWORD,
  2976. /* 207 */ CWORD_CWORD_CWORD_CWORD,
  2977. /* 208 */ CWORD_CWORD_CWORD_CWORD,
  2978. /* 209 */ CWORD_CWORD_CWORD_CWORD,
  2979. /* 210 */ CWORD_CWORD_CWORD_CWORD,
  2980. /* 211 */ CWORD_CWORD_CWORD_CWORD,
  2981. /* 212 */ CWORD_CWORD_CWORD_CWORD,
  2982. /* 213 */ CWORD_CWORD_CWORD_CWORD,
  2983. /* 214 */ CWORD_CWORD_CWORD_CWORD,
  2984. /* 215 */ CWORD_CWORD_CWORD_CWORD,
  2985. /* 216 */ CWORD_CWORD_CWORD_CWORD,
  2986. /* 217 */ CWORD_CWORD_CWORD_CWORD,
  2987. /* 218 */ CWORD_CWORD_CWORD_CWORD,
  2988. /* 219 */ CWORD_CWORD_CWORD_CWORD,
  2989. /* 220 */ CWORD_CWORD_CWORD_CWORD,
  2990. /* 221 */ CWORD_CWORD_CWORD_CWORD,
  2991. /* 222 */ CWORD_CWORD_CWORD_CWORD,
  2992. /* 223 */ CWORD_CWORD_CWORD_CWORD,
  2993. /* 224 */ CWORD_CWORD_CWORD_CWORD,
  2994. /* 225 */ CWORD_CWORD_CWORD_CWORD,
  2995. /* 226 */ CWORD_CWORD_CWORD_CWORD,
  2996. /* 227 */ CWORD_CWORD_CWORD_CWORD,
  2997. /* 228 */ CWORD_CWORD_CWORD_CWORD,
  2998. /* 229 */ CWORD_CWORD_CWORD_CWORD,
  2999. /* 230 */ CWORD_CWORD_CWORD_CWORD,
  3000. /* 231 */ CWORD_CWORD_CWORD_CWORD,
  3001. /* 232 */ CWORD_CWORD_CWORD_CWORD,
  3002. /* 233 */ CWORD_CWORD_CWORD_CWORD,
  3003. /* 234 */ CWORD_CWORD_CWORD_CWORD,
  3004. /* 235 */ CWORD_CWORD_CWORD_CWORD,
  3005. /* 236 */ CWORD_CWORD_CWORD_CWORD,
  3006. /* 237 */ CWORD_CWORD_CWORD_CWORD,
  3007. /* 238 */ CWORD_CWORD_CWORD_CWORD,
  3008. /* 239 */ CWORD_CWORD_CWORD_CWORD,
  3009. /* 230 */ CWORD_CWORD_CWORD_CWORD,
  3010. /* 241 */ CWORD_CWORD_CWORD_CWORD,
  3011. /* 242 */ CWORD_CWORD_CWORD_CWORD,
  3012. /* 243 */ CWORD_CWORD_CWORD_CWORD,
  3013. /* 244 */ CWORD_CWORD_CWORD_CWORD,
  3014. /* 245 */ CWORD_CWORD_CWORD_CWORD,
  3015. /* 246 */ CWORD_CWORD_CWORD_CWORD,
  3016. /* 247 */ CWORD_CWORD_CWORD_CWORD,
  3017. /* 248 */ CWORD_CWORD_CWORD_CWORD,
  3018. /* 249 */ CWORD_CWORD_CWORD_CWORD,
  3019. /* 250 */ CWORD_CWORD_CWORD_CWORD,
  3020. /* 251 */ CWORD_CWORD_CWORD_CWORD,
  3021. /* 252 */ CWORD_CWORD_CWORD_CWORD,
  3022. /* 253 */ CWORD_CWORD_CWORD_CWORD,
  3023. /* 254 */ CWORD_CWORD_CWORD_CWORD,
  3024. /* 255 */ CWORD_CWORD_CWORD_CWORD,
  3025. /* PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
  3026. # if ENABLE_ASH_ALIAS
  3027. /* PEOA */ CSPCL_CIGN_CIGN_CIGN,
  3028. # endif
  3029. };
  3030. #if 1
  3031. # define SIT(c, syntax) ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf)
  3032. #else /* debug version, caught one signed char bug */
  3033. # define SIT(c, syntax) \
  3034. ({ \
  3035. if ((c) < 0 || (c) > (PEOF + ENABLE_ASH_ALIAS)) \
  3036. bb_error_msg_and_die("line:%d c:%d", __LINE__, (c)); \
  3037. if ((syntax) < 0 || (syntax) > (2 + ENABLE_FEATURE_SH_MATH)) \
  3038. bb_error_msg_and_die("line:%d c:%d", __LINE__, (c)); \
  3039. ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf); \
  3040. })
  3041. #endif
  3042. #endif /* !USE_SIT_FUNCTION */
  3043. /* ============ Alias handling */
  3044. #if ENABLE_ASH_ALIAS
  3045. #define ALIASINUSE 1
  3046. #define ALIASDEAD 2
  3047. struct alias {
  3048. struct alias *next;
  3049. char *name;
  3050. char *val;
  3051. int flag;
  3052. };
  3053. static struct alias **atab; // [ATABSIZE];
  3054. #define INIT_G_alias() do { \
  3055. atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
  3056. } while (0)
  3057. static struct alias **
  3058. __lookupalias(const char *name)
  3059. {
  3060. unsigned int hashval;
  3061. struct alias **app;
  3062. const char *p;
  3063. unsigned int ch;
  3064. p = name;
  3065. ch = (unsigned char)*p;
  3066. hashval = ch << 4;
  3067. while (ch) {
  3068. hashval += ch;
  3069. ch = (unsigned char)*++p;
  3070. }
  3071. app = &atab[hashval % ATABSIZE];
  3072. for (; *app; app = &(*app)->next) {
  3073. if (strcmp(name, (*app)->name) == 0) {
  3074. break;
  3075. }
  3076. }
  3077. return app;
  3078. }
  3079. static struct alias *
  3080. lookupalias(const char *name, int check)
  3081. {
  3082. struct alias *ap = *__lookupalias(name);
  3083. if (check && ap && (ap->flag & ALIASINUSE))
  3084. return NULL;
  3085. return ap;
  3086. }
  3087. static struct alias *
  3088. freealias(struct alias *ap)
  3089. {
  3090. struct alias *next;
  3091. if (ap->flag & ALIASINUSE) {
  3092. ap->flag |= ALIASDEAD;
  3093. return ap;
  3094. }
  3095. next = ap->next;
  3096. free(ap->name);
  3097. free(ap->val);
  3098. free(ap);
  3099. return next;
  3100. }
  3101. static void
  3102. setalias(const char *name, const char *val)
  3103. {
  3104. struct alias *ap, **app;
  3105. app = __lookupalias(name);
  3106. ap = *app;
  3107. INT_OFF;
  3108. if (ap) {
  3109. if (!(ap->flag & ALIASINUSE)) {
  3110. free(ap->val);
  3111. }
  3112. ap->val = ckstrdup(val);
  3113. ap->flag &= ~ALIASDEAD;
  3114. } else {
  3115. /* not found */
  3116. ap = ckzalloc(sizeof(struct alias));
  3117. ap->name = ckstrdup(name);
  3118. ap->val = ckstrdup(val);
  3119. /*ap->flag = 0; - ckzalloc did it */
  3120. /*ap->next = NULL;*/
  3121. *app = ap;
  3122. }
  3123. INT_ON;
  3124. }
  3125. static int
  3126. unalias(const char *name)
  3127. {
  3128. struct alias **app;
  3129. app = __lookupalias(name);
  3130. if (*app) {
  3131. INT_OFF;
  3132. *app = freealias(*app);
  3133. INT_ON;
  3134. return 0;
  3135. }
  3136. return 1;
  3137. }
  3138. static void
  3139. rmaliases(void)
  3140. {
  3141. struct alias *ap, **app;
  3142. int i;
  3143. INT_OFF;
  3144. for (i = 0; i < ATABSIZE; i++) {
  3145. app = &atab[i];
  3146. for (ap = *app; ap; ap = *app) {
  3147. *app = freealias(*app);
  3148. if (ap == *app) {
  3149. app = &ap->next;
  3150. }
  3151. }
  3152. }
  3153. INT_ON;
  3154. }
  3155. static void
  3156. printalias(const struct alias *ap)
  3157. {
  3158. out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
  3159. }
  3160. /*
  3161. * TODO - sort output
  3162. */
  3163. static int FAST_FUNC
  3164. aliascmd(int argc UNUSED_PARAM, char **argv)
  3165. {
  3166. char *n, *v;
  3167. int ret = 0;
  3168. struct alias *ap;
  3169. if (!argv[1]) {
  3170. int i;
  3171. for (i = 0; i < ATABSIZE; i++) {
  3172. for (ap = atab[i]; ap; ap = ap->next) {
  3173. printalias(ap);
  3174. }
  3175. }
  3176. return 0;
  3177. }
  3178. while ((n = *++argv) != NULL) {
  3179. v = strchr(n+1, '=');
  3180. if (v == NULL) { /* n+1: funny ksh stuff */
  3181. ap = *__lookupalias(n);
  3182. if (ap == NULL) {
  3183. fprintf(stderr, "%s: %s not found\n", "alias", n);
  3184. ret = 1;
  3185. } else
  3186. printalias(ap);
  3187. } else {
  3188. *v++ = '\0';
  3189. setalias(n, v);
  3190. }
  3191. }
  3192. return ret;
  3193. }
  3194. static int FAST_FUNC
  3195. unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  3196. {
  3197. int i;
  3198. while (nextopt("a") != '\0') {
  3199. rmaliases();
  3200. return 0;
  3201. }
  3202. for (i = 0; *argptr; argptr++) {
  3203. if (unalias(*argptr)) {
  3204. fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
  3205. i = 1;
  3206. }
  3207. }
  3208. return i;
  3209. }
  3210. #endif /* ASH_ALIAS */
  3211. /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
  3212. #define FORK_FG 0
  3213. #define FORK_BG 1
  3214. #define FORK_NOJOB 2
  3215. /* mode flags for showjob(s) */
  3216. #define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
  3217. #define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
  3218. #define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
  3219. #define SHOW_STDERR 0x08 /* print to stderr (else stdout) */
  3220. /*
  3221. * A job structure contains information about a job. A job is either a
  3222. * single process or a set of processes contained in a pipeline. In the
  3223. * latter case, pidlist will be non-NULL, and will point to a -1 terminated
  3224. * array of pids.
  3225. */
  3226. struct procstat {
  3227. pid_t ps_pid; /* process id */
  3228. int ps_status; /* last process status from wait() */
  3229. char *ps_cmd; /* text of command being run */
  3230. };
  3231. struct job {
  3232. struct procstat ps0; /* status of process */
  3233. struct procstat *ps; /* status of processes when more than one */
  3234. #if JOBS
  3235. int stopstatus; /* status of a stopped job */
  3236. #endif
  3237. unsigned nprocs; /* number of processes */
  3238. #define JOBRUNNING 0 /* at least one proc running */
  3239. #define JOBSTOPPED 1 /* all procs are stopped */
  3240. #define JOBDONE 2 /* all procs are completed */
  3241. unsigned
  3242. state: 8,
  3243. #if JOBS
  3244. sigint: 1, /* job was killed by SIGINT */
  3245. jobctl: 1, /* job running under job control */
  3246. #endif
  3247. waited: 1, /* true if this entry has been waited for */
  3248. used: 1, /* true if this entry is in used */
  3249. changed: 1; /* true if status has changed */
  3250. struct job *prev_job; /* previous job */
  3251. };
  3252. static struct job *makejob(/*union node *,*/ int);
  3253. static int forkshell(struct job *, union node *, int);
  3254. static int waitforjob(struct job *);
  3255. #if !JOBS
  3256. enum { doing_jobctl = 0 };
  3257. #define setjobctl(on) do {} while (0)
  3258. #else
  3259. static smallint doing_jobctl; //references:8
  3260. static void setjobctl(int);
  3261. #endif
  3262. /*
  3263. * Ignore a signal.
  3264. */
  3265. static void
  3266. ignoresig(int signo)
  3267. {
  3268. /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
  3269. if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
  3270. /* No, need to do it */
  3271. signal(signo, SIG_IGN);
  3272. }
  3273. sigmode[signo - 1] = S_HARD_IGN;
  3274. }
  3275. /*
  3276. * Only one usage site - in setsignal()
  3277. */
  3278. static void
  3279. signal_handler(int signo)
  3280. {
  3281. if (signo == SIGCHLD) {
  3282. got_sigchld = 1;
  3283. if (!trap[SIGCHLD])
  3284. return;
  3285. }
  3286. gotsig[signo - 1] = 1;
  3287. pending_sig = signo;
  3288. if (signo == SIGINT && !trap[SIGINT]) {
  3289. if (!suppress_int) {
  3290. pending_sig = 0;
  3291. raise_interrupt(); /* does not return */
  3292. }
  3293. pending_int = 1;
  3294. }
  3295. }
  3296. /*
  3297. * Set the signal handler for the specified signal. The routine figures
  3298. * out what it should be set to.
  3299. */
  3300. static void
  3301. setsignal(int signo)
  3302. {
  3303. char *t;
  3304. char cur_act, new_act;
  3305. struct sigaction act;
  3306. t = trap[signo];
  3307. new_act = S_DFL;
  3308. if (t != NULL) { /* trap for this sig is set */
  3309. new_act = S_CATCH;
  3310. if (t[0] == '\0') /* trap is "": ignore this sig */
  3311. new_act = S_IGN;
  3312. }
  3313. if (rootshell && new_act == S_DFL) {
  3314. switch (signo) {
  3315. case SIGINT:
  3316. if (iflag || minusc || sflag == 0)
  3317. new_act = S_CATCH;
  3318. break;
  3319. case SIGQUIT:
  3320. #if DEBUG
  3321. if (debug)
  3322. break;
  3323. #endif
  3324. /* man bash:
  3325. * "In all cases, bash ignores SIGQUIT. Non-builtin
  3326. * commands run by bash have signal handlers
  3327. * set to the values inherited by the shell
  3328. * from its parent". */
  3329. new_act = S_IGN;
  3330. break;
  3331. case SIGTERM:
  3332. if (iflag)
  3333. new_act = S_IGN;
  3334. break;
  3335. #if JOBS
  3336. case SIGTSTP:
  3337. case SIGTTOU:
  3338. if (mflag)
  3339. new_act = S_IGN;
  3340. break;
  3341. #endif
  3342. }
  3343. }
  3344. /* if !rootshell, we reset SIGQUIT to DFL,
  3345. * whereas we have to restore it to what shell got on entry.
  3346. * This is handled by the fact that if signal was IGNored on entry,
  3347. * then cur_act is S_HARD_IGN and we never change its sigaction
  3348. * (see code below).
  3349. */
  3350. if (signo == SIGCHLD)
  3351. new_act = S_CATCH;
  3352. t = &sigmode[signo - 1];
  3353. cur_act = *t;
  3354. if (cur_act == 0) {
  3355. /* current setting is not yet known */
  3356. if (sigaction(signo, NULL, &act)) {
  3357. /* pretend it worked; maybe we should give a warning,
  3358. * but other shells don't. We don't alter sigmode,
  3359. * so we retry every time.
  3360. * btw, in Linux it never fails. --vda */
  3361. return;
  3362. }
  3363. if (act.sa_handler == SIG_IGN) {
  3364. cur_act = S_HARD_IGN;
  3365. if (mflag
  3366. && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
  3367. ) {
  3368. cur_act = S_IGN; /* don't hard ignore these */
  3369. }
  3370. }
  3371. if (act.sa_handler == SIG_DFL && new_act == S_DFL) {
  3372. /* installing SIG_DFL over SIG_DFL is a no-op */
  3373. /* saves one sigaction call in each "sh -c SCRIPT" invocation */
  3374. *t = S_DFL;
  3375. return;
  3376. }
  3377. }
  3378. if (cur_act == S_HARD_IGN || cur_act == new_act)
  3379. return;
  3380. *t = new_act;
  3381. act.sa_handler = SIG_DFL;
  3382. switch (new_act) {
  3383. case S_CATCH:
  3384. act.sa_handler = signal_handler;
  3385. break;
  3386. case S_IGN:
  3387. act.sa_handler = SIG_IGN;
  3388. break;
  3389. }
  3390. /* flags and mask matter only if !DFL and !IGN, but we do it
  3391. * for all cases for more deterministic behavior:
  3392. */
  3393. act.sa_flags = 0; //TODO: why not SA_RESTART?
  3394. sigfillset(&act.sa_mask);
  3395. sigaction_set(signo, &act);
  3396. }
  3397. /* mode flags for set_curjob */
  3398. #define CUR_DELETE 2
  3399. #define CUR_RUNNING 1
  3400. #define CUR_STOPPED 0
  3401. #if JOBS
  3402. /* pgrp of shell on invocation */
  3403. static int initialpgrp; //references:2
  3404. static int ttyfd = -1; //5
  3405. #endif
  3406. /* array of jobs */
  3407. static struct job *jobtab; //5
  3408. /* size of array */
  3409. static unsigned njobs; //4
  3410. /* current job */
  3411. static struct job *curjob; //lots
  3412. #if 0
  3413. /* Bash has a feature: it restores termios after a successful wait for
  3414. * a foreground job which had at least one stopped or sigkilled member.
  3415. * The probable rationale is that SIGSTOP and SIGKILL can preclude task from
  3416. * properly restoring tty state. Should we do this too?
  3417. * A reproducer: ^Z an interactive python:
  3418. *
  3419. * # python
  3420. * Python 2.7.12 (...)
  3421. * >>> ^Z
  3422. * { python leaves tty in -icanon -echo state. We do survive that... }
  3423. * [1]+ Stopped python
  3424. * { ...however, next program (python #2) does not survive it well: }
  3425. * # python
  3426. * Python 2.7.12 (...)
  3427. * >>> Traceback (most recent call last):
  3428. * { above, I typed "qwerty<CR>", but -echo state is still in effect }
  3429. * File "<stdin>", line 1, in <module>
  3430. * NameError: name 'qwerty' is not defined
  3431. *
  3432. * The implementation below is modeled on bash code and seems to work.
  3433. * However, I'm not sure we should do this. For one: what if I'd fg
  3434. * the stopped python instead? It'll be confused by "restored" tty state.
  3435. */
  3436. static struct termios shell_tty_info;
  3437. static void
  3438. get_tty_state(void)
  3439. {
  3440. if (rootshell && ttyfd >= 0)
  3441. tcgetattr(ttyfd, &shell_tty_info);
  3442. }
  3443. static void
  3444. set_tty_state(void)
  3445. {
  3446. /* if (rootshell) - caller ensures this */
  3447. if (ttyfd >= 0)
  3448. tcsetattr(ttyfd, TCSADRAIN, &shell_tty_info);
  3449. }
  3450. static int
  3451. job_signal_status(struct job *jp)
  3452. {
  3453. int status;
  3454. unsigned i;
  3455. struct procstat *ps = jp->ps;
  3456. for (i = 0; i < jp->nprocs; i++) {
  3457. status = ps[i].ps_status;
  3458. if (WIFSIGNALED(status) || WIFSTOPPED(status))
  3459. return status;
  3460. }
  3461. return 0;
  3462. }
  3463. static void
  3464. restore_tty_if_stopped_or_signaled(struct job *jp)
  3465. {
  3466. //TODO: check what happens if we come from waitforjob() in expbackq()
  3467. if (rootshell) {
  3468. int s = job_signal_status(jp);
  3469. if (s) /* WIFSIGNALED(s) || WIFSTOPPED(s) */
  3470. set_tty_state();
  3471. }
  3472. }
  3473. #else
  3474. # define get_tty_state() ((void)0)
  3475. # define restore_tty_if_stopped_or_signaled(jp) ((void)0)
  3476. #endif
  3477. static void
  3478. set_curjob(struct job *jp, unsigned mode)
  3479. {
  3480. struct job *jp1;
  3481. struct job **jpp, **curp;
  3482. /* first remove from list */
  3483. jpp = curp = &curjob;
  3484. while (1) {
  3485. jp1 = *jpp;
  3486. if (jp1 == jp)
  3487. break;
  3488. jpp = &jp1->prev_job;
  3489. }
  3490. *jpp = jp1->prev_job;
  3491. /* Then re-insert in correct position */
  3492. jpp = curp;
  3493. switch (mode) {
  3494. default:
  3495. #if DEBUG
  3496. abort();
  3497. #endif
  3498. case CUR_DELETE:
  3499. /* job being deleted */
  3500. break;
  3501. case CUR_RUNNING:
  3502. /* newly created job or backgrounded job,
  3503. * put after all stopped jobs.
  3504. */
  3505. while (1) {
  3506. jp1 = *jpp;
  3507. #if JOBS
  3508. if (!jp1 || jp1->state != JOBSTOPPED)
  3509. #endif
  3510. break;
  3511. jpp = &jp1->prev_job;
  3512. }
  3513. /* FALLTHROUGH */
  3514. #if JOBS
  3515. case CUR_STOPPED:
  3516. #endif
  3517. /* newly stopped job - becomes curjob */
  3518. jp->prev_job = *jpp;
  3519. *jpp = jp;
  3520. break;
  3521. }
  3522. }
  3523. #if JOBS || DEBUG
  3524. static int
  3525. jobno(const struct job *jp)
  3526. {
  3527. return jp - jobtab + 1;
  3528. }
  3529. #endif
  3530. /*
  3531. * Convert a job name to a job structure.
  3532. */
  3533. #if !JOBS
  3534. #define getjob(name, getctl) getjob(name)
  3535. #endif
  3536. static struct job *
  3537. getjob(const char *name, int getctl)
  3538. {
  3539. struct job *jp;
  3540. struct job *found;
  3541. const char *err_msg = "%s: no such job";
  3542. unsigned num;
  3543. int c;
  3544. const char *p;
  3545. char *(*match)(const char *, const char *);
  3546. jp = curjob;
  3547. p = name;
  3548. if (!p)
  3549. goto currentjob;
  3550. if (*p != '%')
  3551. goto err;
  3552. c = *++p;
  3553. if (!c)
  3554. goto currentjob;
  3555. if (!p[1]) {
  3556. if (c == '+' || c == '%') {
  3557. currentjob:
  3558. err_msg = "No current job";
  3559. goto check;
  3560. }
  3561. if (c == '-') {
  3562. if (jp)
  3563. jp = jp->prev_job;
  3564. err_msg = "No previous job";
  3565. check:
  3566. if (!jp)
  3567. goto err;
  3568. goto gotit;
  3569. }
  3570. }
  3571. if (is_number(p)) {
  3572. num = atoi(p);
  3573. if (num > 0 && num <= njobs) {
  3574. jp = jobtab + num - 1;
  3575. if (jp->used)
  3576. goto gotit;
  3577. goto err;
  3578. }
  3579. }
  3580. match = prefix;
  3581. if (*p == '?') {
  3582. match = strstr;
  3583. p++;
  3584. }
  3585. found = NULL;
  3586. while (jp) {
  3587. if (match(jp->ps[0].ps_cmd, p)) {
  3588. if (found)
  3589. goto err;
  3590. found = jp;
  3591. err_msg = "%s: ambiguous";
  3592. }
  3593. jp = jp->prev_job;
  3594. }
  3595. if (!found)
  3596. goto err;
  3597. jp = found;
  3598. gotit:
  3599. #if JOBS
  3600. err_msg = "job %s not created under job control";
  3601. if (getctl && jp->jobctl == 0)
  3602. goto err;
  3603. #endif
  3604. return jp;
  3605. err:
  3606. ash_msg_and_raise_error(err_msg, name);
  3607. }
  3608. /*
  3609. * Mark a job structure as unused.
  3610. */
  3611. static void
  3612. freejob(struct job *jp)
  3613. {
  3614. struct procstat *ps;
  3615. int i;
  3616. INT_OFF;
  3617. for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
  3618. if (ps->ps_cmd != nullstr)
  3619. free(ps->ps_cmd);
  3620. }
  3621. if (jp->ps != &jp->ps0)
  3622. free(jp->ps);
  3623. jp->used = 0;
  3624. set_curjob(jp, CUR_DELETE);
  3625. INT_ON;
  3626. }
  3627. #if JOBS
  3628. static void
  3629. xtcsetpgrp(int fd, pid_t pgrp)
  3630. {
  3631. if (tcsetpgrp(fd, pgrp))
  3632. ash_msg_and_raise_perror("can't set tty process group");
  3633. }
  3634. /*
  3635. * Turn job control on and off.
  3636. *
  3637. * Note: This code assumes that the third arg to ioctl is a character
  3638. * pointer, which is true on Berkeley systems but not System V. Since
  3639. * System V doesn't have job control yet, this isn't a problem now.
  3640. *
  3641. * Called with interrupts off.
  3642. */
  3643. static void
  3644. setjobctl(int on)
  3645. {
  3646. int fd;
  3647. int pgrp;
  3648. if (on == doing_jobctl || rootshell == 0)
  3649. return;
  3650. if (on) {
  3651. int ofd;
  3652. ofd = fd = open(_PATH_TTY, O_RDWR);
  3653. if (fd < 0) {
  3654. /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
  3655. * That sometimes helps to acquire controlling tty.
  3656. * Obviously, a workaround for bugs when someone
  3657. * failed to provide a controlling tty to bash! :) */
  3658. fd = 2;
  3659. while (!isatty(fd))
  3660. if (--fd < 0)
  3661. goto out;
  3662. }
  3663. /* fd is a tty at this point */
  3664. fd = fcntl(fd, F_DUPFD_CLOEXEC, 10);
  3665. if (ofd >= 0) /* if it is "/dev/tty", close. If 0/1/2, don't */
  3666. close(ofd);
  3667. if (fd < 0)
  3668. goto out; /* F_DUPFD failed */
  3669. if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
  3670. close_on_exec_on(fd);
  3671. while (1) { /* while we are in the background */
  3672. pgrp = tcgetpgrp(fd);
  3673. if (pgrp < 0) {
  3674. out:
  3675. ash_msg("can't access tty; job control turned off");
  3676. mflag = on = 0;
  3677. goto close;
  3678. }
  3679. if (pgrp == getpgrp())
  3680. break;
  3681. killpg(0, SIGTTIN);
  3682. }
  3683. initialpgrp = pgrp;
  3684. setsignal(SIGTSTP);
  3685. setsignal(SIGTTOU);
  3686. setsignal(SIGTTIN);
  3687. pgrp = rootpid;
  3688. setpgid(0, pgrp);
  3689. xtcsetpgrp(fd, pgrp);
  3690. } else {
  3691. /* turning job control off */
  3692. fd = ttyfd;
  3693. pgrp = initialpgrp;
  3694. /* was xtcsetpgrp, but this can make exiting ash
  3695. * loop forever if pty is already deleted */
  3696. tcsetpgrp(fd, pgrp);
  3697. setpgid(0, pgrp);
  3698. setsignal(SIGTSTP);
  3699. setsignal(SIGTTOU);
  3700. setsignal(SIGTTIN);
  3701. close:
  3702. if (fd >= 0)
  3703. close(fd);
  3704. fd = -1;
  3705. }
  3706. ttyfd = fd;
  3707. doing_jobctl = on;
  3708. }
  3709. static int FAST_FUNC
  3710. killcmd(int argc, char **argv)
  3711. {
  3712. if (argv[1] && strcmp(argv[1], "-l") != 0) {
  3713. int i = 1;
  3714. do {
  3715. if (argv[i][0] == '%') {
  3716. /*
  3717. * "kill %N" - job kill
  3718. * Converting to pgrp / pid kill
  3719. */
  3720. struct job *jp;
  3721. char *dst;
  3722. int j, n;
  3723. jp = getjob(argv[i], 0);
  3724. /*
  3725. * In jobs started under job control, we signal
  3726. * entire process group by kill -PGRP_ID.
  3727. * This happens, f.e., in interactive shell.
  3728. *
  3729. * Otherwise, we signal each child via
  3730. * kill PID1 PID2 PID3.
  3731. * Testcases:
  3732. * sh -c 'sleep 1|sleep 1 & kill %1'
  3733. * sh -c 'true|sleep 2 & sleep 1; kill %1'
  3734. * sh -c 'true|sleep 1 & sleep 2; kill %1'
  3735. */
  3736. n = jp->nprocs; /* can't be 0 (I hope) */
  3737. if (jp->jobctl)
  3738. n = 1;
  3739. dst = alloca(n * sizeof(int)*4);
  3740. argv[i] = dst;
  3741. for (j = 0; j < n; j++) {
  3742. struct procstat *ps = &jp->ps[j];
  3743. /* Skip non-running and not-stopped members
  3744. * (i.e. dead members) of the job
  3745. */
  3746. if (ps->ps_status != -1 && !WIFSTOPPED(ps->ps_status))
  3747. continue;
  3748. /*
  3749. * kill_main has matching code to expect
  3750. * leading space. Needed to not confuse
  3751. * negative pids with "kill -SIGNAL_NO" syntax
  3752. */
  3753. dst += sprintf(dst, jp->jobctl ? " -%u" : " %u", (int)ps->ps_pid);
  3754. }
  3755. *dst = '\0';
  3756. }
  3757. } while (argv[++i]);
  3758. }
  3759. return kill_main(argc, argv);
  3760. }
  3761. static void
  3762. showpipe(struct job *jp /*, FILE *out*/)
  3763. {
  3764. struct procstat *ps;
  3765. struct procstat *psend;
  3766. psend = jp->ps + jp->nprocs;
  3767. for (ps = jp->ps + 1; ps < psend; ps++)
  3768. printf(" | %s", ps->ps_cmd);
  3769. newline_and_flush(stdout);
  3770. flush_stdout_stderr();
  3771. }
  3772. static int
  3773. restartjob(struct job *jp, int mode)
  3774. {
  3775. struct procstat *ps;
  3776. int i;
  3777. int status;
  3778. pid_t pgid;
  3779. INT_OFF;
  3780. if (jp->state == JOBDONE)
  3781. goto out;
  3782. jp->state = JOBRUNNING;
  3783. pgid = jp->ps[0].ps_pid;
  3784. if (mode == FORK_FG) {
  3785. get_tty_state();
  3786. xtcsetpgrp(ttyfd, pgid);
  3787. }
  3788. killpg(pgid, SIGCONT);
  3789. ps = jp->ps;
  3790. i = jp->nprocs;
  3791. do {
  3792. if (WIFSTOPPED(ps->ps_status)) {
  3793. ps->ps_status = -1;
  3794. }
  3795. ps++;
  3796. } while (--i);
  3797. out:
  3798. status = (mode == FORK_FG) ? waitforjob(jp) : 0;
  3799. INT_ON;
  3800. return status;
  3801. }
  3802. static int FAST_FUNC
  3803. fg_bgcmd(int argc UNUSED_PARAM, char **argv)
  3804. {
  3805. struct job *jp;
  3806. int mode;
  3807. int retval;
  3808. mode = (**argv == 'f') ? FORK_FG : FORK_BG;
  3809. nextopt(nullstr);
  3810. argv = argptr;
  3811. do {
  3812. jp = getjob(*argv, 1);
  3813. if (mode == FORK_BG) {
  3814. set_curjob(jp, CUR_RUNNING);
  3815. printf("[%d] ", jobno(jp));
  3816. }
  3817. out1str(jp->ps[0].ps_cmd);
  3818. showpipe(jp /*, stdout*/);
  3819. retval = restartjob(jp, mode);
  3820. } while (*argv && *++argv);
  3821. return retval;
  3822. }
  3823. #endif
  3824. static int
  3825. sprint_status48(char *os, int status, int sigonly)
  3826. {
  3827. char *s = os;
  3828. int st;
  3829. if (!WIFEXITED(status)) {
  3830. #if JOBS
  3831. if (WIFSTOPPED(status))
  3832. st = WSTOPSIG(status);
  3833. else
  3834. #endif
  3835. st = WTERMSIG(status);
  3836. if (sigonly) {
  3837. if (st == SIGINT || st == SIGPIPE)
  3838. goto out;
  3839. #if JOBS
  3840. if (WIFSTOPPED(status))
  3841. goto out;
  3842. #endif
  3843. }
  3844. st &= 0x7f;
  3845. //TODO: use bbox's get_signame? strsignal adds ~600 bytes to text+rodata
  3846. //s = stpncpy(s, strsignal(st), 32); //not all libc have stpncpy()
  3847. s += fmtstr(s, 32, strsignal(st));
  3848. if (WCOREDUMP(status)) {
  3849. s = stpcpy(s, " (core dumped)");
  3850. }
  3851. } else if (!sigonly) {
  3852. st = WEXITSTATUS(status);
  3853. s += fmtstr(s, 16, (st ? "Done(%d)" : "Done"), st);
  3854. }
  3855. out:
  3856. return s - os;
  3857. }
  3858. static int
  3859. wait_block_or_sig(int *status)
  3860. {
  3861. int pid;
  3862. do {
  3863. sigset_t mask;
  3864. /* Poll all children for changes in their state */
  3865. got_sigchld = 0;
  3866. /* if job control is active, accept stopped processes too */
  3867. pid = waitpid(-1, status, doing_jobctl ? (WNOHANG|WUNTRACED) : WNOHANG);
  3868. if (pid != 0)
  3869. break; /* Error (e.g. EINTR, ECHILD) or pid */
  3870. /* Children exist, but none are ready. Sleep until interesting signal */
  3871. #if 1
  3872. sigfillset(&mask);
  3873. sigprocmask2(SIG_SETMASK, &mask); /* mask is updated */
  3874. while (!got_sigchld && !pending_sig) {
  3875. sigsuspend(&mask);
  3876. /* ^^^ add "sigdelset(&mask, SIGCHLD);" before sigsuspend
  3877. * to make sure SIGCHLD is not masked off?
  3878. * It was reported that this:
  3879. * fn() { : | return; }
  3880. * shopt -s lastpipe
  3881. * fn
  3882. * exec ash SCRIPT
  3883. * under bash 4.4.23 runs SCRIPT with SIGCHLD masked,
  3884. * making "wait" commands in SCRIPT block forever.
  3885. */
  3886. }
  3887. sigprocmask(SIG_SETMASK, &mask, NULL);
  3888. #else /* unsafe: a signal can set pending_sig after check, but before pause() */
  3889. while (!got_sigchld && !pending_sig)
  3890. pause();
  3891. #endif
  3892. /* If it was SIGCHLD, poll children again */
  3893. } while (got_sigchld);
  3894. return pid;
  3895. }
  3896. #define DOWAIT_NONBLOCK 0
  3897. #define DOWAIT_BLOCK 1
  3898. #define DOWAIT_BLOCK_OR_SIG 2
  3899. #if BASH_WAIT_N
  3900. # define DOWAIT_JOBSTATUS 0x10 /* OR this to get job's exitstatus instead of pid */
  3901. #endif
  3902. static int
  3903. waitone(int block, struct job *job)
  3904. {
  3905. int pid;
  3906. int status;
  3907. struct job *jp;
  3908. struct job *thisjob;
  3909. #if BASH_WAIT_N
  3910. bool want_jobexitstatus = (block & DOWAIT_JOBSTATUS);
  3911. block = (block & ~DOWAIT_JOBSTATUS);
  3912. #endif
  3913. TRACE(("dowait(0x%x) called\n", block));
  3914. /* It's wrong to call waitpid() outside of INT_OFF region:
  3915. * signal can arrive just after syscall return and handler can
  3916. * longjmp away, losing stop/exit notification processing.
  3917. * Thus, for "jobs" builtin, and for waiting for a fg job,
  3918. * we call waitpid() (blocking or non-blocking) inside INT_OFF.
  3919. *
  3920. * However, for "wait" builtin it is wrong to simply call waitpid()
  3921. * in INT_OFF region: "wait" needs to wait for any running job
  3922. * to change state, but should exit on any trap too.
  3923. * In INT_OFF region, a signal just before syscall entry can set
  3924. * pending_sig variables, but we can't check them, and we would
  3925. * either enter a sleeping waitpid() (BUG), or need to busy-loop.
  3926. *
  3927. * Because of this, we run inside INT_OFF, but use a special routine
  3928. * which combines waitpid() and sigsuspend().
  3929. * This is the reason why we need to have a handler for SIGCHLD:
  3930. * SIG_DFL handler does not wake sigsuspend().
  3931. */
  3932. INT_OFF;
  3933. if (block == DOWAIT_BLOCK_OR_SIG) {
  3934. pid = wait_block_or_sig(&status);
  3935. } else {
  3936. int wait_flags = 0;
  3937. if (block == DOWAIT_NONBLOCK)
  3938. wait_flags = WNOHANG;
  3939. /* if job control is active, accept stopped processes too */
  3940. if (doing_jobctl)
  3941. wait_flags |= WUNTRACED;
  3942. /* NB: _not_ safe_waitpid, we need to detect EINTR */
  3943. pid = waitpid(-1, &status, wait_flags);
  3944. }
  3945. TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
  3946. pid, status, errno, strerror(errno)));
  3947. thisjob = NULL;
  3948. if (pid <= 0)
  3949. goto out;
  3950. for (jp = curjob; jp; jp = jp->prev_job) {
  3951. int jobstate;
  3952. struct procstat *ps;
  3953. struct procstat *psend;
  3954. if (jp->state == JOBDONE)
  3955. continue;
  3956. jobstate = JOBDONE;
  3957. ps = jp->ps;
  3958. psend = ps + jp->nprocs;
  3959. do {
  3960. if (ps->ps_pid == pid) {
  3961. TRACE(("Job %d: changing status of proc %d "
  3962. "from 0x%x to 0x%x\n",
  3963. jobno(jp), pid, ps->ps_status, status));
  3964. ps->ps_status = status;
  3965. thisjob = jp;
  3966. }
  3967. if (ps->ps_status == -1)
  3968. jobstate = JOBRUNNING;
  3969. #if JOBS
  3970. if (jobstate == JOBRUNNING)
  3971. continue;
  3972. if (WIFSTOPPED(ps->ps_status)) {
  3973. jp->stopstatus = ps->ps_status;
  3974. jobstate = JOBSTOPPED;
  3975. }
  3976. #endif
  3977. } while (++ps < psend);
  3978. if (!thisjob)
  3979. continue;
  3980. /* Found the job where one of its processes changed its state.
  3981. * Is there at least one live and running process in this job? */
  3982. if (jobstate != JOBRUNNING) {
  3983. /* No. All live processes in the job are stopped
  3984. * (JOBSTOPPED) or there are no live processes (JOBDONE)
  3985. */
  3986. thisjob->changed = 1;
  3987. if (thisjob->state != jobstate) {
  3988. TRACE(("Job %d: changing state from %d to %d\n",
  3989. jobno(thisjob), thisjob->state, jobstate));
  3990. thisjob->state = jobstate;
  3991. #if JOBS
  3992. if (jobstate == JOBSTOPPED)
  3993. set_curjob(thisjob, CUR_STOPPED);
  3994. #endif
  3995. }
  3996. }
  3997. goto out;
  3998. }
  3999. /* The process wasn't found in job list */
  4000. out:
  4001. INT_ON;
  4002. #if BASH_WAIT_N
  4003. if (want_jobexitstatus) {
  4004. pid = -1;
  4005. if (thisjob && thisjob->state == JOBDONE)
  4006. pid = thisjob->ps[thisjob->nprocs - 1].ps_status;
  4007. }
  4008. #endif
  4009. if (thisjob && thisjob == job) {
  4010. char s[48 + 1];
  4011. int len;
  4012. len = sprint_status48(s, status, 1);
  4013. if (len) {
  4014. s[len] = '\n';
  4015. s[len + 1] = '\0';
  4016. out2str(s);
  4017. }
  4018. }
  4019. return pid;
  4020. }
  4021. static int
  4022. dowait(int block, struct job *jp)
  4023. {
  4024. int pid = block == DOWAIT_NONBLOCK ? got_sigchld : 1;
  4025. while (jp ? jp->state == JOBRUNNING : pid > 0) {
  4026. if (!jp)
  4027. got_sigchld = 0;
  4028. pid = waitone(block, jp);
  4029. }
  4030. return pid;
  4031. }
  4032. #if JOBS
  4033. static void
  4034. showjob(struct job *jp, int mode)
  4035. {
  4036. struct procstat *ps;
  4037. struct procstat *psend;
  4038. int col;
  4039. int indent_col;
  4040. char s[16 + 16 + 48];
  4041. FILE *out = (mode & SHOW_STDERR ? stderr : stdout);
  4042. ps = jp->ps;
  4043. if (mode & SHOW_ONLY_PGID) { /* jobs -p */
  4044. /* just output process (group) id of pipeline */
  4045. fprintf(out, "%d\n", ps->ps_pid);
  4046. return;
  4047. }
  4048. col = fmtstr(s, 16, "[%d] ", jobno(jp));
  4049. indent_col = col;
  4050. if (jp == curjob)
  4051. s[col - 3] = '+';
  4052. else if (curjob && jp == curjob->prev_job)
  4053. s[col - 3] = '-';
  4054. if (mode & SHOW_PIDS)
  4055. col += fmtstr(s + col, 16, "%d ", ps->ps_pid);
  4056. psend = ps + jp->nprocs;
  4057. if (jp->state == JOBRUNNING) {
  4058. strcpy(s + col, "Running");
  4059. col += sizeof("Running") - 1;
  4060. } else {
  4061. int status = psend[-1].ps_status;
  4062. if (jp->state == JOBSTOPPED)
  4063. status = jp->stopstatus;
  4064. col += sprint_status48(s + col, status, 0);
  4065. }
  4066. /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
  4067. /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
  4068. * or prints several "PID | <cmdN>" lines,
  4069. * depending on SHOW_PIDS bit.
  4070. * We do not print status of individual processes
  4071. * between PID and <cmdN>. bash does it, but not very well:
  4072. * first line shows overall job status, not process status,
  4073. * making it impossible to know 1st process status.
  4074. */
  4075. goto start;
  4076. do {
  4077. /* for each process */
  4078. s[0] = '\0';
  4079. col = 33;
  4080. if (mode & SHOW_PIDS)
  4081. col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->ps_pid) - 1;
  4082. start:
  4083. fprintf(out, "%s%*c%s%s",
  4084. s,
  4085. 33 - col >= 0 ? 33 - col : 0, ' ',
  4086. ps == jp->ps ? "" : "| ",
  4087. ps->ps_cmd
  4088. );
  4089. } while (++ps != psend);
  4090. newline_and_flush(out);
  4091. jp->changed = 0;
  4092. if (jp->state == JOBDONE) {
  4093. TRACE(("showjob: freeing job %d\n", jobno(jp)));
  4094. freejob(jp);
  4095. }
  4096. }
  4097. /*
  4098. * Print a list of jobs. If "change" is nonzero, only print jobs whose
  4099. * statuses have changed since the last call to showjobs.
  4100. */
  4101. static void
  4102. showjobs(int mode)
  4103. {
  4104. struct job *jp;
  4105. TRACE(("showjobs(0x%x) called\n", mode));
  4106. /* Handle all finished jobs */
  4107. dowait(DOWAIT_NONBLOCK, NULL);
  4108. for (jp = curjob; jp; jp = jp->prev_job) {
  4109. if (!(mode & SHOW_CHANGED) || jp->changed) {
  4110. showjob(jp, mode);
  4111. }
  4112. }
  4113. }
  4114. static int FAST_FUNC
  4115. jobscmd(int argc UNUSED_PARAM, char **argv)
  4116. {
  4117. int mode, m;
  4118. mode = 0;
  4119. while ((m = nextopt("lp")) != '\0') {
  4120. if (m == 'l')
  4121. mode |= SHOW_PIDS;
  4122. else
  4123. mode |= SHOW_ONLY_PGID;
  4124. }
  4125. argv = argptr;
  4126. if (*argv) {
  4127. do
  4128. showjob(getjob(*argv, 0), mode);
  4129. while (*++argv);
  4130. } else {
  4131. showjobs(mode);
  4132. }
  4133. return 0;
  4134. }
  4135. #endif /* JOBS */
  4136. /* Called only on finished or stopped jobs (no members are running) */
  4137. static int
  4138. getstatus(struct job *job)
  4139. {
  4140. int status;
  4141. int retval;
  4142. struct procstat *ps;
  4143. /* Fetch last member's status */
  4144. ps = job->ps + job->nprocs - 1;
  4145. status = ps->ps_status;
  4146. if (pipefail) {
  4147. /* "set -o pipefail" mode: use last _nonzero_ status */
  4148. while (status == 0 && --ps >= job->ps)
  4149. status = ps->ps_status;
  4150. }
  4151. retval = WEXITSTATUS(status);
  4152. if (!WIFEXITED(status)) {
  4153. #if JOBS
  4154. retval = WSTOPSIG(status);
  4155. if (!WIFSTOPPED(status))
  4156. #endif
  4157. {
  4158. /* XXX: limits number of signals */
  4159. retval = WTERMSIG(status);
  4160. #if JOBS
  4161. if (retval == SIGINT)
  4162. job->sigint = 1;
  4163. #endif
  4164. }
  4165. retval += 128;
  4166. }
  4167. TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
  4168. jobno(job), job->nprocs, status, retval));
  4169. return retval;
  4170. }
  4171. static int FAST_FUNC
  4172. waitcmd(int argc UNUSED_PARAM, char **argv)
  4173. {
  4174. struct job *job;
  4175. int retval;
  4176. struct job *jp;
  4177. #if BASH_WAIT_N
  4178. int status;
  4179. char one = nextopt("n");
  4180. #else
  4181. nextopt(nullstr);
  4182. #endif
  4183. retval = 0;
  4184. argv = argptr;
  4185. if (!argv[0]) {
  4186. /* wait for all jobs / one job if -n */
  4187. for (;;) {
  4188. jp = curjob;
  4189. #if BASH_WAIT_N
  4190. if (one && !jp)
  4191. /* exitcode of "wait -n" with nothing to wait for is 127, not 0 */
  4192. retval = 127;
  4193. #endif
  4194. while (1) {
  4195. if (!jp) /* no running procs */
  4196. goto ret;
  4197. if (jp->state == JOBRUNNING)
  4198. break;
  4199. jp->waited = 1;
  4200. jp = jp->prev_job;
  4201. }
  4202. /* man bash:
  4203. * "When bash is waiting for an asynchronous command via
  4204. * the wait builtin, the reception of a signal for which a trap
  4205. * has been set will cause the wait builtin to return immediately
  4206. * with an exit status greater than 128, immediately after which
  4207. * the trap is executed."
  4208. */
  4209. #if BASH_WAIT_N
  4210. status = dowait(DOWAIT_BLOCK_OR_SIG | DOWAIT_JOBSTATUS, NULL);
  4211. #else
  4212. dowait(DOWAIT_BLOCK_OR_SIG, NULL);
  4213. #endif
  4214. /* if child sends us a signal *and immediately exits*,
  4215. * dowait() returns pid > 0. Check this case,
  4216. * not "if (dowait() < 0)"!
  4217. */
  4218. if (pending_sig)
  4219. goto sigout;
  4220. #if BASH_WAIT_N
  4221. if (one) {
  4222. /* wait -n waits for one _job_, not one _process_.
  4223. * date; sleep 3 & sleep 2 | sleep 1 & wait -n; date
  4224. * should wait for 2 seconds. Not 1 or 3.
  4225. */
  4226. if (status != -1 && !WIFSTOPPED(status)) {
  4227. retval = WEXITSTATUS(status);
  4228. if (WIFSIGNALED(status))
  4229. retval = WTERMSIG(status) + 128;
  4230. goto ret;
  4231. }
  4232. }
  4233. #endif
  4234. }
  4235. }
  4236. retval = 127;
  4237. do {
  4238. if (**argv != '%') {
  4239. pid_t pid = number(*argv);
  4240. job = curjob;
  4241. while (1) {
  4242. if (!job)
  4243. goto repeat;
  4244. if (job->ps[job->nprocs - 1].ps_pid == pid)
  4245. break;
  4246. job = job->prev_job;
  4247. }
  4248. } else {
  4249. job = getjob(*argv, 0);
  4250. }
  4251. /* loop until process terminated or stopped */
  4252. dowait(DOWAIT_BLOCK_OR_SIG, NULL);
  4253. if (pending_sig)
  4254. goto sigout;
  4255. job->waited = 1;
  4256. retval = getstatus(job);
  4257. repeat: ;
  4258. } while (*++argv);
  4259. ret:
  4260. return retval;
  4261. sigout:
  4262. retval = 128 + pending_sig;
  4263. return retval;
  4264. }
  4265. static struct job *
  4266. growjobtab(void)
  4267. {
  4268. size_t len;
  4269. ptrdiff_t offset;
  4270. struct job *jp, *jq;
  4271. len = njobs * sizeof(*jp);
  4272. jq = jobtab;
  4273. jp = ckrealloc(jq, len + 4 * sizeof(*jp));
  4274. offset = (char *)jp - (char *)jq;
  4275. if (offset) {
  4276. /* Relocate pointers */
  4277. size_t l = len;
  4278. jq = (struct job *)((char *)jq + l);
  4279. while (l) {
  4280. l -= sizeof(*jp);
  4281. jq--;
  4282. #define joff(p) ((struct job *)((char *)(p) + l))
  4283. #define jmove(p) (p) = (void *)((char *)(p) + offset)
  4284. if (joff(jp)->ps == &jq->ps0)
  4285. jmove(joff(jp)->ps);
  4286. if (joff(jp)->prev_job)
  4287. jmove(joff(jp)->prev_job);
  4288. }
  4289. if (curjob)
  4290. jmove(curjob);
  4291. #undef joff
  4292. #undef jmove
  4293. }
  4294. njobs += 4;
  4295. jobtab = jp;
  4296. jp = (struct job *)((char *)jp + len);
  4297. jq = jp + 3;
  4298. do {
  4299. jq->used = 0;
  4300. } while (--jq >= jp);
  4301. return jp;
  4302. }
  4303. /*
  4304. * Return a new job structure.
  4305. * Called with interrupts off.
  4306. */
  4307. static struct job *
  4308. makejob(/*union node *node,*/ int nprocs)
  4309. {
  4310. int i;
  4311. struct job *jp;
  4312. for (i = njobs, jp = jobtab; ; jp++) {
  4313. if (--i < 0) {
  4314. jp = growjobtab();
  4315. break;
  4316. }
  4317. if (jp->used == 0)
  4318. break;
  4319. if (jp->state != JOBDONE || !jp->waited)
  4320. continue;
  4321. #if JOBS
  4322. if (doing_jobctl)
  4323. continue;
  4324. #endif
  4325. freejob(jp);
  4326. break;
  4327. }
  4328. memset(jp, 0, sizeof(*jp));
  4329. #if JOBS
  4330. /* jp->jobctl is a bitfield.
  4331. * "jp->jobctl |= doing_jobctl" likely to give awful code */
  4332. if (doing_jobctl)
  4333. jp->jobctl = 1;
  4334. #endif
  4335. jp->prev_job = curjob;
  4336. curjob = jp;
  4337. jp->used = 1;
  4338. jp->ps = &jp->ps0;
  4339. if (nprocs > 1) {
  4340. jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
  4341. }
  4342. TRACE(("makejob(%d) returns %%%d\n", nprocs,
  4343. jobno(jp)));
  4344. return jp;
  4345. }
  4346. #if JOBS
  4347. /*
  4348. * Return a string identifying a command (to be printed by the
  4349. * jobs command).
  4350. */
  4351. static char *cmdnextc;
  4352. static void
  4353. cmdputs(const char *s)
  4354. {
  4355. static const char vstype[VSTYPE + 1][3] = {
  4356. "", "}", "-", "+", "?", "=",
  4357. "%", "%%", "#", "##"
  4358. IF_BASH_SUBSTR(, ":")
  4359. IF_BASH_PATTERN_SUBST(, "/", "//")
  4360. };
  4361. const char *p, *str;
  4362. char cc[2];
  4363. char *nextc;
  4364. unsigned char c;
  4365. unsigned char subtype = 0;
  4366. int quoted = 0;
  4367. cc[1] = '\0';
  4368. nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
  4369. p = s;
  4370. while ((c = *p++) != '\0') {
  4371. str = NULL;
  4372. switch (c) {
  4373. case CTLESC:
  4374. c = *p++;
  4375. break;
  4376. case CTLVAR:
  4377. subtype = *p++;
  4378. if ((subtype & VSTYPE) == VSLENGTH)
  4379. str = "${#";
  4380. else
  4381. str = "${";
  4382. goto dostr;
  4383. case CTLENDVAR:
  4384. str = "\"}";
  4385. str += !(quoted & 1);
  4386. quoted >>= 1;
  4387. subtype = 0;
  4388. goto dostr;
  4389. case CTLBACKQ:
  4390. str = "$(...)";
  4391. goto dostr;
  4392. #if ENABLE_FEATURE_SH_MATH
  4393. case CTLARI:
  4394. str = "$((";
  4395. goto dostr;
  4396. case CTLENDARI:
  4397. str = "))";
  4398. goto dostr;
  4399. #endif
  4400. case CTLQUOTEMARK:
  4401. quoted ^= 1;
  4402. c = '"';
  4403. break;
  4404. case '=':
  4405. if (subtype == 0)
  4406. break;
  4407. if ((subtype & VSTYPE) != VSNORMAL)
  4408. quoted <<= 1;
  4409. str = vstype[subtype & VSTYPE];
  4410. if (subtype & VSNUL)
  4411. c = ':';
  4412. else
  4413. goto checkstr;
  4414. break;
  4415. case '\'':
  4416. case '\\':
  4417. case '"':
  4418. case '$':
  4419. /* These can only happen inside quotes */
  4420. cc[0] = c;
  4421. str = cc;
  4422. //FIXME:
  4423. // $ true $$ &
  4424. // $ <cr>
  4425. // [1]+ Done true ${\$} <<=== BUG: ${\$} is not a valid way to write $$ (${$} would be ok)
  4426. c = '\\';
  4427. break;
  4428. default:
  4429. break;
  4430. }
  4431. USTPUTC(c, nextc);
  4432. checkstr:
  4433. if (!str)
  4434. continue;
  4435. dostr:
  4436. while ((c = *str++) != '\0') {
  4437. USTPUTC(c, nextc);
  4438. }
  4439. } /* while *p++ not NUL */
  4440. if (quoted & 1) {
  4441. USTPUTC('"', nextc);
  4442. }
  4443. *nextc = 0;
  4444. cmdnextc = nextc;
  4445. }
  4446. /* cmdtxt() and cmdlist() call each other */
  4447. static void cmdtxt(union node *n);
  4448. static void
  4449. cmdlist(union node *np, int sep)
  4450. {
  4451. for (; np; np = np->narg.next) {
  4452. if (!sep)
  4453. cmdputs(" ");
  4454. cmdtxt(np);
  4455. if (sep && np->narg.next)
  4456. cmdputs(" ");
  4457. }
  4458. }
  4459. static void
  4460. cmdtxt(union node *n)
  4461. {
  4462. union node *np;
  4463. struct nodelist *lp;
  4464. const char *p;
  4465. if (!n)
  4466. return;
  4467. switch (n->type) {
  4468. default:
  4469. #if DEBUG
  4470. abort();
  4471. #endif
  4472. case NPIPE:
  4473. lp = n->npipe.cmdlist;
  4474. for (;;) {
  4475. cmdtxt(lp->n);
  4476. lp = lp->next;
  4477. if (!lp)
  4478. break;
  4479. cmdputs(" | ");
  4480. }
  4481. break;
  4482. case NSEMI:
  4483. p = "; ";
  4484. goto binop;
  4485. case NAND:
  4486. p = " && ";
  4487. goto binop;
  4488. case NOR:
  4489. p = " || ";
  4490. binop:
  4491. cmdtxt(n->nbinary.ch1);
  4492. cmdputs(p);
  4493. n = n->nbinary.ch2;
  4494. goto donode;
  4495. case NREDIR:
  4496. case NBACKGND:
  4497. n = n->nredir.n;
  4498. goto donode;
  4499. case NNOT:
  4500. cmdputs("!");
  4501. n = n->nnot.com;
  4502. donode:
  4503. cmdtxt(n);
  4504. break;
  4505. case NIF:
  4506. cmdputs("if ");
  4507. cmdtxt(n->nif.test);
  4508. cmdputs("; then ");
  4509. if (n->nif.elsepart) {
  4510. cmdtxt(n->nif.ifpart);
  4511. cmdputs("; else ");
  4512. n = n->nif.elsepart;
  4513. } else {
  4514. n = n->nif.ifpart;
  4515. }
  4516. p = "; fi";
  4517. goto dotail;
  4518. case NSUBSHELL:
  4519. cmdputs("(");
  4520. n = n->nredir.n;
  4521. p = ")";
  4522. goto dotail;
  4523. case NWHILE:
  4524. p = "while ";
  4525. goto until;
  4526. case NUNTIL:
  4527. p = "until ";
  4528. until:
  4529. cmdputs(p);
  4530. cmdtxt(n->nbinary.ch1);
  4531. n = n->nbinary.ch2;
  4532. p = "; done";
  4533. dodo:
  4534. cmdputs("; do ");
  4535. dotail:
  4536. cmdtxt(n);
  4537. goto dotail2;
  4538. case NFOR:
  4539. cmdputs("for ");
  4540. cmdputs(n->nfor.var);
  4541. cmdputs(" in ");
  4542. cmdlist(n->nfor.args, 1);
  4543. n = n->nfor.body;
  4544. p = "; done";
  4545. goto dodo;
  4546. case NDEFUN:
  4547. cmdputs(n->ndefun.text);
  4548. p = "() { ... }";
  4549. goto dotail2;
  4550. case NCMD:
  4551. cmdlist(n->ncmd.args, 1);
  4552. cmdlist(n->ncmd.redirect, 0);
  4553. break;
  4554. case NARG:
  4555. p = n->narg.text;
  4556. dotail2:
  4557. cmdputs(p);
  4558. break;
  4559. case NHERE:
  4560. case NXHERE:
  4561. p = "<<...";
  4562. goto dotail2;
  4563. case NCASE:
  4564. cmdputs("case ");
  4565. cmdputs(n->ncase.expr->narg.text);
  4566. cmdputs(" in ");
  4567. for (np = n->ncase.cases; np; np = np->nclist.next) {
  4568. cmdtxt(np->nclist.pattern);
  4569. cmdputs(") ");
  4570. cmdtxt(np->nclist.body);
  4571. cmdputs(";; ");
  4572. }
  4573. p = "esac";
  4574. goto dotail2;
  4575. case NTO:
  4576. p = ">";
  4577. goto redir;
  4578. case NCLOBBER:
  4579. p = ">|";
  4580. goto redir;
  4581. case NAPPEND:
  4582. p = ">>";
  4583. goto redir;
  4584. #if BASH_REDIR_OUTPUT
  4585. case NTO2:
  4586. #endif
  4587. case NTOFD:
  4588. p = ">&";
  4589. goto redir;
  4590. case NFROM:
  4591. p = "<";
  4592. goto redir;
  4593. case NFROMFD:
  4594. p = "<&";
  4595. goto redir;
  4596. case NFROMTO:
  4597. p = "<>";
  4598. redir:
  4599. cmdputs(utoa(n->nfile.fd));
  4600. cmdputs(p);
  4601. if (n->type == NTOFD || n->type == NFROMFD) {
  4602. if (n->ndup.dupfd >= 0)
  4603. cmdputs(utoa(n->ndup.dupfd));
  4604. else
  4605. cmdputs("-");
  4606. break;
  4607. }
  4608. n = n->nfile.fname;
  4609. goto donode;
  4610. }
  4611. }
  4612. static char *
  4613. commandtext(union node *n)
  4614. {
  4615. char *name;
  4616. STARTSTACKSTR(cmdnextc);
  4617. cmdtxt(n);
  4618. name = stackblock();
  4619. TRACE(("commandtext: name %p, end %p\n", name, cmdnextc));
  4620. return ckstrdup(name);
  4621. }
  4622. #endif /* JOBS */
  4623. /*
  4624. * Fork off a subshell. If we are doing job control, give the subshell its
  4625. * own process group. Jp is a job structure that the job is to be added to.
  4626. * N is the command that will be evaluated by the child. Both jp and n may
  4627. * be NULL. The mode parameter can be one of the following:
  4628. * FORK_FG - Fork off a foreground process.
  4629. * FORK_BG - Fork off a background process.
  4630. * FORK_NOJOB - Like FORK_FG, but don't give the process its own
  4631. * process group even if job control is on.
  4632. *
  4633. * When job control is turned off, background processes have their standard
  4634. * input redirected to /dev/null (except for the second and later processes
  4635. * in a pipeline).
  4636. *
  4637. * Called with interrupts off.
  4638. */
  4639. /*
  4640. * Clear traps on a fork.
  4641. */
  4642. static void
  4643. clear_traps(void)
  4644. {
  4645. char **tp;
  4646. INT_OFF;
  4647. for (tp = trap; tp < &trap[NSIG]; tp++) {
  4648. if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
  4649. if (trap_ptr == trap)
  4650. free(*tp);
  4651. /* else: it "belongs" to trap_ptr vector, don't free */
  4652. *tp = NULL;
  4653. if ((tp - trap) != 0)
  4654. setsignal(tp - trap);
  4655. }
  4656. }
  4657. may_have_traps = 0;
  4658. INT_ON;
  4659. }
  4660. /* Lives far away from here, needed for forkchild */
  4661. static void closescript(void);
  4662. /* Called after fork(), in child */
  4663. /* jp and n are NULL when called by openhere() for heredoc support */
  4664. static NOINLINE void
  4665. forkchild(struct job *jp, union node *n, int mode)
  4666. {
  4667. int oldlvl;
  4668. TRACE(("Child shell %d\n", getpid()));
  4669. oldlvl = shlvl;
  4670. shlvl++;
  4671. /* man bash: "Non-builtin commands run by bash have signal handlers
  4672. * set to the values inherited by the shell from its parent".
  4673. * Do we do it correctly? */
  4674. closescript();
  4675. if (mode == FORK_NOJOB /* is it `xxx` ? */
  4676. && n && n->type == NCMD /* is it single cmd? */
  4677. /* && n->ncmd.args->type == NARG - always true? */
  4678. && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "trap") == 0
  4679. && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
  4680. /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
  4681. ) {
  4682. TRACE(("Trap hack\n"));
  4683. /* Awful hack for `trap` or $(trap).
  4684. *
  4685. * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
  4686. * contains an example where "trap" is executed in a subshell:
  4687. *
  4688. * save_traps=$(trap)
  4689. * ...
  4690. * eval "$save_traps"
  4691. *
  4692. * Standard does not say that "trap" in subshell shall print
  4693. * parent shell's traps. It only says that its output
  4694. * must have suitable form, but then, in the above example
  4695. * (which is not supposed to be normative), it implies that.
  4696. *
  4697. * bash (and probably other shell) does implement it
  4698. * (traps are reset to defaults, but "trap" still shows them),
  4699. * but as a result, "trap" logic is hopelessly messed up:
  4700. *
  4701. * # trap
  4702. * trap -- 'echo Ho' SIGWINCH <--- we have a handler
  4703. * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
  4704. * # true | trap <--- trap is in subshell - no output (ditto)
  4705. * # echo `true | trap` <--- in subshell - output (but traps are reset!)
  4706. * trap -- 'echo Ho' SIGWINCH
  4707. * # echo `(trap)` <--- in subshell in subshell - output
  4708. * trap -- 'echo Ho' SIGWINCH
  4709. * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
  4710. * trap -- 'echo Ho' SIGWINCH
  4711. *
  4712. * The rules when to forget and when to not forget traps
  4713. * get really complex and nonsensical.
  4714. *
  4715. * Our solution: ONLY bare $(trap) or `trap` is special.
  4716. */
  4717. /* Save trap handler strings for trap builtin to print */
  4718. trap_ptr = xmemdup(trap, sizeof(trap));
  4719. /* Fall through into clearing traps */
  4720. }
  4721. clear_traps();
  4722. #if JOBS
  4723. /* do job control only in root shell */
  4724. doing_jobctl = 0;
  4725. if (mode != FORK_NOJOB && jp->jobctl && oldlvl == 0) {
  4726. pid_t pgrp;
  4727. if (jp->nprocs == 0)
  4728. pgrp = getpid();
  4729. else
  4730. pgrp = jp->ps[0].ps_pid;
  4731. /* this can fail because we are doing it in the parent also */
  4732. setpgid(0, pgrp);
  4733. if (mode == FORK_FG)
  4734. xtcsetpgrp(ttyfd, pgrp);
  4735. setsignal(SIGTSTP);
  4736. setsignal(SIGTTOU);
  4737. } else
  4738. #endif
  4739. if (mode == FORK_BG) {
  4740. /* man bash: "When job control is not in effect,
  4741. * asynchronous commands ignore SIGINT and SIGQUIT" */
  4742. ignoresig(SIGINT);
  4743. ignoresig(SIGQUIT);
  4744. if (jp->nprocs == 0) {
  4745. close(0);
  4746. if (open(bb_dev_null, O_RDONLY) != 0)
  4747. ash_msg_and_raise_perror("can't open '%s'", bb_dev_null);
  4748. }
  4749. }
  4750. if (oldlvl == 0) {
  4751. if (iflag) { /* why if iflag only? */
  4752. setsignal(SIGINT);
  4753. setsignal(SIGTERM);
  4754. }
  4755. /* man bash:
  4756. * "In all cases, bash ignores SIGQUIT. Non-builtin
  4757. * commands run by bash have signal handlers
  4758. * set to the values inherited by the shell
  4759. * from its parent".
  4760. * Take care of the second rule: */
  4761. setsignal(SIGQUIT);
  4762. }
  4763. #if JOBS
  4764. if (n && n->type == NCMD
  4765. && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "jobs") == 0
  4766. ) {
  4767. TRACE(("Job hack\n"));
  4768. /* "jobs": we do not want to clear job list for it,
  4769. * instead we remove only _its_ own_ job from job list.
  4770. * This makes "jobs .... | cat" more useful.
  4771. */
  4772. freejob(curjob);
  4773. return;
  4774. }
  4775. #endif
  4776. for (jp = curjob; jp; jp = jp->prev_job)
  4777. freejob(jp);
  4778. }
  4779. /* Called after fork(), in parent */
  4780. #if !JOBS
  4781. #define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
  4782. #endif
  4783. static void
  4784. forkparent(struct job *jp, union node *n, int mode, pid_t pid)
  4785. {
  4786. TRACE(("In parent shell: child = %d\n", pid));
  4787. if (!jp) /* jp is NULL when called by openhere() for heredoc support */
  4788. return;
  4789. #if JOBS
  4790. if (mode != FORK_NOJOB && jp->jobctl) {
  4791. int pgrp;
  4792. if (jp->nprocs == 0)
  4793. pgrp = pid;
  4794. else
  4795. pgrp = jp->ps[0].ps_pid;
  4796. /* This can fail because we are doing it in the child also */
  4797. setpgid(pid, pgrp);
  4798. }
  4799. #endif
  4800. if (mode == FORK_BG) {
  4801. backgndpid = pid; /* set $! */
  4802. set_curjob(jp, CUR_RUNNING);
  4803. }
  4804. if (jp) {
  4805. struct procstat *ps = &jp->ps[jp->nprocs++];
  4806. ps->ps_pid = pid;
  4807. ps->ps_status = -1;
  4808. ps->ps_cmd = nullstr;
  4809. #if JOBS
  4810. if (doing_jobctl && n)
  4811. ps->ps_cmd = commandtext(n);
  4812. #endif
  4813. }
  4814. }
  4815. /* jp and n are NULL when called by openhere() for heredoc support */
  4816. static int
  4817. forkshell(struct job *jp, union node *n, int mode)
  4818. {
  4819. int pid;
  4820. TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
  4821. pid = fork();
  4822. if (pid < 0) {
  4823. TRACE(("Fork failed, errno=%d", errno));
  4824. if (jp)
  4825. freejob(jp);
  4826. ash_msg_and_raise_perror("can't fork");
  4827. }
  4828. if (pid == 0) {
  4829. CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
  4830. forkchild(jp, n, mode);
  4831. } else {
  4832. forkparent(jp, n, mode, pid);
  4833. }
  4834. return pid;
  4835. }
  4836. /*
  4837. * Wait for job to finish.
  4838. *
  4839. * Under job control we have the problem that while a child process
  4840. * is running interrupts generated by the user are sent to the child
  4841. * but not to the shell. This means that an infinite loop started by
  4842. * an interactive user may be hard to kill. With job control turned off,
  4843. * an interactive user may place an interactive program inside a loop.
  4844. * If the interactive program catches interrupts, the user doesn't want
  4845. * these interrupts to also abort the loop. The approach we take here
  4846. * is to have the shell ignore interrupt signals while waiting for a
  4847. * foreground process to terminate, and then send itself an interrupt
  4848. * signal if the child process was terminated by an interrupt signal.
  4849. * Unfortunately, some programs want to do a bit of cleanup and then
  4850. * exit on interrupt; unless these processes terminate themselves by
  4851. * sending a signal to themselves (instead of calling exit) they will
  4852. * confuse this approach.
  4853. *
  4854. * Called with interrupts off.
  4855. */
  4856. static int
  4857. waitforjob(struct job *jp)
  4858. {
  4859. int st;
  4860. TRACE(("waitforjob(%%%d) called\n", jp ? jobno(jp) : 0));
  4861. /* In non-interactive shells, we _can_ get
  4862. * a keyboard signal here and be EINTRed, but we just loop
  4863. * inside dowait(), waiting for command to complete.
  4864. *
  4865. * man bash:
  4866. * "If bash is waiting for a command to complete and receives
  4867. * a signal for which a trap has been set, the trap
  4868. * will not be executed until the command completes."
  4869. *
  4870. * Reality is that even if trap is not set, bash
  4871. * will not act on the signal until command completes.
  4872. * Try this. sleep5intoff.c:
  4873. * #include <signal.h>
  4874. * #include <unistd.h>
  4875. * int main() {
  4876. * sigset_t set;
  4877. * sigemptyset(&set);
  4878. * sigaddset(&set, SIGINT);
  4879. * sigaddset(&set, SIGQUIT);
  4880. * sigprocmask(SIG_BLOCK, &set, NULL);
  4881. * sleep(5);
  4882. * return 0;
  4883. * }
  4884. * $ bash -c './sleep5intoff; echo hi'
  4885. * ^C^C^C^C <--- pressing ^C once a second
  4886. * $ _
  4887. * $ bash -c './sleep5intoff; echo hi'
  4888. * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
  4889. * $ _
  4890. */
  4891. dowait(jp ? DOWAIT_BLOCK : DOWAIT_NONBLOCK, jp);
  4892. if (!jp)
  4893. return exitstatus;
  4894. st = getstatus(jp);
  4895. #if JOBS
  4896. if (jp->jobctl) {
  4897. xtcsetpgrp(ttyfd, rootpid);
  4898. restore_tty_if_stopped_or_signaled(jp);
  4899. /*
  4900. * This is truly gross.
  4901. * If we're doing job control, then we did a TIOCSPGRP which
  4902. * caused us (the shell) to no longer be in the controlling
  4903. * session -- so we wouldn't have seen any ^C/SIGINT. So, we
  4904. * intuit from the subprocess exit status whether a SIGINT
  4905. * occurred, and if so interrupt ourselves. Yuck. - mycroft
  4906. */
  4907. if (jp->sigint) /* TODO: do the same with all signals */
  4908. raise(SIGINT); /* ... by raise(jp->sig) instead? */
  4909. }
  4910. if (jp->state == JOBDONE)
  4911. #endif
  4912. freejob(jp);
  4913. return st;
  4914. }
  4915. /*
  4916. * return 1 if there are stopped jobs, otherwise 0
  4917. */
  4918. static int
  4919. stoppedjobs(void)
  4920. {
  4921. struct job *jp;
  4922. int retval;
  4923. retval = 0;
  4924. if (job_warning)
  4925. goto out;
  4926. jp = curjob;
  4927. if (jp && jp->state == JOBSTOPPED) {
  4928. out2str("You have stopped jobs.\n");
  4929. job_warning = 2;
  4930. retval++;
  4931. }
  4932. out:
  4933. return retval;
  4934. }
  4935. /*
  4936. * Code for dealing with input/output redirection.
  4937. */
  4938. #undef EMPTY
  4939. #undef CLOSED
  4940. #define EMPTY -2 /* marks an unused slot in redirtab */
  4941. #define CLOSED -1 /* marks a slot of previously-closed fd */
  4942. /*
  4943. * Handle here documents. Normally we fork off a process to write the
  4944. * data to a pipe. If the document is short, we can stuff the data in
  4945. * the pipe without forking.
  4946. */
  4947. /* openhere needs this forward reference */
  4948. static void expandhere(union node *arg);
  4949. static int
  4950. openhere(union node *redir)
  4951. {
  4952. char *p;
  4953. int pip[2];
  4954. size_t len = 0;
  4955. if (pipe(pip) < 0)
  4956. ash_msg_and_raise_perror("can't create pipe");
  4957. p = redir->nhere.doc->narg.text;
  4958. if (redir->type == NXHERE) {
  4959. expandhere(redir->nhere.doc);
  4960. p = stackblock();
  4961. }
  4962. len = strlen(p);
  4963. if (len <= PIPE_BUF) {
  4964. xwrite(pip[1], p, len);
  4965. goto out;
  4966. }
  4967. if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
  4968. /* child */
  4969. close(pip[0]);
  4970. ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
  4971. ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
  4972. ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
  4973. ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
  4974. signal(SIGPIPE, SIG_DFL);
  4975. xwrite(pip[1], p, len);
  4976. _exit(EXIT_SUCCESS);
  4977. }
  4978. out:
  4979. close(pip[1]);
  4980. return pip[0];
  4981. }
  4982. static int
  4983. openredirect(union node *redir)
  4984. {
  4985. struct stat sb;
  4986. char *fname;
  4987. int f;
  4988. switch (redir->nfile.type) {
  4989. /* Can't happen, our single caller does this itself */
  4990. // case NTOFD:
  4991. // case NFROMFD:
  4992. // return -1;
  4993. case NHERE:
  4994. case NXHERE:
  4995. return openhere(redir);
  4996. }
  4997. /* For N[X]HERE, reading redir->nfile.expfname would touch beyond
  4998. * allocated space. Do it only when we know it is safe.
  4999. */
  5000. fname = redir->nfile.expfname;
  5001. switch (redir->nfile.type) {
  5002. default:
  5003. #if DEBUG
  5004. abort();
  5005. #endif
  5006. case NFROM:
  5007. f = open(fname, O_RDONLY);
  5008. if (f < 0)
  5009. goto eopen;
  5010. break;
  5011. case NFROMTO:
  5012. f = open(fname, O_RDWR|O_CREAT, 0666);
  5013. if (f < 0)
  5014. goto ecreate;
  5015. break;
  5016. case NTO:
  5017. #if BASH_REDIR_OUTPUT
  5018. case NTO2:
  5019. #endif
  5020. /* Take care of noclobber mode. */
  5021. if (Cflag) {
  5022. if (stat(fname, &sb) < 0) {
  5023. f = open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
  5024. if (f < 0)
  5025. goto ecreate;
  5026. } else if (!S_ISREG(sb.st_mode)) {
  5027. f = open(fname, O_WRONLY, 0666);
  5028. if (f < 0)
  5029. goto ecreate;
  5030. if (!fstat(f, &sb) && S_ISREG(sb.st_mode)) {
  5031. close(f);
  5032. errno = EEXIST;
  5033. goto ecreate;
  5034. }
  5035. } else {
  5036. errno = EEXIST;
  5037. goto ecreate;
  5038. }
  5039. break;
  5040. }
  5041. /* FALLTHROUGH */
  5042. case NCLOBBER:
  5043. f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
  5044. if (f < 0)
  5045. goto ecreate;
  5046. break;
  5047. case NAPPEND:
  5048. f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
  5049. if (f < 0)
  5050. goto ecreate;
  5051. break;
  5052. }
  5053. return f;
  5054. ecreate:
  5055. ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
  5056. eopen:
  5057. ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
  5058. }
  5059. /*
  5060. * Copy a file descriptor to be >= 10. Throws exception on error.
  5061. */
  5062. static int
  5063. savefd(int from)
  5064. {
  5065. int newfd;
  5066. int err;
  5067. newfd = fcntl(from, F_DUPFD_CLOEXEC, 10);
  5068. err = newfd < 0 ? errno : 0;
  5069. if (err != EBADF) {
  5070. if (err)
  5071. ash_msg_and_raise_perror("%d", from);
  5072. close(from);
  5073. if (F_DUPFD_CLOEXEC == F_DUPFD)
  5074. close_on_exec_on(newfd);
  5075. }
  5076. return newfd;
  5077. }
  5078. static int
  5079. dup2_or_raise(int from, int to)
  5080. {
  5081. int newfd;
  5082. newfd = (from != to) ? dup2(from, to) : to;
  5083. if (newfd < 0) {
  5084. /* Happens when source fd is not open: try "echo >&99" */
  5085. ash_msg_and_raise_perror("%d", from);
  5086. }
  5087. return newfd;
  5088. }
  5089. static int
  5090. dup_CLOEXEC(int fd, int avoid_fd)
  5091. {
  5092. int newfd;
  5093. repeat:
  5094. newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
  5095. if (newfd >= 0) {
  5096. if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
  5097. close_on_exec_on(newfd);
  5098. } else { /* newfd < 0 */
  5099. if (errno == EBUSY)
  5100. goto repeat;
  5101. if (errno == EINTR)
  5102. goto repeat;
  5103. }
  5104. return newfd;
  5105. }
  5106. static int
  5107. xdup_CLOEXEC_and_close(int fd, int avoid_fd)
  5108. {
  5109. int newfd;
  5110. repeat:
  5111. newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
  5112. if (newfd < 0) {
  5113. if (errno == EBUSY)
  5114. goto repeat;
  5115. if (errno == EINTR)
  5116. goto repeat;
  5117. /* fd was not open? */
  5118. if (errno == EBADF)
  5119. return fd;
  5120. ash_msg_and_raise_perror("%d", newfd);
  5121. }
  5122. if (F_DUPFD_CLOEXEC == F_DUPFD)
  5123. close_on_exec_on(newfd);
  5124. close(fd);
  5125. return newfd;
  5126. }
  5127. /* Struct def and variable are moved down to the first usage site */
  5128. struct squirrel {
  5129. int orig_fd;
  5130. int moved_to;
  5131. };
  5132. struct redirtab {
  5133. struct redirtab *next;
  5134. int pair_count;
  5135. struct squirrel two_fd[];
  5136. };
  5137. #define redirlist (G_var.redirlist)
  5138. static void
  5139. add_squirrel_closed(struct redirtab *sq, int fd)
  5140. {
  5141. int i;
  5142. if (!sq)
  5143. return;
  5144. for (i = 0; sq->two_fd[i].orig_fd != EMPTY; i++) {
  5145. /* If we collide with an already moved fd... */
  5146. if (fd == sq->two_fd[i].orig_fd) {
  5147. /* Examples:
  5148. * "echo 3>FILE 3>&- 3>FILE"
  5149. * "echo 3>&- 3>FILE"
  5150. * No need for last redirect to insert
  5151. * another "need to close 3" indicator.
  5152. */
  5153. TRACE(("redirect_fd %d: already moved or closed\n", fd));
  5154. return;
  5155. }
  5156. }
  5157. TRACE(("redirect_fd %d: previous fd was closed\n", fd));
  5158. sq->two_fd[i].orig_fd = fd;
  5159. sq->two_fd[i].moved_to = CLOSED;
  5160. }
  5161. static int
  5162. save_fd_on_redirect(int fd, int avoid_fd, struct redirtab *sq)
  5163. {
  5164. int i, new_fd;
  5165. if (avoid_fd < 9) /* the important case here is that it can be -1 */
  5166. avoid_fd = 9;
  5167. #if JOBS
  5168. if (fd == ttyfd) {
  5169. /* Testcase: "ls -l /proc/$$/fd 10>&-" should work */
  5170. ttyfd = xdup_CLOEXEC_and_close(ttyfd, avoid_fd);
  5171. TRACE(("redirect_fd %d: matches ttyfd, moving it to %d\n", fd, ttyfd));
  5172. return 1; /* "we closed fd" */
  5173. }
  5174. #endif
  5175. /* Are we called from redirect(0)? E.g. redirect
  5176. * in a forked child. No need to save fds,
  5177. * we aren't going to use them anymore, ok to trash.
  5178. */
  5179. if (!sq)
  5180. return 0;
  5181. /* If this one of script's fds? */
  5182. if (fd != 0) {
  5183. struct parsefile *pf = g_parsefile;
  5184. while (pf) {
  5185. /* We skip fd == 0 case because of the following:
  5186. * $ ash # running ash interactively
  5187. * $ . ./script.sh
  5188. * and in script.sh: "exec 9>&0".
  5189. * Even though top-level pf_fd _is_ 0,
  5190. * it's still ok to use it: "read" builtin uses it,
  5191. * why should we cripple "exec" builtin?
  5192. */
  5193. if (fd == pf->pf_fd) {
  5194. pf->pf_fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
  5195. return 1; /* "we closed fd" */
  5196. }
  5197. pf = pf->prev;
  5198. }
  5199. }
  5200. /* Check whether it collides with any open fds (e.g. stdio), save fds as needed */
  5201. /* First: do we collide with some already moved fds? */
  5202. for (i = 0; sq->two_fd[i].orig_fd != EMPTY; i++) {
  5203. /* If we collide with an already moved fd... */
  5204. if (fd == sq->two_fd[i].moved_to) {
  5205. new_fd = dup_CLOEXEC(fd, avoid_fd);
  5206. sq->two_fd[i].moved_to = new_fd;
  5207. TRACE(("redirect_fd %d: already busy, moving to %d\n", fd, new_fd));
  5208. if (new_fd < 0) /* what? */
  5209. xfunc_die();
  5210. return 0; /* "we did not close fd" */
  5211. }
  5212. if (fd == sq->two_fd[i].orig_fd) {
  5213. /* Example: echo Hello >/dev/null 1>&2 */
  5214. TRACE(("redirect_fd %d: already moved\n", fd));
  5215. return 0; /* "we did not close fd" */
  5216. }
  5217. }
  5218. /* If this fd is open, we move and remember it; if it's closed, new_fd = CLOSED (-1) */
  5219. new_fd = dup_CLOEXEC(fd, avoid_fd);
  5220. TRACE(("redirect_fd %d: previous fd is moved to %d (-1 if it was closed)\n", fd, new_fd));
  5221. if (new_fd < 0) {
  5222. if (errno != EBADF)
  5223. xfunc_die();
  5224. /* new_fd = CLOSED; - already is -1 */
  5225. }
  5226. sq->two_fd[i].moved_to = new_fd;
  5227. sq->two_fd[i].orig_fd = fd;
  5228. /* if we move stderr, let "set -x" code know */
  5229. if (fd == preverrout_fd)
  5230. preverrout_fd = new_fd;
  5231. return 0; /* "we did not close fd" */
  5232. }
  5233. static int
  5234. internally_opened_fd(int fd, struct redirtab *sq)
  5235. {
  5236. int i;
  5237. #if JOBS
  5238. if (fd == ttyfd)
  5239. return 1;
  5240. #endif
  5241. /* If this one of script's fds? */
  5242. if (fd != 0) {
  5243. struct parsefile *pf = g_parsefile;
  5244. while (pf) {
  5245. if (fd == pf->pf_fd)
  5246. return 1;
  5247. pf = pf->prev;
  5248. }
  5249. }
  5250. if (sq) for (i = 0; i < sq->pair_count && sq->two_fd[i].orig_fd != EMPTY; i++) {
  5251. if (fd == sq->two_fd[i].moved_to)
  5252. return 1;
  5253. }
  5254. return 0;
  5255. }
  5256. /*
  5257. * Process a list of redirection commands. If the REDIR_PUSH flag is set,
  5258. * old file descriptors are stashed away so that the redirection can be
  5259. * undone by calling popredir.
  5260. */
  5261. /* flags passed to redirect */
  5262. #define REDIR_PUSH 01 /* save previous values of file descriptors */
  5263. static void
  5264. redirect(union node *redir, int flags)
  5265. {
  5266. struct redirtab *sv;
  5267. if (!redir)
  5268. return;
  5269. sv = NULL;
  5270. INT_OFF;
  5271. if (flags & REDIR_PUSH)
  5272. sv = redirlist;
  5273. do {
  5274. int fd;
  5275. int newfd;
  5276. int close_fd;
  5277. int closed;
  5278. fd = redir->nfile.fd;
  5279. if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
  5280. //bb_error_msg("doing %d > %d", fd, newfd);
  5281. newfd = redir->ndup.dupfd;
  5282. close_fd = -1;
  5283. } else {
  5284. newfd = openredirect(redir); /* always >= 0 */
  5285. if (fd == newfd) {
  5286. /* open() gave us precisely the fd we wanted.
  5287. * This means that this fd was not busy
  5288. * (not opened to anywhere).
  5289. * Remember to close it on restore:
  5290. */
  5291. add_squirrel_closed(sv, fd);
  5292. continue;
  5293. }
  5294. close_fd = newfd;
  5295. }
  5296. if (fd == newfd)
  5297. continue;
  5298. /* if "N>FILE": move newfd to fd */
  5299. /* if "N>&M": dup newfd to fd */
  5300. /* if "N>&-": close fd (newfd is -1) */
  5301. IF_BASH_REDIR_OUTPUT(redirect_more:)
  5302. closed = save_fd_on_redirect(fd, /*avoid:*/ newfd, sv);
  5303. if (newfd == -1) {
  5304. /* "N>&-" means "close me" */
  5305. if (!closed) {
  5306. /* ^^^ optimization: saving may already
  5307. * have closed it. If not... */
  5308. close(fd);
  5309. }
  5310. } else {
  5311. /* if newfd is a script fd or saved fd, simulate EBADF */
  5312. if (internally_opened_fd(newfd, sv)) {
  5313. errno = EBADF;
  5314. ash_msg_and_raise_perror("%d", newfd);
  5315. }
  5316. dup2_or_raise(newfd, fd);
  5317. if (close_fd >= 0) /* "N>FILE" or ">&FILE" or heredoc? */
  5318. close(close_fd);
  5319. #if BASH_REDIR_OUTPUT
  5320. if (redir->nfile.type == NTO2 && fd == 1) {
  5321. /* ">&FILE". we already redirected to 1, now copy 1 to 2 */
  5322. fd = 2;
  5323. newfd = 1;
  5324. close_fd = -1;
  5325. goto redirect_more;
  5326. }
  5327. #endif
  5328. }
  5329. } while ((redir = redir->nfile.next) != NULL);
  5330. INT_ON;
  5331. //dash:#define REDIR_SAVEFD2 03 /* set preverrout */
  5332. #define REDIR_SAVEFD2 0
  5333. // dash has a bug: since REDIR_SAVEFD2=3 and REDIR_PUSH=1, this test
  5334. // triggers for pure REDIR_PUSH too. Thus, this is done almost always,
  5335. // not only for calls with flags containing REDIR_SAVEFD2.
  5336. // We do this unconditionally (see save_fd_on_redirect()).
  5337. //if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
  5338. // preverrout_fd = copied_fd2;
  5339. }
  5340. static int
  5341. redirectsafe(union node *redir, int flags)
  5342. {
  5343. int err;
  5344. volatile int saveint;
  5345. struct jmploc *volatile savehandler = exception_handler;
  5346. struct jmploc jmploc;
  5347. SAVE_INT(saveint);
  5348. /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
  5349. err = setjmp(jmploc.loc); /* was = setjmp(jmploc.loc) * 2; */
  5350. if (!err) {
  5351. exception_handler = &jmploc;
  5352. redirect(redir, flags);
  5353. }
  5354. exception_handler = savehandler;
  5355. if (err && exception_type != EXERROR)
  5356. longjmp(exception_handler->loc, 1);
  5357. RESTORE_INT(saveint);
  5358. return err;
  5359. }
  5360. static struct redirtab*
  5361. pushredir(union node *redir)
  5362. {
  5363. struct redirtab *sv;
  5364. int i;
  5365. if (!redir)
  5366. return redirlist;
  5367. i = 0;
  5368. do {
  5369. i++;
  5370. #if BASH_REDIR_OUTPUT
  5371. if (redir->nfile.type == NTO2)
  5372. i++;
  5373. #endif
  5374. redir = redir->nfile.next;
  5375. } while (redir);
  5376. sv = ckzalloc(sizeof(*sv) + i * sizeof(sv->two_fd[0]));
  5377. sv->pair_count = i;
  5378. while (--i >= 0)
  5379. sv->two_fd[i].orig_fd = sv->two_fd[i].moved_to = EMPTY;
  5380. sv->next = redirlist;
  5381. redirlist = sv;
  5382. return sv->next;
  5383. }
  5384. /*
  5385. * Undo the effects of the last redirection.
  5386. */
  5387. static void
  5388. popredir(int drop)
  5389. {
  5390. struct redirtab *rp;
  5391. int i;
  5392. if (redirlist == NULL)
  5393. return;
  5394. INT_OFF;
  5395. rp = redirlist;
  5396. for (i = 0; i < rp->pair_count; i++) {
  5397. int fd = rp->two_fd[i].orig_fd;
  5398. int copy = rp->two_fd[i].moved_to;
  5399. if (copy == CLOSED) {
  5400. if (!drop)
  5401. close(fd);
  5402. continue;
  5403. }
  5404. if (copy != EMPTY) {
  5405. if (!drop) {
  5406. /*close(fd);*/
  5407. dup2_or_raise(copy, fd);
  5408. }
  5409. close(copy);
  5410. }
  5411. }
  5412. redirlist = rp->next;
  5413. free(rp);
  5414. INT_ON;
  5415. }
  5416. static void
  5417. unwindredir(struct redirtab *stop)
  5418. {
  5419. while (redirlist != stop)
  5420. popredir(/*drop:*/ 0);
  5421. }
  5422. /* ============ Routines to expand arguments to commands
  5423. *
  5424. * We have to deal with backquotes, shell variables, and file metacharacters.
  5425. */
  5426. #if ENABLE_FEATURE_SH_MATH
  5427. static arith_t
  5428. ash_arith(const char *s)
  5429. {
  5430. arith_state_t math_state;
  5431. arith_t result;
  5432. math_state.lookupvar = lookupvar;
  5433. math_state.setvar = setvar0;
  5434. //math_state.endofname = endofname;
  5435. INT_OFF;
  5436. result = arith(&math_state, s);
  5437. if (math_state.errmsg)
  5438. ash_msg_and_raise_error(math_state.errmsg);
  5439. INT_ON;
  5440. return result;
  5441. }
  5442. #endif
  5443. #if BASH_SUBSTR
  5444. # if ENABLE_FEATURE_SH_MATH
  5445. static int substr_atoi(const char *s)
  5446. {
  5447. arith_t t = ash_arith(s);
  5448. if (sizeof(t) > sizeof(int)) {
  5449. /* clamp very large or very large negative nums for ${v:N:M}:
  5450. * else "${v:0:0x100000001}" would work as "${v:0:1}"
  5451. */
  5452. if (t > INT_MAX)
  5453. t = INT_MAX;
  5454. if (t < INT_MIN)
  5455. t = INT_MIN;
  5456. }
  5457. return t;
  5458. }
  5459. # else
  5460. # define substr_atoi(s) number(s)
  5461. # endif
  5462. #endif
  5463. /*
  5464. * expandarg flags
  5465. */
  5466. #define EXP_FULL 0x1 /* perform word splitting & file globbing */
  5467. #define EXP_TILDE 0x2 /* do normal tilde expansion */
  5468. #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
  5469. #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
  5470. /* ^^^^^^^^^^^^^^ this is meant to support constructs such as "cmd >file*.txt"
  5471. * POSIX says for this case:
  5472. * Pathname expansion shall not be performed on the word by a
  5473. * non-interactive shell; an interactive shell may perform it, but shall
  5474. * do so only when the expansion would result in one word.
  5475. * Currently, our code complies to the above rule by never globbing
  5476. * redirection filenames.
  5477. * Bash performs globbing, unless it is non-interactive and in POSIX mode.
  5478. * (this means that on a typical Linux distro, bash almost always
  5479. * performs globbing, and thus diverges from what we do).
  5480. */
  5481. #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
  5482. #define EXP_VARTILDE2 0x20 /* expand tildes after colons only */
  5483. #define EXP_WORD 0x40 /* expand word in parameter expansion */
  5484. #define EXP_QUOTED 0x100 /* expand word in double quotes */
  5485. #define EXP_KEEPNUL 0x200 /* do not skip NUL characters */
  5486. #define EXP_DISCARD 0x400 /* discard result of expansion */
  5487. /*
  5488. * rmescape() flags
  5489. */
  5490. #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
  5491. #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
  5492. #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
  5493. #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
  5494. /* Add CTLESC when necessary. */
  5495. #define QUOTES_ESC (EXP_FULL | EXP_CASE)
  5496. /*
  5497. * Structure specifying which parts of the string should be searched
  5498. * for IFS characters.
  5499. */
  5500. struct ifsregion {
  5501. struct ifsregion *next; /* next region in list */
  5502. int begoff; /* offset of start of region */
  5503. int endoff; /* offset of end of region */
  5504. int nulonly; /* search for nul bytes only */
  5505. };
  5506. struct arglist {
  5507. struct strlist *list;
  5508. struct strlist **lastp;
  5509. };
  5510. /* output of current string */
  5511. static char *expdest;
  5512. /* list of back quote expressions */
  5513. static struct nodelist *argbackq;
  5514. /* first struct in list of ifs regions */
  5515. static struct ifsregion ifsfirst;
  5516. /* last struct in list */
  5517. static struct ifsregion *ifslastp;
  5518. /* holds expanded arg list */
  5519. static struct arglist exparg;
  5520. /*
  5521. * Break the argument string into pieces based upon IFS and add the
  5522. * strings to the argument list. The regions of the string to be
  5523. * searched for IFS characters have been stored by recordregion.
  5524. */
  5525. static void
  5526. ifsbreakup(char *string, struct arglist *arglist)
  5527. {
  5528. struct ifsregion *ifsp;
  5529. struct strlist *sp;
  5530. char *start;
  5531. char *p;
  5532. char *q;
  5533. const char *ifs, *realifs;
  5534. int ifsspc;
  5535. int nulonly;
  5536. start = string;
  5537. if (ifslastp != NULL) {
  5538. ifsspc = 0;
  5539. nulonly = 0;
  5540. realifs = ifsset() ? ifsval() : defifs;
  5541. ifsp = &ifsfirst;
  5542. do {
  5543. int afternul;
  5544. p = string + ifsp->begoff;
  5545. afternul = nulonly;
  5546. nulonly = ifsp->nulonly;
  5547. ifs = nulonly ? nullstr : realifs;
  5548. ifsspc = 0;
  5549. while (p < string + ifsp->endoff) {
  5550. q = p;
  5551. if ((unsigned char)*p == CTLESC)
  5552. p++;
  5553. if (!strchr(ifs, *p)) {
  5554. p++;
  5555. continue;
  5556. }
  5557. if (!(afternul || nulonly))
  5558. ifsspc = (strchr(defifs, *p) != NULL);
  5559. /* Ignore IFS whitespace at start */
  5560. if (q == start && ifsspc) {
  5561. p++;
  5562. start = p;
  5563. continue;
  5564. }
  5565. *q = '\0';
  5566. sp = stzalloc(sizeof(*sp));
  5567. sp->text = start;
  5568. *arglist->lastp = sp;
  5569. arglist->lastp = &sp->next;
  5570. p++;
  5571. if (!nulonly) {
  5572. for (;;) {
  5573. if (p >= string + ifsp->endoff) {
  5574. break;
  5575. }
  5576. q = p;
  5577. if ((unsigned char)*p == CTLESC)
  5578. p++;
  5579. if (strchr(ifs, *p) == NULL) {
  5580. p = q;
  5581. break;
  5582. }
  5583. if (strchr(defifs, *p) == NULL) {
  5584. if (ifsspc) {
  5585. p++;
  5586. ifsspc = 0;
  5587. } else {
  5588. p = q;
  5589. break;
  5590. }
  5591. } else
  5592. p++;
  5593. }
  5594. }
  5595. start = p;
  5596. } /* while */
  5597. ifsp = ifsp->next;
  5598. } while (ifsp != NULL);
  5599. if (nulonly)
  5600. goto add;
  5601. }
  5602. if (!*start)
  5603. return;
  5604. add:
  5605. sp = stzalloc(sizeof(*sp));
  5606. sp->text = start;
  5607. *arglist->lastp = sp;
  5608. arglist->lastp = &sp->next;
  5609. }
  5610. static void
  5611. ifsfree(void)
  5612. {
  5613. struct ifsregion *p = ifsfirst.next;
  5614. if (!p)
  5615. goto out;
  5616. INT_OFF;
  5617. do {
  5618. struct ifsregion *ifsp;
  5619. ifsp = p->next;
  5620. free(p);
  5621. p = ifsp;
  5622. } while (p);
  5623. ifsfirst.next = NULL;
  5624. INT_ON;
  5625. out:
  5626. ifslastp = NULL;
  5627. }
  5628. static size_t
  5629. esclen(const char *start, const char *p)
  5630. {
  5631. size_t esc = 0;
  5632. while (p > start && (unsigned char)*--p == CTLESC) {
  5633. esc++;
  5634. }
  5635. return esc;
  5636. }
  5637. /*
  5638. * Remove any CTLESC characters from a string.
  5639. */
  5640. #if !BASH_PATTERN_SUBST
  5641. #define rmescapes(str, flag, slash_position) \
  5642. rmescapes(str, flag)
  5643. #endif
  5644. static char *
  5645. rmescapes(char *str, int flag, int *slash_position)
  5646. {
  5647. static const char qchars[] ALIGN1 = {
  5648. IF_BASH_PATTERN_SUBST('/',) CTLESC, CTLQUOTEMARK, '\0' };
  5649. char *p, *q, *r;
  5650. unsigned protect_against_glob;
  5651. unsigned globbing;
  5652. p = strpbrk(str, qchars IF_BASH_PATTERN_SUBST(+ !slash_position));
  5653. if (!p)
  5654. return str;
  5655. q = p;
  5656. r = str;
  5657. if (flag & RMESCAPE_ALLOC) {
  5658. size_t len = p - str;
  5659. size_t fulllen = len + strlen(p) + 1;
  5660. if (flag & RMESCAPE_GROW) {
  5661. int strloc = str - (char *)stackblock();
  5662. r = makestrspace(fulllen, expdest);
  5663. /* p and str may be invalidated by makestrspace */
  5664. str = (char *)stackblock() + strloc;
  5665. p = str + len;
  5666. } else if (flag & RMESCAPE_HEAP) {
  5667. r = ckmalloc(fulllen);
  5668. } else {
  5669. r = stalloc(fulllen);
  5670. }
  5671. q = r;
  5672. if (len > 0) {
  5673. q = (char *)mempcpy(q, str, len);
  5674. }
  5675. }
  5676. globbing = flag & RMESCAPE_GLOB;
  5677. protect_against_glob = globbing;
  5678. while (*p) {
  5679. if ((unsigned char)*p == CTLQUOTEMARK) {
  5680. // Note: protect_against_glob only affect whether
  5681. // CTLESC,<ch> gets converted to <ch> or to \<ch>
  5682. p++;
  5683. protect_against_glob = globbing;
  5684. continue;
  5685. }
  5686. if (*p == '\\') {
  5687. /* naked back slash */
  5688. protect_against_glob = 0;
  5689. goto copy;
  5690. }
  5691. if ((unsigned char)*p == CTLESC) {
  5692. p++;
  5693. #if DEBUG
  5694. if (*p == '\0')
  5695. ash_msg_and_raise_error("CTLESC at EOL (shouldn't happen)");
  5696. #endif
  5697. if (protect_against_glob) {
  5698. /*
  5699. * We used to trust glob() and fnmatch() to eat
  5700. * superfluous escapes (\z where z has no
  5701. * special meaning anyway). But this causes
  5702. * bugs such as string of one greek letter rho
  5703. * (unicode-encoded as two bytes "cf,81")
  5704. * getting encoded as "cf,CTLESC,81"
  5705. * and here, converted to "cf,\,81" -
  5706. * which does not go well with some flavors
  5707. * of fnmatch() in unicode locales
  5708. * (for example, glibc <= 2.22).
  5709. *
  5710. * Lets add "\" only on the chars which need it.
  5711. * Testcases for less obvious chars are shown.
  5712. */
  5713. if (*p == '*'
  5714. || *p == '?'
  5715. || *p == '['
  5716. || *p == '\\' /* case '\' in \\ ) echo ok;; *) echo WRONG;; esac */
  5717. || *p == ']' /* case ']' in [a\]] ) echo ok;; *) echo WRONG;; esac */
  5718. || *p == '-' /* case '-' in [a\-c]) echo ok;; *) echo WRONG;; esac */
  5719. || *p == '!' /* case '!' in [\!] ) echo ok;; *) echo WRONG;; esac */
  5720. /* Some libc support [^negate], that's why "^" also needs love */
  5721. || *p == '^' /* case '^' in [\^] ) echo ok;; *) echo WRONG;; esac */
  5722. ) {
  5723. *q++ = '\\';
  5724. }
  5725. }
  5726. }
  5727. #if BASH_PATTERN_SUBST
  5728. else if (slash_position && p == str + *slash_position) {
  5729. /* stop handling globbing */
  5730. globbing = 0;
  5731. *slash_position = q - r;
  5732. slash_position = NULL;
  5733. }
  5734. #endif
  5735. protect_against_glob = globbing;
  5736. copy:
  5737. *q++ = *p++;
  5738. }
  5739. *q = '\0';
  5740. if (flag & RMESCAPE_GROW) {
  5741. expdest = r;
  5742. STADJUST(q - r + 1, expdest);
  5743. }
  5744. return r;
  5745. }
  5746. #define pmatch(a, b) !fnmatch((a), (b), 0)
  5747. /*
  5748. * Prepare a pattern for a expmeta (internal glob(3)) call.
  5749. *
  5750. * Returns an stalloced string.
  5751. */
  5752. static char *
  5753. preglob(const char *pattern, int flag)
  5754. {
  5755. return rmescapes((char *)pattern, flag | RMESCAPE_GLOB, NULL);
  5756. }
  5757. /*
  5758. * Put a string on the stack.
  5759. */
  5760. static size_t
  5761. memtodest(const char *p, size_t len, int flags)
  5762. {
  5763. int syntax = flags & EXP_QUOTED ? DQSYNTAX : BASESYNTAX;
  5764. char *q;
  5765. char *s;
  5766. if (!len)
  5767. return 0;
  5768. q = makestrspace(len * 2, expdest);
  5769. s = q;
  5770. do {
  5771. unsigned char c = *p++;
  5772. if (c) {
  5773. if (flags & QUOTES_ESC) {
  5774. int n = SIT(c, syntax);
  5775. if (n == CCTL
  5776. || ((flags & EXP_QUOTED) && n == CBACK)
  5777. ) {
  5778. USTPUTC(CTLESC, q);
  5779. }
  5780. }
  5781. } else if (!(flags & EXP_KEEPNUL))
  5782. continue;
  5783. USTPUTC(c, q);
  5784. } while (--len);
  5785. expdest = q;
  5786. return q - s;
  5787. }
  5788. static size_t
  5789. strtodest(const char *p, int flags)
  5790. {
  5791. size_t len = strlen(p);
  5792. memtodest(p, len, flags);
  5793. return len;
  5794. }
  5795. /*
  5796. * Our own itoa().
  5797. * cvtnum() is used even if math support is off (to prepare $? values and such).
  5798. */
  5799. static int
  5800. cvtnum(arith_t num, int flags)
  5801. {
  5802. /* 32-bit and wider ints require buffer size of bytes*3 (or less) */
  5803. /* If narrower: worst case, 1-byte ints: need 5 bytes: "-127<NUL>" */
  5804. int len = (sizeof(arith_t) >= 4) ? sizeof(arith_t) * 3 : sizeof(arith_t) * 3 + 2;
  5805. char buf[len];
  5806. len = fmtstr(buf, len, ARITH_FMT, num);
  5807. return memtodest(buf, len, flags);
  5808. }
  5809. /*
  5810. * Record the fact that we have to scan this region of the
  5811. * string for IFS characters.
  5812. */
  5813. static void
  5814. recordregion(int start, int end, int nulonly)
  5815. {
  5816. struct ifsregion *ifsp;
  5817. if (ifslastp == NULL) {
  5818. ifsp = &ifsfirst;
  5819. } else {
  5820. INT_OFF;
  5821. ifsp = ckzalloc(sizeof(*ifsp));
  5822. /*ifsp->next = NULL; - ckzalloc did it */
  5823. ifslastp->next = ifsp;
  5824. INT_ON;
  5825. }
  5826. ifslastp = ifsp;
  5827. ifslastp->begoff = start;
  5828. ifslastp->endoff = end;
  5829. ifslastp->nulonly = nulonly;
  5830. }
  5831. static void
  5832. removerecordregions(int endoff)
  5833. {
  5834. if (ifslastp == NULL)
  5835. return;
  5836. if (ifsfirst.endoff > endoff) {
  5837. while (ifsfirst.next) {
  5838. struct ifsregion *ifsp;
  5839. INT_OFF;
  5840. ifsp = ifsfirst.next->next;
  5841. free(ifsfirst.next);
  5842. ifsfirst.next = ifsp;
  5843. INT_ON;
  5844. }
  5845. if (ifsfirst.begoff > endoff) {
  5846. ifslastp = NULL;
  5847. } else {
  5848. ifslastp = &ifsfirst;
  5849. ifsfirst.endoff = endoff;
  5850. }
  5851. return;
  5852. }
  5853. ifslastp = &ifsfirst;
  5854. while (ifslastp->next && ifslastp->next->begoff < endoff)
  5855. ifslastp = ifslastp->next;
  5856. while (ifslastp->next) {
  5857. struct ifsregion *ifsp;
  5858. INT_OFF;
  5859. ifsp = ifslastp->next->next;
  5860. free(ifslastp->next);
  5861. ifslastp->next = ifsp;
  5862. INT_ON;
  5863. }
  5864. if (ifslastp->endoff > endoff)
  5865. ifslastp->endoff = endoff;
  5866. }
  5867. static char *
  5868. exptilde(char *startp, int flag)
  5869. {
  5870. unsigned char c;
  5871. char *name;
  5872. struct passwd *pw;
  5873. const char *home;
  5874. char *p;
  5875. p = startp;
  5876. name = p + 1;
  5877. while ((c = *++p) != '\0') {
  5878. switch (c) {
  5879. case CTLESC:
  5880. return startp;
  5881. case CTLQUOTEMARK:
  5882. return startp;
  5883. case ':':
  5884. if (flag & EXP_VARTILDE)
  5885. goto done;
  5886. break;
  5887. case '/':
  5888. case CTLENDVAR:
  5889. goto done;
  5890. }
  5891. }
  5892. done:
  5893. if (flag & EXP_DISCARD)
  5894. goto out;
  5895. *p = '\0';
  5896. if (*name == '\0') {
  5897. home = lookupvar("HOME");
  5898. } else {
  5899. pw = getpwnam(name);
  5900. if (pw == NULL)
  5901. goto lose;
  5902. home = pw->pw_dir;
  5903. }
  5904. *p = c;
  5905. if (!home)
  5906. goto lose;
  5907. strtodest(home, flag | EXP_QUOTED);
  5908. out:
  5909. return p;
  5910. lose:
  5911. return startp;
  5912. }
  5913. /*
  5914. * Execute a command inside back quotes. If it's a builtin command, we
  5915. * want to save its output in a block obtained from malloc. Otherwise
  5916. * we fork off a subprocess and get the output of the command via a pipe.
  5917. * Should be called with interrupts off.
  5918. */
  5919. struct backcmd { /* result of evalbackcmd */
  5920. int fd; /* file descriptor to read from */
  5921. int nleft; /* number of chars in buffer */
  5922. char *buf; /* buffer */
  5923. struct job *jp; /* job structure for command */
  5924. };
  5925. /* These forward decls are needed to use "eval" code for backticks handling: */
  5926. /* flags in argument to evaltree */
  5927. #define EV_EXIT 01 /* exit after evaluating tree */
  5928. #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
  5929. static int evaltree(union node *, int);
  5930. /* An evaltree() which is known to never return.
  5931. * Used to use an alias:
  5932. * static int evaltreenr(union node *, int) __attribute__((alias("evaltree"),__noreturn__));
  5933. * but clang was reported to "transfer" noreturn-ness to evaltree() as well.
  5934. */
  5935. static ALWAYS_INLINE NORETURN void
  5936. evaltreenr(union node *n, int flags)
  5937. {
  5938. evaltree(n, flags);
  5939. bb_unreachable(abort());
  5940. /* NOTREACHED */
  5941. }
  5942. static void FAST_FUNC
  5943. evalbackcmd(union node *n, struct backcmd *result)
  5944. {
  5945. int pip[2];
  5946. struct job *jp;
  5947. result->fd = -1;
  5948. result->buf = NULL;
  5949. result->nleft = 0;
  5950. result->jp = NULL;
  5951. if (n == NULL) {
  5952. goto out;
  5953. }
  5954. if (pipe(pip) < 0)
  5955. ash_msg_and_raise_perror("can't create pipe");
  5956. jp = makejob(/*n,*/ 1);
  5957. if (forkshell(jp, n, FORK_NOJOB) == 0) {
  5958. /* child */
  5959. FORCE_INT_ON;
  5960. close(pip[0]);
  5961. if (pip[1] != 1) {
  5962. /*close(1);*/
  5963. dup2_or_raise(pip[1], 1);
  5964. close(pip[1]);
  5965. }
  5966. /* TODO: eflag clearing makes the following not abort:
  5967. * ash -c 'set -e; z=$(false;echo foo); echo $z'
  5968. * which is what bash does (unless it is in POSIX mode).
  5969. * dash deleted "eflag = 0" line in the commit
  5970. * Date: Mon, 28 Jun 2010 17:11:58 +1000
  5971. * [EVAL] Don't clear eflag in evalbackcmd
  5972. * For now, preserve bash-like behavior, it seems to be somewhat more useful:
  5973. */
  5974. eflag = 0;
  5975. ifsfree();
  5976. evaltreenr(n, EV_EXIT);
  5977. /* NOTREACHED */
  5978. }
  5979. /* parent */
  5980. close(pip[1]);
  5981. result->fd = pip[0];
  5982. result->jp = jp;
  5983. out:
  5984. TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
  5985. result->fd, result->buf, result->nleft, result->jp));
  5986. }
  5987. /*
  5988. * Expand stuff in backwards quotes.
  5989. */
  5990. static void
  5991. expbackq(union node *cmd, int flag)
  5992. {
  5993. struct backcmd in;
  5994. int i;
  5995. char buf[128];
  5996. char *p;
  5997. char *dest;
  5998. int startloc;
  5999. struct stackmark smark;
  6000. if (flag & EXP_DISCARD)
  6001. goto out;
  6002. INT_OFF;
  6003. startloc = expdest - (char *)stackblock();
  6004. pushstackmark(&smark, startloc);
  6005. evalbackcmd(cmd, &in);
  6006. popstackmark(&smark);
  6007. p = in.buf;
  6008. i = in.nleft;
  6009. if (i == 0)
  6010. goto read;
  6011. for (;;) {
  6012. memtodest(p, i, flag);
  6013. read:
  6014. if (in.fd < 0)
  6015. break;
  6016. i = nonblock_immune_read(in.fd, buf, sizeof(buf));
  6017. TRACE(("expbackq: read returns %d\n", i));
  6018. if (i <= 0)
  6019. break;
  6020. p = buf;
  6021. }
  6022. free(in.buf);
  6023. if (in.fd >= 0) {
  6024. close(in.fd);
  6025. back_exitstatus = waitforjob(in.jp);
  6026. }
  6027. INT_ON;
  6028. /* Eat all trailing newlines */
  6029. dest = expdest;
  6030. for (; dest > ((char *)stackblock() + startloc) && dest[-1] == '\n';)
  6031. STUNPUTC(dest);
  6032. expdest = dest;
  6033. if (!(flag & EXP_QUOTED))
  6034. recordregion(startloc, dest - (char *)stackblock(), 0);
  6035. TRACE(("evalbackq: size:%d:'%.*s'\n",
  6036. (int)((dest - (char *)stackblock()) - startloc),
  6037. (int)((dest - (char *)stackblock()) - startloc),
  6038. stackblock() + startloc));
  6039. out:
  6040. argbackq = argbackq->next;
  6041. }
  6042. /* expari needs it */
  6043. static char *argstr(char *p, int flag);
  6044. #if ENABLE_FEATURE_SH_MATH
  6045. /*
  6046. * Expand arithmetic expression. Backup to start of expression,
  6047. * evaluate, place result in (backed up) result, adjust string position.
  6048. */
  6049. static char *
  6050. expari(char *start, int flag)
  6051. {
  6052. struct stackmark sm;
  6053. int begoff;
  6054. int endoff;
  6055. int len;
  6056. arith_t result;
  6057. char *p;
  6058. p = stackblock();
  6059. begoff = expdest - p;
  6060. p = argstr(start, flag & EXP_DISCARD);
  6061. if (flag & EXP_DISCARD)
  6062. goto out;
  6063. start = stackblock();
  6064. endoff = expdest - start;
  6065. start += begoff;
  6066. STADJUST(start - expdest, expdest);
  6067. removerecordregions(begoff);
  6068. if (flag & QUOTES_ESC)
  6069. rmescapes(start, 0, NULL);
  6070. pushstackmark(&sm, endoff);
  6071. result = ash_arith(start);
  6072. popstackmark(&sm);
  6073. len = cvtnum(result, flag);
  6074. if (!(flag & EXP_QUOTED))
  6075. recordregion(begoff, begoff + len, 0);
  6076. out:
  6077. return p;
  6078. }
  6079. #endif
  6080. /* argstr needs it */
  6081. static char *evalvar(char *p, int flags);
  6082. /*
  6083. * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
  6084. * characters to allow for further processing. Otherwise treat
  6085. * $@ like $* since no splitting will be performed.
  6086. */
  6087. static char *
  6088. argstr(char *p, int flag)
  6089. {
  6090. static const char spclchars[] ALIGN1 = {
  6091. '=',
  6092. ':',
  6093. CTLQUOTEMARK,
  6094. CTLENDVAR,
  6095. CTLESC,
  6096. CTLVAR,
  6097. CTLBACKQ,
  6098. #if ENABLE_FEATURE_SH_MATH
  6099. CTLARI,
  6100. CTLENDARI,
  6101. #endif
  6102. '\0'
  6103. };
  6104. const char *reject = spclchars;
  6105. int breakall = (flag & (EXP_WORD | EXP_QUOTED)) == EXP_WORD;
  6106. int inquotes;
  6107. size_t length;
  6108. int startloc;
  6109. reject += !!(flag & EXP_VARTILDE2);
  6110. reject += flag & EXP_VARTILDE ? 0 : 2;
  6111. inquotes = 0;
  6112. length = 0;
  6113. if (flag & EXP_TILDE) {
  6114. flag &= ~EXP_TILDE;
  6115. tilde:
  6116. if (*p == '~')
  6117. p = exptilde(p, flag);
  6118. }
  6119. start:
  6120. startloc = expdest - (char *)stackblock();
  6121. for (;;) {
  6122. int end;
  6123. unsigned char c;
  6124. length += strcspn(p + length, reject);
  6125. end = 0;
  6126. c = p[length];
  6127. if (!(c & 0x80)
  6128. IF_FEATURE_SH_MATH(|| c == CTLENDARI)
  6129. || c == CTLENDVAR
  6130. ) {
  6131. /*
  6132. * c == '=' || c == ':' || c == '\0' ||
  6133. * c == CTLENDARI || c == CTLENDVAR
  6134. */
  6135. length++;
  6136. /* c == '\0' || c == CTLENDARI || c == CTLENDVAR */
  6137. end = !!((c - 1) & 0x80);
  6138. }
  6139. if (length > 0 && !(flag & EXP_DISCARD)) {
  6140. int newloc;
  6141. char *q;
  6142. q = stnputs(p, length, expdest);
  6143. q[-1] &= end - 1;
  6144. expdest = q - (flag & EXP_WORD ? end : 0);
  6145. newloc = q - (char *)stackblock() - end;
  6146. if (breakall && !inquotes && newloc > startloc) {
  6147. recordregion(startloc, newloc, 0);
  6148. }
  6149. startloc = newloc;
  6150. }
  6151. p += length + 1;
  6152. length = 0;
  6153. if (end)
  6154. break;
  6155. switch (c) {
  6156. case '=':
  6157. flag |= EXP_VARTILDE2;
  6158. reject++;
  6159. /* fall through */
  6160. case ':':
  6161. /*
  6162. * sort of a hack - expand tildes in variable
  6163. * assignments (after the first '=' and after ':'s).
  6164. */
  6165. if (*--p == '~') {
  6166. goto tilde;
  6167. }
  6168. continue;
  6169. case CTLQUOTEMARK:
  6170. /* "$@" syntax adherence hack */
  6171. if (!inquotes && !memcmp(p, dolatstr + 1, DOLATSTRLEN - 1)) {
  6172. p = evalvar(p + 1, flag | EXP_QUOTED) + 1;
  6173. goto start;
  6174. }
  6175. inquotes ^= EXP_QUOTED;
  6176. addquote:
  6177. if (flag & QUOTES_ESC) {
  6178. p--;
  6179. length++;
  6180. startloc++;
  6181. }
  6182. break;
  6183. case CTLESC:
  6184. startloc++;
  6185. length++;
  6186. goto addquote;
  6187. case CTLVAR:
  6188. TRACE(("argstr: evalvar('%s')\n", p));
  6189. p = evalvar(p, flag | inquotes);
  6190. TRACE(("argstr: evalvar:'%s'\n", (char *)stackblock()));
  6191. goto start;
  6192. case CTLBACKQ:
  6193. expbackq(argbackq->n, flag | inquotes);
  6194. goto start;
  6195. #if ENABLE_FEATURE_SH_MATH
  6196. case CTLARI:
  6197. p = expari(p, flag | inquotes);
  6198. goto start;
  6199. #endif
  6200. }
  6201. }
  6202. return p - 1;
  6203. }
  6204. static char *
  6205. scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM,
  6206. char *pattern, int quotes, int zero)
  6207. {
  6208. char *loc, *loc2;
  6209. char c;
  6210. loc = startp;
  6211. loc2 = rmesc;
  6212. do {
  6213. int match;
  6214. const char *s = loc2;
  6215. c = *loc2;
  6216. if (zero) {
  6217. *loc2 = '\0';
  6218. s = rmesc;
  6219. }
  6220. match = pmatch(pattern, s);
  6221. *loc2 = c;
  6222. if (match)
  6223. return loc;
  6224. if (quotes && (unsigned char)*loc == CTLESC)
  6225. loc++;
  6226. loc++;
  6227. loc2++;
  6228. } while (c);
  6229. return NULL;
  6230. }
  6231. static char *
  6232. scanright(char *startp, char *rmesc, char *rmescend,
  6233. char *pattern, int quotes, int match_at_start)
  6234. {
  6235. #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
  6236. int try2optimize = match_at_start;
  6237. #endif
  6238. int esc = 0;
  6239. char *loc;
  6240. char *loc2;
  6241. /* If we called by "${v/pattern/repl}" or "${v//pattern/repl}":
  6242. * startp="escaped_value_of_v" rmesc="raw_value_of_v"
  6243. * rmescend=""(ptr to NUL in rmesc) pattern="pattern" quotes=match_at_start=1
  6244. * Logic:
  6245. * loc starts at NUL at the end of startp, loc2 starts at the end of rmesc,
  6246. * and on each iteration they go back two/one char until they reach the beginning.
  6247. * We try to find a match in "raw_value_of_v", "raw_value_of_", "raw_value_of" etc.
  6248. */
  6249. /* TODO: document in what other circumstances we are called. */
  6250. for (loc = pattern - 1, loc2 = rmescend; loc >= startp; loc2--) {
  6251. int match;
  6252. char c = *loc2;
  6253. const char *s = loc2;
  6254. if (match_at_start) {
  6255. *loc2 = '\0';
  6256. s = rmesc;
  6257. }
  6258. match = pmatch(pattern, s);
  6259. //bb_error_msg("pmatch(pattern:'%s',s:'%s'):%d", pattern, s, match);
  6260. *loc2 = c;
  6261. if (match)
  6262. return loc;
  6263. #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
  6264. if (try2optimize) {
  6265. /* Maybe we can optimize this:
  6266. * if pattern ends with unescaped *, we can avoid checking
  6267. * shorter strings: if "foo*" doesn't match "raw_value_of_v",
  6268. * it won't match truncated "raw_value_of_" strings too.
  6269. */
  6270. unsigned plen = strlen(pattern);
  6271. /* Does it end with "*"? */
  6272. if (plen != 0 && pattern[--plen] == '*') {
  6273. /* "xxxx*" is not escaped */
  6274. /* "xxx\*" is escaped */
  6275. /* "xx\\*" is not escaped */
  6276. /* "x\\\*" is escaped */
  6277. int slashes = 0;
  6278. while (plen != 0 && pattern[--plen] == '\\')
  6279. slashes++;
  6280. if (!(slashes & 1))
  6281. break; /* ends with unescaped "*" */
  6282. }
  6283. try2optimize = 0;
  6284. }
  6285. #endif
  6286. loc--;
  6287. if (quotes) {
  6288. if (--esc < 0) {
  6289. esc = esclen(startp, loc);
  6290. }
  6291. if (esc % 2) {
  6292. esc--;
  6293. loc--;
  6294. }
  6295. }
  6296. }
  6297. return NULL;
  6298. }
  6299. static void varunset(const char *, const char *, const char *, int) NORETURN;
  6300. static void
  6301. varunset(const char *end, const char *var, const char *umsg, int varflags)
  6302. {
  6303. const char *msg;
  6304. const char *tail;
  6305. tail = nullstr;
  6306. msg = "parameter not set";
  6307. if (umsg) {
  6308. if ((unsigned char)*end == CTLENDVAR) {
  6309. if (varflags & VSNUL)
  6310. tail = " or null";
  6311. } else {
  6312. msg = umsg;
  6313. }
  6314. }
  6315. ash_msg_and_raise_error("%.*s: %s%s", (int)(end - var - 1), var, msg, tail);
  6316. }
  6317. static char *
  6318. subevalvar(char *start, char *str, int strloc,
  6319. int startloc, int varflags, int flag)
  6320. {
  6321. int subtype = varflags & VSTYPE;
  6322. int quotes = flag & QUOTES_ESC;
  6323. char *startp;
  6324. char *loc;
  6325. char *rmesc, *rmescend;
  6326. long amount;
  6327. int resetloc;
  6328. int argstr_flags;
  6329. IF_BASH_PATTERN_SUBST(int workloc;)
  6330. IF_BASH_PATTERN_SUBST(int slash_pos;)
  6331. IF_BASH_PATTERN_SUBST(char *repl;)
  6332. int zero;
  6333. char *(*scan)(char*, char*, char*, char*, int, int);
  6334. char *p;
  6335. //bb_error_msg("subevalvar(start:'%s',str:'%s',strloc:%d,startloc:%d,varflags:%x,quotes:%d)",
  6336. // start, str, strloc, startloc, varflags, quotes);
  6337. #if BASH_PATTERN_SUBST
  6338. /* For "${v/pattern/repl}", we must find the delimiter _before_
  6339. * argstr() call expands possible variable references in pattern:
  6340. * think about "v=a; a=a/; echo ${v/$a/r}" case.
  6341. */
  6342. repl = NULL;
  6343. if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
  6344. /* Find '/' and replace with NUL */
  6345. repl = start;
  6346. /* The pattern can't be empty.
  6347. * IOW: if the first char after "${v//" is a slash,
  6348. * it does not terminate the pattern - it's the first char of the pattern:
  6349. * v=/dev/ram; echo ${v////-} prints -dev-ram (pattern is "/")
  6350. * v=/dev/ram; echo ${v///r/-} prints /dev-am (pattern is "/r")
  6351. */
  6352. if (*repl == '/')
  6353. repl++;
  6354. for (;;) {
  6355. if (*repl == '\0') {
  6356. repl = NULL;
  6357. break;
  6358. }
  6359. if (*repl == '/') {
  6360. *repl = '\0';
  6361. break;
  6362. }
  6363. /* Handle escaped slashes, e.g. "${v/\//_}" (they are CTLESC'ed by this point) */
  6364. if ((unsigned char)*repl == CTLESC && repl[1])
  6365. repl++;
  6366. repl++;
  6367. }
  6368. }
  6369. #endif
  6370. argstr_flags = (flag & EXP_DISCARD) | EXP_TILDE;
  6371. if (!str
  6372. #if BASH_SUBSTR
  6373. && subtype != VSSUBSTR
  6374. #endif
  6375. ) {
  6376. /* EXP_CASE keeps CTLESC's */
  6377. argstr_flags |= EXP_CASE;
  6378. }
  6379. p = argstr(start, argstr_flags);
  6380. //bb_error_msg("str0:'%s'", (char *)stackblock() + strloc);
  6381. #if BASH_PATTERN_SUBST
  6382. slash_pos = -1;
  6383. if (repl) {
  6384. slash_pos = expdest - ((char *)stackblock() + strloc);
  6385. STPUTC('/', expdest);
  6386. //bb_error_msg("repl+1:'%s'", repl + 1);
  6387. p = argstr(repl + 1, (flag & EXP_DISCARD) | EXP_TILDE); /* EXP_TILDE: echo "${v/x/~}" expands ~ ! */
  6388. *repl = '/';
  6389. }
  6390. #endif
  6391. if (flag & EXP_DISCARD)
  6392. return p;
  6393. startp = (char *)stackblock() + startloc;
  6394. //bb_error_msg("str1:'%s'", (char *)stackblock() + strloc);
  6395. switch (subtype) {
  6396. case VSASSIGN:
  6397. setvar0(str, startp);
  6398. loc = startp;
  6399. goto out;
  6400. case VSQUESTION:
  6401. varunset(start, str, startp, varflags);
  6402. /* NOTREACHED */
  6403. #if BASH_SUBSTR
  6404. case VSSUBSTR: {
  6405. int pos, len, orig_len;
  6406. char *colon;
  6407. char *vstr;
  6408. loc = vstr = stackblock() + strloc;
  6409. /* Read POS in ${var:POS:LEN} */
  6410. colon = strchr(loc, ':');
  6411. if (colon) *colon = '\0';
  6412. pos = substr_atoi(loc);
  6413. if (colon) *colon = ':';
  6414. /* Read LEN in ${var:POS:LEN} */
  6415. len = vstr - startp - 1;
  6416. /* *loc != '\0', guaranteed by parser */
  6417. if (quotes) {
  6418. char *ptr;
  6419. /* Adjust the length by the number of escapes */
  6420. for (ptr = startp; ptr < (vstr - 1); ptr++) {
  6421. if ((unsigned char)*ptr == CTLESC) {
  6422. len--;
  6423. ptr++;
  6424. }
  6425. }
  6426. }
  6427. orig_len = len;
  6428. if (*loc++ == ':') {
  6429. /* ${var::LEN} */
  6430. len = substr_atoi(loc);
  6431. } else {
  6432. /* Skip POS in ${var:POS:LEN} */
  6433. len = orig_len;
  6434. while (*loc && *loc != ':')
  6435. loc++;
  6436. if (*loc++ == ':')
  6437. len = substr_atoi(loc);
  6438. }
  6439. if (pos < 0) {
  6440. /* ${VAR:$((-n)):l} starts n chars from the end */
  6441. pos = orig_len + pos;
  6442. }
  6443. if ((unsigned)pos >= orig_len) {
  6444. /* apart from obvious ${VAR:999999:l},
  6445. * covers ${VAR:$((-9999999)):l} - result is ""
  6446. * (bash compat)
  6447. */
  6448. pos = 0;
  6449. len = 0;
  6450. }
  6451. if (len < 0) {
  6452. /* ${VAR:N:-M} sets LEN to strlen()-M */
  6453. len = (orig_len - pos) + len;
  6454. }
  6455. if ((unsigned)len > (orig_len - pos))
  6456. len = orig_len - pos;
  6457. for (vstr = startp; pos; vstr++, pos--) {
  6458. if (quotes && (unsigned char)*vstr == CTLESC)
  6459. vstr++;
  6460. }
  6461. for (loc = startp; len; len--) {
  6462. if (quotes && (unsigned char)*vstr == CTLESC)
  6463. *loc++ = *vstr++;
  6464. *loc++ = *vstr++;
  6465. }
  6466. *loc = '\0';
  6467. goto out;
  6468. }
  6469. #endif /* BASH_SUBSTR */
  6470. }
  6471. resetloc = expdest - (char *)stackblock();
  6472. #if BASH_PATTERN_SUBST
  6473. repl = NULL;
  6474. /* We'll comeback here if we grow the stack while handling
  6475. * a VSREPLACE or VSREPLACEALL, since our pointers into the
  6476. * stack will need rebasing, and we'll need to remove our work
  6477. * areas each time
  6478. */
  6479. restart:
  6480. #endif
  6481. amount = expdest - ((char *)stackblock() + resetloc);
  6482. STADJUST(-amount, expdest);
  6483. startp = (char *)stackblock() + startloc;
  6484. rmesc = startp;
  6485. rmescend = (char *)stackblock() + strloc;
  6486. //bb_error_msg("str7:'%s'", rmescend);
  6487. if (quotes) {
  6488. //TODO: how to handle slash_pos here if string changes (shortens?)
  6489. rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW, NULL);
  6490. if (rmesc != startp) {
  6491. rmescend = expdest;
  6492. startp = (char *)stackblock() + startloc;
  6493. }
  6494. }
  6495. rmescend--;
  6496. str = (char *)stackblock() + strloc;
  6497. /*
  6498. * Example: v='a\bc'; echo ${v/\\b/_\\_\z_}
  6499. * The result is a_\_z_c (not a\_\_z_c)!
  6500. *
  6501. * The search pattern and replace string treat backslashes differently!
  6502. * "&slash_pos" causes rmescapes() to work differently on the pattern
  6503. * and string. It's only used on the first call.
  6504. */
  6505. //bb_error_msg("str8:'%s' slash_pos:%d", str, slash_pos);
  6506. rmescapes(str, RMESCAPE_GLOB,
  6507. repl ? NULL : (slash_pos < 0 ? NULL : &slash_pos)
  6508. );
  6509. #if BASH_PATTERN_SUBST
  6510. workloc = expdest - (char *)stackblock();
  6511. if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
  6512. int len;
  6513. char *idx, *end;
  6514. if (!repl) {
  6515. //bb_error_msg("str9:'%s' slash_pos:%d", str, slash_pos);
  6516. repl = nullstr;
  6517. if (slash_pos >= 0) {
  6518. repl = str + slash_pos;
  6519. *repl++ = '\0';
  6520. }
  6521. }
  6522. //bb_error_msg("str:'%s' repl:'%s'", str, repl);
  6523. /* If there's no pattern to match, return the expansion unmolested */
  6524. if (str[0] == '\0')
  6525. goto out1;
  6526. len = 0;
  6527. idx = startp;
  6528. end = str - 1;
  6529. while (idx < end) {
  6530. try_to_match:
  6531. loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
  6532. //bb_error_msg("scanright('%s'):'%s'", str, loc);
  6533. if (!loc) {
  6534. /* No match, advance */
  6535. char *restart_detect = stackblock();
  6536. skip_matching:
  6537. STPUTC(*idx, expdest);
  6538. if (quotes && (unsigned char)*idx == CTLESC) {
  6539. idx++;
  6540. len++;
  6541. STPUTC(*idx, expdest);
  6542. }
  6543. if (stackblock() != restart_detect)
  6544. goto restart;
  6545. idx++;
  6546. len++;
  6547. rmesc++;
  6548. /* continue; - prone to quadratic behavior, smarter code: */
  6549. if (idx >= end)
  6550. break;
  6551. if (str[0] == '*') {
  6552. /* Pattern is "*foo". If "*foo" does not match "long_string",
  6553. * it would never match "ong_string" etc, no point in trying.
  6554. */
  6555. goto skip_matching;
  6556. }
  6557. goto try_to_match;
  6558. }
  6559. if (subtype == VSREPLACEALL) {
  6560. while (idx < loc) {
  6561. if (quotes && (unsigned char)*idx == CTLESC)
  6562. idx++;
  6563. idx++;
  6564. rmesc++;
  6565. }
  6566. } else {
  6567. idx = loc;
  6568. }
  6569. //bb_error_msg("repl:'%s'", repl);
  6570. for (loc = (char*)repl; *loc; loc++) {
  6571. char *restart_detect = stackblock();
  6572. if (quotes && *loc == '\\') {
  6573. STPUTC(CTLESC, expdest);
  6574. len++;
  6575. }
  6576. STPUTC(*loc, expdest);
  6577. if (stackblock() != restart_detect)
  6578. goto restart;
  6579. len++;
  6580. }
  6581. if (subtype == VSREPLACE) {
  6582. //bb_error_msg("tail:'%s', quotes:%x", idx, quotes);
  6583. while (*idx) {
  6584. char *restart_detect = stackblock();
  6585. STPUTC(*idx, expdest);
  6586. if (stackblock() != restart_detect)
  6587. goto restart;
  6588. len++;
  6589. idx++;
  6590. }
  6591. break;
  6592. }
  6593. }
  6594. /* We've put the replaced text into a buffer at workloc, now
  6595. * move it to the right place and adjust the stack.
  6596. */
  6597. STPUTC('\0', expdest);
  6598. startp = (char *)stackblock() + startloc;
  6599. memmove(startp, (char *)stackblock() + workloc, len + 1);
  6600. //bb_error_msg("startp:'%s'", startp);
  6601. loc = startp + len;
  6602. goto out;
  6603. }
  6604. #endif /* BASH_PATTERN_SUBST */
  6605. subtype -= VSTRIMRIGHT;
  6606. #if DEBUG
  6607. if (subtype < 0 || subtype > 7)
  6608. abort();
  6609. #endif
  6610. /* zero = (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX) */
  6611. zero = subtype >> 1;
  6612. /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
  6613. scan = (subtype & 1) ^ zero ? scanleft : scanright;
  6614. loc = scan(startp, rmesc, rmescend, str, quotes, zero);
  6615. if (loc) {
  6616. if (zero) {
  6617. memmove(startp, loc, str - loc);
  6618. loc = startp + (str - loc) - 1;
  6619. }
  6620. *loc = '\0';
  6621. } else
  6622. loc = str - 1;
  6623. out:
  6624. amount = loc - expdest;
  6625. STADJUST(amount, expdest);
  6626. out1:
  6627. /* Remove any recorded regions beyond start of variable */
  6628. removerecordregions(startloc);
  6629. return p;
  6630. }
  6631. /*
  6632. * Add the value of a specialized variable to the stack string.
  6633. * name parameter (examples):
  6634. * ash -c 'echo $1' name:'1='
  6635. * ash -c 'echo $qwe' name:'qwe='
  6636. * ash -c 'echo $$' name:'$='
  6637. * ash -c 'echo ${$}' name:'$='
  6638. * ash -c 'echo ${$##q}' name:'$=q'
  6639. * ash -c 'echo ${#$}' name:'$='
  6640. * note: examples with bad shell syntax:
  6641. * ash -c 'echo ${#$1}' name:'$=1'
  6642. * ash -c 'echo ${#1#}' name:'1=#'
  6643. */
  6644. static NOINLINE ssize_t
  6645. varvalue(char *name, int varflags, int flags, int quoted)
  6646. {
  6647. const char *p;
  6648. int num;
  6649. int i;
  6650. ssize_t len = 0;
  6651. int sep;
  6652. int subtype = varflags & VSTYPE;
  6653. int discard = (subtype == VSPLUS || subtype == VSLENGTH) | (flags & EXP_DISCARD);
  6654. if (!subtype) {
  6655. if (discard)
  6656. return -1;
  6657. raise_error_syntax("bad substitution");
  6658. }
  6659. flags |= EXP_KEEPNUL;
  6660. flags &= discard ? ~QUOTES_ESC : ~0;
  6661. sep = (flags & EXP_FULL) << CHAR_BIT;
  6662. switch (*name) {
  6663. case '$':
  6664. num = rootpid;
  6665. goto numvar;
  6666. case '?':
  6667. num = exitstatus;
  6668. goto numvar;
  6669. case '#':
  6670. num = shellparam.nparam;
  6671. goto numvar;
  6672. case '!':
  6673. num = backgndpid;
  6674. if (num == 0)
  6675. return -1;
  6676. numvar:
  6677. len = cvtnum(num, flags);
  6678. goto check_1char_name;
  6679. case '-':
  6680. expdest = makestrspace(NOPTS, expdest);
  6681. for (i = NOPTS - 1; i >= 0; i--) {
  6682. if (optlist[i] && optletters(i)) {
  6683. USTPUTC(optletters(i), expdest);
  6684. len++;
  6685. }
  6686. }
  6687. check_1char_name:
  6688. #if 0
  6689. /* handles cases similar to ${#$1} */
  6690. if (name[2] != '\0')
  6691. raise_error_syntax("bad substitution");
  6692. #endif
  6693. break;
  6694. case '@':
  6695. if (quoted && sep)
  6696. goto param;
  6697. /* fall through */
  6698. case '*': {
  6699. char **ap;
  6700. char sepc;
  6701. char c;
  6702. /* We will set c to 0 or ~0 depending on whether
  6703. * we're doing field splitting. We won't do field
  6704. * splitting if either we're quoted or sep is zero.
  6705. *
  6706. * Instead of testing (quoted || !sep) the following
  6707. * trick optimises away any branches by using the
  6708. * fact that EXP_QUOTED (which is the only bit that
  6709. * can be set in quoted) is the same as EXP_FULL <<
  6710. * CHAR_BIT (which is the only bit that can be set
  6711. * in sep).
  6712. */
  6713. #if EXP_QUOTED >> CHAR_BIT != EXP_FULL
  6714. #error The following two lines expect EXP_QUOTED == EXP_FULL << CHAR_BIT
  6715. #endif
  6716. c = !((quoted | ~sep) & EXP_QUOTED) - 1;
  6717. sep &= ~quoted;
  6718. sep |= ifsset() ? (unsigned char)(c & ifsval()[0]) : ' ';
  6719. param:
  6720. sepc = sep;
  6721. ap = shellparam.p;
  6722. if (!ap)
  6723. return -1;
  6724. while ((p = *ap++) != NULL) {
  6725. len += strtodest(p, flags);
  6726. if (*ap && sep) {
  6727. len++;
  6728. memtodest(&sepc, 1, flags);
  6729. }
  6730. }
  6731. break;
  6732. } /* case '*' */
  6733. case '0':
  6734. case '1':
  6735. case '2':
  6736. case '3':
  6737. case '4':
  6738. case '5':
  6739. case '6':
  6740. case '7':
  6741. case '8':
  6742. case '9':
  6743. num = atoi(name); /* number(name) fails on ${N#str} etc */
  6744. if (num < 0 || num > shellparam.nparam)
  6745. return -1;
  6746. p = num ? shellparam.p[num - 1] : arg0;
  6747. goto value;
  6748. default:
  6749. /* NB: name has form "VAR=..." */
  6750. p = lookupvar(name);
  6751. value:
  6752. if (!p)
  6753. return -1;
  6754. len = strtodest(p, flags);
  6755. #if ENABLE_UNICODE_SUPPORT
  6756. if (subtype == VSLENGTH && len > 0) {
  6757. reinit_unicode_for_ash();
  6758. if (unicode_status == UNICODE_ON) {
  6759. STADJUST(-len, expdest);
  6760. discard = 0;
  6761. len = unicode_strlen(p);
  6762. }
  6763. }
  6764. #endif
  6765. break;
  6766. }
  6767. if (discard)
  6768. STADJUST(-len, expdest);
  6769. return len;
  6770. }
  6771. /*
  6772. * Expand a variable, and return a pointer to the next character in the
  6773. * input string.
  6774. */
  6775. static char *
  6776. evalvar(char *p, int flag)
  6777. {
  6778. char varflags;
  6779. char subtype;
  6780. char *var;
  6781. int patloc;
  6782. int startloc;
  6783. ssize_t varlen;
  6784. int discard;
  6785. int quoted;
  6786. varflags = (unsigned char) *p++;
  6787. subtype = varflags & VSTYPE;
  6788. quoted = flag & EXP_QUOTED;
  6789. var = p;
  6790. startloc = expdest - (char *)stackblock();
  6791. p = strchr(p, '=') + 1; //TODO: use var_end(p)?
  6792. again:
  6793. varlen = varvalue(var, varflags, flag, quoted);
  6794. if (varflags & VSNUL)
  6795. varlen--;
  6796. discard = varlen < 0 ? EXP_DISCARD : 0;
  6797. switch (subtype) {
  6798. case VSPLUS:
  6799. discard ^= EXP_DISCARD;
  6800. /* fall through */
  6801. case 0:
  6802. case VSMINUS:
  6803. p = argstr(p, flag | EXP_TILDE | EXP_WORD | (discard ^ EXP_DISCARD));
  6804. goto record;
  6805. case VSASSIGN:
  6806. case VSQUESTION:
  6807. p = subevalvar(p, var, 0, startloc, varflags,
  6808. (flag & ~QUOTES_ESC) | (discard ^ EXP_DISCARD));
  6809. if ((flag | ~discard) & EXP_DISCARD)
  6810. goto record;
  6811. varflags &= ~VSNUL;
  6812. subtype = VSNORMAL;
  6813. goto again;
  6814. }
  6815. if ((discard & ~flag) && uflag)
  6816. varunset(p, var, 0, 0);
  6817. if (subtype == VSLENGTH) {
  6818. p++;
  6819. if (flag & EXP_DISCARD)
  6820. return p;
  6821. cvtnum(varlen > 0 ? varlen : 0, flag);
  6822. goto really_record;
  6823. }
  6824. if (subtype == VSNORMAL)
  6825. goto record;
  6826. #if DEBUG
  6827. switch (subtype) {
  6828. case VSTRIMLEFT:
  6829. case VSTRIMLEFTMAX:
  6830. case VSTRIMRIGHT:
  6831. case VSTRIMRIGHTMAX:
  6832. #if BASH_SUBSTR
  6833. case VSSUBSTR:
  6834. #endif
  6835. #if BASH_PATTERN_SUBST
  6836. case VSREPLACE:
  6837. case VSREPLACEALL:
  6838. #endif
  6839. break;
  6840. default:
  6841. abort();
  6842. }
  6843. #endif
  6844. flag |= discard;
  6845. if (!(flag & EXP_DISCARD)) {
  6846. /*
  6847. * Terminate the string and start recording the pattern
  6848. * right after it
  6849. */
  6850. STPUTC('\0', expdest);
  6851. }
  6852. patloc = expdest - (char *)stackblock();
  6853. p = subevalvar(p, NULL, patloc, startloc, varflags, flag);
  6854. record:
  6855. if ((flag | discard) & EXP_DISCARD)
  6856. return p;
  6857. really_record:
  6858. if (quoted) {
  6859. quoted = *var == '@' && shellparam.nparam;
  6860. if (!quoted)
  6861. return p;
  6862. }
  6863. recordregion(startloc, expdest - (char *)stackblock(), quoted);
  6864. return p;
  6865. }
  6866. /*
  6867. * Add a file name to the list.
  6868. */
  6869. static void
  6870. addfname(const char *name)
  6871. {
  6872. struct strlist *sp;
  6873. sp = stzalloc(sizeof(*sp));
  6874. sp->text = sstrdup(name);
  6875. *exparg.lastp = sp;
  6876. exparg.lastp = &sp->next;
  6877. }
  6878. /* Avoid glob() (and thus, stat() et al) for words like "echo" */
  6879. static int
  6880. hasmeta(const char *p)
  6881. {
  6882. static const char chars[] ALIGN1 = {
  6883. '*', '?', '[', '\\', CTLQUOTEMARK, CTLESC, 0
  6884. };
  6885. for (;;) {
  6886. p = strpbrk(p, chars);
  6887. if (!p)
  6888. break;
  6889. switch ((unsigned char)*p) {
  6890. case CTLQUOTEMARK:
  6891. for (;;) {
  6892. p++;
  6893. if ((unsigned char)*p == CTLQUOTEMARK)
  6894. break;
  6895. if ((unsigned char)*p == CTLESC)
  6896. p++;
  6897. if (*p == '\0') /* huh? */
  6898. return 0;
  6899. }
  6900. break;
  6901. case '\\':
  6902. case CTLESC:
  6903. p++;
  6904. if (*p == '\0')
  6905. return 0;
  6906. break;
  6907. case '[':
  6908. if (!strchr(p + 1, ']')) {
  6909. /* It's not a properly closed [] pattern,
  6910. * but other metas may follow. Continue checking.
  6911. * my[file* _is_ globbed by bash
  6912. * and matches filenames like "my[file1".
  6913. */
  6914. break;
  6915. }
  6916. /* fallthrough */
  6917. default:
  6918. /* case '*': */
  6919. /* case '?': */
  6920. return 1;
  6921. }
  6922. p++;
  6923. }
  6924. return 0;
  6925. }
  6926. /* If we want to use glob() from libc... */
  6927. #if !ENABLE_ASH_INTERNAL_GLOB
  6928. /* Add the result of glob() to the list */
  6929. static void
  6930. addglob(const glob_t *pglob)
  6931. {
  6932. char **p = pglob->gl_pathv;
  6933. do {
  6934. addfname(*p);
  6935. } while (*++p);
  6936. }
  6937. static void
  6938. expandmeta(struct strlist *str /*, int flag*/)
  6939. {
  6940. /* TODO - EXP_REDIR */
  6941. while (str) {
  6942. char *p;
  6943. glob_t pglob;
  6944. int i;
  6945. if (fflag)
  6946. goto nometa;
  6947. if (!hasmeta(str->text))
  6948. goto nometa;
  6949. INT_OFF;
  6950. p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
  6951. // GLOB_NOMAGIC (GNU): if no *?[ chars in pattern, return it even if no match
  6952. // GLOB_NOCHECK: if no match, return unchanged pattern (sans \* escapes?)
  6953. //
  6954. // glibc 2.24.90 glob(GLOB_NOMAGIC) does not remove backslashes used for escaping:
  6955. // if you pass it "file\?", it returns "file\?", not "file?", if no match.
  6956. // Which means you need to unescape the string, right? Not so fast:
  6957. // if there _is_ a file named "file\?" (with backslash), it is returned
  6958. // as "file\?" too (whichever pattern you used to find it, say, "file*").
  6959. // You DON'T KNOW by looking at the result whether you need to unescape it.
  6960. //
  6961. // Worse, globbing of "file\?" in a directory with two files, "file?" and "file\?",
  6962. // returns "file\?" - which is WRONG: "file\?" pattern matches "file?" file.
  6963. // Without GLOB_NOMAGIC, this works correctly ("file?" is returned as a match).
  6964. // With GLOB_NOMAGIC | GLOB_NOCHECK, this also works correctly.
  6965. // i = glob(p, GLOB_NOMAGIC | GLOB_NOCHECK, NULL, &pglob);
  6966. // i = glob(p, GLOB_NOMAGIC, NULL, &pglob);
  6967. i = glob(p, 0, NULL, &pglob);
  6968. //bb_error_msg("glob('%s'):%d '%s'...", p, i, pglob.gl_pathv ? pglob.gl_pathv[0] : "-");
  6969. if (p != str->text)
  6970. free(p);
  6971. switch (i) {
  6972. case 0:
  6973. #if 0 // glibc 2.24.90 bug? Patterns like "*/file", when match, don't set GLOB_MAGCHAR
  6974. /* GLOB_MAGCHAR is set if *?[ chars were seen (GNU) */
  6975. if (!(pglob.gl_flags & GLOB_MAGCHAR))
  6976. goto nometa2;
  6977. #endif
  6978. addglob(&pglob);
  6979. globfree(&pglob);
  6980. INT_ON;
  6981. break;
  6982. case GLOB_NOMATCH:
  6983. //nometa2:
  6984. globfree(&pglob);
  6985. INT_ON;
  6986. nometa:
  6987. *exparg.lastp = str;
  6988. rmescapes(str->text, 0, NULL);
  6989. exparg.lastp = &str->next;
  6990. break;
  6991. default: /* GLOB_NOSPACE */
  6992. globfree(&pglob);
  6993. INT_ON;
  6994. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  6995. }
  6996. str = str->next;
  6997. }
  6998. }
  6999. #else
  7000. /* ENABLE_ASH_INTERNAL_GLOB: Homegrown globbing code. (dash also has both, uses homegrown one.) */
  7001. /*
  7002. * Do metacharacter (i.e. *, ?, [...]) expansion.
  7003. */
  7004. typedef struct exp_t {
  7005. char *dir;
  7006. unsigned dir_max;
  7007. } exp_t;
  7008. static void
  7009. expmeta(exp_t *exp, char *name, unsigned name_len, unsigned expdir_len)
  7010. {
  7011. #define expdir exp->dir
  7012. #define expdir_max exp->dir_max
  7013. char *enddir = expdir + expdir_len;
  7014. char *p;
  7015. const char *cp;
  7016. char *start;
  7017. char *endname;
  7018. int metaflag;
  7019. struct stat statb;
  7020. DIR *dirp;
  7021. struct dirent *dp;
  7022. int atend;
  7023. int matchdot;
  7024. int esc;
  7025. metaflag = 0;
  7026. start = name;
  7027. for (p = name; esc = 0, *p; p += esc + 1) {
  7028. if (*p == '*' || *p == '?')
  7029. metaflag = 1;
  7030. else if (*p == '[') {
  7031. char *q = p + 1;
  7032. if (*q == '!')
  7033. q++;
  7034. for (;;) {
  7035. if (*q == '\\')
  7036. q++;
  7037. if (*q == '/' || *q == '\0')
  7038. break;
  7039. if (*++q == ']') {
  7040. metaflag = 1;
  7041. break;
  7042. }
  7043. }
  7044. } else {
  7045. if (*p == '\\' && p[1])
  7046. esc++;
  7047. if (p[esc] == '/') {
  7048. if (metaflag)
  7049. break;
  7050. start = p + esc + 1;
  7051. }
  7052. }
  7053. }
  7054. if (metaflag == 0) { /* we've reached the end of the file name */
  7055. if (!expdir_len)
  7056. return;
  7057. p = name;
  7058. do {
  7059. if (*p == '\\' && p[1])
  7060. p++;
  7061. *enddir++ = *p;
  7062. } while (*p++);
  7063. if (lstat(expdir, &statb) == 0)
  7064. addfname(expdir);
  7065. return;
  7066. }
  7067. endname = p;
  7068. if (name < start) {
  7069. p = name;
  7070. do {
  7071. if (*p == '\\' && p[1])
  7072. p++;
  7073. *enddir++ = *p++;
  7074. } while (p < start);
  7075. }
  7076. *enddir = '\0';
  7077. cp = expdir;
  7078. expdir_len = enddir - cp;
  7079. if (!expdir_len)
  7080. cp = ".";
  7081. dirp = opendir(cp);
  7082. if (dirp == NULL)
  7083. return;
  7084. if (*endname == 0) {
  7085. atend = 1;
  7086. } else {
  7087. atend = 0;
  7088. *endname = '\0';
  7089. endname += esc + 1;
  7090. }
  7091. name_len -= endname - name;
  7092. matchdot = 0;
  7093. p = start;
  7094. if (*p == '\\')
  7095. p++;
  7096. if (*p == '.')
  7097. matchdot++;
  7098. while (!pending_int && (dp = readdir(dirp)) != NULL) {
  7099. if (dp->d_name[0] == '.' && !matchdot)
  7100. continue;
  7101. if (pmatch(start, dp->d_name)) {
  7102. if (atend) {
  7103. strcpy(enddir, dp->d_name);
  7104. addfname(expdir);
  7105. } else {
  7106. unsigned offset;
  7107. unsigned len;
  7108. p = stpcpy(enddir, dp->d_name);
  7109. *p = '/';
  7110. offset = p - expdir + 1;
  7111. len = offset + name_len + NAME_MAX;
  7112. if (len > expdir_max) {
  7113. len += PATH_MAX;
  7114. expdir = ckrealloc(expdir, len);
  7115. expdir_max = len;
  7116. }
  7117. expmeta(exp, endname, name_len, offset);
  7118. enddir = expdir + expdir_len;
  7119. }
  7120. }
  7121. }
  7122. closedir(dirp);
  7123. if (!atend)
  7124. endname[-esc - 1] = esc ? '\\' : '/';
  7125. #undef expdir
  7126. #undef expdir_max
  7127. }
  7128. static struct strlist *
  7129. msort(struct strlist *list, int len)
  7130. {
  7131. struct strlist *p, *q = NULL;
  7132. struct strlist **lpp;
  7133. int half;
  7134. int n;
  7135. if (len <= 1)
  7136. return list;
  7137. half = len >> 1;
  7138. p = list;
  7139. for (n = half; --n >= 0;) {
  7140. q = p;
  7141. p = p->next;
  7142. }
  7143. q->next = NULL; /* terminate first half of list */
  7144. q = msort(list, half); /* sort first half of list */
  7145. p = msort(p, len - half); /* sort second half */
  7146. lpp = &list;
  7147. for (;;) {
  7148. #if ENABLE_LOCALE_SUPPORT
  7149. if (strcoll(p->text, q->text) < 0)
  7150. #else
  7151. if (strcmp(p->text, q->text) < 0)
  7152. #endif
  7153. {
  7154. *lpp = p;
  7155. lpp = &p->next;
  7156. p = *lpp;
  7157. if (p == NULL) {
  7158. *lpp = q;
  7159. break;
  7160. }
  7161. } else {
  7162. *lpp = q;
  7163. lpp = &q->next;
  7164. q = *lpp;
  7165. if (q == NULL) {
  7166. *lpp = p;
  7167. break;
  7168. }
  7169. }
  7170. }
  7171. return list;
  7172. }
  7173. /*
  7174. * Sort the results of file name expansion. It calculates the number of
  7175. * strings to sort and then calls msort (short for merge sort) to do the
  7176. * work.
  7177. */
  7178. static struct strlist *
  7179. expsort(struct strlist *str)
  7180. {
  7181. int len;
  7182. struct strlist *sp;
  7183. len = 0;
  7184. for (sp = str; sp; sp = sp->next)
  7185. len++;
  7186. return msort(str, len);
  7187. }
  7188. static void
  7189. expandmeta(struct strlist *str /*, int flag*/)
  7190. {
  7191. /* TODO - EXP_REDIR */
  7192. while (str) {
  7193. exp_t exp;
  7194. struct strlist **savelastp;
  7195. struct strlist *sp;
  7196. char *p;
  7197. unsigned len;
  7198. if (fflag)
  7199. goto nometa;
  7200. if (!hasmeta(str->text))
  7201. goto nometa;
  7202. savelastp = exparg.lastp;
  7203. INT_OFF;
  7204. p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
  7205. len = strlen(p);
  7206. exp.dir_max = len + PATH_MAX;
  7207. exp.dir = ckmalloc(exp.dir_max);
  7208. expmeta(&exp, p, len, 0);
  7209. free(exp.dir);
  7210. if (p != str->text)
  7211. free(p);
  7212. INT_ON;
  7213. if (exparg.lastp == savelastp) {
  7214. /*
  7215. * no matches
  7216. */
  7217. nometa:
  7218. *exparg.lastp = str;
  7219. rmescapes(str->text, 0, NULL);
  7220. exparg.lastp = &str->next;
  7221. } else {
  7222. *exparg.lastp = NULL;
  7223. *savelastp = sp = expsort(*savelastp);
  7224. while (sp->next != NULL)
  7225. sp = sp->next;
  7226. exparg.lastp = &sp->next;
  7227. }
  7228. str = str->next;
  7229. }
  7230. }
  7231. #endif /* ENABLE_ASH_INTERNAL_GLOB */
  7232. /*
  7233. * Perform variable substitution and command substitution on an argument,
  7234. * placing the resulting list of arguments in arglist. If EXP_FULL is true,
  7235. * perform splitting and file name expansion. When arglist is NULL, perform
  7236. * here document expansion.
  7237. */
  7238. static void
  7239. expandarg(union node *arg, struct arglist *arglist, int flag)
  7240. {
  7241. struct strlist *sp;
  7242. char *p;
  7243. argbackq = arg->narg.backquote;
  7244. STARTSTACKSTR(expdest);
  7245. TRACE(("expandarg: argstr('%s',flags:%x)\n", arg->narg.text, flag));
  7246. argstr(arg->narg.text, flag);
  7247. if (arglist == NULL) {
  7248. /* here document expanded */
  7249. goto out;
  7250. }
  7251. p = grabstackstr(expdest);
  7252. TRACE(("expandarg: p:'%s'\n", p));
  7253. exparg.lastp = &exparg.list;
  7254. /*
  7255. * TODO - EXP_REDIR
  7256. */
  7257. if (flag & EXP_FULL) {
  7258. ifsbreakup(p, &exparg);
  7259. *exparg.lastp = NULL;
  7260. exparg.lastp = &exparg.list;
  7261. expandmeta(exparg.list /*, flag*/);
  7262. } else {
  7263. sp = stzalloc(sizeof(*sp));
  7264. sp->text = p;
  7265. *exparg.lastp = sp;
  7266. exparg.lastp = &sp->next;
  7267. }
  7268. *exparg.lastp = NULL;
  7269. if (exparg.list) {
  7270. *arglist->lastp = exparg.list;
  7271. arglist->lastp = exparg.lastp;
  7272. }
  7273. out:
  7274. ifsfree();
  7275. }
  7276. /*
  7277. * Expand shell variables and backquotes inside a here document.
  7278. */
  7279. static void
  7280. expandhere(union node *arg)
  7281. {
  7282. expandarg(arg, (struct arglist *)NULL, EXP_QUOTED);
  7283. }
  7284. /*
  7285. * Returns true if the pattern matches the string.
  7286. */
  7287. static int
  7288. patmatch(char *pattern, const char *string)
  7289. {
  7290. char *p = preglob(pattern, 0);
  7291. int r = pmatch(p, string);
  7292. //bb_error_msg("!fnmatch(pattern:'%s',str:'%s',0):%d", p, string, r);
  7293. return r;
  7294. }
  7295. /*
  7296. * See if a pattern matches in a case statement.
  7297. */
  7298. static int
  7299. casematch(union node *pattern, char *val)
  7300. {
  7301. struct stackmark smark;
  7302. int result;
  7303. setstackmark(&smark);
  7304. argbackq = pattern->narg.backquote;
  7305. STARTSTACKSTR(expdest);
  7306. argstr(pattern->narg.text, EXP_TILDE | EXP_CASE);
  7307. ifsfree();
  7308. result = patmatch(stackblock(), val);
  7309. popstackmark(&smark);
  7310. return result;
  7311. }
  7312. /* ============ find_command */
  7313. struct builtincmd {
  7314. const char *name;
  7315. int (*builtin)(int, char **) FAST_FUNC;
  7316. /* unsigned flags; */
  7317. };
  7318. #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
  7319. /* "regular" builtins always take precedence over commands,
  7320. * regardless of PATH=....%builtin... position */
  7321. #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
  7322. #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
  7323. struct cmdentry {
  7324. smallint cmdtype; /* CMDxxx */
  7325. union param {
  7326. int index;
  7327. /* index >= 0 for commands without path (slashes) */
  7328. /* (TODO: what exactly does the value mean? PATH position?) */
  7329. /* index == -1 for commands with slashes */
  7330. /* index == (-2 - applet_no) for NOFORK applets */
  7331. const struct builtincmd *cmd;
  7332. struct funcnode *func;
  7333. } u;
  7334. };
  7335. /* values of cmdtype */
  7336. #define CMDUNKNOWN -1 /* no entry in table for command */
  7337. #define CMDNORMAL 0 /* command is an executable program */
  7338. #define CMDFUNCTION 1 /* command is a shell function */
  7339. #define CMDBUILTIN 2 /* command is a shell builtin */
  7340. /* action to find_command() */
  7341. #define DO_ERR 0x01 /* prints errors */
  7342. #define DO_ABS 0x02 /* checks absolute paths */
  7343. #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
  7344. #define DO_ALTPATH 0x08 /* using alternate path */
  7345. #define DO_REGBLTIN 0x10 /* regular built-ins and functions only */
  7346. static void find_command(char *, struct cmdentry *, int, const char *);
  7347. /* ============ Hashing commands */
  7348. /*
  7349. * When commands are first encountered, they are entered in a hash table.
  7350. * This ensures that a full path search will not have to be done for them
  7351. * on each invocation.
  7352. *
  7353. * We should investigate converting to a linear search, even though that
  7354. * would make the command name "hash" a misnomer.
  7355. */
  7356. struct tblentry {
  7357. struct tblentry *next; /* next entry in hash chain */
  7358. union param param; /* definition of builtin function */
  7359. smallint cmdtype; /* CMDxxx */
  7360. char rehash; /* if set, cd done since entry created */
  7361. char cmdname[1]; /* name of command */
  7362. };
  7363. static struct tblentry **cmdtable;
  7364. #define INIT_G_cmdtable() do { \
  7365. cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
  7366. } while (0)
  7367. static int builtinloc = -1; /* index in path of %builtin, or -1 */
  7368. static void
  7369. tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) const char *cmd, char **argv, char **envp)
  7370. {
  7371. #if ENABLE_FEATURE_SH_STANDALONE
  7372. if (applet_no >= 0) {
  7373. if (APPLET_IS_NOEXEC(applet_no)) {
  7374. clearenv();
  7375. while (*envp)
  7376. putenv(*envp++);
  7377. popredir(/*drop:*/ 1);
  7378. run_noexec_applet_and_exit(applet_no, cmd, argv);
  7379. }
  7380. /* re-exec ourselves with the new arguments */
  7381. execve(bb_busybox_exec_path, argv, envp);
  7382. /* If they called chroot or otherwise made the binary no longer
  7383. * executable, fall through */
  7384. }
  7385. #endif
  7386. repeat:
  7387. #ifdef SYSV
  7388. do {
  7389. execve(cmd, argv, envp);
  7390. } while (errno == EINTR);
  7391. #else
  7392. execve(cmd, argv, envp);
  7393. #endif
  7394. if (cmd != bb_busybox_exec_path && errno == ENOEXEC) {
  7395. /* Run "cmd" as a shell script:
  7396. * http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
  7397. * "If the execve() function fails with ENOEXEC, the shell
  7398. * shall execute a command equivalent to having a shell invoked
  7399. * with the command name as its first operand,
  7400. * with any remaining arguments passed to the new shell"
  7401. *
  7402. * That is, do not use $SHELL, user's shell, or /bin/sh;
  7403. * just call ourselves.
  7404. *
  7405. * Note that bash reads ~80 chars of the file, and if it sees
  7406. * a zero byte before it sees newline, it doesn't try to
  7407. * interpret it, but fails with "cannot execute binary file"
  7408. * message and exit code 126. For one, this prevents attempts
  7409. * to interpret foreign ELF binaries as shell scripts.
  7410. */
  7411. argv[0] = (char*) cmd;
  7412. cmd = bb_busybox_exec_path;
  7413. /* NB: this is only possible because all callers of shellexec()
  7414. * ensure that the argv[-1] slot exists!
  7415. */
  7416. argv--;
  7417. argv[0] = (char*) "ash";
  7418. goto repeat;
  7419. }
  7420. }
  7421. /*
  7422. * Exec a program. Never returns. If you change this routine, you may
  7423. * have to change the find_command routine as well.
  7424. * argv[-1] must exist and be writable! See tryexec() for why.
  7425. */
  7426. static void shellexec(char *prog, char **argv, const char *path, int idx) NORETURN;
  7427. static void shellexec(char *prog, char **argv, const char *path, int idx)
  7428. {
  7429. char *cmdname;
  7430. int e;
  7431. char **envp;
  7432. int exerrno;
  7433. int applet_no = -1; /* used only by FEATURE_SH_STANDALONE */
  7434. envp = listvars(VEXPORT, VUNSET, /*strlist:*/ NULL, /*end:*/ NULL);
  7435. if (strchr(prog, '/') != NULL
  7436. #if ENABLE_FEATURE_SH_STANDALONE
  7437. || (applet_no = find_applet_by_name(prog)) >= 0
  7438. #endif
  7439. ) {
  7440. tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) prog, argv, envp);
  7441. if (applet_no >= 0) {
  7442. /* We tried execing ourself, but it didn't work.
  7443. * Maybe /proc/self/exe doesn't exist?
  7444. * Try $PATH search.
  7445. */
  7446. goto try_PATH;
  7447. }
  7448. e = errno;
  7449. } else {
  7450. try_PATH:
  7451. e = ENOENT;
  7452. while (padvance(&path, argv[0]) >= 0) {
  7453. cmdname = stackblock();
  7454. if (--idx < 0 && pathopt == NULL) {
  7455. tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
  7456. if (errno != ENOENT && errno != ENOTDIR)
  7457. e = errno;
  7458. }
  7459. }
  7460. }
  7461. /* Map to POSIX errors */
  7462. switch (e) {
  7463. default:
  7464. exerrno = 126;
  7465. break;
  7466. case ELOOP:
  7467. case ENAMETOOLONG:
  7468. case ENOENT:
  7469. case ENOTDIR:
  7470. exerrno = 127;
  7471. break;
  7472. }
  7473. exitstatus = exerrno;
  7474. TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
  7475. prog, e, suppress_int));
  7476. ash_msg_and_raise(EXEND, "%s: %s", prog, errmsg(e, "not found"));
  7477. /* NOTREACHED */
  7478. }
  7479. static void
  7480. printentry(struct tblentry *cmdp)
  7481. {
  7482. int idx;
  7483. const char *path;
  7484. char *name;
  7485. idx = cmdp->param.index;
  7486. path = pathval();
  7487. do {
  7488. padvance(&path, cmdp->cmdname);
  7489. } while (--idx >= 0);
  7490. name = stackblock();
  7491. out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
  7492. }
  7493. /*
  7494. * Clear out command entries.
  7495. */
  7496. static void
  7497. clearcmdentry(void)
  7498. {
  7499. struct tblentry **tblp;
  7500. struct tblentry **pp;
  7501. struct tblentry *cmdp;
  7502. INT_OFF;
  7503. for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
  7504. pp = tblp;
  7505. while ((cmdp = *pp) != NULL) {
  7506. if (cmdp->cmdtype == CMDNORMAL
  7507. || (cmdp->cmdtype == CMDBUILTIN
  7508. && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
  7509. && builtinloc > 0
  7510. )
  7511. ) {
  7512. *pp = cmdp->next;
  7513. free(cmdp);
  7514. } else {
  7515. pp = &cmdp->next;
  7516. }
  7517. }
  7518. }
  7519. INT_ON;
  7520. }
  7521. /*
  7522. * Locate a command in the command hash table. If "add" is nonzero,
  7523. * add the command to the table if it is not already present. The
  7524. * variable "lastcmdentry" is set to point to the address of the link
  7525. * pointing to the entry, so that delete_cmd_entry can delete the
  7526. * entry.
  7527. *
  7528. * Interrupts must be off if called with add != 0.
  7529. */
  7530. static struct tblentry **lastcmdentry;
  7531. static struct tblentry *
  7532. cmdlookup(const char *name, int add)
  7533. {
  7534. unsigned int hashval;
  7535. const char *p;
  7536. struct tblentry *cmdp;
  7537. struct tblentry **pp;
  7538. p = name;
  7539. hashval = (unsigned char)*p << 4;
  7540. while (*p)
  7541. hashval += (unsigned char)*p++;
  7542. hashval &= 0x7FFF;
  7543. pp = &cmdtable[hashval % CMDTABLESIZE];
  7544. for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
  7545. if (strcmp(cmdp->cmdname, name) == 0)
  7546. break;
  7547. pp = &cmdp->next;
  7548. }
  7549. if (add && cmdp == NULL) {
  7550. cmdp = *pp = ckzalloc(sizeof(struct tblentry)
  7551. + strlen(name)
  7552. /* + 1 - already done because
  7553. * tblentry::cmdname is char[1] */);
  7554. /*cmdp->next = NULL; - ckzalloc did it */
  7555. cmdp->cmdtype = CMDUNKNOWN;
  7556. strcpy(cmdp->cmdname, name);
  7557. }
  7558. lastcmdentry = pp;
  7559. return cmdp;
  7560. }
  7561. /*
  7562. * Delete the command entry returned on the last lookup.
  7563. */
  7564. static void
  7565. delete_cmd_entry(void)
  7566. {
  7567. struct tblentry *cmdp;
  7568. INT_OFF;
  7569. cmdp = *lastcmdentry;
  7570. *lastcmdentry = cmdp->next;
  7571. if (cmdp->cmdtype == CMDFUNCTION)
  7572. freefunc(cmdp->param.func);
  7573. free(cmdp);
  7574. INT_ON;
  7575. }
  7576. /*
  7577. * Add a new command entry, replacing any existing command entry for
  7578. * the same name - except special builtins.
  7579. */
  7580. static void
  7581. addcmdentry(char *name, struct cmdentry *entry)
  7582. {
  7583. struct tblentry *cmdp;
  7584. cmdp = cmdlookup(name, 1);
  7585. if (cmdp->cmdtype == CMDFUNCTION) {
  7586. freefunc(cmdp->param.func);
  7587. }
  7588. cmdp->cmdtype = entry->cmdtype;
  7589. cmdp->param = entry->u;
  7590. cmdp->rehash = 0;
  7591. }
  7592. static int FAST_FUNC
  7593. hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  7594. {
  7595. struct tblentry **pp;
  7596. struct tblentry *cmdp;
  7597. int c;
  7598. struct cmdentry entry;
  7599. char *name;
  7600. if (nextopt("r") != '\0') {
  7601. clearcmdentry();
  7602. return 0;
  7603. }
  7604. if (*argptr == NULL) {
  7605. for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
  7606. for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
  7607. if (cmdp->cmdtype == CMDNORMAL)
  7608. printentry(cmdp);
  7609. }
  7610. }
  7611. return 0;
  7612. }
  7613. c = 0;
  7614. while ((name = *argptr) != NULL) {
  7615. cmdp = cmdlookup(name, 0);
  7616. if (cmdp != NULL
  7617. && (cmdp->cmdtype == CMDNORMAL
  7618. || (cmdp->cmdtype == CMDBUILTIN
  7619. && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
  7620. && builtinloc > 0
  7621. )
  7622. )
  7623. ) {
  7624. delete_cmd_entry();
  7625. }
  7626. find_command(name, &entry, DO_ERR, pathval());
  7627. if (entry.cmdtype == CMDUNKNOWN)
  7628. c = 1;
  7629. argptr++;
  7630. }
  7631. return c;
  7632. }
  7633. /*
  7634. * Called when a cd is done. Marks all commands so the next time they
  7635. * are executed they will be rehashed.
  7636. */
  7637. static void
  7638. hashcd(void)
  7639. {
  7640. struct tblentry **pp;
  7641. struct tblentry *cmdp;
  7642. for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
  7643. for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
  7644. if (cmdp->cmdtype == CMDNORMAL
  7645. || (cmdp->cmdtype == CMDBUILTIN
  7646. && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
  7647. && builtinloc > 0)
  7648. ) {
  7649. cmdp->rehash = 1;
  7650. }
  7651. }
  7652. }
  7653. }
  7654. /*
  7655. * Fix command hash table when PATH changed.
  7656. * Called before PATH is changed. The argument is the new value of PATH;
  7657. * pathval() still returns the old value at this point.
  7658. * Called with interrupts off.
  7659. */
  7660. static void FAST_FUNC
  7661. changepath(const char *newval)
  7662. {
  7663. const char *new;
  7664. int idx;
  7665. int bltin;
  7666. new = newval;
  7667. idx = 0;
  7668. bltin = -1;
  7669. for (;;) {
  7670. if (*new == '%' && prefix(new + 1, "builtin")) {
  7671. bltin = idx;
  7672. break;
  7673. }
  7674. new = strchr(new, ':');
  7675. if (!new)
  7676. break;
  7677. idx++;
  7678. new++;
  7679. }
  7680. builtinloc = bltin;
  7681. clearcmdentry();
  7682. }
  7683. enum {
  7684. TEOF,
  7685. TNL,
  7686. TREDIR,
  7687. TWORD,
  7688. TSEMI,
  7689. TBACKGND,
  7690. TAND,
  7691. TOR,
  7692. TPIPE,
  7693. TLP,
  7694. TRP,
  7695. TENDCASE,
  7696. TENDBQUOTE,
  7697. TNOT,
  7698. TCASE,
  7699. TDO,
  7700. TDONE,
  7701. TELIF,
  7702. TELSE,
  7703. TESAC,
  7704. TFI,
  7705. TFOR,
  7706. #if BASH_FUNCTION
  7707. TFUNCTION,
  7708. #endif
  7709. TIF,
  7710. TIN,
  7711. TTHEN,
  7712. TUNTIL,
  7713. TWHILE,
  7714. TBEGIN,
  7715. TEND
  7716. };
  7717. typedef smallint token_id_t;
  7718. /* Nth bit indicates if token marks the end of a list */
  7719. enum {
  7720. tokendlist = 0
  7721. /* 0 */ | (1u << TEOF)
  7722. /* 1 */ | (0u << TNL)
  7723. /* 2 */ | (0u << TREDIR)
  7724. /* 3 */ | (0u << TWORD)
  7725. /* 4 */ | (0u << TSEMI)
  7726. /* 5 */ | (0u << TBACKGND)
  7727. /* 6 */ | (0u << TAND)
  7728. /* 7 */ | (0u << TOR)
  7729. /* 8 */ | (0u << TPIPE)
  7730. /* 9 */ | (0u << TLP)
  7731. /* 10 */ | (1u << TRP)
  7732. /* 11 */ | (1u << TENDCASE)
  7733. /* 12 */ | (1u << TENDBQUOTE)
  7734. /* 13 */ | (0u << TNOT)
  7735. /* 14 */ | (0u << TCASE)
  7736. /* 15 */ | (1u << TDO)
  7737. /* 16 */ | (1u << TDONE)
  7738. /* 17 */ | (1u << TELIF)
  7739. /* 18 */ | (1u << TELSE)
  7740. /* 19 */ | (1u << TESAC)
  7741. /* 20 */ | (1u << TFI)
  7742. /* 21 */ | (0u << TFOR)
  7743. #if BASH_FUNCTION
  7744. /* 22 */ | (0u << TFUNCTION)
  7745. #endif
  7746. /* 23 */ | (0u << TIF)
  7747. /* 24 */ | (0u << TIN)
  7748. /* 25 */ | (1u << TTHEN)
  7749. /* 26 */ | (0u << TUNTIL)
  7750. /* 27 */ | (0u << TWHILE)
  7751. /* 28 */ | (0u << TBEGIN)
  7752. /* 29 */ | (1u << TEND)
  7753. , /* thus far 29 bits used */
  7754. };
  7755. static const char *const tokname_array[] = {
  7756. "end of file",
  7757. "newline",
  7758. "redirection",
  7759. "word",
  7760. ";",
  7761. "&",
  7762. "&&",
  7763. "||",
  7764. "|",
  7765. "(",
  7766. ")",
  7767. ";;",
  7768. "`",
  7769. #define KWDOFFSET 13
  7770. /* the following are keywords */
  7771. "!",
  7772. "case",
  7773. "do",
  7774. "done",
  7775. "elif",
  7776. "else",
  7777. "esac",
  7778. "fi",
  7779. "for",
  7780. #if BASH_FUNCTION
  7781. "function",
  7782. #endif
  7783. "if",
  7784. "in",
  7785. "then",
  7786. "until",
  7787. "while",
  7788. "{",
  7789. "}",
  7790. };
  7791. /* Wrapper around strcmp for qsort/bsearch/... */
  7792. static int
  7793. pstrcmp(const void *a, const void *b)
  7794. {
  7795. return strcmp((char*)a, *(char**)b);
  7796. }
  7797. static const char *const *
  7798. findkwd(const char *s)
  7799. {
  7800. return bsearch(s, tokname_array + KWDOFFSET,
  7801. ARRAY_SIZE(tokname_array) - KWDOFFSET,
  7802. sizeof(tokname_array[0]), pstrcmp);
  7803. }
  7804. /*
  7805. * Locate and print what a word is...
  7806. */
  7807. static int
  7808. describe_command(char *command, const char *path, int describe_command_verbose)
  7809. {
  7810. struct cmdentry entry;
  7811. #if ENABLE_ASH_ALIAS
  7812. const struct alias *ap;
  7813. #endif
  7814. path = path ? path : pathval();
  7815. if (describe_command_verbose) {
  7816. out1str(command);
  7817. }
  7818. /* First look at the keywords */
  7819. if (findkwd(command)) {
  7820. out1str(describe_command_verbose ? " is a shell keyword" : command);
  7821. goto out;
  7822. }
  7823. #if ENABLE_ASH_ALIAS
  7824. /* Then look at the aliases */
  7825. ap = lookupalias(command, 0);
  7826. if (ap != NULL) {
  7827. if (!describe_command_verbose) {
  7828. out1str("alias ");
  7829. printalias(ap);
  7830. return 0;
  7831. }
  7832. out1fmt(" is an alias for %s", ap->val);
  7833. goto out;
  7834. }
  7835. #endif
  7836. /* Brute force */
  7837. find_command(command, &entry, DO_ABS, path);
  7838. switch (entry.cmdtype) {
  7839. case CMDNORMAL: {
  7840. int j = entry.u.index;
  7841. char *p;
  7842. if (j < 0) {
  7843. p = command;
  7844. } else {
  7845. do {
  7846. padvance(&path, command);
  7847. } while (--j >= 0);
  7848. p = stackblock();
  7849. }
  7850. if (describe_command_verbose) {
  7851. out1fmt(" is %s", p);
  7852. } else {
  7853. out1str(p);
  7854. }
  7855. break;
  7856. }
  7857. case CMDFUNCTION:
  7858. if (describe_command_verbose) {
  7859. /*out1str(" is a shell function");*/
  7860. out1str(" is a function"); /* bash says this */
  7861. } else {
  7862. out1str(command);
  7863. }
  7864. break;
  7865. case CMDBUILTIN:
  7866. if (describe_command_verbose) {
  7867. out1fmt(" is a %sshell builtin",
  7868. IS_BUILTIN_SPECIAL(entry.u.cmd) ?
  7869. "special " : nullstr
  7870. );
  7871. } else {
  7872. out1str(command);
  7873. }
  7874. break;
  7875. default:
  7876. if (describe_command_verbose) {
  7877. out1str(": not found\n");
  7878. }
  7879. return 127;
  7880. }
  7881. out:
  7882. out1str("\n");
  7883. return 0;
  7884. }
  7885. static int FAST_FUNC
  7886. typecmd(int argc UNUSED_PARAM, char **argv)
  7887. {
  7888. int i = 1;
  7889. int err = 0;
  7890. int verbose = 1;
  7891. /* type -p ... ? (we don't bother checking for 'p') */
  7892. if (argv[1] && argv[1][0] == '-') {
  7893. i++;
  7894. verbose = 0;
  7895. }
  7896. while (argv[i]) {
  7897. err |= describe_command(argv[i++], NULL, verbose);
  7898. }
  7899. return err;
  7900. }
  7901. static struct strlist *
  7902. fill_arglist(struct arglist *arglist, union node **argpp)
  7903. {
  7904. struct strlist **lastp = arglist->lastp;
  7905. union node *argp;
  7906. while ((argp = *argpp) != NULL) {
  7907. expandarg(argp, arglist, EXP_FULL | EXP_TILDE);
  7908. *argpp = argp->narg.next;
  7909. if (*lastp)
  7910. break;
  7911. }
  7912. return *lastp;
  7913. }
  7914. #if ENABLE_ASH_CMDCMD
  7915. /* Is it "command [-p] PROG ARGS" bltin, no other opts? Return ptr to "PROG" if yes */
  7916. static int
  7917. parse_command_args(struct arglist *arglist, union node **argpp, const char **path)
  7918. {
  7919. struct strlist *sp = arglist->list;
  7920. char *cp, c;
  7921. for (;;) {
  7922. sp = sp->next ? sp->next : fill_arglist(arglist, argpp);
  7923. if (!sp)
  7924. return 0;
  7925. cp = sp->text;
  7926. if (*cp++ != '-')
  7927. break;
  7928. c = *cp++;
  7929. if (!c)
  7930. break;
  7931. if (c == '-' && !*cp) {
  7932. if (!sp->next && !fill_arglist(arglist, argpp))
  7933. return 0;
  7934. sp = sp->next;
  7935. break;
  7936. }
  7937. do {
  7938. switch (c) {
  7939. case 'p':
  7940. *path = bb_default_path;
  7941. break;
  7942. default:
  7943. /* run 'typecmd' for other options */
  7944. return 0;
  7945. }
  7946. c = *cp++;
  7947. } while (c);
  7948. }
  7949. arglist->list = sp;
  7950. return DO_NOFUNC;
  7951. }
  7952. static int FAST_FUNC
  7953. commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  7954. {
  7955. char *cmd;
  7956. int c;
  7957. enum {
  7958. VERIFY_BRIEF = 1,
  7959. VERIFY_VERBOSE = 2,
  7960. } verify = 0;
  7961. const char *path = NULL;
  7962. /* "command [-p] PROG ARGS" (that is, without -V or -v)
  7963. * never reaches this function.
  7964. */
  7965. while ((c = nextopt("pvV")) != '\0')
  7966. if (c == 'V')
  7967. verify |= VERIFY_VERBOSE;
  7968. else if (c == 'v')
  7969. /*verify |= VERIFY_BRIEF*/;
  7970. #if DEBUG
  7971. else if (c != 'p')
  7972. abort();
  7973. #endif
  7974. else
  7975. path = bb_default_path;
  7976. /* Mimic bash: just "command -v" doesn't complain, it's a nop */
  7977. cmd = *argptr;
  7978. if (/*verify && */ cmd)
  7979. return describe_command(cmd, path, verify /* - VERIFY_BRIEF*/);
  7980. return 0;
  7981. }
  7982. #endif
  7983. /*static int funcblocksize; // size of structures in function */
  7984. /*static int funcstringsize; // size of strings in node */
  7985. static void *funcblock; /* block to allocate function from */
  7986. static char *funcstring_end; /* end of block to allocate strings from */
  7987. static const uint8_t nodesize[N_NUMBER] ALIGN1 = {
  7988. [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
  7989. [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
  7990. [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
  7991. [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
  7992. [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
  7993. [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
  7994. [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
  7995. [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
  7996. [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
  7997. [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
  7998. [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
  7999. [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
  8000. [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
  8001. [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
  8002. [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
  8003. [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
  8004. [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
  8005. #if BASH_REDIR_OUTPUT
  8006. [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
  8007. #endif
  8008. [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
  8009. [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
  8010. [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
  8011. [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
  8012. [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
  8013. [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
  8014. [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
  8015. [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
  8016. [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
  8017. };
  8018. static int calcsize(int funcblocksize, union node *n);
  8019. static int
  8020. sizenodelist(int funcblocksize, struct nodelist *lp)
  8021. {
  8022. while (lp) {
  8023. funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
  8024. funcblocksize = calcsize(funcblocksize, lp->n);
  8025. lp = lp->next;
  8026. }
  8027. return funcblocksize;
  8028. }
  8029. static int
  8030. calcsize(int funcblocksize, union node *n)
  8031. {
  8032. if (n == NULL)
  8033. return funcblocksize;
  8034. funcblocksize += nodesize[n->type];
  8035. switch (n->type) {
  8036. case NCMD:
  8037. funcblocksize = calcsize(funcblocksize, n->ncmd.redirect);
  8038. funcblocksize = calcsize(funcblocksize, n->ncmd.args);
  8039. funcblocksize = calcsize(funcblocksize, n->ncmd.assign);
  8040. break;
  8041. case NPIPE:
  8042. funcblocksize = sizenodelist(funcblocksize, n->npipe.cmdlist);
  8043. break;
  8044. case NREDIR:
  8045. case NBACKGND:
  8046. case NSUBSHELL:
  8047. funcblocksize = calcsize(funcblocksize, n->nredir.redirect);
  8048. funcblocksize = calcsize(funcblocksize, n->nredir.n);
  8049. break;
  8050. case NAND:
  8051. case NOR:
  8052. case NSEMI:
  8053. case NWHILE:
  8054. case NUNTIL:
  8055. funcblocksize = calcsize(funcblocksize, n->nbinary.ch2);
  8056. funcblocksize = calcsize(funcblocksize, n->nbinary.ch1);
  8057. break;
  8058. case NIF:
  8059. funcblocksize = calcsize(funcblocksize, n->nif.elsepart);
  8060. funcblocksize = calcsize(funcblocksize, n->nif.ifpart);
  8061. funcblocksize = calcsize(funcblocksize, n->nif.test);
  8062. break;
  8063. case NFOR:
  8064. funcblocksize += SHELL_ALIGN(strlen(n->nfor.var) + 1); /* was funcstringsize += ... */
  8065. funcblocksize = calcsize(funcblocksize, n->nfor.body);
  8066. funcblocksize = calcsize(funcblocksize, n->nfor.args);
  8067. break;
  8068. case NCASE:
  8069. funcblocksize = calcsize(funcblocksize, n->ncase.cases);
  8070. funcblocksize = calcsize(funcblocksize, n->ncase.expr);
  8071. break;
  8072. case NCLIST:
  8073. funcblocksize = calcsize(funcblocksize, n->nclist.body);
  8074. funcblocksize = calcsize(funcblocksize, n->nclist.pattern);
  8075. funcblocksize = calcsize(funcblocksize, n->nclist.next);
  8076. break;
  8077. case NDEFUN:
  8078. funcblocksize = calcsize(funcblocksize, n->ndefun.body);
  8079. funcblocksize += SHELL_ALIGN(strlen(n->ndefun.text) + 1);
  8080. break;
  8081. case NARG:
  8082. funcblocksize = sizenodelist(funcblocksize, n->narg.backquote);
  8083. funcblocksize += SHELL_ALIGN(strlen(n->narg.text) + 1); /* was funcstringsize += ... */
  8084. funcblocksize = calcsize(funcblocksize, n->narg.next);
  8085. break;
  8086. case NTO:
  8087. #if BASH_REDIR_OUTPUT
  8088. case NTO2:
  8089. #endif
  8090. case NCLOBBER:
  8091. case NFROM:
  8092. case NFROMTO:
  8093. case NAPPEND:
  8094. funcblocksize = calcsize(funcblocksize, n->nfile.fname);
  8095. funcblocksize = calcsize(funcblocksize, n->nfile.next);
  8096. break;
  8097. case NTOFD:
  8098. case NFROMFD:
  8099. funcblocksize = calcsize(funcblocksize, n->ndup.vname);
  8100. funcblocksize = calcsize(funcblocksize, n->ndup.next);
  8101. break;
  8102. case NHERE:
  8103. case NXHERE:
  8104. funcblocksize = calcsize(funcblocksize, n->nhere.doc);
  8105. funcblocksize = calcsize(funcblocksize, n->nhere.next);
  8106. break;
  8107. case NNOT:
  8108. funcblocksize = calcsize(funcblocksize, n->nnot.com);
  8109. break;
  8110. };
  8111. return funcblocksize;
  8112. }
  8113. static char *
  8114. nodeckstrdup(char *s)
  8115. {
  8116. funcstring_end -= SHELL_ALIGN(strlen(s) + 1);
  8117. return strcpy(funcstring_end, s);
  8118. }
  8119. static union node *copynode(union node *);
  8120. static struct nodelist *
  8121. copynodelist(struct nodelist *lp)
  8122. {
  8123. struct nodelist *start;
  8124. struct nodelist **lpp;
  8125. lpp = &start;
  8126. while (lp) {
  8127. *lpp = funcblock;
  8128. funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
  8129. (*lpp)->n = copynode(lp->n);
  8130. lp = lp->next;
  8131. lpp = &(*lpp)->next;
  8132. }
  8133. *lpp = NULL;
  8134. return start;
  8135. }
  8136. static union node *
  8137. copynode(union node *n)
  8138. {
  8139. union node *new;
  8140. if (n == NULL)
  8141. return NULL;
  8142. new = funcblock;
  8143. funcblock = (char *) funcblock + nodesize[n->type];
  8144. switch (n->type) {
  8145. case NCMD:
  8146. new->ncmd.redirect = copynode(n->ncmd.redirect);
  8147. new->ncmd.args = copynode(n->ncmd.args);
  8148. new->ncmd.assign = copynode(n->ncmd.assign);
  8149. new->ncmd.linno = n->ncmd.linno;
  8150. break;
  8151. case NPIPE:
  8152. new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
  8153. new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
  8154. break;
  8155. case NREDIR:
  8156. case NBACKGND:
  8157. case NSUBSHELL:
  8158. new->nredir.redirect = copynode(n->nredir.redirect);
  8159. new->nredir.n = copynode(n->nredir.n);
  8160. new->nredir.linno = n->nredir.linno;
  8161. break;
  8162. case NAND:
  8163. case NOR:
  8164. case NSEMI:
  8165. case NWHILE:
  8166. case NUNTIL:
  8167. new->nbinary.ch2 = copynode(n->nbinary.ch2);
  8168. new->nbinary.ch1 = copynode(n->nbinary.ch1);
  8169. break;
  8170. case NIF:
  8171. new->nif.elsepart = copynode(n->nif.elsepart);
  8172. new->nif.ifpart = copynode(n->nif.ifpart);
  8173. new->nif.test = copynode(n->nif.test);
  8174. break;
  8175. case NFOR:
  8176. new->nfor.var = nodeckstrdup(n->nfor.var);
  8177. new->nfor.body = copynode(n->nfor.body);
  8178. new->nfor.args = copynode(n->nfor.args);
  8179. new->nfor.linno = n->nfor.linno;
  8180. break;
  8181. case NCASE:
  8182. new->ncase.cases = copynode(n->ncase.cases);
  8183. new->ncase.expr = copynode(n->ncase.expr);
  8184. new->ncase.linno = n->ncase.linno;
  8185. break;
  8186. case NCLIST:
  8187. new->nclist.body = copynode(n->nclist.body);
  8188. new->nclist.pattern = copynode(n->nclist.pattern);
  8189. new->nclist.next = copynode(n->nclist.next);
  8190. break;
  8191. case NDEFUN:
  8192. new->ndefun.body = copynode(n->ndefun.body);
  8193. new->ndefun.text = nodeckstrdup(n->ndefun.text);
  8194. new->ndefun.linno = n->ndefun.linno;
  8195. break;
  8196. case NARG:
  8197. new->narg.backquote = copynodelist(n->narg.backquote);
  8198. new->narg.text = nodeckstrdup(n->narg.text);
  8199. new->narg.next = copynode(n->narg.next);
  8200. break;
  8201. case NTO:
  8202. #if BASH_REDIR_OUTPUT
  8203. case NTO2:
  8204. #endif
  8205. case NCLOBBER:
  8206. case NFROM:
  8207. case NFROMTO:
  8208. case NAPPEND:
  8209. new->nfile.fname = copynode(n->nfile.fname);
  8210. new->nfile.fd = n->nfile.fd;
  8211. new->nfile.next = copynode(n->nfile.next);
  8212. break;
  8213. case NTOFD:
  8214. case NFROMFD:
  8215. new->ndup.vname = copynode(n->ndup.vname);
  8216. new->ndup.dupfd = n->ndup.dupfd;
  8217. new->ndup.fd = n->ndup.fd;
  8218. new->ndup.next = copynode(n->ndup.next);
  8219. break;
  8220. case NHERE:
  8221. case NXHERE:
  8222. new->nhere.doc = copynode(n->nhere.doc);
  8223. new->nhere.fd = n->nhere.fd;
  8224. new->nhere.next = copynode(n->nhere.next);
  8225. break;
  8226. case NNOT:
  8227. new->nnot.com = copynode(n->nnot.com);
  8228. break;
  8229. };
  8230. new->type = n->type;
  8231. return new;
  8232. }
  8233. /*
  8234. * Make a copy of a parse tree.
  8235. */
  8236. static struct funcnode *
  8237. copyfunc(union node *n)
  8238. {
  8239. struct funcnode *f;
  8240. size_t blocksize;
  8241. /*funcstringsize = 0;*/
  8242. blocksize = offsetof(struct funcnode, n) + calcsize(0, n);
  8243. f = ckzalloc(blocksize /* + funcstringsize */);
  8244. funcblock = (char *) f + offsetof(struct funcnode, n);
  8245. funcstring_end = (char *) f + blocksize;
  8246. copynode(n);
  8247. /* f->count = 0; - ckzalloc did it */
  8248. return f;
  8249. }
  8250. /*
  8251. * Define a shell function.
  8252. */
  8253. static void
  8254. defun(union node *func)
  8255. {
  8256. struct cmdentry entry;
  8257. INT_OFF;
  8258. entry.cmdtype = CMDFUNCTION;
  8259. entry.u.func = copyfunc(func);
  8260. addcmdentry(func->ndefun.text, &entry);
  8261. INT_ON;
  8262. }
  8263. /* Reasons for skipping commands (see comment on breakcmd routine) */
  8264. #define SKIPBREAK (1 << 0)
  8265. #define SKIPCONT (1 << 1)
  8266. #define SKIPFUNC (1 << 2)
  8267. #define SKIPFUNCDEF (1 << 3)
  8268. static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
  8269. static int skipcount; /* number of levels to skip */
  8270. static int loopnest; /* current loop nesting level */
  8271. static int funcline; /* starting line number of current function, or 0 if not in a function */
  8272. /* Forward decl way out to parsing code - dotrap needs it */
  8273. static int evalstring(char *s, int flags);
  8274. /* Called to execute a trap.
  8275. * Single callsite - at the end of evaltree().
  8276. * If we return non-zero, evaltree raises EXEXIT exception.
  8277. *
  8278. * Perhaps we should avoid entering new trap handlers
  8279. * while we are executing a trap handler. [is it a TODO?]
  8280. */
  8281. static void
  8282. dotrap(void)
  8283. {
  8284. uint8_t *g;
  8285. int sig;
  8286. int status, last_status;
  8287. if (!pending_sig)
  8288. return;
  8289. status = savestatus;
  8290. last_status = status;
  8291. if (status < 0) {
  8292. status = exitstatus;
  8293. savestatus = status;
  8294. }
  8295. pending_sig = 0;
  8296. barrier();
  8297. TRACE(("dotrap entered\n"));
  8298. for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
  8299. char *p;
  8300. if (!*g)
  8301. continue;
  8302. if (evalskip) {
  8303. pending_sig = sig;
  8304. break;
  8305. }
  8306. p = trap[sig];
  8307. /* non-trapped SIGINT is handled separately by raise_interrupt,
  8308. * don't upset it by resetting gotsig[SIGINT-1] */
  8309. if (sig == SIGINT && !p)
  8310. continue;
  8311. TRACE(("sig %d is active, will run handler '%s'\n", sig, p));
  8312. *g = 0;
  8313. if (!p)
  8314. continue;
  8315. evalstring(p, 0);
  8316. if (evalskip != SKIPFUNC)
  8317. exitstatus = status;
  8318. }
  8319. savestatus = last_status;
  8320. TRACE(("dotrap returns\n"));
  8321. }
  8322. /* forward declarations - evaluation is fairly recursive business... */
  8323. static int evalloop(union node *, int);
  8324. static int evalfor(union node *, int);
  8325. static int evalcase(union node *, int);
  8326. static int evalsubshell(union node *, int);
  8327. static void expredir(union node *);
  8328. static int evalpipe(union node *, int);
  8329. static int evalcommand(union node *, int);
  8330. static int evalbltin(const struct builtincmd *, int, char **, int);
  8331. static void prehash(union node *);
  8332. /*
  8333. * Evaluate a parse tree. The value is left in the global variable
  8334. * exitstatus.
  8335. */
  8336. static int
  8337. evaltree(union node *n, int flags)
  8338. {
  8339. int checkexit = 0;
  8340. int (*evalfn)(union node *, int);
  8341. struct stackmark smark;
  8342. int status = 0;
  8343. setstackmark(&smark);
  8344. if (n == NULL) {
  8345. TRACE(("evaltree(NULL) called\n"));
  8346. goto out;
  8347. }
  8348. TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
  8349. dotrap();
  8350. switch (n->type) {
  8351. default:
  8352. #if DEBUG
  8353. out1fmt("Node type = %d\n", n->type);
  8354. fflush_all();
  8355. break;
  8356. #endif
  8357. case NNOT:
  8358. status = !evaltree(n->nnot.com, EV_TESTED);
  8359. goto setstatus;
  8360. case NREDIR:
  8361. errlinno = lineno = n->nredir.linno;
  8362. if (funcline)
  8363. lineno -= funcline - 1;
  8364. expredir(n->nredir.redirect);
  8365. pushredir(n->nredir.redirect);
  8366. status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
  8367. if (!status) {
  8368. status = evaltree(n->nredir.n, flags & EV_TESTED);
  8369. }
  8370. if (n->nredir.redirect)
  8371. popredir(/*drop:*/ 0);
  8372. goto setstatus;
  8373. case NCMD:
  8374. evalfn = evalcommand;
  8375. checkexit:
  8376. if (eflag && !(flags & EV_TESTED))
  8377. checkexit = ~0;
  8378. goto calleval;
  8379. case NFOR:
  8380. evalfn = evalfor;
  8381. goto calleval;
  8382. case NWHILE:
  8383. case NUNTIL:
  8384. evalfn = evalloop;
  8385. goto calleval;
  8386. case NSUBSHELL:
  8387. case NBACKGND:
  8388. evalfn = evalsubshell;
  8389. goto checkexit;
  8390. case NPIPE:
  8391. evalfn = evalpipe;
  8392. goto checkexit;
  8393. case NCASE:
  8394. evalfn = evalcase;
  8395. goto calleval;
  8396. case NAND:
  8397. case NOR:
  8398. case NSEMI: {
  8399. #if NAND + 1 != NOR
  8400. #error NAND + 1 != NOR
  8401. #endif
  8402. #if NOR + 1 != NSEMI
  8403. #error NOR + 1 != NSEMI
  8404. #endif
  8405. unsigned is_or = n->type - NAND;
  8406. status = evaltree(
  8407. n->nbinary.ch1,
  8408. (flags | ((is_or >> 1) - 1)) & EV_TESTED
  8409. );
  8410. if ((!status) == is_or || evalskip)
  8411. break;
  8412. n = n->nbinary.ch2;
  8413. evaln:
  8414. evalfn = evaltree;
  8415. calleval:
  8416. status = evalfn(n, flags);
  8417. goto setstatus;
  8418. }
  8419. case NIF:
  8420. status = evaltree(n->nif.test, EV_TESTED);
  8421. if (evalskip)
  8422. break;
  8423. if (!status) {
  8424. n = n->nif.ifpart;
  8425. goto evaln;
  8426. }
  8427. if (n->nif.elsepart) {
  8428. n = n->nif.elsepart;
  8429. goto evaln;
  8430. }
  8431. status = 0;
  8432. goto setstatus;
  8433. case NDEFUN:
  8434. defun(n);
  8435. /* Not necessary. To test it:
  8436. * "false; f() { qwerty; }; echo $?" should print 0.
  8437. */
  8438. /* status = 0; */
  8439. setstatus:
  8440. exitstatus = status;
  8441. break;
  8442. }
  8443. out:
  8444. /* Order of checks below is important:
  8445. * signal handlers trigger before exit caused by "set -e".
  8446. */
  8447. dotrap();
  8448. if (checkexit & status)
  8449. raise_exception(EXEND);
  8450. if (flags & EV_EXIT)
  8451. raise_exception(EXEND);
  8452. popstackmark(&smark);
  8453. TRACE(("leaving evaltree (no interrupts)\n"));
  8454. return exitstatus;
  8455. }
  8456. static int
  8457. skiploop(void)
  8458. {
  8459. int skip = evalskip;
  8460. switch (skip) {
  8461. case 0:
  8462. break;
  8463. case SKIPBREAK:
  8464. case SKIPCONT:
  8465. if (--skipcount <= 0) {
  8466. evalskip = 0;
  8467. break;
  8468. }
  8469. skip = SKIPBREAK;
  8470. break;
  8471. }
  8472. return skip;
  8473. }
  8474. static int
  8475. evalloop(union node *n, int flags)
  8476. {
  8477. int skip;
  8478. int status;
  8479. loopnest++;
  8480. status = 0;
  8481. flags &= EV_TESTED;
  8482. do {
  8483. int i;
  8484. i = evaltree(n->nbinary.ch1, EV_TESTED);
  8485. skip = skiploop();
  8486. if (skip == SKIPFUNC)
  8487. status = i;
  8488. if (skip)
  8489. continue;
  8490. if (n->type != NWHILE)
  8491. i = !i;
  8492. if (i != 0)
  8493. break;
  8494. status = evaltree(n->nbinary.ch2, flags);
  8495. skip = skiploop();
  8496. } while (!(skip & ~SKIPCONT));
  8497. loopnest--;
  8498. return status;
  8499. }
  8500. static int
  8501. evalfor(union node *n, int flags)
  8502. {
  8503. struct arglist arglist;
  8504. union node *argp;
  8505. struct strlist *sp;
  8506. int status = 0;
  8507. errlinno = lineno = n->ncase.linno;
  8508. if (funcline)
  8509. lineno -= funcline - 1;
  8510. arglist.list = NULL;
  8511. arglist.lastp = &arglist.list;
  8512. for (argp = n->nfor.args; argp; argp = argp->narg.next) {
  8513. expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
  8514. }
  8515. *arglist.lastp = NULL;
  8516. loopnest++;
  8517. flags &= EV_TESTED;
  8518. for (sp = arglist.list; sp; sp = sp->next) {
  8519. setvar0(n->nfor.var, sp->text);
  8520. status = evaltree(n->nfor.body, flags);
  8521. if (skiploop() & ~SKIPCONT)
  8522. break;
  8523. }
  8524. loopnest--;
  8525. return status;
  8526. }
  8527. static int
  8528. evalcase(union node *n, int flags)
  8529. {
  8530. union node *cp;
  8531. union node *patp;
  8532. struct arglist arglist;
  8533. int status = 0;
  8534. errlinno = lineno = n->ncase.linno;
  8535. if (funcline)
  8536. lineno -= funcline - 1;
  8537. arglist.list = NULL;
  8538. arglist.lastp = &arglist.list;
  8539. expandarg(n->ncase.expr, &arglist, EXP_TILDE);
  8540. for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
  8541. for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
  8542. if (casematch(patp, arglist.list->text)) {
  8543. /* Ensure body is non-empty as otherwise
  8544. * EV_EXIT may prevent us from setting the
  8545. * exit status.
  8546. */
  8547. if (evalskip == 0 && cp->nclist.body) {
  8548. status = evaltree(cp->nclist.body, flags);
  8549. }
  8550. goto out;
  8551. }
  8552. }
  8553. }
  8554. out:
  8555. return status;
  8556. }
  8557. /*
  8558. * Kick off a subshell to evaluate a tree.
  8559. */
  8560. static int
  8561. evalsubshell(union node *n, int flags)
  8562. {
  8563. struct job *jp;
  8564. int backgnd = (n->type == NBACKGND); /* FORK_BG(1) if yes, else FORK_FG(0) */
  8565. int status;
  8566. errlinno = lineno = n->nredir.linno;
  8567. if (funcline)
  8568. lineno -= funcline - 1;
  8569. expredir(n->nredir.redirect);
  8570. if (!backgnd && (flags & EV_EXIT) && !may_have_traps)
  8571. goto nofork;
  8572. INT_OFF;
  8573. if (backgnd == FORK_FG)
  8574. get_tty_state();
  8575. jp = makejob(/*n,*/ 1);
  8576. if (forkshell(jp, n, backgnd) == 0) {
  8577. /* child */
  8578. INT_ON;
  8579. flags |= EV_EXIT;
  8580. if (backgnd)
  8581. flags &= ~EV_TESTED;
  8582. nofork:
  8583. redirect(n->nredir.redirect, 0);
  8584. evaltreenr(n->nredir.n, flags);
  8585. /* never returns */
  8586. }
  8587. /* parent */
  8588. status = 0;
  8589. if (backgnd == FORK_FG)
  8590. status = waitforjob(jp);
  8591. INT_ON;
  8592. return status;
  8593. }
  8594. /*
  8595. * Compute the names of the files in a redirection list.
  8596. */
  8597. static void fixredir(union node *, const char *, int);
  8598. static void
  8599. expredir(union node *n)
  8600. {
  8601. union node *redir;
  8602. for (redir = n; redir; redir = redir->nfile.next) {
  8603. struct arglist fn;
  8604. fn.list = NULL;
  8605. fn.lastp = &fn.list;
  8606. switch (redir->type) {
  8607. case NFROMTO:
  8608. case NFROM:
  8609. case NTO:
  8610. #if BASH_REDIR_OUTPUT
  8611. case NTO2:
  8612. #endif
  8613. case NCLOBBER:
  8614. case NAPPEND:
  8615. expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
  8616. TRACE(("expredir expanded to '%s'\n", fn.list->text));
  8617. #if BASH_REDIR_OUTPUT
  8618. store_expfname:
  8619. #endif
  8620. #if 0
  8621. // By the design of stack allocator, the loop of this kind:
  8622. // while true; do while true; do break; done </dev/null; done
  8623. // will look like a memory leak: ash plans to free expfname's
  8624. // of "/dev/null" as soon as it finishes running the loop
  8625. // (in this case, never).
  8626. // This "fix" is wrong:
  8627. if (redir->nfile.expfname)
  8628. stunalloc(redir->nfile.expfname);
  8629. // It results in corrupted state of stacked allocations.
  8630. #endif
  8631. redir->nfile.expfname = fn.list->text;
  8632. break;
  8633. case NFROMFD:
  8634. case NTOFD: /* >& */
  8635. if (redir->ndup.vname) {
  8636. expandarg(redir->ndup.vname, &fn, EXP_TILDE | EXP_REDIR);
  8637. if (fn.list == NULL)
  8638. ash_msg_and_raise_error("redir error");
  8639. #if BASH_REDIR_OUTPUT
  8640. if (!isdigit_str9(fn.list->text)) {
  8641. /* >&file, not >&fd */
  8642. if (redir->nfile.fd != 1) /* 123>&file - BAD */
  8643. ash_msg_and_raise_error("redir error");
  8644. redir->type = NTO2;
  8645. goto store_expfname;
  8646. }
  8647. #endif
  8648. fixredir(redir, fn.list->text, 1);
  8649. }
  8650. break;
  8651. }
  8652. }
  8653. }
  8654. /*
  8655. * Evaluate a pipeline. All the processes in the pipeline are children
  8656. * of the process creating the pipeline. (This differs from some versions
  8657. * of the shell, which make the last process in a pipeline the parent
  8658. * of all the rest.)
  8659. */
  8660. static int
  8661. evalpipe(union node *n, int flags)
  8662. {
  8663. struct job *jp;
  8664. struct nodelist *lp;
  8665. int pipelen;
  8666. int prevfd;
  8667. int pip[2];
  8668. int status = 0;
  8669. TRACE(("evalpipe(0x%lx) called\n", (long)n));
  8670. pipelen = 0;
  8671. for (lp = n->npipe.cmdlist; lp; lp = lp->next)
  8672. pipelen++;
  8673. flags |= EV_EXIT;
  8674. INT_OFF;
  8675. if (n->npipe.pipe_backgnd == 0)
  8676. get_tty_state();
  8677. jp = makejob(/*n,*/ pipelen);
  8678. prevfd = -1;
  8679. for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
  8680. prehash(lp->n);
  8681. pip[1] = -1;
  8682. if (lp->next) {
  8683. if (pipe(pip) < 0) {
  8684. close(prevfd);
  8685. ash_msg_and_raise_perror("can't create pipe");
  8686. }
  8687. }
  8688. if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
  8689. /* child */
  8690. INT_ON;
  8691. if (pip[1] >= 0) {
  8692. close(pip[0]);
  8693. }
  8694. if (prevfd > 0) {
  8695. dup2(prevfd, 0);
  8696. close(prevfd);
  8697. }
  8698. if (pip[1] > 1) {
  8699. dup2(pip[1], 1);
  8700. close(pip[1]);
  8701. }
  8702. evaltreenr(lp->n, flags);
  8703. /* never returns */
  8704. }
  8705. /* parent */
  8706. if (prevfd >= 0)
  8707. close(prevfd);
  8708. prevfd = pip[0];
  8709. /* Don't want to trigger debugging */
  8710. if (pip[1] != -1)
  8711. close(pip[1]);
  8712. }
  8713. if (n->npipe.pipe_backgnd == 0) {
  8714. status = waitforjob(jp);
  8715. TRACE(("evalpipe: job done exit status %d\n", status));
  8716. }
  8717. INT_ON;
  8718. return status;
  8719. }
  8720. /* setinteractive needs this forward reference */
  8721. #if EDITING_HAS_get_exe_name
  8722. static const char *get_builtin_name(int i) FAST_FUNC;
  8723. #endif
  8724. /*
  8725. * Controls whether the shell is interactive or not.
  8726. */
  8727. static void
  8728. setinteractive(int on)
  8729. {
  8730. static smallint is_interactive;
  8731. if (++on == is_interactive)
  8732. return;
  8733. is_interactive = on;
  8734. setsignal(SIGINT);
  8735. setsignal(SIGQUIT);
  8736. setsignal(SIGTERM);
  8737. if (is_interactive > 1) {
  8738. #if !ENABLE_FEATURE_SH_EXTRA_QUIET
  8739. /* Looks like they want an interactive shell */
  8740. static smallint did_banner;
  8741. if (!did_banner) {
  8742. /* note: ash and hush share this string */
  8743. out1fmt("\n\n%s %s\n"
  8744. IF_ASH_HELP("Enter 'help' for a list of built-in commands.\n")
  8745. "\n",
  8746. bb_banner,
  8747. "built-in shell (ash)"
  8748. );
  8749. did_banner = 1;
  8750. }
  8751. #endif
  8752. #if ENABLE_FEATURE_EDITING
  8753. if (!line_input_state) {
  8754. line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
  8755. # if EDITING_HAS_get_exe_name
  8756. line_input_state->get_exe_name = get_builtin_name;
  8757. # endif
  8758. }
  8759. #endif
  8760. }
  8761. }
  8762. static void
  8763. optschanged(void)
  8764. {
  8765. #if DEBUG
  8766. opentrace();
  8767. #endif
  8768. setinteractive(iflag);
  8769. setjobctl(mflag);
  8770. #if ENABLE_FEATURE_EDITING_VI
  8771. if (line_input_state) {
  8772. if (viflag)
  8773. line_input_state->flags |= VI_MODE;
  8774. else
  8775. line_input_state->flags &= ~VI_MODE;
  8776. }
  8777. #else
  8778. viflag = 0; /* forcibly keep the option off */
  8779. #endif
  8780. }
  8781. struct localvar_list {
  8782. struct localvar_list *next;
  8783. struct localvar *lv;
  8784. };
  8785. static struct localvar_list *localvar_stack;
  8786. /*
  8787. * Called after a function returns.
  8788. * Interrupts must be off.
  8789. */
  8790. static void
  8791. poplocalvars(int keep)
  8792. {
  8793. struct localvar_list *ll;
  8794. struct localvar *lvp, *next;
  8795. struct var *vp;
  8796. INT_OFF;
  8797. ll = localvar_stack;
  8798. localvar_stack = ll->next;
  8799. next = ll->lv;
  8800. free(ll);
  8801. while ((lvp = next) != NULL) {
  8802. next = lvp->next;
  8803. vp = lvp->vp;
  8804. TRACE(("poplocalvar %s\n", vp ? vp->var_text : "-"));
  8805. if (keep) {
  8806. int bits = VSTRFIXED;
  8807. if (lvp->flags != VUNSET) {
  8808. if (vp->var_text == lvp->text)
  8809. bits |= VTEXTFIXED;
  8810. else if (!(lvp->flags & (VTEXTFIXED|VSTACK)))
  8811. free((char*)lvp->text);
  8812. }
  8813. vp->flags &= ~bits;
  8814. vp->flags |= (lvp->flags & bits);
  8815. if ((vp->flags &
  8816. (VEXPORT|VREADONLY|VSTRFIXED|VUNSET)) == VUNSET)
  8817. unsetvar(vp->var_text);
  8818. } else if (vp == NULL) { /* $- saved */
  8819. memcpy(optlist, lvp->text, sizeof(optlist));
  8820. free((char*)lvp->text);
  8821. optschanged();
  8822. } else if (lvp->flags == VUNSET) {
  8823. vp->flags &= ~(VSTRFIXED|VREADONLY);
  8824. unsetvar(vp->var_text);
  8825. } else {
  8826. if (vp->var_func)
  8827. vp->var_func(var_end(lvp->text));
  8828. if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
  8829. free((char*)vp->var_text);
  8830. vp->flags = lvp->flags;
  8831. vp->var_text = lvp->text;
  8832. }
  8833. free(lvp);
  8834. }
  8835. INT_ON;
  8836. }
  8837. /*
  8838. * Create a new localvar environment.
  8839. */
  8840. static struct localvar_list *
  8841. pushlocalvars(int push)
  8842. {
  8843. struct localvar_list *ll;
  8844. struct localvar_list *top;
  8845. top = localvar_stack;
  8846. if (!push)
  8847. goto out;
  8848. INT_OFF;
  8849. ll = ckzalloc(sizeof(*ll));
  8850. /*ll->lv = NULL; - zalloc did it */
  8851. ll->next = top;
  8852. localvar_stack = ll;
  8853. INT_ON;
  8854. out:
  8855. return top;
  8856. }
  8857. static void
  8858. unwindlocalvars(struct localvar_list *stop)
  8859. {
  8860. while (localvar_stack != stop)
  8861. poplocalvars(0);
  8862. }
  8863. static int
  8864. evalfun(struct funcnode *func, int argc, char **argv, int flags)
  8865. {
  8866. volatile struct shparam saveparam;
  8867. struct jmploc *volatile savehandler;
  8868. struct jmploc jmploc;
  8869. int e;
  8870. int savefuncline;
  8871. saveparam = shellparam;
  8872. savefuncline = funcline;
  8873. savehandler = exception_handler;
  8874. e = setjmp(jmploc.loc);
  8875. if (e) {
  8876. goto funcdone;
  8877. }
  8878. INT_OFF;
  8879. exception_handler = &jmploc;
  8880. shellparam.malloced = 0;
  8881. func->count++;
  8882. funcline = func->n.ndefun.linno;
  8883. INT_ON;
  8884. shellparam.nparam = argc - 1;
  8885. shellparam.p = argv + 1;
  8886. #if ENABLE_ASH_GETOPTS
  8887. shellparam.optind = 1;
  8888. shellparam.optoff = -1;
  8889. #endif
  8890. evaltree(func->n.ndefun.body, flags & EV_TESTED);
  8891. funcdone:
  8892. INT_OFF;
  8893. funcline = savefuncline;
  8894. freefunc(func);
  8895. freeparam(&shellparam);
  8896. shellparam = saveparam;
  8897. exception_handler = savehandler;
  8898. INT_ON;
  8899. evalskip &= ~(SKIPFUNC | SKIPFUNCDEF);
  8900. return e;
  8901. }
  8902. /*
  8903. * Make a variable a local variable. When a variable is made local, it's
  8904. * value and flags are saved in a localvar structure. The saved values
  8905. * will be restored when the shell function returns. We handle the name
  8906. * "-" as a special case: it makes changes to "set +-options" local
  8907. * (options will be restored on return from the function).
  8908. */
  8909. static void
  8910. mklocal(char *name, int flags)
  8911. {
  8912. struct localvar *lvp;
  8913. struct var **vpp;
  8914. struct var *vp;
  8915. char *eq = strchr(name, '=');
  8916. INT_OFF;
  8917. /* Cater for duplicate "local". Examples:
  8918. * x=0; f() { local x=1; echo $x; local x; echo $x; }; f; echo $x
  8919. * x=0; f() { local x=1; echo $x; local x=2; echo $x; }; f; echo $x
  8920. */
  8921. lvp = localvar_stack->lv;
  8922. while (lvp) {
  8923. if (lvp->vp && varcmp(lvp->vp->var_text, name) == 0) {
  8924. if (eq)
  8925. setvareq(name, 0);
  8926. /* else:
  8927. * it's a duplicate "local VAR" declaration, do nothing
  8928. */
  8929. goto ret;
  8930. }
  8931. lvp = lvp->next;
  8932. }
  8933. lvp = ckzalloc(sizeof(*lvp));
  8934. if (LONE_DASH(name)) {
  8935. char *p;
  8936. p = ckmalloc(sizeof(optlist));
  8937. lvp->text = memcpy(p, optlist, sizeof(optlist));
  8938. vp = NULL;
  8939. } else {
  8940. vpp = hashvar(name);
  8941. vp = *findvar(vpp, name);
  8942. if (vp == NULL) {
  8943. /* variable did not exist yet */
  8944. if (eq)
  8945. vp = setvareq(name, VSTRFIXED | flags);
  8946. else
  8947. vp = setvar(name, NULL, VSTRFIXED | flags);
  8948. lvp->flags = VUNSET;
  8949. } else {
  8950. lvp->text = vp->var_text;
  8951. lvp->flags = vp->flags;
  8952. /* make sure neither "struct var" nor string gets freed
  8953. * during (un)setting:
  8954. */
  8955. vp->flags |= VSTRFIXED|VTEXTFIXED;
  8956. if (eq)
  8957. setvareq(name, flags);
  8958. else
  8959. /* "local VAR" unsets VAR: */
  8960. setvar0(name, NULL);
  8961. }
  8962. }
  8963. lvp->vp = vp;
  8964. lvp->next = localvar_stack->lv;
  8965. localvar_stack->lv = lvp;
  8966. ret:
  8967. INT_ON;
  8968. }
  8969. /*
  8970. * The "local" command.
  8971. */
  8972. static int FAST_FUNC
  8973. localcmd(int argc UNUSED_PARAM, char **argv)
  8974. {
  8975. char *name;
  8976. if (!localvar_stack)
  8977. ash_msg_and_raise_error("not in a function");
  8978. argv = argptr;
  8979. while ((name = *argv++) != NULL) {
  8980. mklocal(name, 0);
  8981. }
  8982. return 0;
  8983. }
  8984. static int FAST_FUNC
  8985. falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  8986. {
  8987. return 1;
  8988. }
  8989. static int FAST_FUNC
  8990. truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  8991. {
  8992. return 0;
  8993. }
  8994. static int FAST_FUNC
  8995. execcmd(int argc UNUSED_PARAM, char **argv)
  8996. {
  8997. optionarg = NULL;
  8998. while (nextopt("a:") != '\0')
  8999. /* nextopt() sets optionarg to "-a ARGV0" */;
  9000. argv = argptr;
  9001. if (argv[0]) {
  9002. char *prog;
  9003. iflag = 0; /* exit on error */
  9004. mflag = 0;
  9005. optschanged();
  9006. /* We should set up signals for "exec CMD"
  9007. * the same way as for "CMD" without "exec".
  9008. * But optschanged->setinteractive->setsignal
  9009. * still thought we are a root shell. Therefore, for example,
  9010. * SIGQUIT is still set to IGN. Fix it:
  9011. */
  9012. shlvl++;
  9013. setsignal(SIGQUIT);
  9014. /*setsignal(SIGTERM); - unnecessary because of iflag=0 */
  9015. /*setsignal(SIGTSTP); - unnecessary because of mflag=0 */
  9016. /*setsignal(SIGTTOU); - unnecessary because of mflag=0 */
  9017. prog = argv[0];
  9018. if (optionarg)
  9019. argv[0] = optionarg;
  9020. shellexec(prog, argv, pathval(), 0);
  9021. /* NOTREACHED */
  9022. }
  9023. return 0;
  9024. }
  9025. /*
  9026. * The return command.
  9027. */
  9028. static int FAST_FUNC
  9029. returncmd(int argc UNUSED_PARAM, char **argv)
  9030. {
  9031. int skip;
  9032. int status;
  9033. /*
  9034. * If called outside a function, do what ksh does;
  9035. * skip the rest of the file.
  9036. */
  9037. if (argv[1]) {
  9038. skip = SKIPFUNC;
  9039. status = number(argv[1]);
  9040. } else {
  9041. skip = SKIPFUNCDEF;
  9042. status = exitstatus;
  9043. }
  9044. evalskip = skip;
  9045. return status;
  9046. }
  9047. /* Forward declarations for builtintab[] */
  9048. static int breakcmd(int, char **) FAST_FUNC;
  9049. static int dotcmd(int, char **) FAST_FUNC;
  9050. static int evalcmd(int, char **, int) FAST_FUNC;
  9051. static int exitcmd(int, char **) FAST_FUNC;
  9052. static int exportcmd(int, char **) FAST_FUNC;
  9053. #if ENABLE_ASH_GETOPTS
  9054. static int getoptscmd(int, char **) FAST_FUNC;
  9055. #endif
  9056. #if ENABLE_ASH_HELP
  9057. static int helpcmd(int, char **) FAST_FUNC;
  9058. #endif
  9059. #if MAX_HISTORY
  9060. static int historycmd(int, char **) FAST_FUNC;
  9061. #endif
  9062. #if ENABLE_FEATURE_SH_MATH
  9063. static int letcmd(int, char **) FAST_FUNC;
  9064. #endif
  9065. static int readcmd(int, char **) FAST_FUNC;
  9066. static int setcmd(int, char **) FAST_FUNC;
  9067. static int shiftcmd(int, char **) FAST_FUNC;
  9068. static int timescmd(int, char **) FAST_FUNC;
  9069. static int trapcmd(int, char **) FAST_FUNC;
  9070. static int umaskcmd(int, char **) FAST_FUNC;
  9071. static int unsetcmd(int, char **) FAST_FUNC;
  9072. static int ulimitcmd(int, char **) FAST_FUNC;
  9073. #define BUILTIN_NOSPEC "0"
  9074. #define BUILTIN_SPECIAL "1"
  9075. #define BUILTIN_REGULAR "2"
  9076. #define BUILTIN_SPEC_REG "3"
  9077. #define BUILTIN_ASSIGN "4"
  9078. #define BUILTIN_SPEC_ASSG "5"
  9079. #define BUILTIN_REG_ASSG "6"
  9080. #define BUILTIN_SPEC_REG_ASSG "7"
  9081. /* Stubs for calling non-FAST_FUNC's */
  9082. #if ENABLE_ASH_ECHO
  9083. static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
  9084. #endif
  9085. #if ENABLE_ASH_PRINTF
  9086. static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
  9087. #endif
  9088. #if ENABLE_ASH_TEST || BASH_TEST2
  9089. static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
  9090. #endif
  9091. /* Keep these in proper order since it is searched via bsearch() */
  9092. static const struct builtincmd builtintab[] = {
  9093. { BUILTIN_SPEC_REG "." , dotcmd },
  9094. { BUILTIN_SPEC_REG ":" , truecmd },
  9095. #if ENABLE_ASH_TEST
  9096. { BUILTIN_REGULAR "[" , testcmd },
  9097. #endif
  9098. #if BASH_TEST2
  9099. { BUILTIN_REGULAR "[[" , testcmd },
  9100. #endif
  9101. #if ENABLE_ASH_ALIAS
  9102. { BUILTIN_REG_ASSG "alias" , aliascmd },
  9103. #endif
  9104. #if JOBS
  9105. { BUILTIN_REGULAR "bg" , fg_bgcmd },
  9106. #endif
  9107. { BUILTIN_SPEC_REG "break" , breakcmd },
  9108. { BUILTIN_REGULAR "cd" , cdcmd },
  9109. { BUILTIN_NOSPEC "chdir" , cdcmd },
  9110. #if ENABLE_ASH_CMDCMD
  9111. { BUILTIN_REGULAR "command" , commandcmd },
  9112. #endif
  9113. { BUILTIN_SPEC_REG "continue", breakcmd },
  9114. #if ENABLE_ASH_ECHO
  9115. { BUILTIN_REGULAR "echo" , echocmd },
  9116. #endif
  9117. { BUILTIN_SPEC_REG "eval" , NULL }, /*evalcmd() has a differing prototype*/
  9118. { BUILTIN_SPEC_REG "exec" , execcmd },
  9119. { BUILTIN_SPEC_REG "exit" , exitcmd },
  9120. { BUILTIN_SPEC_REG_ASSG "export" , exportcmd },
  9121. { BUILTIN_REGULAR "false" , falsecmd },
  9122. #if JOBS
  9123. { BUILTIN_REGULAR "fg" , fg_bgcmd },
  9124. #endif
  9125. #if ENABLE_ASH_GETOPTS
  9126. { BUILTIN_REGULAR "getopts" , getoptscmd },
  9127. #endif
  9128. { BUILTIN_REGULAR "hash" , hashcmd },
  9129. #if ENABLE_ASH_HELP
  9130. { BUILTIN_NOSPEC "help" , helpcmd },
  9131. #endif
  9132. #if MAX_HISTORY
  9133. { BUILTIN_NOSPEC "history" , historycmd },
  9134. #endif
  9135. #if JOBS
  9136. { BUILTIN_REGULAR "jobs" , jobscmd },
  9137. { BUILTIN_REGULAR "kill" , killcmd },
  9138. #endif
  9139. #if ENABLE_FEATURE_SH_MATH
  9140. { BUILTIN_NOSPEC "let" , letcmd },
  9141. #endif
  9142. { BUILTIN_SPEC_REG_ASSG "local" , localcmd },
  9143. #if ENABLE_ASH_PRINTF
  9144. { BUILTIN_REGULAR "printf" , printfcmd },
  9145. #endif
  9146. { BUILTIN_REGULAR "pwd" , pwdcmd },
  9147. { BUILTIN_REGULAR "read" , readcmd },
  9148. { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
  9149. { BUILTIN_SPEC_REG "return" , returncmd },
  9150. { BUILTIN_SPEC_REG "set" , setcmd },
  9151. { BUILTIN_SPEC_REG "shift" , shiftcmd },
  9152. #if BASH_SOURCE
  9153. { BUILTIN_SPEC_REG "source" , dotcmd },
  9154. #endif
  9155. #if ENABLE_ASH_TEST
  9156. { BUILTIN_REGULAR "test" , testcmd },
  9157. #endif
  9158. { BUILTIN_SPEC_REG "times" , timescmd },
  9159. { BUILTIN_SPEC_REG "trap" , trapcmd },
  9160. { BUILTIN_REGULAR "true" , truecmd },
  9161. { BUILTIN_REGULAR "type" , typecmd },
  9162. { BUILTIN_REGULAR "ulimit" , ulimitcmd },
  9163. { BUILTIN_REGULAR "umask" , umaskcmd },
  9164. #if ENABLE_ASH_ALIAS
  9165. { BUILTIN_REGULAR "unalias" , unaliascmd },
  9166. #endif
  9167. { BUILTIN_SPEC_REG "unset" , unsetcmd },
  9168. { BUILTIN_REGULAR "wait" , waitcmd },
  9169. };
  9170. /* Should match the above table! */
  9171. #define COMMANDCMD (builtintab + \
  9172. /* . : */ 2 + \
  9173. /* [ */ 1 * ENABLE_ASH_TEST + \
  9174. /* [[ */ 1 * BASH_TEST2 + \
  9175. /* alias */ 1 * ENABLE_ASH_ALIAS + \
  9176. /* bg */ 1 * ENABLE_ASH_JOB_CONTROL + \
  9177. /* break cd cddir */ 3)
  9178. #define EVALCMD (COMMANDCMD + \
  9179. /* command */ 1 * ENABLE_ASH_CMDCMD + \
  9180. /* continue */ 1 + \
  9181. /* echo */ 1 * ENABLE_ASH_ECHO + \
  9182. 0)
  9183. #define EXECCMD (EVALCMD + \
  9184. /* eval */ 1)
  9185. /*
  9186. * Search the table of builtin commands.
  9187. */
  9188. static int
  9189. pstrcmp1(const void *a, const void *b)
  9190. {
  9191. return strcmp((char*)a, *(char**)b + 1);
  9192. }
  9193. static struct builtincmd *
  9194. find_builtin(const char *name)
  9195. {
  9196. struct builtincmd *bp;
  9197. bp = bsearch(
  9198. name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
  9199. pstrcmp1
  9200. );
  9201. return bp;
  9202. }
  9203. #if EDITING_HAS_get_exe_name
  9204. static const char * FAST_FUNC
  9205. get_builtin_name(int i)
  9206. {
  9207. return /*i >= 0 &&*/ i < ARRAY_SIZE(builtintab) ? builtintab[i].name + 1 : NULL;
  9208. }
  9209. #endif
  9210. /*
  9211. * Execute a simple command.
  9212. */
  9213. static void unwindfiles(struct parsefile *stop);
  9214. static int
  9215. isassignment(const char *p)
  9216. {
  9217. const char *q = endofname(p);
  9218. if (p == q)
  9219. return 0;
  9220. return *q == '=';
  9221. }
  9222. static int FAST_FUNC
  9223. bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  9224. {
  9225. /* Preserve exitstatus of a previous possible redirection
  9226. * as POSIX mandates */
  9227. return back_exitstatus;
  9228. }
  9229. static int
  9230. evalcommand(union node *cmd, int flags)
  9231. {
  9232. static const struct builtincmd null_bltin = {
  9233. BUILTIN_REGULAR "", bltincmd
  9234. };
  9235. struct localvar_list *localvar_stop;
  9236. struct parsefile *file_stop;
  9237. struct redirtab *redir_stop;
  9238. union node *argp;
  9239. struct arglist arglist;
  9240. struct arglist varlist;
  9241. char **argv;
  9242. int argc;
  9243. struct strlist *osp;
  9244. const struct strlist *sp;
  9245. struct cmdentry cmdentry;
  9246. struct job *jp;
  9247. char *lastarg;
  9248. const char *path;
  9249. int spclbltin;
  9250. int cmd_flag;
  9251. int status;
  9252. char **nargv;
  9253. smallint cmd_is_exec;
  9254. int vflags;
  9255. int vlocal;
  9256. errlinno = lineno = cmd->ncmd.linno;
  9257. if (funcline)
  9258. lineno -= funcline - 1;
  9259. /* First expand the arguments. */
  9260. TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
  9261. file_stop = g_parsefile;
  9262. back_exitstatus = 0;
  9263. cmdentry.cmdtype = CMDBUILTIN;
  9264. cmdentry.u.cmd = &null_bltin;
  9265. varlist.lastp = &varlist.list;
  9266. *varlist.lastp = NULL;
  9267. arglist.lastp = &arglist.list;
  9268. *arglist.lastp = NULL;
  9269. cmd_flag = 0;
  9270. cmd_is_exec = 0;
  9271. spclbltin = -1;
  9272. vflags = 0;
  9273. vlocal = 0;
  9274. path = NULL;
  9275. argc = 0;
  9276. argp = cmd->ncmd.args;
  9277. osp = fill_arglist(&arglist, &argp);
  9278. if (osp) {
  9279. int pseudovarflag = 0;
  9280. for (;;) {
  9281. find_command(arglist.list->text, &cmdentry,
  9282. cmd_flag | DO_REGBLTIN, pathval());
  9283. vlocal++;
  9284. /* implement bltin and command here */
  9285. if (cmdentry.cmdtype != CMDBUILTIN)
  9286. break;
  9287. pseudovarflag = IS_BUILTIN_ASSIGN(cmdentry.u.cmd);
  9288. if (spclbltin < 0) {
  9289. spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
  9290. vlocal = !spclbltin;
  9291. }
  9292. cmd_is_exec = cmdentry.u.cmd == EXECCMD;
  9293. #if ENABLE_ASH_CMDCMD
  9294. if (cmdentry.u.cmd != COMMANDCMD)
  9295. break;
  9296. cmd_flag = parse_command_args(&arglist, &argp, &path);
  9297. if (!cmd_flag)
  9298. #endif
  9299. break;
  9300. }
  9301. for (; argp; argp = argp->narg.next)
  9302. expandarg(argp, &arglist,
  9303. pseudovarflag &&
  9304. isassignment(argp->narg.text) ?
  9305. EXP_VARTILDE : EXP_FULL | EXP_TILDE);
  9306. for (sp = arglist.list; sp; sp = sp->next)
  9307. argc++;
  9308. if (cmd_is_exec && argc > 1)
  9309. vflags = VEXPORT;
  9310. }
  9311. localvar_stop = pushlocalvars(vlocal);
  9312. /* Reserve one extra spot at the front for shellexec. */
  9313. nargv = stalloc(sizeof(char *) * (argc + 2));
  9314. argv = ++nargv;
  9315. for (sp = arglist.list; sp; sp = sp->next) {
  9316. TRACE(("evalcommand arg: %s\n", sp->text));
  9317. *nargv++ = sp->text;
  9318. }
  9319. *nargv = NULL;
  9320. lastarg = NULL;
  9321. if (iflag && funcline == 0 && argc > 0)
  9322. lastarg = nargv[-1];
  9323. expredir(cmd->ncmd.redirect);
  9324. redir_stop = pushredir(cmd->ncmd.redirect);
  9325. preverrout_fd = 2;
  9326. if (BASH_XTRACEFD && xflag) {
  9327. /* NB: bash closes fd == $BASH_XTRACEFD when it is changed.
  9328. * we do not emulate this. We only use its value.
  9329. */
  9330. const char *xtracefd = lookupvar("BASH_XTRACEFD");
  9331. if (xtracefd && is_number(xtracefd))
  9332. preverrout_fd = atoi(xtracefd);
  9333. }
  9334. status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
  9335. if (status) {
  9336. bail:
  9337. exitstatus = status;
  9338. /* We have a redirection error. */
  9339. if (spclbltin > 0)
  9340. raise_exception(EXERROR);
  9341. goto out;
  9342. }
  9343. for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
  9344. struct strlist **spp;
  9345. spp = varlist.lastp;
  9346. expandarg(argp, &varlist, EXP_VARTILDE);
  9347. if (vlocal)
  9348. mklocal((*spp)->text, VEXPORT);
  9349. else
  9350. setvareq((*spp)->text, vflags);
  9351. }
  9352. /* Print the command if xflag is set. */
  9353. if (xflag) {
  9354. const char *pfx = "";
  9355. fdprintf(preverrout_fd, "%s", expandstr(ps4val(), DQSYNTAX));
  9356. sp = varlist.list;
  9357. while (sp) {
  9358. char *varval = sp->text;
  9359. char *eq = strchrnul(varval, '=');
  9360. if (*eq)
  9361. eq++;
  9362. fdprintf(preverrout_fd, "%s%.*s%s",
  9363. pfx,
  9364. (int)(eq - varval), varval,
  9365. maybe_single_quote(eq)
  9366. );
  9367. sp = sp->next;
  9368. pfx = " ";
  9369. }
  9370. sp = arglist.list;
  9371. while (sp) {
  9372. fdprintf(preverrout_fd, "%s%s",
  9373. pfx,
  9374. /* always quote if matches reserved word: */
  9375. findkwd(sp->text)
  9376. ? single_quote(sp->text)
  9377. : maybe_single_quote(sp->text)
  9378. );
  9379. sp = sp->next;
  9380. pfx = " ";
  9381. }
  9382. safe_write(preverrout_fd, "\n", 1);
  9383. }
  9384. /* Now locate the command. */
  9385. if (cmdentry.cmdtype != CMDBUILTIN
  9386. || !(IS_BUILTIN_REGULAR(cmdentry.u.cmd))
  9387. ) {
  9388. path = path ? path : pathval();
  9389. find_command(argv[0], &cmdentry, cmd_flag | DO_ERR, path);
  9390. }
  9391. jp = NULL;
  9392. /* Execute the command. */
  9393. switch (cmdentry.cmdtype) {
  9394. case CMDUNKNOWN:
  9395. status = 127;
  9396. flush_stdout_stderr();
  9397. goto bail;
  9398. default: {
  9399. #if ENABLE_FEATURE_SH_STANDALONE \
  9400. && ENABLE_FEATURE_SH_NOFORK \
  9401. && NUM_APPLETS > 1
  9402. /* (1) BUG: if variables are set, we need to fork, or save/restore them
  9403. * around run_nofork_applet() call.
  9404. * (2) Should this check also be done in forkshell()?
  9405. * (perhaps it should, so that "VAR=VAL nofork" at least avoids exec...)
  9406. */
  9407. /* find_command() encodes applet_no as (-2 - applet_no) */
  9408. int applet_no = (- cmdentry.u.index - 2);
  9409. if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
  9410. char **sv_environ;
  9411. INT_OFF;
  9412. sv_environ = environ;
  9413. environ = listvars(VEXPORT, VUNSET, varlist.list, /*end:*/ NULL);
  9414. /*
  9415. * Run <applet>_main().
  9416. * Signals (^C) can't interrupt here.
  9417. * Otherwise we can mangle stdio or malloc internal state.
  9418. * This makes applets which can run for a long time
  9419. * and/or wait for user input ineligible for NOFORK:
  9420. * for example, "yes" or "rm" (rm -i waits for input).
  9421. */
  9422. exitstatus = run_nofork_applet(applet_no, argv);
  9423. environ = sv_environ;
  9424. /*
  9425. * Try enabling NOFORK for "yes" applet.
  9426. * ^C _will_ stop it (write returns EINTR),
  9427. * but this causes stdout FILE to be stuck
  9428. * and needing clearerr(). What if other applets
  9429. * also can get EINTRs? Do we need to switch
  9430. * our signals to SA_RESTART?
  9431. */
  9432. /*clearerr(stdout);*/
  9433. INT_ON;
  9434. break;
  9435. }
  9436. #endif
  9437. /* Can we avoid forking? For example, very last command
  9438. * in a script or a subshell does not need forking,
  9439. * we can just exec it.
  9440. */
  9441. if (!(flags & EV_EXIT) || may_have_traps) {
  9442. /* No, forking off a child is necessary */
  9443. INT_OFF;
  9444. get_tty_state();
  9445. jp = makejob(/*cmd,*/ 1);
  9446. if (forkshell(jp, cmd, FORK_FG) != 0) {
  9447. /* parent */
  9448. break;
  9449. }
  9450. /* child */
  9451. FORCE_INT_ON;
  9452. /* fall through to exec'ing external program */
  9453. }
  9454. shellexec(argv[0], argv, path, cmdentry.u.index);
  9455. /* NOTREACHED */
  9456. } /* default */
  9457. case CMDBUILTIN:
  9458. if (evalbltin(cmdentry.u.cmd, argc, argv, flags)
  9459. && !(exception_type == EXERROR && spclbltin <= 0)
  9460. ) {
  9461. raise:
  9462. longjmp(exception_handler->loc, 1);
  9463. }
  9464. break;
  9465. case CMDFUNCTION:
  9466. if (evalfun(cmdentry.u.func, argc, argv, flags))
  9467. goto raise;
  9468. break;
  9469. } /* switch */
  9470. status = waitforjob(jp);
  9471. if (jp)
  9472. TRACE(("forked child exited with %d\n", status));
  9473. FORCE_INT_ON;
  9474. out:
  9475. if (cmd->ncmd.redirect)
  9476. popredir(/*drop:*/ cmd_is_exec);
  9477. unwindredir(redir_stop);
  9478. unwindfiles(file_stop);
  9479. unwindlocalvars(localvar_stop);
  9480. if (lastarg) {
  9481. /* dsl: I think this is intended to be used to support
  9482. * '_' in 'vi' command mode during line editing...
  9483. * However I implemented that within libedit itself.
  9484. */
  9485. setvar0("_", lastarg);
  9486. }
  9487. return status;
  9488. }
  9489. static int
  9490. evalbltin(const struct builtincmd *cmd, int argc, char **argv, int flags)
  9491. {
  9492. char *volatile savecmdname;
  9493. struct jmploc *volatile savehandler;
  9494. struct jmploc jmploc;
  9495. int status;
  9496. int i;
  9497. savecmdname = commandname;
  9498. savehandler = exception_handler;
  9499. i = setjmp(jmploc.loc);
  9500. if (i)
  9501. goto cmddone;
  9502. exception_handler = &jmploc;
  9503. commandname = argv[0];
  9504. argptr = argv + 1;
  9505. optptr = NULL; /* initialize nextopt */
  9506. if (cmd == EVALCMD)
  9507. status = evalcmd(argc, argv, flags);
  9508. else
  9509. status = (*cmd->builtin)(argc, argv);
  9510. flush_stdout_stderr();
  9511. status |= ferror(stdout);
  9512. exitstatus = status;
  9513. cmddone:
  9514. clearerr(stdout);
  9515. commandname = savecmdname;
  9516. exception_handler = savehandler;
  9517. return i;
  9518. }
  9519. static int
  9520. goodname(const char *p)
  9521. {
  9522. return endofname(p)[0] == '\0';
  9523. }
  9524. /*
  9525. * Search for a command. This is called before we fork so that the
  9526. * location of the command will be available in the parent as well as
  9527. * the child. The check for "goodname" is an overly conservative
  9528. * check that the name will not be subject to expansion.
  9529. */
  9530. static void
  9531. prehash(union node *n)
  9532. {
  9533. struct cmdentry entry;
  9534. if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
  9535. find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
  9536. }
  9537. /* ============ Builtin commands
  9538. *
  9539. * Builtin commands whose functions are closely tied to evaluation
  9540. * are implemented here.
  9541. */
  9542. /*
  9543. * Handle break and continue commands. Break, continue, and return are
  9544. * all handled by setting the evalskip flag. The evaluation routines
  9545. * above all check this flag, and if it is set they start skipping
  9546. * commands rather than executing them. The variable skipcount is
  9547. * the number of loops to break/continue, or the number of function
  9548. * levels to return. (The latter is always 1.) It should probably
  9549. * be an error to break out of more loops than exist, but it isn't
  9550. * in the standard shell so we don't make it one here.
  9551. */
  9552. static int FAST_FUNC
  9553. breakcmd(int argc UNUSED_PARAM, char **argv)
  9554. {
  9555. int n = argv[1] ? number(argv[1]) : 1;
  9556. if (n <= 0)
  9557. ash_msg_and_raise_error(msg_illnum, argv[1]);
  9558. if (n > loopnest)
  9559. n = loopnest;
  9560. if (n > 0) {
  9561. evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
  9562. skipcount = n;
  9563. }
  9564. return 0;
  9565. }
  9566. /*
  9567. * This implements the input routines used by the parser.
  9568. */
  9569. enum {
  9570. INPUT_PUSH_FILE = 1,
  9571. INPUT_NOFILE_OK = 2,
  9572. };
  9573. static smallint checkkwd;
  9574. /* values of checkkwd variable */
  9575. #define CHKALIAS 0x1
  9576. #define CHKKWD 0x2
  9577. #define CHKNL 0x4
  9578. #define CHKEOFMARK 0x8
  9579. /*
  9580. * Push a string back onto the input at this current parsefile level.
  9581. * We handle aliases this way.
  9582. */
  9583. #if !ENABLE_ASH_ALIAS
  9584. #define pushstring(s, ap) pushstring(s)
  9585. #endif
  9586. static void
  9587. pushstring(char *s, struct alias *ap)
  9588. {
  9589. struct strpush *sp;
  9590. int len;
  9591. len = strlen(s);
  9592. INT_OFF;
  9593. if (g_parsefile->strpush) {
  9594. sp = ckzalloc(sizeof(*sp));
  9595. sp->prev = g_parsefile->strpush;
  9596. } else {
  9597. sp = &(g_parsefile->basestrpush);
  9598. }
  9599. g_parsefile->strpush = sp;
  9600. sp->prev_string = g_parsefile->next_to_pgetc;
  9601. sp->prev_left_in_line = g_parsefile->left_in_line;
  9602. sp->unget = g_parsefile->unget;
  9603. memcpy(sp->lastc, g_parsefile->lastc, sizeof(sp->lastc));
  9604. #if ENABLE_ASH_ALIAS
  9605. sp->ap = ap;
  9606. if (ap) {
  9607. ap->flag |= ALIASINUSE;
  9608. sp->string = s;
  9609. }
  9610. #endif
  9611. g_parsefile->next_to_pgetc = s;
  9612. g_parsefile->left_in_line = len;
  9613. g_parsefile->unget = 0;
  9614. INT_ON;
  9615. }
  9616. static void
  9617. popstring(void)
  9618. {
  9619. struct strpush *sp = g_parsefile->strpush;
  9620. INT_OFF;
  9621. #if ENABLE_ASH_ALIAS
  9622. if (sp->ap) {
  9623. if (g_parsefile->next_to_pgetc[-1] == ' '
  9624. || g_parsefile->next_to_pgetc[-1] == '\t'
  9625. ) {
  9626. checkkwd |= CHKALIAS;
  9627. }
  9628. if (sp->string != sp->ap->val) {
  9629. free(sp->string);
  9630. }
  9631. sp->ap->flag &= ~ALIASINUSE;
  9632. if (sp->ap->flag & ALIASDEAD) {
  9633. unalias(sp->ap->name);
  9634. }
  9635. }
  9636. #endif
  9637. g_parsefile->next_to_pgetc = sp->prev_string;
  9638. g_parsefile->left_in_line = sp->prev_left_in_line;
  9639. g_parsefile->unget = sp->unget;
  9640. memcpy(g_parsefile->lastc, sp->lastc, sizeof(sp->lastc));
  9641. g_parsefile->strpush = sp->prev;
  9642. if (sp != &(g_parsefile->basestrpush))
  9643. free(sp);
  9644. INT_ON;
  9645. }
  9646. static int
  9647. preadfd(void)
  9648. {
  9649. int nr;
  9650. char *buf = g_parsefile->buf;
  9651. g_parsefile->next_to_pgetc = buf;
  9652. #if ENABLE_FEATURE_EDITING
  9653. retry:
  9654. if (!iflag || g_parsefile->pf_fd != STDIN_FILENO)
  9655. nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
  9656. else {
  9657. # if ENABLE_ASH_IDLE_TIMEOUT
  9658. int timeout = -1;
  9659. const char *tmout_var = lookupvar("TMOUT");
  9660. if (tmout_var) {
  9661. timeout = atoi(tmout_var) * 1000;
  9662. if (timeout <= 0)
  9663. timeout = -1;
  9664. }
  9665. line_input_state->timeout = timeout;
  9666. # endif
  9667. # if ENABLE_FEATURE_TAB_COMPLETION
  9668. line_input_state->path_lookup = pathval();
  9669. # endif
  9670. reinit_unicode_for_ash();
  9671. nr = read_line_input(line_input_state, cmdedit_prompt, buf, IBUFSIZ);
  9672. if (nr == 0) {
  9673. /* ^C pressed, "convert" to SIGINT */
  9674. write(STDOUT_FILENO, "^C", 2);
  9675. if (trap[SIGINT]) {
  9676. buf[0] = '\n';
  9677. buf[1] = '\0';
  9678. raise(SIGINT);
  9679. return 1;
  9680. }
  9681. exitstatus = 128 + SIGINT;
  9682. bb_putchar('\n');
  9683. goto retry;
  9684. }
  9685. if (nr < 0) {
  9686. if (errno == 0) {
  9687. /* Ctrl+D pressed */
  9688. nr = 0;
  9689. }
  9690. # if ENABLE_ASH_IDLE_TIMEOUT
  9691. else if (errno == EAGAIN && timeout > 0) {
  9692. puts("\007timed out waiting for input: auto-logout");
  9693. exitshell();
  9694. }
  9695. # endif
  9696. }
  9697. }
  9698. #else
  9699. nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
  9700. #endif
  9701. #if 0 /* disabled: nonblock_immune_read() handles this problem */
  9702. if (nr < 0) {
  9703. if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
  9704. int flags = fcntl(0, F_GETFL);
  9705. if (flags >= 0 && (flags & O_NONBLOCK)) {
  9706. flags &= ~O_NONBLOCK;
  9707. if (fcntl(0, F_SETFL, flags) >= 0) {
  9708. out2str("sh: turning off NDELAY mode\n");
  9709. goto retry;
  9710. }
  9711. }
  9712. }
  9713. }
  9714. #endif
  9715. return nr;
  9716. }
  9717. /*
  9718. * Refill the input buffer and return the next input character:
  9719. *
  9720. * 1) If a string was pushed back on the input, pop it;
  9721. * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
  9722. * or we are reading from a string so we can't refill the buffer,
  9723. * return EOF.
  9724. * 3) If there is more stuff in this buffer, use it else call read to fill it.
  9725. * 4) Process input up to the next newline, deleting nul characters.
  9726. */
  9727. //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
  9728. #define pgetc_debug(...) ((void)0)
  9729. static int pgetc(void);
  9730. static int
  9731. preadbuffer(void)
  9732. {
  9733. char *q;
  9734. int more;
  9735. if (g_parsefile->strpush) {
  9736. #if ENABLE_ASH_ALIAS
  9737. if (g_parsefile->left_in_line == -1
  9738. && g_parsefile->strpush->ap
  9739. && g_parsefile->next_to_pgetc[-1] != ' '
  9740. && g_parsefile->next_to_pgetc[-1] != '\t'
  9741. ) {
  9742. pgetc_debug("preadbuffer PEOA");
  9743. return PEOA;
  9744. }
  9745. #endif
  9746. popstring();
  9747. return pgetc();
  9748. }
  9749. /* on both branches above g_parsefile->left_in_line < 0.
  9750. * "pgetc" needs refilling.
  9751. */
  9752. /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
  9753. * pungetc() may increment it a few times.
  9754. * Assuming it won't increment it to less than -90.
  9755. */
  9756. if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
  9757. pgetc_debug("preadbuffer PEOF1");
  9758. /* even in failure keep left_in_line and next_to_pgetc
  9759. * in lock step, for correct multi-layer pungetc.
  9760. * left_in_line was decremented before preadbuffer(),
  9761. * must inc next_to_pgetc: */
  9762. g_parsefile->next_to_pgetc++;
  9763. return PEOF;
  9764. }
  9765. more = g_parsefile->left_in_buffer;
  9766. if (more <= 0) {
  9767. flush_stdout_stderr();
  9768. again:
  9769. more = preadfd();
  9770. if (more <= 0) {
  9771. /* don't try reading again */
  9772. g_parsefile->left_in_line = -99;
  9773. pgetc_debug("preadbuffer PEOF2");
  9774. g_parsefile->next_to_pgetc++;
  9775. return PEOF;
  9776. }
  9777. }
  9778. /* Find out where's the end of line.
  9779. * Set g_parsefile->left_in_line
  9780. * and g_parsefile->left_in_buffer acordingly.
  9781. * NUL chars are deleted.
  9782. */
  9783. q = g_parsefile->next_to_pgetc;
  9784. for (;;) {
  9785. char c;
  9786. more--;
  9787. c = *q;
  9788. if (c == '\0') {
  9789. memmove(q, q + 1, more);
  9790. } else {
  9791. q++;
  9792. if (c == '\n') {
  9793. g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
  9794. break;
  9795. }
  9796. }
  9797. if (more <= 0) {
  9798. g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
  9799. if (g_parsefile->left_in_line < 0)
  9800. goto again;
  9801. break;
  9802. }
  9803. }
  9804. g_parsefile->left_in_buffer = more;
  9805. if (vflag) {
  9806. char save = *q;
  9807. *q = '\0';
  9808. out2str(g_parsefile->next_to_pgetc);
  9809. *q = save;
  9810. }
  9811. pgetc_debug("preadbuffer at %d:%p'%s'",
  9812. g_parsefile->left_in_line,
  9813. g_parsefile->next_to_pgetc,
  9814. g_parsefile->next_to_pgetc);
  9815. return (unsigned char)*g_parsefile->next_to_pgetc++;
  9816. }
  9817. static void
  9818. nlprompt(void)
  9819. {
  9820. g_parsefile->linno++;
  9821. setprompt_if(doprompt, 2);
  9822. }
  9823. static void
  9824. nlnoprompt(void)
  9825. {
  9826. g_parsefile->linno++;
  9827. needprompt = doprompt;
  9828. }
  9829. static int
  9830. pgetc(void)
  9831. {
  9832. int c;
  9833. pgetc_debug("pgetc at %d:%p'%s'",
  9834. g_parsefile->left_in_line,
  9835. g_parsefile->next_to_pgetc,
  9836. g_parsefile->next_to_pgetc);
  9837. if (g_parsefile->unget)
  9838. return g_parsefile->lastc[--g_parsefile->unget];
  9839. if (--g_parsefile->left_in_line >= 0)
  9840. c = (unsigned char)*g_parsefile->next_to_pgetc++;
  9841. else
  9842. c = preadbuffer();
  9843. g_parsefile->lastc[1] = g_parsefile->lastc[0];
  9844. g_parsefile->lastc[0] = c;
  9845. return c;
  9846. }
  9847. #if ENABLE_ASH_ALIAS
  9848. static int
  9849. pgetc_without_PEOA(void)
  9850. {
  9851. int c;
  9852. do {
  9853. pgetc_debug("pgetc at %d:%p'%s'",
  9854. g_parsefile->left_in_line,
  9855. g_parsefile->next_to_pgetc,
  9856. g_parsefile->next_to_pgetc);
  9857. c = pgetc();
  9858. } while (c == PEOA);
  9859. return c;
  9860. }
  9861. #else
  9862. # define pgetc_without_PEOA() pgetc()
  9863. #endif
  9864. /*
  9865. * Undo a call to pgetc. Only two characters may be pushed back.
  9866. * PEOF may be pushed back.
  9867. */
  9868. static void
  9869. pungetc(void)
  9870. {
  9871. g_parsefile->unget++;
  9872. }
  9873. /* This one eats backslash+newline */
  9874. static int
  9875. pgetc_eatbnl(void)
  9876. {
  9877. int c;
  9878. while ((c = pgetc()) == '\\') {
  9879. if (pgetc() != '\n') {
  9880. pungetc();
  9881. break;
  9882. }
  9883. nlprompt();
  9884. }
  9885. return c;
  9886. }
  9887. struct synstack {
  9888. smalluint syntax;
  9889. uint8_t innerdq :1;
  9890. uint8_t varpushed :1;
  9891. uint8_t dblquote :1;
  9892. int varnest; /* levels of variables expansion */
  9893. int dqvarnest; /* levels of variables expansion within double quotes */
  9894. int parenlevel; /* levels of parens in arithmetic */
  9895. struct synstack *prev;
  9896. struct synstack *next;
  9897. };
  9898. static int
  9899. pgetc_top(struct synstack *stack)
  9900. {
  9901. return stack->syntax == SQSYNTAX ? pgetc() : pgetc_eatbnl();
  9902. }
  9903. static void
  9904. synstack_push(struct synstack **stack, struct synstack *next, int syntax)
  9905. {
  9906. memset(next, 0, sizeof(*next));
  9907. next->syntax = syntax;
  9908. next->next = *stack;
  9909. (*stack)->prev = next;
  9910. *stack = next;
  9911. }
  9912. static ALWAYS_INLINE void
  9913. synstack_pop(struct synstack **stack)
  9914. {
  9915. *stack = (*stack)->next;
  9916. }
  9917. /*
  9918. * To handle the "." command, a stack of input files is used. Pushfile
  9919. * adds a new entry to the stack and popfile restores the previous level.
  9920. */
  9921. static void
  9922. pushfile(void)
  9923. {
  9924. struct parsefile *pf;
  9925. pf = ckzalloc(sizeof(*pf));
  9926. pf->prev = g_parsefile;
  9927. pf->pf_fd = -1;
  9928. /*pf->strpush = NULL; - ckzalloc did it */
  9929. /*pf->basestrpush.prev = NULL;*/
  9930. /*pf->unget = 0;*/
  9931. g_parsefile = pf;
  9932. }
  9933. static void
  9934. popfile(void)
  9935. {
  9936. struct parsefile *pf = g_parsefile;
  9937. if (pf == &basepf)
  9938. return;
  9939. INT_OFF;
  9940. if (pf->pf_fd >= 0)
  9941. close(pf->pf_fd);
  9942. free(pf->buf);
  9943. while (pf->strpush)
  9944. popstring();
  9945. g_parsefile = pf->prev;
  9946. free(pf);
  9947. INT_ON;
  9948. }
  9949. static void
  9950. unwindfiles(struct parsefile *stop)
  9951. {
  9952. while (g_parsefile != stop)
  9953. popfile();
  9954. }
  9955. /*
  9956. * Return to top level.
  9957. */
  9958. static void
  9959. popallfiles(void)
  9960. {
  9961. unwindfiles(&basepf);
  9962. }
  9963. /*
  9964. * Close the file(s) that the shell is reading commands from. Called
  9965. * after a fork is done.
  9966. */
  9967. static void
  9968. closescript(void)
  9969. {
  9970. popallfiles();
  9971. if (g_parsefile->pf_fd > 0) {
  9972. close(g_parsefile->pf_fd);
  9973. g_parsefile->pf_fd = 0;
  9974. }
  9975. }
  9976. /*
  9977. * Like setinputfile, but takes an open file descriptor. Call this with
  9978. * interrupts off.
  9979. */
  9980. static void
  9981. setinputfd(int fd, int push)
  9982. {
  9983. if (push) {
  9984. pushfile();
  9985. g_parsefile->buf = NULL;
  9986. }
  9987. g_parsefile->pf_fd = fd;
  9988. if (g_parsefile->buf == NULL)
  9989. g_parsefile->buf = ckmalloc(IBUFSIZ);
  9990. g_parsefile->left_in_buffer = 0;
  9991. g_parsefile->left_in_line = 0;
  9992. g_parsefile->linno = 1;
  9993. }
  9994. /*
  9995. * Set the input to take input from a file. If push is set, push the
  9996. * old input onto the stack first.
  9997. */
  9998. static int
  9999. setinputfile(const char *fname, int flags)
  10000. {
  10001. int fd;
  10002. INT_OFF;
  10003. fd = open(fname, O_RDONLY | O_CLOEXEC);
  10004. if (fd < 0) {
  10005. if (flags & INPUT_NOFILE_OK)
  10006. goto out;
  10007. exitstatus = 127;
  10008. ash_msg_and_raise_perror("can't open '%s'", fname);
  10009. }
  10010. if (fd < 10)
  10011. fd = savefd(fd);
  10012. else if (O_CLOEXEC == 0) /* old libc */
  10013. close_on_exec_on(fd);
  10014. setinputfd(fd, flags & INPUT_PUSH_FILE);
  10015. out:
  10016. INT_ON;
  10017. return fd;
  10018. }
  10019. /*
  10020. * Like setinputfile, but takes input from a string.
  10021. */
  10022. static void
  10023. setinputstring(char *string)
  10024. {
  10025. INT_OFF;
  10026. pushfile();
  10027. g_parsefile->next_to_pgetc = string;
  10028. g_parsefile->left_in_line = strlen(string);
  10029. g_parsefile->buf = NULL;
  10030. g_parsefile->linno = 1;
  10031. INT_ON;
  10032. }
  10033. /*
  10034. * Routines to check for mail.
  10035. */
  10036. #if ENABLE_ASH_MAIL
  10037. /* Hash of mtimes of mailboxes */
  10038. static unsigned mailtime_hash;
  10039. /* Set if MAIL or MAILPATH is changed. */
  10040. static smallint mail_var_path_changed;
  10041. /*
  10042. * Print appropriate message(s) if mail has arrived.
  10043. * If mail_var_path_changed is set,
  10044. * then the value of MAIL has mail_var_path_changed,
  10045. * so we just update the values.
  10046. */
  10047. static void
  10048. chkmail(void)
  10049. {
  10050. const char *mpath;
  10051. char *p;
  10052. char *q;
  10053. unsigned new_hash;
  10054. struct stackmark smark;
  10055. struct stat statb;
  10056. setstackmark(&smark);
  10057. mpath = mpathset() ? mpathval() : mailval();
  10058. new_hash = 0;
  10059. for (;;) {
  10060. int len;
  10061. len = padvance_magic(&mpath, nullstr, 2);
  10062. if (!len)
  10063. break;
  10064. p = stackblock();
  10065. break;
  10066. if (*p == '\0')
  10067. continue;
  10068. for (q = p; *q; q++)
  10069. continue;
  10070. #if DEBUG
  10071. if (q[-1] != '/')
  10072. abort();
  10073. #endif
  10074. q[-1] = '\0'; /* delete trailing '/' */
  10075. if (stat(p, &statb) < 0) {
  10076. continue;
  10077. }
  10078. /* Very simplistic "hash": just a sum of all mtimes */
  10079. new_hash += (unsigned)statb.st_mtime;
  10080. }
  10081. if (!mail_var_path_changed && mailtime_hash != new_hash) {
  10082. if (mailtime_hash != 0)
  10083. out2str("you have mail\n");
  10084. mailtime_hash = new_hash;
  10085. }
  10086. mail_var_path_changed = 0;
  10087. popstackmark(&smark);
  10088. }
  10089. static void FAST_FUNC
  10090. changemail(const char *val UNUSED_PARAM)
  10091. {
  10092. mail_var_path_changed = 1;
  10093. }
  10094. #endif /* ASH_MAIL */
  10095. /* ============ ??? */
  10096. /*
  10097. * Set the shell parameters.
  10098. */
  10099. static void
  10100. setparam(char **argv)
  10101. {
  10102. char **newparam;
  10103. char **ap;
  10104. int nparam;
  10105. for (nparam = 0; argv[nparam]; nparam++)
  10106. continue;
  10107. ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
  10108. while (*argv) {
  10109. *ap++ = ckstrdup(*argv++);
  10110. }
  10111. *ap = NULL;
  10112. freeparam(&shellparam);
  10113. shellparam.malloced = 1;
  10114. shellparam.nparam = nparam;
  10115. shellparam.p = newparam;
  10116. #if ENABLE_ASH_GETOPTS
  10117. shellparam.optind = 1;
  10118. shellparam.optoff = -1;
  10119. #endif
  10120. }
  10121. /*
  10122. * Process shell options. The global variable argptr contains a pointer
  10123. * to the argument list; we advance it past the options.
  10124. *
  10125. * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
  10126. * For a non-interactive shell, an error condition encountered
  10127. * by a special built-in ... shall cause the shell to write a diagnostic message
  10128. * to standard error and exit as shown in the following table:
  10129. * Error Special Built-In
  10130. * ...
  10131. * Utility syntax error (option or operand error) Shall exit
  10132. * ...
  10133. * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
  10134. * we see that bash does not do that (set "finishes" with error code 1 instead,
  10135. * and shell continues), and people rely on this behavior!
  10136. * Testcase:
  10137. * set -o barfoo 2>/dev/null
  10138. * echo $?
  10139. *
  10140. * Oh well. Let's mimic that.
  10141. */
  10142. static int
  10143. plus_minus_o(char *name, int val)
  10144. {
  10145. int i;
  10146. if (name) {
  10147. for (i = 0; i < NOPTS; i++) {
  10148. if (strcmp(name, optnames(i)) == 0) {
  10149. optlist[i] = val;
  10150. return 0;
  10151. }
  10152. }
  10153. ash_msg("illegal option %co %s", val ? '-' : '+', name);
  10154. return 1;
  10155. }
  10156. for (i = 0; i < NOPTS; i++) {
  10157. if (optnames(i)[0] == '\0')
  10158. continue;
  10159. if (val) {
  10160. out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
  10161. } else {
  10162. out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
  10163. }
  10164. }
  10165. return 0;
  10166. }
  10167. static void
  10168. setoption(int flag, int val)
  10169. {
  10170. int i;
  10171. for (i = 0; i < NOPTS; i++) {
  10172. if (optletters(i) == flag && optnames(i)[0] != '\0') {
  10173. optlist[i] = val;
  10174. return;
  10175. }
  10176. }
  10177. ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
  10178. /* NOTREACHED */
  10179. }
  10180. /* If login_sh is not NULL, we are called to parse command line opts,
  10181. * not "set -opts"
  10182. */
  10183. static int
  10184. options(int *login_sh)
  10185. {
  10186. char *p;
  10187. int val;
  10188. int c;
  10189. if (login_sh)
  10190. minusc = NULL;
  10191. while ((p = *argptr) != NULL) {
  10192. c = *p++;
  10193. if (c != '-' && c != '+')
  10194. break;
  10195. argptr++;
  10196. val = 0; /* val = 0 if c == '+' */
  10197. if (c == '-') {
  10198. val = 1;
  10199. if (p[0] == '\0' || LONE_DASH(p)) {
  10200. if (!login_sh) {
  10201. /* "-" means turn off -x and -v */
  10202. if (p[0] == '\0')
  10203. xflag = vflag = 0;
  10204. /* "--" means reset params */
  10205. else if (*argptr == NULL)
  10206. setparam(argptr);
  10207. }
  10208. break; /* "-" or "--" terminates options */
  10209. }
  10210. }
  10211. /* first char was + or - */
  10212. while ((c = *p++) != '\0') {
  10213. if (login_sh) {
  10214. /* bash 3.2 indeed handles -c CMD and +c CMD the same */
  10215. if (c == 'c') {
  10216. minusc = p; /* command is after shell args */
  10217. cflag = 1;
  10218. continue;
  10219. }
  10220. if (c == 's') { /* -s, +s */
  10221. sflag = 1;
  10222. continue;
  10223. }
  10224. if (c == 'i') { /* -i, +i */
  10225. iflag = 1;
  10226. continue;
  10227. }
  10228. if (c == 'l') {
  10229. *login_sh = 1; /* -l or +l == --login */
  10230. continue;
  10231. }
  10232. /* bash does not accept +-login, we also won't */
  10233. if (val && (c == '-')) { /* long options */
  10234. if (strcmp(p, "login") == 0) {
  10235. *login_sh = 1;
  10236. }
  10237. break;
  10238. }
  10239. }
  10240. if (c == 'o') {
  10241. if (plus_minus_o(*argptr, val)) {
  10242. /* it already printed err message */
  10243. return 1; /* error */
  10244. }
  10245. if (*argptr)
  10246. argptr++;
  10247. } else {
  10248. setoption(c, val);
  10249. }
  10250. }
  10251. }
  10252. return 0;
  10253. }
  10254. /*
  10255. * The shift builtin command.
  10256. */
  10257. static int FAST_FUNC
  10258. shiftcmd(int argc UNUSED_PARAM, char **argv)
  10259. {
  10260. int n;
  10261. char **ap1, **ap2;
  10262. n = 1;
  10263. if (argv[1])
  10264. n = number(argv[1]);
  10265. if (n > shellparam.nparam)
  10266. return 1;
  10267. INT_OFF;
  10268. shellparam.nparam -= n;
  10269. for (ap1 = shellparam.p; --n >= 0; ap1++) {
  10270. if (shellparam.malloced)
  10271. free(*ap1);
  10272. }
  10273. ap2 = shellparam.p;
  10274. while ((*ap2++ = *ap1++) != NULL)
  10275. continue;
  10276. #if ENABLE_ASH_GETOPTS
  10277. shellparam.optind = 1;
  10278. shellparam.optoff = -1;
  10279. #endif
  10280. INT_ON;
  10281. return 0;
  10282. }
  10283. /*
  10284. * POSIX requires that 'set' (but not export or readonly) output the
  10285. * variables in lexicographic order - by the locale's collating order (sigh).
  10286. * Maybe we could keep them in an ordered balanced binary tree
  10287. * instead of hashed lists.
  10288. * For now just roll 'em through qsort for printing...
  10289. */
  10290. static int
  10291. showvars(const char *sep_prefix, int on, int off)
  10292. {
  10293. const char *sep;
  10294. char **ep, **epend;
  10295. ep = listvars(on, off, /*strlist:*/ NULL, &epend);
  10296. qsort(ep, epend - ep, sizeof(char *), vpcmp);
  10297. sep = *sep_prefix ? " " : sep_prefix;
  10298. for (; ep < epend; ep++) {
  10299. const char *p;
  10300. const char *q;
  10301. p = endofname(*ep);
  10302. /* Used to have simple "p = strchrnul(*ep, '=')" here instead, but this
  10303. * makes "export -p" to have output not suitable for "eval":
  10304. * import os
  10305. * os.environ["test-test"]="test"
  10306. * if os.fork() == 0:
  10307. * os.execv("ash", [ 'ash', '-c', 'eval $(export -p); echo OK' ]) # fixes this
  10308. * os.execv("ash", [ 'ash', '-c', 'env | grep test-test' ])
  10309. */
  10310. q = nullstr;
  10311. if (*p == '=')
  10312. q = single_quote(++p);
  10313. out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
  10314. }
  10315. return 0;
  10316. }
  10317. /*
  10318. * The set command builtin.
  10319. */
  10320. static int FAST_FUNC
  10321. setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  10322. {
  10323. int retval;
  10324. if (!argv[1])
  10325. return showvars(nullstr, 0, VUNSET);
  10326. INT_OFF;
  10327. retval = options(/*login_sh:*/ NULL);
  10328. if (retval == 0) { /* if no parse error... */
  10329. optschanged();
  10330. if (*argptr != NULL) {
  10331. setparam(argptr);
  10332. }
  10333. }
  10334. INT_ON;
  10335. return retval;
  10336. }
  10337. #if ENABLE_ASH_RANDOM_SUPPORT
  10338. static void FAST_FUNC
  10339. change_random(const char *value)
  10340. {
  10341. uint32_t t;
  10342. if (value == NULL) {
  10343. /* "get", generate */
  10344. t = next_random(&random_gen);
  10345. /* set without recursion */
  10346. setvar(vrandom.var_text, utoa(t), VNOFUNC);
  10347. vrandom.flags &= ~VNOFUNC;
  10348. } else {
  10349. /* set/reset */
  10350. t = strtoul(value, NULL, 10);
  10351. INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
  10352. }
  10353. }
  10354. #endif
  10355. #if BASH_EPOCH_VARS
  10356. static void FAST_FUNC
  10357. change_epoch(struct var *vepoch, const char *fmt)
  10358. {
  10359. struct timeval tv;
  10360. char buffer[sizeof("%lu.nnnnnn") + sizeof(long)*3];
  10361. gettimeofday(&tv, NULL);
  10362. sprintf(buffer, fmt, (unsigned long)tv.tv_sec, (unsigned)tv.tv_usec);
  10363. setvar(vepoch->var_text, buffer, VNOFUNC);
  10364. vepoch->flags &= ~VNOFUNC;
  10365. }
  10366. static void FAST_FUNC
  10367. change_seconds(const char *value UNUSED_PARAM)
  10368. {
  10369. change_epoch(&vepochs, "%lu");
  10370. }
  10371. static void FAST_FUNC
  10372. change_realtime(const char *value UNUSED_PARAM)
  10373. {
  10374. change_epoch(&vepochr, "%lu.%06u");
  10375. }
  10376. #endif
  10377. #if ENABLE_ASH_GETOPTS
  10378. static int
  10379. getopts(char *optstr, char *optvar, char **optfirst)
  10380. {
  10381. char *p, *q;
  10382. char c = '?';
  10383. int done = 0;
  10384. char sbuf[2];
  10385. char **optnext;
  10386. int ind = shellparam.optind;
  10387. int off = shellparam.optoff;
  10388. sbuf[1] = '\0';
  10389. shellparam.optind = -1;
  10390. optnext = optfirst + ind - 1;
  10391. if (ind <= 1 || off < 0 || (int)strlen(optnext[-1]) < off)
  10392. p = NULL;
  10393. else
  10394. p = optnext[-1] + off;
  10395. if (p == NULL || *p == '\0') {
  10396. /* Current word is done, advance */
  10397. p = *optnext;
  10398. if (p == NULL || *p != '-' || *++p == '\0') {
  10399. atend:
  10400. unsetvar("OPTARG");
  10401. p = NULL;
  10402. done = 1;
  10403. goto out;
  10404. }
  10405. optnext++;
  10406. if (LONE_DASH(p)) /* check for "--" */
  10407. goto atend;
  10408. }
  10409. c = *p++;
  10410. for (q = optstr; *q != c;) {
  10411. if (*q == '\0') {
  10412. /* OPTERR is a bashism */
  10413. const char *cp = lookupvar("OPTERR");
  10414. if ((cp && LONE_CHAR(cp, '0'))
  10415. || (optstr[0] == ':')
  10416. ) {
  10417. sbuf[0] = c;
  10418. /*sbuf[1] = '\0'; - already is */
  10419. setvar0("OPTARG", sbuf);
  10420. } else {
  10421. fprintf(stderr, "Illegal option -%c\n", c);
  10422. unsetvar("OPTARG");
  10423. }
  10424. c = '?';
  10425. goto out;
  10426. }
  10427. if (*++q == ':')
  10428. q++;
  10429. }
  10430. if (*++q == ':') {
  10431. if (*p == '\0' && (p = *optnext) == NULL) {
  10432. /* OPTERR is a bashism */
  10433. const char *cp = lookupvar("OPTERR");
  10434. if ((cp && LONE_CHAR(cp, '0'))
  10435. || (optstr[0] == ':')
  10436. ) {
  10437. sbuf[0] = c;
  10438. /*sbuf[1] = '\0'; - already is */
  10439. setvar0("OPTARG", sbuf);
  10440. c = ':';
  10441. } else {
  10442. fprintf(stderr, "No arg for -%c option\n", c);
  10443. unsetvar("OPTARG");
  10444. c = '?';
  10445. }
  10446. goto out;
  10447. }
  10448. if (p == *optnext)
  10449. optnext++;
  10450. setvar0("OPTARG", p);
  10451. p = NULL;
  10452. } else
  10453. setvar0("OPTARG", nullstr);
  10454. out:
  10455. ind = optnext - optfirst + 1;
  10456. setvar("OPTIND", itoa(ind), VNOFUNC);
  10457. sbuf[0] = c;
  10458. /*sbuf[1] = '\0'; - already is */
  10459. setvar0(optvar, sbuf);
  10460. shellparam.optoff = p ? p - *(optnext - 1) : -1;
  10461. shellparam.optind = ind;
  10462. return done;
  10463. }
  10464. /*
  10465. * The getopts builtin. Shellparam.optnext points to the next argument
  10466. * to be processed. Shellparam.optptr points to the next character to
  10467. * be processed in the current argument. If shellparam.optnext is NULL,
  10468. * then it's the first time getopts has been called.
  10469. */
  10470. static int FAST_FUNC
  10471. getoptscmd(int argc, char **argv)
  10472. {
  10473. char **optbase;
  10474. if (argc < 3)
  10475. ash_msg_and_raise_error("usage: getopts optstring var [arg]");
  10476. if (argc == 3) {
  10477. optbase = shellparam.p;
  10478. if ((unsigned)shellparam.optind > shellparam.nparam + 1) {
  10479. shellparam.optind = 1;
  10480. shellparam.optoff = -1;
  10481. }
  10482. } else {
  10483. optbase = &argv[3];
  10484. if ((unsigned)shellparam.optind > argc - 2) {
  10485. shellparam.optind = 1;
  10486. shellparam.optoff = -1;
  10487. }
  10488. }
  10489. return getopts(argv[1], argv[2], optbase);
  10490. }
  10491. #endif /* ASH_GETOPTS */
  10492. /* ============ Shell parser */
  10493. struct heredoc {
  10494. struct heredoc *next; /* next here document in list */
  10495. union node *here; /* redirection node */
  10496. char *eofmark; /* string indicating end of input */
  10497. smallint striptabs; /* if set, strip leading tabs */
  10498. };
  10499. static smallint tokpushback; /* last token pushed back */
  10500. static smallint quoteflag; /* set if (part of) last token was quoted */
  10501. static token_id_t lasttoken; /* last token read (integer id Txxx) */
  10502. static struct heredoc *heredoclist; /* list of here documents to read */
  10503. static char *wordtext; /* text of last word returned by readtoken */
  10504. static struct nodelist *backquotelist;
  10505. static union node *redirnode;
  10506. static struct heredoc *heredoc;
  10507. static const char *
  10508. tokname(char *buf, int tok)
  10509. {
  10510. if (tok < TSEMI)
  10511. return tokname_array[tok];
  10512. sprintf(buf, "\"%s\"", tokname_array[tok]);
  10513. return buf;
  10514. }
  10515. /* raise_error_unexpected_syntax:
  10516. * Called when an unexpected token is read during the parse. The argument
  10517. * is the token that is expected, or -1 if more than one type of token can
  10518. * occur at this point.
  10519. */
  10520. static void raise_error_unexpected_syntax(int) NORETURN;
  10521. static void
  10522. raise_error_unexpected_syntax(int token)
  10523. {
  10524. char msg[64];
  10525. char buf[16];
  10526. int l;
  10527. l = sprintf(msg, "unexpected %s", tokname(buf, lasttoken));
  10528. if (token >= 0)
  10529. sprintf(msg + l, " (expecting %s)", tokname(buf, token));
  10530. raise_error_syntax(msg);
  10531. /* NOTREACHED */
  10532. }
  10533. /* parsing is heavily cross-recursive, need these forward decls */
  10534. static union node *andor(void);
  10535. static union node *pipeline(void);
  10536. static union node *parse_command(void);
  10537. static void parseheredoc(void);
  10538. static int peektoken(void);
  10539. static int readtoken(void);
  10540. static union node *
  10541. list(int nlflag)
  10542. {
  10543. union node *n1, *n2, *n3;
  10544. int tok;
  10545. n1 = NULL;
  10546. for (;;) {
  10547. switch (readtoken()) {
  10548. case TNL:
  10549. if (!(nlflag & 1))
  10550. break;
  10551. parseheredoc();
  10552. return n1;
  10553. case TEOF:
  10554. if (!n1 && (nlflag & 1))
  10555. n1 = NODE_EOF;
  10556. parseheredoc();
  10557. tokpushback++;
  10558. lasttoken = TEOF;
  10559. return n1;
  10560. }
  10561. tokpushback++;
  10562. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  10563. if (nlflag == 2 && ((1 << peektoken()) & tokendlist))
  10564. return n1;
  10565. nlflag |= 2;
  10566. n2 = andor();
  10567. tok = readtoken();
  10568. if (tok == TBACKGND) {
  10569. if (n2->type == NPIPE) {
  10570. n2->npipe.pipe_backgnd = 1;
  10571. } else {
  10572. if (n2->type != NREDIR) {
  10573. n3 = stzalloc(sizeof(struct nredir));
  10574. n3->nredir.n = n2;
  10575. /*n3->nredir.redirect = NULL; - stzalloc did it */
  10576. n2 = n3;
  10577. }
  10578. n2->type = NBACKGND;
  10579. }
  10580. }
  10581. if (n1 == NULL) {
  10582. n1 = n2;
  10583. } else {
  10584. n3 = stzalloc(sizeof(struct nbinary));
  10585. n3->type = NSEMI;
  10586. n3->nbinary.ch1 = n1;
  10587. n3->nbinary.ch2 = n2;
  10588. n1 = n3;
  10589. }
  10590. switch (tok) {
  10591. case TNL:
  10592. case TEOF:
  10593. tokpushback = 1;
  10594. /* fall through */
  10595. case TBACKGND:
  10596. case TSEMI:
  10597. break;
  10598. default:
  10599. if ((nlflag & 1))
  10600. raise_error_unexpected_syntax(-1);
  10601. tokpushback = 1;
  10602. return n1;
  10603. }
  10604. }
  10605. }
  10606. static union node *
  10607. andor(void)
  10608. {
  10609. union node *n1, *n2, *n3;
  10610. int t;
  10611. n1 = pipeline();
  10612. for (;;) {
  10613. t = readtoken();
  10614. if (t == TAND) {
  10615. t = NAND;
  10616. } else if (t == TOR) {
  10617. t = NOR;
  10618. } else {
  10619. tokpushback = 1;
  10620. return n1;
  10621. }
  10622. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  10623. n2 = pipeline();
  10624. n3 = stzalloc(sizeof(struct nbinary));
  10625. n3->type = t;
  10626. n3->nbinary.ch1 = n1;
  10627. n3->nbinary.ch2 = n2;
  10628. n1 = n3;
  10629. }
  10630. }
  10631. static union node *
  10632. pipeline(void)
  10633. {
  10634. union node *n1, *n2, *pipenode;
  10635. struct nodelist *lp, *prev;
  10636. int negate;
  10637. negate = 0;
  10638. TRACE(("pipeline: entered\n"));
  10639. if (readtoken() == TNOT) {
  10640. negate = !negate;
  10641. checkkwd = CHKKWD | CHKALIAS;
  10642. } else
  10643. tokpushback = 1;
  10644. n1 = parse_command();
  10645. if (readtoken() == TPIPE) {
  10646. pipenode = stzalloc(sizeof(struct npipe));
  10647. pipenode->type = NPIPE;
  10648. /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
  10649. lp = stzalloc(sizeof(struct nodelist));
  10650. pipenode->npipe.cmdlist = lp;
  10651. lp->n = n1;
  10652. do {
  10653. prev = lp;
  10654. lp = stzalloc(sizeof(struct nodelist));
  10655. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  10656. lp->n = parse_command();
  10657. prev->next = lp;
  10658. } while (readtoken() == TPIPE);
  10659. lp->next = NULL;
  10660. n1 = pipenode;
  10661. }
  10662. tokpushback = 1;
  10663. if (negate) {
  10664. n2 = stzalloc(sizeof(struct nnot));
  10665. n2->type = NNOT;
  10666. n2->nnot.com = n1;
  10667. return n2;
  10668. }
  10669. return n1;
  10670. }
  10671. static union node *
  10672. makename(void)
  10673. {
  10674. union node *n;
  10675. n = stzalloc(sizeof(struct narg));
  10676. n->type = NARG;
  10677. /*n->narg.next = NULL; - stzalloc did it */
  10678. n->narg.text = wordtext;
  10679. n->narg.backquote = backquotelist;
  10680. return n;
  10681. }
  10682. static void
  10683. fixredir(union node *n, const char *text, int err)
  10684. {
  10685. int fd;
  10686. TRACE(("Fix redir %s %d\n", text, err));
  10687. if (!err)
  10688. n->ndup.vname = NULL;
  10689. fd = bb_strtou(text, NULL, 10);
  10690. if (!errno && fd >= 0)
  10691. n->ndup.dupfd = fd;
  10692. else if (LONE_DASH(text))
  10693. n->ndup.dupfd = -1;
  10694. else {
  10695. if (err)
  10696. raise_error_syntax("bad fd number");
  10697. n->ndup.vname = makename();
  10698. }
  10699. }
  10700. static void
  10701. parsefname(void)
  10702. {
  10703. union node *n = redirnode;
  10704. if (n->type == NHERE)
  10705. checkkwd = CHKEOFMARK;
  10706. if (readtoken() != TWORD)
  10707. raise_error_unexpected_syntax(-1);
  10708. if (n->type == NHERE) {
  10709. struct heredoc *here = heredoc;
  10710. struct heredoc *p;
  10711. if (quoteflag == 0)
  10712. n->type = NXHERE;
  10713. TRACE(("Here document %d\n", n->type));
  10714. rmescapes(wordtext, 0, NULL);
  10715. here->eofmark = wordtext;
  10716. here->next = NULL;
  10717. if (heredoclist == NULL)
  10718. heredoclist = here;
  10719. else {
  10720. for (p = heredoclist; p->next; p = p->next)
  10721. continue;
  10722. p->next = here;
  10723. }
  10724. } else if (n->type == NTOFD || n->type == NFROMFD) {
  10725. fixredir(n, wordtext, 0);
  10726. } else {
  10727. n->nfile.fname = makename();
  10728. }
  10729. }
  10730. static union node *
  10731. simplecmd(void)
  10732. {
  10733. union node *args, **app;
  10734. union node *n = NULL;
  10735. union node *vars, **vpp;
  10736. union node **rpp, *redir;
  10737. int savecheckkwd;
  10738. int savelinno;
  10739. #if BASH_TEST2
  10740. smallint double_brackets_flag = 0;
  10741. #endif
  10742. IF_BASH_FUNCTION(smallint function_flag = 0;)
  10743. args = NULL;
  10744. app = &args;
  10745. vars = NULL;
  10746. vpp = &vars;
  10747. redir = NULL;
  10748. rpp = &redir;
  10749. savecheckkwd = CHKALIAS;
  10750. savelinno = g_parsefile->linno;
  10751. for (;;) {
  10752. int t;
  10753. checkkwd = savecheckkwd;
  10754. t = readtoken();
  10755. switch (t) {
  10756. #if BASH_FUNCTION
  10757. case TFUNCTION:
  10758. if (peektoken() != TWORD)
  10759. raise_error_unexpected_syntax(TWORD);
  10760. function_flag = 1;
  10761. break;
  10762. #endif
  10763. #if BASH_TEST2
  10764. case TAND: /* "&&" */
  10765. case TOR: /* "||" */
  10766. if (!double_brackets_flag) {
  10767. tokpushback = 1;
  10768. goto out;
  10769. }
  10770. wordtext = (char *) (t == TAND ? "-a" : "-o");
  10771. #endif
  10772. case TWORD:
  10773. n = stzalloc(sizeof(struct narg));
  10774. n->type = NARG;
  10775. /*n->narg.next = NULL; - stzalloc did it */
  10776. n->narg.text = wordtext;
  10777. #if BASH_TEST2
  10778. if (strcmp("[[", wordtext) == 0)
  10779. double_brackets_flag = 1;
  10780. else if (strcmp("]]", wordtext) == 0)
  10781. double_brackets_flag = 0;
  10782. #endif
  10783. n->narg.backquote = backquotelist;
  10784. if (savecheckkwd && isassignment(wordtext)) {
  10785. *vpp = n;
  10786. vpp = &n->narg.next;
  10787. } else {
  10788. *app = n;
  10789. app = &n->narg.next;
  10790. savecheckkwd = 0;
  10791. }
  10792. #if BASH_FUNCTION
  10793. if (function_flag) {
  10794. checkkwd = CHKNL | CHKKWD;
  10795. switch (peektoken()) {
  10796. case TBEGIN:
  10797. case TIF:
  10798. case TCASE:
  10799. case TUNTIL:
  10800. case TWHILE:
  10801. case TFOR:
  10802. goto do_func;
  10803. case TLP:
  10804. function_flag = 0;
  10805. break;
  10806. # if BASH_TEST2
  10807. case TWORD:
  10808. if (strcmp("[[", wordtext) == 0)
  10809. goto do_func;
  10810. /* fall through */
  10811. # endif
  10812. default:
  10813. raise_error_unexpected_syntax(-1);
  10814. }
  10815. }
  10816. #endif
  10817. break;
  10818. case TREDIR:
  10819. *rpp = n = redirnode;
  10820. rpp = &n->nfile.next;
  10821. parsefname(); /* read name of redirection file */
  10822. break;
  10823. case TLP:
  10824. IF_BASH_FUNCTION(do_func:)
  10825. if (args && app == &args->narg.next
  10826. && !vars && !redir
  10827. ) {
  10828. struct builtincmd *bcmd;
  10829. const char *name;
  10830. /* We have a function */
  10831. if (IF_BASH_FUNCTION(!function_flag &&) readtoken() != TRP)
  10832. raise_error_unexpected_syntax(TRP);
  10833. name = n->narg.text;
  10834. if (!goodname(name)
  10835. || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
  10836. ) {
  10837. raise_error_syntax("bad function name");
  10838. }
  10839. n->type = NDEFUN;
  10840. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  10841. n->ndefun.text = n->narg.text;
  10842. n->ndefun.linno = g_parsefile->linno;
  10843. n->ndefun.body = parse_command();
  10844. return n;
  10845. }
  10846. IF_BASH_FUNCTION(function_flag = 0;)
  10847. /* fall through */
  10848. default:
  10849. tokpushback = 1;
  10850. goto out;
  10851. }
  10852. }
  10853. out:
  10854. *app = NULL;
  10855. *vpp = NULL;
  10856. *rpp = NULL;
  10857. n = stzalloc(sizeof(struct ncmd));
  10858. if (NCMD != 0)
  10859. n->type = NCMD;
  10860. n->ncmd.linno = savelinno;
  10861. n->ncmd.args = args;
  10862. n->ncmd.assign = vars;
  10863. n->ncmd.redirect = redir;
  10864. return n;
  10865. }
  10866. static union node *
  10867. parse_command(void)
  10868. {
  10869. union node *n1, *n2;
  10870. union node *ap, **app;
  10871. union node *cp, **cpp;
  10872. union node *redir, **rpp;
  10873. union node **rpp2;
  10874. int t;
  10875. int savelinno;
  10876. redir = NULL;
  10877. rpp2 = &redir;
  10878. savelinno = g_parsefile->linno;
  10879. switch (readtoken()) {
  10880. default:
  10881. raise_error_unexpected_syntax(-1);
  10882. /* NOTREACHED */
  10883. case TIF:
  10884. n1 = stzalloc(sizeof(struct nif));
  10885. n1->type = NIF;
  10886. n1->nif.test = list(0);
  10887. if (readtoken() != TTHEN)
  10888. raise_error_unexpected_syntax(TTHEN);
  10889. n1->nif.ifpart = list(0);
  10890. n2 = n1;
  10891. while (readtoken() == TELIF) {
  10892. n2->nif.elsepart = stzalloc(sizeof(struct nif));
  10893. n2 = n2->nif.elsepart;
  10894. n2->type = NIF;
  10895. n2->nif.test = list(0);
  10896. if (readtoken() != TTHEN)
  10897. raise_error_unexpected_syntax(TTHEN);
  10898. n2->nif.ifpart = list(0);
  10899. }
  10900. if (lasttoken == TELSE)
  10901. n2->nif.elsepart = list(0);
  10902. else {
  10903. n2->nif.elsepart = NULL;
  10904. tokpushback = 1;
  10905. }
  10906. t = TFI;
  10907. break;
  10908. case TWHILE:
  10909. case TUNTIL: {
  10910. int got;
  10911. n1 = stzalloc(sizeof(struct nbinary));
  10912. n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
  10913. n1->nbinary.ch1 = list(0);
  10914. got = readtoken();
  10915. if (got != TDO) {
  10916. TRACE(("expecting DO got '%s' %s\n", tokname_array[got],
  10917. got == TWORD ? wordtext : ""));
  10918. raise_error_unexpected_syntax(TDO);
  10919. }
  10920. n1->nbinary.ch2 = list(0);
  10921. t = TDONE;
  10922. break;
  10923. }
  10924. case TFOR:
  10925. if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
  10926. raise_error_syntax("bad for loop variable");
  10927. n1 = stzalloc(sizeof(struct nfor));
  10928. n1->type = NFOR;
  10929. n1->nfor.linno = savelinno;
  10930. n1->nfor.var = wordtext;
  10931. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  10932. if (readtoken() == TIN) {
  10933. app = &ap;
  10934. while (readtoken() == TWORD) {
  10935. n2 = stzalloc(sizeof(struct narg));
  10936. n2->type = NARG;
  10937. /*n2->narg.next = NULL; - stzalloc did it */
  10938. n2->narg.text = wordtext;
  10939. n2->narg.backquote = backquotelist;
  10940. *app = n2;
  10941. app = &n2->narg.next;
  10942. }
  10943. *app = NULL;
  10944. n1->nfor.args = ap;
  10945. if (lasttoken != TNL && lasttoken != TSEMI)
  10946. raise_error_unexpected_syntax(-1);
  10947. } else {
  10948. n2 = stzalloc(sizeof(struct narg));
  10949. n2->type = NARG;
  10950. /*n2->narg.next = NULL; - stzalloc did it */
  10951. n2->narg.text = (char *)dolatstr;
  10952. /*n2->narg.backquote = NULL;*/
  10953. n1->nfor.args = n2;
  10954. /*
  10955. * Newline or semicolon here is optional (but note
  10956. * that the original Bourne shell only allowed NL).
  10957. */
  10958. if (lasttoken != TSEMI)
  10959. tokpushback = 1;
  10960. }
  10961. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  10962. if (readtoken() != TDO)
  10963. raise_error_unexpected_syntax(TDO);
  10964. n1->nfor.body = list(0);
  10965. t = TDONE;
  10966. break;
  10967. case TCASE:
  10968. n1 = stzalloc(sizeof(struct ncase));
  10969. n1->type = NCASE;
  10970. n1->ncase.linno = savelinno;
  10971. if (readtoken() != TWORD)
  10972. raise_error_unexpected_syntax(TWORD);
  10973. n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
  10974. n2->type = NARG;
  10975. /*n2->narg.next = NULL; - stzalloc did it */
  10976. n2->narg.text = wordtext;
  10977. n2->narg.backquote = backquotelist;
  10978. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  10979. if (readtoken() != TIN)
  10980. raise_error_unexpected_syntax(TIN);
  10981. cpp = &n1->ncase.cases;
  10982. next_case:
  10983. checkkwd = CHKNL | CHKKWD;
  10984. t = readtoken();
  10985. while (t != TESAC) {
  10986. if (lasttoken == TLP)
  10987. readtoken();
  10988. *cpp = cp = stzalloc(sizeof(struct nclist));
  10989. cp->type = NCLIST;
  10990. app = &cp->nclist.pattern;
  10991. for (;;) {
  10992. *app = ap = stzalloc(sizeof(struct narg));
  10993. ap->type = NARG;
  10994. /*ap->narg.next = NULL; - stzalloc did it */
  10995. ap->narg.text = wordtext;
  10996. ap->narg.backquote = backquotelist;
  10997. if (readtoken() != TPIPE)
  10998. break;
  10999. app = &ap->narg.next;
  11000. readtoken();
  11001. }
  11002. //ap->narg.next = NULL;
  11003. if (lasttoken != TRP)
  11004. raise_error_unexpected_syntax(TRP);
  11005. cp->nclist.body = list(2);
  11006. cpp = &cp->nclist.next;
  11007. checkkwd = CHKNL | CHKKWD;
  11008. t = readtoken();
  11009. if (t != TESAC) {
  11010. if (t != TENDCASE)
  11011. raise_error_unexpected_syntax(TENDCASE);
  11012. goto next_case;
  11013. }
  11014. }
  11015. *cpp = NULL;
  11016. goto redir;
  11017. case TLP:
  11018. n1 = stzalloc(sizeof(struct nredir));
  11019. n1->type = NSUBSHELL;
  11020. n1->nredir.linno = savelinno;
  11021. n1->nredir.n = list(0);
  11022. /*n1->nredir.redirect = NULL; - stzalloc did it */
  11023. t = TRP;
  11024. break;
  11025. case TBEGIN:
  11026. n1 = list(0);
  11027. t = TEND;
  11028. break;
  11029. IF_BASH_FUNCTION(case TFUNCTION:)
  11030. case TWORD:
  11031. case TREDIR:
  11032. tokpushback = 1;
  11033. return simplecmd();
  11034. }
  11035. if (readtoken() != t)
  11036. raise_error_unexpected_syntax(t);
  11037. redir:
  11038. /* Now check for redirection which may follow command */
  11039. checkkwd = CHKKWD | CHKALIAS;
  11040. rpp = rpp2;
  11041. while (readtoken() == TREDIR) {
  11042. *rpp = n2 = redirnode;
  11043. rpp = &n2->nfile.next;
  11044. parsefname();
  11045. }
  11046. tokpushback = 1;
  11047. *rpp = NULL;
  11048. if (redir) {
  11049. if (n1->type != NSUBSHELL) {
  11050. n2 = stzalloc(sizeof(struct nredir));
  11051. n2->type = NREDIR;
  11052. n2->nredir.linno = savelinno;
  11053. n2->nredir.n = n1;
  11054. n1 = n2;
  11055. }
  11056. n1->nredir.redirect = redir;
  11057. }
  11058. return n1;
  11059. }
  11060. #if BASH_DOLLAR_SQUOTE
  11061. static int
  11062. decode_dollar_squote(void)
  11063. {
  11064. static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
  11065. int c, cnt;
  11066. char *p;
  11067. char buf[4];
  11068. c = pgetc();
  11069. p = strchr(C_escapes, c);
  11070. if (p) {
  11071. buf[0] = c;
  11072. p = buf;
  11073. cnt = 3;
  11074. if ((unsigned char)(c - '0') <= 7) { /* \ooo */
  11075. do {
  11076. c = pgetc();
  11077. *++p = c;
  11078. } while ((unsigned char)(c - '0') <= 7 && --cnt);
  11079. pungetc();
  11080. } else if (c == 'x') { /* \xHH */
  11081. do {
  11082. c = pgetc();
  11083. *++p = c;
  11084. } while (isxdigit(c) && --cnt);
  11085. pungetc();
  11086. if (cnt == 3) { /* \x but next char is "bad" */
  11087. c = 'x';
  11088. goto unrecognized;
  11089. }
  11090. } else { /* simple seq like \\ or \t */
  11091. p++;
  11092. }
  11093. *p = '\0';
  11094. p = buf;
  11095. c = bb_process_escape_sequence((void*)&p);
  11096. } else { /* unrecognized "\z": print both chars unless ' or " */
  11097. if (c != '\'' && c != '"') {
  11098. unrecognized:
  11099. c |= 0x100; /* "please encode \, then me" */
  11100. }
  11101. }
  11102. return c;
  11103. }
  11104. #endif
  11105. /* Used by expandstr to get here-doc like behaviour. */
  11106. #define FAKEEOFMARK ((char*)(uintptr_t)1)
  11107. static ALWAYS_INLINE int
  11108. realeofmark(const char *eofmark)
  11109. {
  11110. return eofmark && eofmark != FAKEEOFMARK;
  11111. }
  11112. /*
  11113. * If eofmark is NULL, read a word or a redirection symbol. If eofmark
  11114. * is not NULL, read a here document. In the latter case, eofmark is the
  11115. * word which marks the end of the document and striptabs is true if
  11116. * leading tabs should be stripped from the document. The argument c
  11117. * is the first character of the input token or document.
  11118. *
  11119. * Because C does not have internal subroutines, I have simulated them
  11120. * using goto's to implement the subroutine linkage. The following macros
  11121. * will run code that appears at the end of readtoken1.
  11122. */
  11123. #define CHECKEND() {goto checkend; checkend_return:;}
  11124. #define PARSEREDIR() {goto parseredir; parseredir_return:;}
  11125. #define PARSESUB() {goto parsesub; parsesub_return:;}
  11126. #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
  11127. #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
  11128. #define PARSEARITH() {goto parsearith; parsearith_return:;}
  11129. static int
  11130. readtoken1(int c, int syntax, char *eofmark, int striptabs)
  11131. {
  11132. /* NB: syntax parameter fits into smallint */
  11133. /* c parameter is an unsigned char or PEOF or PEOA */
  11134. char *out;
  11135. size_t len;
  11136. struct nodelist *bqlist;
  11137. smallint quotef;
  11138. smallint oldstyle;
  11139. smallint pssyntax; /* we are expanding a prompt string */
  11140. IF_BASH_DOLLAR_SQUOTE(smallint bash_dollar_squote = 0;)
  11141. /* syntax stack */
  11142. struct synstack synbase = { };
  11143. struct synstack *synstack = &synbase;
  11144. #if ENABLE_ASH_EXPAND_PRMT
  11145. pssyntax = (syntax == PSSYNTAX);
  11146. if (pssyntax)
  11147. syntax = DQSYNTAX;
  11148. #else
  11149. pssyntax = 0; /* constant */
  11150. #endif
  11151. synstack->syntax = syntax;
  11152. if (syntax == DQSYNTAX)
  11153. synstack->dblquote = 1;
  11154. quotef = 0;
  11155. bqlist = NULL;
  11156. STARTSTACKSTR(out);
  11157. loop:
  11158. /* For each line, until end of word */
  11159. CHECKEND(); /* set c to PEOF if at end of here document */
  11160. for (;;) { /* until end of line or end of word */
  11161. CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
  11162. switch (SIT(c, synstack->syntax)) {
  11163. case CNL: /* '\n' */
  11164. if (synstack->syntax == BASESYNTAX
  11165. && !synstack->varnest
  11166. ) {
  11167. goto endword; /* exit outer loop */
  11168. }
  11169. USTPUTC(c, out);
  11170. nlprompt();
  11171. c = pgetc_top(synstack);
  11172. goto loop; /* continue outer loop */
  11173. case CWORD:
  11174. USTPUTC(c, out);
  11175. break;
  11176. case CCTL:
  11177. #if BASH_DOLLAR_SQUOTE
  11178. if (c == '\\' && bash_dollar_squote) {
  11179. c = decode_dollar_squote();
  11180. if (c == '\0') {
  11181. /* skip $'\000', $'\x00' (like bash) */
  11182. break;
  11183. }
  11184. if (c & 0x100) {
  11185. /* Unknown escape. Encode as '\z' */
  11186. c = (unsigned char)c;
  11187. if (eofmark == NULL || synstack->dblquote)
  11188. USTPUTC(CTLESC, out);
  11189. USTPUTC('\\', out);
  11190. }
  11191. }
  11192. #endif
  11193. if (!eofmark || synstack->dblquote || synstack->varnest)
  11194. USTPUTC(CTLESC, out);
  11195. USTPUTC(c, out);
  11196. break;
  11197. case CBACK: /* backslash */
  11198. c = pgetc_without_PEOA();
  11199. if (c == PEOF) {
  11200. USTPUTC(CTLESC, out);
  11201. USTPUTC('\\', out);
  11202. pungetc();
  11203. } else {
  11204. if (pssyntax && c == '$') {
  11205. USTPUTC(CTLESC, out);
  11206. USTPUTC('\\', out);
  11207. }
  11208. /* Backslash is retained if we are in "str"
  11209. * and next char isn't dquote-special.
  11210. */
  11211. if (synstack->dblquote
  11212. && c != '\\'
  11213. && c != '`'
  11214. && c != '$'
  11215. && (c != '"' || (eofmark != NULL && !synstack->varnest))
  11216. && (c != '}' || !synstack->varnest)
  11217. ) {
  11218. USTPUTC(CTLESC, out); /* protect '\' from glob */
  11219. USTPUTC('\\', out);
  11220. }
  11221. USTPUTC(CTLESC, out);
  11222. USTPUTC(c, out);
  11223. quotef = 1;
  11224. }
  11225. break;
  11226. case CSQUOTE:
  11227. synstack->syntax = SQSYNTAX;
  11228. quotemark:
  11229. if (eofmark == NULL) {
  11230. USTPUTC(CTLQUOTEMARK, out);
  11231. }
  11232. break;
  11233. case CDQUOTE:
  11234. synstack->syntax = DQSYNTAX;
  11235. synstack->dblquote = 1;
  11236. toggledq:
  11237. if (synstack->varnest)
  11238. synstack->innerdq ^= 1;
  11239. goto quotemark;
  11240. case CENDQUOTE:
  11241. IF_BASH_DOLLAR_SQUOTE(bash_dollar_squote = 0;)
  11242. if (eofmark != NULL && synstack->varnest == 0) {
  11243. USTPUTC(c, out);
  11244. break;
  11245. }
  11246. if (synstack->dqvarnest == 0) {
  11247. synstack->syntax = BASESYNTAX;
  11248. synstack->dblquote = 0;
  11249. }
  11250. quotef = 1;
  11251. if (c == '"')
  11252. goto toggledq;
  11253. goto quotemark;
  11254. case CVAR: /* '$' */
  11255. PARSESUB(); /* parse substitution */
  11256. break;
  11257. case CENDVAR: /* '}' */
  11258. if (!synstack->innerdq && synstack->varnest > 0) {
  11259. if (!--synstack->varnest && synstack->varpushed)
  11260. synstack_pop(&synstack);
  11261. else if (synstack->dqvarnest > 0)
  11262. synstack->dqvarnest--;
  11263. c = CTLENDVAR;
  11264. }
  11265. USTPUTC(c, out);
  11266. break;
  11267. #if ENABLE_FEATURE_SH_MATH
  11268. case CLP: /* '(' in arithmetic */
  11269. synstack->parenlevel++;
  11270. USTPUTC(c, out);
  11271. break;
  11272. case CRP: /* ')' in arithmetic */
  11273. if (synstack->parenlevel > 0) {
  11274. synstack->parenlevel--;
  11275. } else {
  11276. if (pgetc_eatbnl() == ')') {
  11277. c = CTLENDARI;
  11278. synstack_pop(&synstack);
  11279. } else {
  11280. /*
  11281. * unbalanced parens
  11282. * (don't 2nd guess - no error)
  11283. */
  11284. pungetc();
  11285. }
  11286. }
  11287. USTPUTC(c, out);
  11288. break;
  11289. #endif
  11290. case CBQUOTE: /* '`' */
  11291. if (checkkwd & CHKEOFMARK) {
  11292. quotef = 1;
  11293. USTPUTC('`', out);
  11294. break;
  11295. }
  11296. PARSEBACKQOLD();
  11297. break;
  11298. case CENDFILE:
  11299. goto endword; /* exit outer loop */
  11300. case CIGN:
  11301. break;
  11302. default:
  11303. if (synstack->varnest == 0) {
  11304. #if BASH_REDIR_OUTPUT
  11305. if (c == '&') {
  11306. //Can't call pgetc_eatbnl() here, this requires three-deep pungetc()
  11307. if (pgetc() == '>')
  11308. c = 0x100 + '>'; /* flag &> */
  11309. pungetc();
  11310. }
  11311. #endif
  11312. goto endword; /* exit outer loop */
  11313. }
  11314. IF_ASH_ALIAS(if (c != PEOA))
  11315. USTPUTC(c, out);
  11316. }
  11317. c = pgetc_top(synstack);
  11318. } /* for (;;) */
  11319. endword:
  11320. #if ENABLE_FEATURE_SH_MATH
  11321. if (synstack->syntax == ARISYNTAX)
  11322. raise_error_syntax("missing '))'");
  11323. #endif
  11324. if (synstack->syntax != BASESYNTAX && eofmark == NULL)
  11325. raise_error_syntax("unterminated quoted string");
  11326. if (synstack->varnest != 0) {
  11327. /* { */
  11328. raise_error_syntax("missing '}'");
  11329. }
  11330. USTPUTC('\0', out);
  11331. len = out - (char *)stackblock();
  11332. out = stackblock();
  11333. if (eofmark == NULL) {
  11334. if ((c == '>' || c == '<' IF_BASH_REDIR_OUTPUT( || c == 0x100 + '>'))
  11335. && quotef == 0
  11336. ) {
  11337. if (isdigit_str9(out)) {
  11338. PARSEREDIR(); /* passed as params: out, c */
  11339. lasttoken = TREDIR;
  11340. return lasttoken;
  11341. }
  11342. /* else: non-number X seen, interpret it
  11343. * as "NNNX>file" = "NNNX >file" */
  11344. }
  11345. pungetc();
  11346. }
  11347. quoteflag = quotef;
  11348. backquotelist = bqlist;
  11349. grabstackblock(len);
  11350. wordtext = out;
  11351. lasttoken = TWORD;
  11352. return lasttoken;
  11353. /* end of readtoken routine */
  11354. /*
  11355. * Check to see whether we are at the end of the here document. When this
  11356. * is called, c is set to the first character of the next input line. If
  11357. * we are at the end of the here document, this routine sets the c to PEOF.
  11358. */
  11359. checkend: {
  11360. if (realeofmark(eofmark)) {
  11361. int markloc;
  11362. char *p;
  11363. #if ENABLE_ASH_ALIAS
  11364. if (c == PEOA)
  11365. c = pgetc_without_PEOA();
  11366. #endif
  11367. if (striptabs) {
  11368. while (c == '\t') {
  11369. c = pgetc_without_PEOA();
  11370. }
  11371. }
  11372. markloc = out - (char *)stackblock();
  11373. for (p = eofmark; STPUTC(c, out), *p; p++) {
  11374. if (c != *p)
  11375. goto more_heredoc;
  11376. /* FIXME: fails for backslash-newlined terminator:
  11377. * cat <<EOF
  11378. * ...
  11379. * EO\
  11380. * F
  11381. * (see heredoc_bkslash_newline2.tests)
  11382. */
  11383. c = pgetc_without_PEOA();
  11384. }
  11385. if (c == '\n' || c == PEOF) {
  11386. c = PEOF;
  11387. g_parsefile->linno++;
  11388. needprompt = doprompt;
  11389. } else {
  11390. int len_here;
  11391. more_heredoc:
  11392. p = (char *)stackblock() + markloc + 1;
  11393. len_here = out - p;
  11394. if (len_here) {
  11395. len_here -= (c >= PEOF);
  11396. c = p[-1];
  11397. if (len_here) {
  11398. char *str;
  11399. str = alloca(len_here + 1);
  11400. *(char *)mempcpy(str, p, len_here) = '\0';
  11401. pushstring(str, NULL);
  11402. }
  11403. }
  11404. }
  11405. STADJUST((char *)stackblock() + markloc - out, out);
  11406. }
  11407. goto checkend_return;
  11408. }
  11409. /*
  11410. * Parse a redirection operator. The variable "out" points to a string
  11411. * specifying the fd to be redirected. The variable "c" contains the
  11412. * first character of the redirection operator.
  11413. */
  11414. parseredir: {
  11415. /* out is already checked to be a valid number or "" */
  11416. int fd = (*out == '\0' ? -1 : atoi(out));
  11417. union node *np;
  11418. np = stzalloc(sizeof(struct nfile));
  11419. if (c == '>') {
  11420. np->nfile.fd = 1;
  11421. c = pgetc_eatbnl();
  11422. if (c == '>')
  11423. np->type = NAPPEND;
  11424. else if (c == '|')
  11425. np->type = NCLOBBER;
  11426. else if (c == '&')
  11427. np->type = NTOFD;
  11428. /* it also can be NTO2 (>&file), but we can't figure it out yet */
  11429. else {
  11430. np->type = NTO;
  11431. pungetc();
  11432. }
  11433. }
  11434. #if BASH_REDIR_OUTPUT
  11435. else if (c == 0x100 + '>') { /* this flags &> redirection */
  11436. np->nfile.fd = 1;
  11437. pgetc(); /* this is '>', no need to check */
  11438. np->type = NTO2;
  11439. }
  11440. #endif
  11441. else { /* c == '<' */
  11442. /*np->nfile.fd = 0; - stzalloc did it */
  11443. c = pgetc_eatbnl();
  11444. switch (c) {
  11445. case '<':
  11446. if (sizeof(struct nfile) != sizeof(struct nhere)) {
  11447. np = stzalloc(sizeof(struct nhere));
  11448. /*np->nfile.fd = 0; - stzalloc did it */
  11449. }
  11450. np->type = NHERE;
  11451. heredoc = stzalloc(sizeof(struct heredoc));
  11452. heredoc->here = np;
  11453. c = pgetc_eatbnl();
  11454. if (c == '-') {
  11455. heredoc->striptabs = 1;
  11456. } else {
  11457. /*heredoc->striptabs = 0; - stzalloc did it */
  11458. pungetc();
  11459. }
  11460. break;
  11461. case '&':
  11462. np->type = NFROMFD;
  11463. break;
  11464. case '>':
  11465. np->type = NFROMTO;
  11466. break;
  11467. default:
  11468. np->type = NFROM;
  11469. pungetc();
  11470. break;
  11471. }
  11472. }
  11473. if (fd >= 0)
  11474. np->nfile.fd = fd;
  11475. redirnode = np;
  11476. goto parseredir_return;
  11477. }
  11478. /*
  11479. * Parse a substitution. At this point, we have read the dollar sign
  11480. * and nothing else.
  11481. */
  11482. /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
  11483. * (assuming ascii char codes, as the original implementation did) */
  11484. #define is_special(c) \
  11485. (((unsigned)(c) - 33 < 32) \
  11486. && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
  11487. parsesub: {
  11488. unsigned char subtype;
  11489. int typeloc;
  11490. c = pgetc_eatbnl();
  11491. if ((checkkwd & CHKEOFMARK)
  11492. || c > 255 /* PEOA or PEOF */
  11493. || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
  11494. ) {
  11495. #if BASH_DOLLAR_SQUOTE
  11496. if (synstack->syntax != DQSYNTAX && c == '\'')
  11497. bash_dollar_squote = 1;
  11498. else
  11499. #endif
  11500. USTPUTC('$', out);
  11501. pungetc();
  11502. } else if (c == '(') {
  11503. /* $(command) or $((arith)) */
  11504. if (pgetc_eatbnl() == '(') {
  11505. #if ENABLE_FEATURE_SH_MATH
  11506. PARSEARITH();
  11507. #else
  11508. raise_error_syntax("support for $((arith)) is disabled");
  11509. #endif
  11510. } else {
  11511. pungetc();
  11512. PARSEBACKQNEW();
  11513. }
  11514. } else {
  11515. /* $VAR, $<specialchar>, ${...}, or PEOA/PEOF */
  11516. smalluint newsyn = synstack->syntax;
  11517. USTPUTC(CTLVAR, out);
  11518. typeloc = out - (char *)stackblock();
  11519. STADJUST(1, out);
  11520. subtype = VSNORMAL;
  11521. if (c == '{') {
  11522. c = pgetc_eatbnl();
  11523. subtype = 0;
  11524. }
  11525. varname:
  11526. if (is_name(c)) {
  11527. /* $[{[#]]NAME[}] */
  11528. do {
  11529. STPUTC(c, out);
  11530. c = pgetc_eatbnl();
  11531. } while (is_in_name(c));
  11532. } else if (isdigit(c)) {
  11533. /* $[{[#]]NUM[}] */
  11534. do {
  11535. STPUTC(c, out);
  11536. c = pgetc_eatbnl();
  11537. } while (!subtype && isdigit(c));
  11538. } else if (c != '}') {
  11539. /* $[{[#]]<specialchar>[}] */
  11540. int cc = c;
  11541. c = pgetc_eatbnl();
  11542. if (!subtype && cc == '#') {
  11543. subtype = VSLENGTH;
  11544. if (c == '_' || isalnum(c))
  11545. goto varname;
  11546. cc = c;
  11547. c = pgetc_eatbnl();
  11548. if (cc == '}' || c != '}') {
  11549. pungetc();
  11550. subtype = 0;
  11551. c = cc;
  11552. cc = '#';
  11553. }
  11554. }
  11555. if (!is_special(cc)) {
  11556. if (subtype == VSLENGTH)
  11557. subtype = 0;
  11558. goto badsub;
  11559. }
  11560. USTPUTC(cc, out);
  11561. } else
  11562. goto badsub;
  11563. if (c != '}' && subtype == VSLENGTH) {
  11564. /* ${#VAR didn't end with } */
  11565. goto badsub;
  11566. }
  11567. if (subtype == 0) {
  11568. static const char types[] ALIGN1 = "}-+?=";
  11569. /* ${VAR...} but not $VAR or ${#VAR} */
  11570. /* c == first char after VAR */
  11571. int cc = c;
  11572. switch (c) {
  11573. case ':':
  11574. c = pgetc_eatbnl();
  11575. #if BASH_SUBSTR
  11576. /* This check is only needed to not misinterpret
  11577. * ${VAR:-WORD}, ${VAR:+WORD}, ${VAR:=WORD}, ${VAR:?WORD}
  11578. * constructs.
  11579. */
  11580. if (!strchr(types, c)) {
  11581. subtype = VSSUBSTR;
  11582. pungetc();
  11583. break; /* "goto badsub" is bigger (!) */
  11584. }
  11585. #endif
  11586. subtype = VSNUL;
  11587. /*FALLTHROUGH*/
  11588. default: {
  11589. const char *p = strchr(types, c);
  11590. if (p == NULL)
  11591. break;
  11592. subtype |= p - types + VSNORMAL;
  11593. break;
  11594. }
  11595. case '%':
  11596. case '#':
  11597. subtype = (c == '#' ? VSTRIMLEFT : VSTRIMRIGHT);
  11598. c = pgetc_eatbnl();
  11599. if (c == cc)
  11600. subtype++;
  11601. else
  11602. pungetc();
  11603. newsyn = BASESYNTAX;
  11604. break;
  11605. #if BASH_PATTERN_SUBST
  11606. case '/':
  11607. /* ${v/[/]pattern/repl} */
  11608. //TODO: encode pattern and repl separately.
  11609. // Currently cases like: v=1;echo ${v/$((1/1))/ONE}
  11610. // are broken (should print "ONE")
  11611. subtype = VSREPLACE;
  11612. newsyn = BASESYNTAX;
  11613. c = pgetc_eatbnl();
  11614. if (c != '/')
  11615. goto badsub;
  11616. subtype++; /* VSREPLACEALL */
  11617. break;
  11618. #endif
  11619. }
  11620. } else {
  11621. badsub:
  11622. pungetc();
  11623. }
  11624. if (newsyn == ARISYNTAX)
  11625. newsyn = DQSYNTAX;
  11626. if ((newsyn != synstack->syntax || synstack->innerdq)
  11627. && subtype != VSNORMAL
  11628. ) {
  11629. synstack_push(&synstack,
  11630. synstack->prev ?: alloca(sizeof(*synstack)),
  11631. newsyn);
  11632. synstack->varpushed = 1;
  11633. synstack->dblquote = newsyn != BASESYNTAX;
  11634. }
  11635. ((unsigned char *)stackblock())[typeloc] = subtype;
  11636. if (subtype != VSNORMAL) {
  11637. synstack->varnest++;
  11638. if (synstack->dblquote)
  11639. synstack->dqvarnest++;
  11640. }
  11641. STPUTC('=', out);
  11642. }
  11643. goto parsesub_return;
  11644. }
  11645. /*
  11646. * Called to parse command substitutions. Newstyle is set if the command
  11647. * is enclosed inside $(...); nlpp is a pointer to the head of the linked
  11648. * list of commands (passed by reference), and savelen is the number of
  11649. * characters on the top of the stack which must be preserved.
  11650. */
  11651. parsebackq: {
  11652. struct nodelist **nlpp;
  11653. union node *n;
  11654. char *str;
  11655. size_t savelen;
  11656. struct heredoc *saveheredoclist;
  11657. smallint saveprompt = 0;
  11658. str = NULL;
  11659. savelen = out - (char *)stackblock();
  11660. if (savelen > 0) {
  11661. /*
  11662. * FIXME: this can allocate very large block on stack and SEGV.
  11663. * Example:
  11664. * echo "..<100kbytes>..`true` $(true) `true` ..."
  11665. * allocates 100kb for every command subst. With about
  11666. * a hundred command substitutions stack overflows.
  11667. * With larger prepended string, SEGV happens sooner.
  11668. */
  11669. str = alloca(savelen);
  11670. memcpy(str, stackblock(), savelen);
  11671. }
  11672. if (oldstyle) {
  11673. /* We must read until the closing backquote, giving special
  11674. * treatment to some slashes, and then push the string and
  11675. * reread it as input, interpreting it normally.
  11676. */
  11677. char *pout;
  11678. size_t psavelen;
  11679. char *pstr;
  11680. STARTSTACKSTR(pout);
  11681. for (;;) {
  11682. int pc;
  11683. setprompt_if(needprompt, 2);
  11684. pc = pgetc_eatbnl();
  11685. switch (pc) {
  11686. case '`':
  11687. goto done;
  11688. case '\\':
  11689. pc = pgetc(); /* or pgetc_eatbnl()? why (example)? */
  11690. if (pc != '\\' && pc != '`' && pc != '$'
  11691. && (!synstack->dblquote || pc != '"')
  11692. ) {
  11693. STPUTC('\\', pout);
  11694. }
  11695. if (pc <= 255 /* not PEOA or PEOF */) {
  11696. break;
  11697. }
  11698. /* fall through */
  11699. case PEOF:
  11700. IF_ASH_ALIAS(case PEOA:)
  11701. raise_error_syntax("EOF in backquote substitution");
  11702. case '\n':
  11703. nlnoprompt();
  11704. break;
  11705. default:
  11706. break;
  11707. }
  11708. STPUTC(pc, pout);
  11709. }
  11710. done:
  11711. STPUTC('\0', pout);
  11712. psavelen = pout - (char *)stackblock();
  11713. if (psavelen > 0) {
  11714. pstr = grabstackstr(pout);
  11715. setinputstring(pstr);
  11716. }
  11717. }
  11718. nlpp = &bqlist;
  11719. while (*nlpp)
  11720. nlpp = &(*nlpp)->next;
  11721. *nlpp = stzalloc(sizeof(**nlpp));
  11722. /* (*nlpp)->next = NULL; - stzalloc did it */
  11723. saveheredoclist = heredoclist;
  11724. heredoclist = NULL;
  11725. if (oldstyle) {
  11726. saveprompt = doprompt;
  11727. doprompt = 0;
  11728. }
  11729. n = list(2);
  11730. if (oldstyle)
  11731. doprompt = saveprompt;
  11732. else {
  11733. if (readtoken() != TRP)
  11734. raise_error_unexpected_syntax(TRP);
  11735. setinputstring(nullstr);
  11736. }
  11737. parseheredoc();
  11738. heredoclist = saveheredoclist;
  11739. (*nlpp)->n = n;
  11740. /* Start reading from old file again. */
  11741. popfile();
  11742. /* Ignore any pushed back tokens left from the backquote parsing. */
  11743. if (oldstyle)
  11744. tokpushback = 0;
  11745. out = growstackto(savelen + 1);
  11746. if (str) {
  11747. memcpy(out, str, savelen);
  11748. STADJUST(savelen, out);
  11749. }
  11750. USTPUTC(CTLBACKQ, out);
  11751. if (oldstyle)
  11752. goto parsebackq_oldreturn;
  11753. goto parsebackq_newreturn;
  11754. }
  11755. #if ENABLE_FEATURE_SH_MATH
  11756. /*
  11757. * Parse an arithmetic expansion (indicate start of one and set state)
  11758. */
  11759. parsearith: {
  11760. synstack_push(&synstack,
  11761. synstack->prev ?: alloca(sizeof(*synstack)),
  11762. ARISYNTAX);
  11763. synstack->dblquote = 1;
  11764. USTPUTC(CTLARI, out);
  11765. goto parsearith_return;
  11766. }
  11767. #endif
  11768. } /* end of readtoken */
  11769. /*
  11770. * Read the next input token.
  11771. * If the token is a word, we set backquotelist to the list of cmds in
  11772. * backquotes. We set quoteflag to true if any part of the word was
  11773. * quoted.
  11774. * If the token is TREDIR, then we set redirnode to a structure containing
  11775. * the redirection.
  11776. *
  11777. * [Change comment: here documents and internal procedures]
  11778. * [Readtoken shouldn't have any arguments. Perhaps we should make the
  11779. * word parsing code into a separate routine. In this case, readtoken
  11780. * doesn't need to have any internal procedures, but parseword does.
  11781. * We could also make parseoperator in essence the main routine, and
  11782. * have parseword (readtoken1?) handle both words and redirection.]
  11783. */
  11784. #define NEW_xxreadtoken
  11785. #ifdef NEW_xxreadtoken
  11786. /* singles must be first! */
  11787. static const char xxreadtoken_chars[7] ALIGN1 = {
  11788. '\n', '(', ')', /* singles */
  11789. '&', '|', ';', /* doubles */
  11790. 0
  11791. };
  11792. #define xxreadtoken_singles 3
  11793. #define xxreadtoken_doubles 3
  11794. static const char xxreadtoken_tokens[] ALIGN1 = {
  11795. TNL, TLP, TRP, /* only single occurrence allowed */
  11796. TBACKGND, TPIPE, TSEMI, /* if single occurrence */
  11797. TEOF, /* corresponds to trailing nul */
  11798. TAND, TOR, TENDCASE /* if double occurrence */
  11799. };
  11800. static int
  11801. xxreadtoken(void)
  11802. {
  11803. int c;
  11804. if (tokpushback) {
  11805. tokpushback = 0;
  11806. return lasttoken;
  11807. }
  11808. setprompt_if(needprompt, 2);
  11809. for (;;) { /* until token or start of word found */
  11810. c = pgetc_eatbnl();
  11811. if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
  11812. continue;
  11813. if (c == '#') {
  11814. while ((c = pgetc()) != '\n' && c != PEOF)
  11815. continue;
  11816. pungetc();
  11817. } else if (c == '\\') {
  11818. break; /* return readtoken1(...) */
  11819. } else {
  11820. const char *p;
  11821. p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
  11822. if (c != PEOF) {
  11823. if (c == '\n') {
  11824. nlnoprompt();
  11825. }
  11826. p = strchr(xxreadtoken_chars, c);
  11827. if (p == NULL)
  11828. break; /* return readtoken1(...) */
  11829. if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
  11830. int cc = pgetc_eatbnl();
  11831. if (cc == c) { /* double occurrence? */
  11832. p += xxreadtoken_doubles + 1;
  11833. } else {
  11834. pungetc();
  11835. #if BASH_REDIR_OUTPUT
  11836. if (c == '&' && cc == '>') /* &> */
  11837. break; /* return readtoken1(...) */
  11838. #endif
  11839. }
  11840. }
  11841. }
  11842. lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
  11843. return lasttoken;
  11844. }
  11845. } /* for (;;) */
  11846. return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
  11847. }
  11848. #else /* old xxreadtoken */
  11849. #define RETURN(token) return lasttoken = token
  11850. static int
  11851. xxreadtoken(void)
  11852. {
  11853. int c;
  11854. if (tokpushback) {
  11855. tokpushback = 0;
  11856. return lasttoken;
  11857. }
  11858. setprompt_if(needprompt, 2);
  11859. for (;;) { /* until token or start of word found */
  11860. c = pgetc_eatbnl();
  11861. switch (c) {
  11862. case ' ': case '\t':
  11863. IF_ASH_ALIAS(case PEOA:)
  11864. continue;
  11865. case '#':
  11866. while ((c = pgetc()) != '\n' && c != PEOF)
  11867. continue;
  11868. pungetc();
  11869. continue;
  11870. case '\n':
  11871. nlnoprompt();
  11872. RETURN(TNL);
  11873. case PEOF:
  11874. RETURN(TEOF);
  11875. case '&':
  11876. if (pgetc_eatbnl() == '&')
  11877. RETURN(TAND);
  11878. pungetc();
  11879. RETURN(TBACKGND);
  11880. case '|':
  11881. if (pgetc_eatbnl() == '|')
  11882. RETURN(TOR);
  11883. pungetc();
  11884. RETURN(TPIPE);
  11885. case ';':
  11886. if (pgetc_eatbnl() == ';')
  11887. RETURN(TENDCASE);
  11888. pungetc();
  11889. RETURN(TSEMI);
  11890. case '(':
  11891. RETURN(TLP);
  11892. case ')':
  11893. RETURN(TRP);
  11894. }
  11895. break;
  11896. }
  11897. return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
  11898. #undef RETURN
  11899. }
  11900. #endif /* old xxreadtoken */
  11901. static int
  11902. readtoken(void)
  11903. {
  11904. int t;
  11905. int kwd = checkkwd;
  11906. #if DEBUG
  11907. smallint alreadyseen = tokpushback;
  11908. #endif
  11909. #if ENABLE_ASH_ALIAS
  11910. top:
  11911. #endif
  11912. t = xxreadtoken();
  11913. /*
  11914. * eat newlines
  11915. */
  11916. if (kwd & CHKNL) {
  11917. while (t == TNL) {
  11918. parseheredoc();
  11919. t = xxreadtoken();
  11920. }
  11921. }
  11922. if (t != TWORD || quoteflag) {
  11923. goto out;
  11924. }
  11925. /*
  11926. * check for keywords
  11927. */
  11928. if (kwd & CHKKWD) {
  11929. const char *const *pp;
  11930. pp = findkwd(wordtext);
  11931. if (pp) {
  11932. lasttoken = t = pp - tokname_array;
  11933. TRACE(("keyword '%s' recognized\n", tokname_array[t]));
  11934. goto out;
  11935. }
  11936. }
  11937. if (checkkwd & CHKALIAS) {
  11938. #if ENABLE_ASH_ALIAS
  11939. struct alias *ap;
  11940. ap = lookupalias(wordtext, 1);
  11941. if (ap != NULL) {
  11942. if (*ap->val) {
  11943. pushstring(ap->val, ap);
  11944. }
  11945. goto top;
  11946. }
  11947. #endif
  11948. }
  11949. out:
  11950. checkkwd = 0;
  11951. #if DEBUG
  11952. if (!alreadyseen)
  11953. TRACE(("token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
  11954. else
  11955. TRACE(("reread token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
  11956. #endif
  11957. return t;
  11958. }
  11959. static int
  11960. peektoken(void)
  11961. {
  11962. int t;
  11963. t = readtoken();
  11964. tokpushback = 1;
  11965. return t;
  11966. }
  11967. /*
  11968. * Read and parse a command. Returns NODE_EOF on end of file.
  11969. * (NULL is a valid parse tree indicating a blank line.)
  11970. */
  11971. static union node *
  11972. parsecmd(int interact)
  11973. {
  11974. tokpushback = 0;
  11975. checkkwd = 0;
  11976. heredoclist = 0;
  11977. doprompt = interact;
  11978. setprompt_if(doprompt, doprompt);
  11979. needprompt = 0;
  11980. return list(1);
  11981. }
  11982. /*
  11983. * Input any here documents.
  11984. */
  11985. static void
  11986. parseheredoc(void)
  11987. {
  11988. struct heredoc *here;
  11989. union node *n;
  11990. here = heredoclist;
  11991. heredoclist = NULL;
  11992. while (here) {
  11993. tokpushback = 0;
  11994. setprompt_if(needprompt, 2);
  11995. if (here->here->type == NHERE)
  11996. readtoken1(pgetc(), SQSYNTAX, here->eofmark, here->striptabs);
  11997. else
  11998. readtoken1(pgetc_eatbnl(), DQSYNTAX, here->eofmark, here->striptabs);
  11999. n = stzalloc(sizeof(struct narg));
  12000. n->narg.type = NARG;
  12001. /*n->narg.next = NULL; - stzalloc did it */
  12002. n->narg.text = wordtext;
  12003. n->narg.backquote = backquotelist;
  12004. here->here->nhere.doc = n;
  12005. here = here->next;
  12006. }
  12007. }
  12008. static const char *
  12009. expandstr(const char *ps, int syntax_type)
  12010. {
  12011. union node n;
  12012. int saveprompt;
  12013. struct parsefile *file_stop = g_parsefile;
  12014. volatile int saveint;
  12015. struct jmploc *volatile savehandler = exception_handler;
  12016. struct jmploc jmploc;
  12017. const char *volatile result;
  12018. int err;
  12019. /* XXX Fix (char *) cast. */
  12020. setinputstring((char *)ps);
  12021. saveprompt = doprompt;
  12022. doprompt = 0;
  12023. result = ps;
  12024. SAVE_INT(saveint);
  12025. err = setjmp(jmploc.loc);
  12026. if (err)
  12027. goto out;
  12028. /* readtoken1() might die horribly.
  12029. * Try a prompt with syntactically wrong command:
  12030. * PS1='$(date "+%H:%M:%S) > '
  12031. */
  12032. exception_handler = &jmploc;
  12033. readtoken1(pgetc(), syntax_type, FAKEEOFMARK, 0);
  12034. n.narg.type = NARG;
  12035. n.narg.next = NULL;
  12036. n.narg.text = wordtext;
  12037. n.narg.backquote = backquotelist;
  12038. /* expandarg() might fail too:
  12039. * PS1='$((123+))'
  12040. */
  12041. expandarg(&n, NULL, EXP_QUOTED);
  12042. result = stackblock();
  12043. out:
  12044. exception_handler = savehandler;
  12045. if (err && exception_type != EXERROR)
  12046. longjmp(exception_handler->loc, 1);
  12047. RESTORE_INT(saveint);
  12048. doprompt = saveprompt;
  12049. /* Try: PS1='`xxx(`' */
  12050. unwindfiles(file_stop);
  12051. return result;
  12052. }
  12053. static inline int
  12054. parser_eof(void)
  12055. {
  12056. return tokpushback && lasttoken == TEOF;
  12057. }
  12058. /*
  12059. * Execute a command or commands contained in a string.
  12060. */
  12061. static int
  12062. evalstring(char *s, int flags)
  12063. {
  12064. struct jmploc *volatile savehandler;
  12065. struct jmploc jmploc;
  12066. int ex;
  12067. union node *n;
  12068. struct stackmark smark;
  12069. int status;
  12070. s = sstrdup(s);
  12071. setinputstring(s);
  12072. setstackmark(&smark);
  12073. status = 0;
  12074. /* On exception inside execution loop, we must popfile().
  12075. * Try interactively:
  12076. * readonly a=a
  12077. * command eval "a=b" # throws "is read only" error
  12078. * "command BLTIN" is not supposed to abort (even in non-interactive use).
  12079. * But if we skip popfile(), we hit EOF in eval's string, and exit.
  12080. */
  12081. savehandler = exception_handler;
  12082. ex = setjmp(jmploc.loc);
  12083. if (ex)
  12084. goto out;
  12085. exception_handler = &jmploc;
  12086. while ((n = parsecmd(0)) != NODE_EOF) {
  12087. int i;
  12088. i = evaltree(n, flags & ~(parser_eof() ? 0 : EV_EXIT));
  12089. if (n)
  12090. status = i;
  12091. popstackmark(&smark);
  12092. if (evalskip)
  12093. break;
  12094. }
  12095. out:
  12096. popstackmark(&smark);
  12097. popfile();
  12098. stunalloc(s);
  12099. exception_handler = savehandler;
  12100. if (ex)
  12101. longjmp(exception_handler->loc, ex);
  12102. return status;
  12103. }
  12104. /*
  12105. * The eval command.
  12106. */
  12107. static int FAST_FUNC
  12108. evalcmd(int argc UNUSED_PARAM, char **argv, int flags)
  12109. {
  12110. char *p;
  12111. char *concat;
  12112. if (argv[1]) {
  12113. p = argv[1];
  12114. argv += 2;
  12115. if (argv[0]) {
  12116. STARTSTACKSTR(concat);
  12117. for (;;) {
  12118. concat = stack_putstr(p, concat);
  12119. p = *argv++;
  12120. if (p == NULL)
  12121. break;
  12122. STPUTC(' ', concat);
  12123. }
  12124. STPUTC('\0', concat);
  12125. p = grabstackstr(concat);
  12126. }
  12127. return evalstring(p, flags & EV_TESTED);
  12128. }
  12129. return 0;
  12130. }
  12131. /*
  12132. * Read and execute commands.
  12133. * "Top" is nonzero for the top level command loop;
  12134. * it turns on prompting if the shell is interactive.
  12135. */
  12136. static int
  12137. cmdloop(int top)
  12138. {
  12139. union node *n;
  12140. struct stackmark smark;
  12141. int inter;
  12142. int status = 0;
  12143. int numeof = 0;
  12144. TRACE(("cmdloop(%d) called\n", top));
  12145. for (;;) {
  12146. int skip;
  12147. setstackmark(&smark);
  12148. #if JOBS
  12149. if (doing_jobctl)
  12150. showjobs(SHOW_CHANGED|SHOW_STDERR);
  12151. #endif
  12152. inter = 0;
  12153. if (iflag && top) {
  12154. inter++;
  12155. chkmail();
  12156. }
  12157. n = parsecmd(inter);
  12158. #if DEBUG
  12159. if (DEBUG > 2 && debug && (n != NODE_EOF))
  12160. showtree(n);
  12161. #endif
  12162. if (n == NODE_EOF) {
  12163. if (!top || numeof >= 50)
  12164. break;
  12165. if (!stoppedjobs()) {
  12166. if (!Iflag) {
  12167. if (iflag) {
  12168. newline_and_flush(stderr);
  12169. }
  12170. break;
  12171. }
  12172. out2str("\nUse \"exit\" to leave shell.\n");
  12173. }
  12174. numeof++;
  12175. } else if (nflag == 0) {
  12176. int i;
  12177. /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
  12178. job_warning >>= 1;
  12179. numeof = 0;
  12180. i = evaltree(n, 0);
  12181. if (n)
  12182. status = i;
  12183. }
  12184. popstackmark(&smark);
  12185. skip = evalskip;
  12186. if (skip) {
  12187. evalskip &= ~(SKIPFUNC | SKIPFUNCDEF);
  12188. break;
  12189. }
  12190. }
  12191. return status;
  12192. }
  12193. /*
  12194. * Take commands from a file. To be compatible we should do a path
  12195. * search for the file, which is necessary to find sub-commands.
  12196. */
  12197. static char *
  12198. find_dot_file(char *basename)
  12199. {
  12200. char *fullname;
  12201. const char *path = pathval();
  12202. struct stat statb;
  12203. int len;
  12204. /* don't try this for absolute or relative paths */
  12205. if (strchr(basename, '/'))
  12206. return basename;
  12207. while ((len = padvance(&path, basename)) >= 0) {
  12208. fullname = stackblock();
  12209. if ((!pathopt || *pathopt == 'f')
  12210. && !stat(fullname, &statb) && S_ISREG(statb.st_mode)
  12211. ) {
  12212. /* This will be freed by the caller. */
  12213. return stalloc(len);
  12214. }
  12215. }
  12216. /* not found in PATH */
  12217. #if ENABLE_ASH_BASH_SOURCE_CURDIR
  12218. return basename;
  12219. #else
  12220. ash_msg_and_raise_error("%s: not found", basename);
  12221. /* NOTREACHED */
  12222. #endif
  12223. }
  12224. static int FAST_FUNC
  12225. dotcmd(int argc_ UNUSED_PARAM, char **argv_ UNUSED_PARAM)
  12226. {
  12227. /* "false; . empty_file; echo $?" should print 0, not 1: */
  12228. int status = 0;
  12229. char *fullname;
  12230. char **argv;
  12231. char *args_need_save;
  12232. volatile struct shparam saveparam;
  12233. //???
  12234. // struct strlist *sp;
  12235. // for (sp = cmdenviron; sp; sp = sp->next)
  12236. // setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
  12237. nextopt(nullstr); /* handle possible "--" */
  12238. argv = argptr;
  12239. if (!argv[0]) {
  12240. /* bash says: "bash: .: filename argument required" */
  12241. return 2; /* bash compat */
  12242. }
  12243. /* This aborts if file isn't found, which is POSIXly correct.
  12244. * bash returns exitcode 1 instead.
  12245. */
  12246. fullname = find_dot_file(argv[0]);
  12247. argv++;
  12248. args_need_save = argv[0];
  12249. if (args_need_save) { /* ". FILE ARGS", and ARGS are not empty */
  12250. int argc;
  12251. saveparam = shellparam;
  12252. shellparam.malloced = 0;
  12253. argc = 1;
  12254. while (argv[argc])
  12255. argc++;
  12256. shellparam.nparam = argc;
  12257. shellparam.p = argv;
  12258. };
  12259. /* This aborts if file can't be opened, which is POSIXly correct.
  12260. * bash returns exitcode 1 instead.
  12261. */
  12262. setinputfile(fullname, INPUT_PUSH_FILE);
  12263. commandname = fullname;
  12264. status = cmdloop(0);
  12265. popfile();
  12266. if (args_need_save) {
  12267. freeparam(&shellparam);
  12268. shellparam = saveparam;
  12269. };
  12270. return status;
  12271. }
  12272. static int FAST_FUNC
  12273. exitcmd(int argc UNUSED_PARAM, char **argv)
  12274. {
  12275. if (stoppedjobs())
  12276. return 0;
  12277. if (argv[1])
  12278. savestatus = number(argv[1]);
  12279. raise_exception(EXEXIT);
  12280. /* NOTREACHED */
  12281. }
  12282. /*
  12283. * Read a file containing shell functions.
  12284. */
  12285. static void
  12286. readcmdfile(char *name)
  12287. {
  12288. setinputfile(name, INPUT_PUSH_FILE);
  12289. cmdloop(0);
  12290. popfile();
  12291. }
  12292. /* ============ find_command inplementation */
  12293. /*
  12294. * Resolve a command name. If you change this routine, you may have to
  12295. * change the shellexec routine as well.
  12296. */
  12297. static void
  12298. find_command(char *name, struct cmdentry *entry, int act, const char *path)
  12299. {
  12300. struct tblentry *cmdp;
  12301. int idx;
  12302. int prev;
  12303. char *fullname;
  12304. struct stat statb;
  12305. int e;
  12306. int updatetbl;
  12307. struct builtincmd *bcmd;
  12308. int len;
  12309. /* If name contains a slash, don't use PATH or hash table */
  12310. if (strchr(name, '/') != NULL) {
  12311. entry->u.index = -1;
  12312. if (act & DO_ABS) {
  12313. while (stat(name, &statb) < 0) {
  12314. #ifdef SYSV
  12315. if (errno == EINTR)
  12316. continue;
  12317. #endif
  12318. entry->cmdtype = CMDUNKNOWN;
  12319. return;
  12320. }
  12321. }
  12322. entry->cmdtype = CMDNORMAL;
  12323. return;
  12324. }
  12325. /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
  12326. updatetbl = (path == pathval());
  12327. if (!updatetbl)
  12328. act |= DO_ALTPATH;
  12329. /* If name is in the table, check answer will be ok */
  12330. cmdp = cmdlookup(name, 0);
  12331. if (cmdp != NULL) {
  12332. int bit;
  12333. switch (cmdp->cmdtype) {
  12334. default:
  12335. #if DEBUG
  12336. abort();
  12337. #endif
  12338. case CMDNORMAL:
  12339. bit = DO_ALTPATH | DO_REGBLTIN;
  12340. break;
  12341. case CMDFUNCTION:
  12342. bit = DO_NOFUNC;
  12343. break;
  12344. case CMDBUILTIN:
  12345. bit = IS_BUILTIN_REGULAR(cmdp->param.cmd) ? 0 : DO_REGBLTIN;
  12346. break;
  12347. }
  12348. if (act & bit) {
  12349. if (act & bit & DO_REGBLTIN)
  12350. goto fail;
  12351. updatetbl = 0;
  12352. cmdp = NULL;
  12353. } else if (cmdp->rehash == 0)
  12354. /* if not invalidated by cd, we're done */
  12355. goto success;
  12356. }
  12357. /* If %builtin not in path, check for builtin next */
  12358. bcmd = find_builtin(name);
  12359. if (bcmd) {
  12360. if (IS_BUILTIN_REGULAR(bcmd))
  12361. goto builtin_success;
  12362. if (act & DO_ALTPATH)
  12363. goto builtin_success;
  12364. if (builtinloc <= 0)
  12365. goto builtin_success;
  12366. }
  12367. if (act & DO_REGBLTIN)
  12368. goto fail;
  12369. #if ENABLE_FEATURE_SH_STANDALONE
  12370. {
  12371. int applet_no = find_applet_by_name(name);
  12372. if (applet_no >= 0) {
  12373. entry->cmdtype = CMDNORMAL;
  12374. entry->u.index = -2 - applet_no;
  12375. return;
  12376. }
  12377. }
  12378. #endif
  12379. /* We have to search path. */
  12380. prev = -1; /* where to start */
  12381. if (cmdp && cmdp->rehash) { /* doing a rehash */
  12382. if (cmdp->cmdtype == CMDBUILTIN)
  12383. prev = builtinloc;
  12384. else
  12385. prev = cmdp->param.index;
  12386. }
  12387. e = ENOENT;
  12388. idx = -1;
  12389. loop:
  12390. while ((len = padvance(&path, name)) >= 0) {
  12391. const char *lpathopt = pathopt;
  12392. fullname = stackblock();
  12393. idx++;
  12394. if (lpathopt) {
  12395. if (*lpathopt == 'b') {
  12396. if (bcmd)
  12397. goto builtin_success;
  12398. continue;
  12399. } else if (!(act & DO_NOFUNC)) {
  12400. /* handled below */
  12401. } else {
  12402. /* ignore unimplemented options */
  12403. continue;
  12404. }
  12405. }
  12406. /* if rehash, don't redo absolute path names */
  12407. if (fullname[0] == '/' && idx <= prev) {
  12408. if (idx < prev)
  12409. continue;
  12410. TRACE(("searchexec \"%s\": no change\n", name));
  12411. goto success;
  12412. }
  12413. while (stat(fullname, &statb) < 0) {
  12414. #ifdef SYSV
  12415. if (errno == EINTR)
  12416. continue;
  12417. #endif
  12418. if (errno != ENOENT && errno != ENOTDIR)
  12419. e = errno;
  12420. goto loop;
  12421. }
  12422. e = EACCES; /* if we fail, this will be the error */
  12423. if (!S_ISREG(statb.st_mode))
  12424. continue;
  12425. if (lpathopt) { /* this is a %func directory */
  12426. stalloc(len);
  12427. /* NB: stalloc will return space pointed by fullname
  12428. * (because we don't have any intervening allocations
  12429. * between stunalloc above and this stalloc) */
  12430. readcmdfile(fullname);
  12431. cmdp = cmdlookup(name, 0);
  12432. if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
  12433. ash_msg_and_raise_error("%s not defined in %s", name, fullname);
  12434. stunalloc(fullname);
  12435. goto success;
  12436. }
  12437. TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
  12438. if (!updatetbl) {
  12439. entry->cmdtype = CMDNORMAL;
  12440. entry->u.index = idx;
  12441. return;
  12442. }
  12443. INT_OFF;
  12444. cmdp = cmdlookup(name, 1);
  12445. cmdp->cmdtype = CMDNORMAL;
  12446. cmdp->param.index = idx;
  12447. INT_ON;
  12448. goto success;
  12449. }
  12450. /* We failed. If there was an entry for this command, delete it */
  12451. if (cmdp && updatetbl)
  12452. delete_cmd_entry();
  12453. if (act & DO_ERR) {
  12454. #if ENABLE_ASH_BASH_NOT_FOUND_HOOK
  12455. struct tblentry *hookp = cmdlookup("command_not_found_handle", 0);
  12456. if (hookp && hookp->cmdtype == CMDFUNCTION) {
  12457. char *argv[3];
  12458. argv[0] = (char*) "command_not_found_handle";
  12459. argv[1] = name;
  12460. argv[2] = NULL;
  12461. evalfun(hookp->param.func, 2, argv, 0);
  12462. entry->cmdtype = CMDUNKNOWN;
  12463. return;
  12464. }
  12465. #endif
  12466. ash_msg("%s: %s", name, errmsg(e, "not found"));
  12467. }
  12468. fail:
  12469. entry->cmdtype = CMDUNKNOWN;
  12470. return;
  12471. builtin_success:
  12472. if (!updatetbl) {
  12473. entry->cmdtype = CMDBUILTIN;
  12474. entry->u.cmd = bcmd;
  12475. return;
  12476. }
  12477. INT_OFF;
  12478. cmdp = cmdlookup(name, 1);
  12479. cmdp->cmdtype = CMDBUILTIN;
  12480. cmdp->param.cmd = bcmd;
  12481. INT_ON;
  12482. success:
  12483. cmdp->rehash = 0;
  12484. entry->cmdtype = cmdp->cmdtype;
  12485. entry->u = cmdp->param;
  12486. }
  12487. /*
  12488. * The trap builtin.
  12489. */
  12490. static int FAST_FUNC
  12491. trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  12492. {
  12493. char *action;
  12494. char **ap;
  12495. int signo, exitcode;
  12496. nextopt(nullstr);
  12497. ap = argptr;
  12498. if (!*ap) {
  12499. for (signo = 0; signo < NSIG; signo++) {
  12500. char *tr = trap_ptr[signo];
  12501. if (tr) {
  12502. /* note: bash adds "SIG", but only if invoked
  12503. * as "bash". If called as "sh", or if set -o posix,
  12504. * then it prints short signal names.
  12505. * We are printing short names: */
  12506. out1fmt("trap -- %s %s\n",
  12507. single_quote(tr),
  12508. get_signame(signo));
  12509. /* trap_ptr != trap only if we are in special-cased `trap` code.
  12510. * In this case, we will exit very soon, no need to free(). */
  12511. /* if (trap_ptr != trap && tp[0]) */
  12512. /* free(tr); */
  12513. }
  12514. }
  12515. /*
  12516. if (trap_ptr != trap) {
  12517. free(trap_ptr);
  12518. trap_ptr = trap;
  12519. }
  12520. */
  12521. return 0;
  12522. }
  12523. /* Why the second check?
  12524. * "trap NUM [sig2]..." is the same as "trap - NUM [sig2]..."
  12525. * In this case, NUM is signal no, not an action.
  12526. */
  12527. action = NULL;
  12528. if (ap[1] && !is_number(ap[0]))
  12529. action = *ap++;
  12530. exitcode = 0;
  12531. while (*ap) {
  12532. signo = get_signum(*ap);
  12533. if (signo < 0) {
  12534. /* Mimic bash message exactly */
  12535. ash_msg("%s: invalid signal specification", *ap);
  12536. exitcode = 1;
  12537. goto next;
  12538. }
  12539. INT_OFF;
  12540. if (action) {
  12541. if (LONE_DASH(action))
  12542. action = NULL;
  12543. else {
  12544. if (action[0]) /* not NULL and not "" and not "-" */
  12545. may_have_traps = 1;
  12546. action = ckstrdup(action);
  12547. }
  12548. }
  12549. free(trap[signo]);
  12550. trap[signo] = action;
  12551. if (signo != 0)
  12552. setsignal(signo);
  12553. INT_ON;
  12554. next:
  12555. ap++;
  12556. }
  12557. return exitcode;
  12558. }
  12559. /* ============ Builtins */
  12560. #if ENABLE_ASH_HELP
  12561. static int FAST_FUNC
  12562. helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  12563. {
  12564. unsigned col;
  12565. unsigned i;
  12566. out1fmt(
  12567. "Built-in commands:\n"
  12568. "------------------\n");
  12569. for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
  12570. col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
  12571. builtintab[i].name + 1);
  12572. if (col > 60) {
  12573. out1fmt("\n");
  12574. col = 0;
  12575. }
  12576. }
  12577. # if ENABLE_FEATURE_SH_STANDALONE
  12578. {
  12579. const char *a = applet_names;
  12580. while (*a) {
  12581. col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
  12582. if (col > 60) {
  12583. out1fmt("\n");
  12584. col = 0;
  12585. }
  12586. while (*a++ != '\0')
  12587. continue;
  12588. }
  12589. }
  12590. # endif
  12591. newline_and_flush(stdout);
  12592. return EXIT_SUCCESS;
  12593. }
  12594. #endif
  12595. #if MAX_HISTORY
  12596. static int FAST_FUNC
  12597. historycmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  12598. {
  12599. if (line_input_state)
  12600. show_history(line_input_state);
  12601. return EXIT_SUCCESS;
  12602. }
  12603. #endif
  12604. /*
  12605. * The export and readonly commands.
  12606. */
  12607. static int FAST_FUNC
  12608. exportcmd(int argc UNUSED_PARAM, char **argv)
  12609. {
  12610. struct var *vp;
  12611. char *name;
  12612. const char *p;
  12613. char **aptr;
  12614. char opt;
  12615. int flag;
  12616. int flag_off;
  12617. /* "readonly" in bash accepts, but ignores -n.
  12618. * We do the same: it saves a conditional in nextopt's param.
  12619. */
  12620. flag_off = 0;
  12621. while ((opt = nextopt("np")) != '\0') {
  12622. if (opt == 'n')
  12623. flag_off = VEXPORT;
  12624. }
  12625. flag = VEXPORT;
  12626. if (argv[0][0] == 'r') {
  12627. flag = VREADONLY;
  12628. flag_off = 0; /* readonly ignores -n */
  12629. }
  12630. flag_off = ~flag_off;
  12631. /*if (opt_p_not_specified) - bash doesn't check this. Try "export -p NAME" */
  12632. {
  12633. aptr = argptr;
  12634. name = *aptr;
  12635. if (name) {
  12636. do {
  12637. p = strchr(name, '=');
  12638. if (p != NULL) {
  12639. p++;
  12640. } else {
  12641. vp = *findvar(hashvar(name), name);
  12642. if (vp) {
  12643. vp->flags = ((vp->flags | flag) & flag_off);
  12644. continue;
  12645. }
  12646. }
  12647. setvar(name, p, (flag & flag_off));
  12648. } while ((name = *++aptr) != NULL);
  12649. return 0;
  12650. }
  12651. }
  12652. /* No arguments. Show the list of exported or readonly vars.
  12653. * -n is ignored.
  12654. */
  12655. showvars(argv[0], flag, 0);
  12656. return 0;
  12657. }
  12658. /*
  12659. * Delete a function if it exists.
  12660. */
  12661. static void
  12662. unsetfunc(const char *name)
  12663. {
  12664. struct tblentry *cmdp;
  12665. cmdp = cmdlookup(name, 0);
  12666. if (cmdp != NULL && cmdp->cmdtype == CMDFUNCTION)
  12667. delete_cmd_entry();
  12668. }
  12669. /*
  12670. * The unset builtin command. We unset the function before we unset the
  12671. * variable to allow a function to be unset when there is a readonly variable
  12672. * with the same name.
  12673. */
  12674. static int FAST_FUNC
  12675. unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  12676. {
  12677. char **ap;
  12678. int i;
  12679. int flag = 0;
  12680. while ((i = nextopt("vf")) != 0) {
  12681. flag = i;
  12682. }
  12683. for (ap = argptr; *ap; ap++) {
  12684. if (flag != 'f') {
  12685. unsetvar(*ap);
  12686. continue;
  12687. }
  12688. if (flag != 'v')
  12689. unsetfunc(*ap);
  12690. }
  12691. return 0;
  12692. }
  12693. static const unsigned char timescmd_str[] ALIGN1 = {
  12694. ' ', offsetof(struct tms, tms_utime),
  12695. '\n', offsetof(struct tms, tms_stime),
  12696. ' ', offsetof(struct tms, tms_cutime),
  12697. '\n', offsetof(struct tms, tms_cstime),
  12698. 0
  12699. };
  12700. static int FAST_FUNC
  12701. timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  12702. {
  12703. unsigned clk_tck;
  12704. const unsigned char *p;
  12705. struct tms buf;
  12706. clk_tck = bb_clk_tck();
  12707. times(&buf);
  12708. p = timescmd_str;
  12709. do {
  12710. unsigned sec, frac;
  12711. unsigned long t;
  12712. t = *(clock_t *)(((char *) &buf) + p[1]);
  12713. sec = t / clk_tck;
  12714. frac = t % clk_tck;
  12715. out1fmt("%um%u.%03us%c",
  12716. sec / 60, sec % 60,
  12717. (frac * 1000) / clk_tck,
  12718. p[0]);
  12719. p += 2;
  12720. } while (*p);
  12721. return 0;
  12722. }
  12723. #if ENABLE_FEATURE_SH_MATH
  12724. /*
  12725. * The let builtin. Partially stolen from GNU Bash, the Bourne Again SHell.
  12726. * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
  12727. *
  12728. * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
  12729. */
  12730. static int FAST_FUNC
  12731. letcmd(int argc UNUSED_PARAM, char **argv)
  12732. {
  12733. arith_t i;
  12734. argv++;
  12735. if (!*argv)
  12736. ash_msg_and_raise_error("expression expected");
  12737. do {
  12738. i = ash_arith(*argv);
  12739. } while (*++argv);
  12740. return !i;
  12741. }
  12742. #endif
  12743. /*
  12744. * The read builtin. Options:
  12745. * -r Do not interpret '\' specially
  12746. * -s Turn off echo (tty only)
  12747. * -n NCHARS Read NCHARS max
  12748. * -p PROMPT Display PROMPT on stderr (if input is from tty)
  12749. * -t SECONDS Timeout after SECONDS (tty or pipe only)
  12750. * -u FD Read from given FD instead of fd 0
  12751. * -d DELIM End on DELIM char, not newline
  12752. * This uses unbuffered input, which may be avoidable in some cases.
  12753. * TODO: bash also has:
  12754. * -a ARRAY Read into array[0],[1],etc
  12755. * -e Use line editing (tty only)
  12756. */
  12757. static int FAST_FUNC
  12758. readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  12759. {
  12760. struct builtin_read_params params;
  12761. const char *r;
  12762. int i;
  12763. memset(&params, 0, sizeof(params));
  12764. while ((i = nextopt("p:u:rt:n:sd:")) != '\0') {
  12765. switch (i) {
  12766. case 'p':
  12767. params.opt_p = optionarg;
  12768. break;
  12769. case 'n':
  12770. params.opt_n = optionarg;
  12771. break;
  12772. case 's':
  12773. params.read_flags |= BUILTIN_READ_SILENT;
  12774. break;
  12775. case 't':
  12776. params.opt_t = optionarg;
  12777. break;
  12778. case 'r':
  12779. params.read_flags |= BUILTIN_READ_RAW;
  12780. break;
  12781. case 'u':
  12782. params.opt_u = optionarg;
  12783. break;
  12784. #if BASH_READ_D
  12785. case 'd':
  12786. params.opt_d = optionarg;
  12787. break;
  12788. #endif
  12789. default:
  12790. break;
  12791. }
  12792. }
  12793. params.argv = argptr;
  12794. params.setvar = setvar0;
  12795. params.ifs = bltinlookup("IFS"); /* can be NULL */
  12796. /* "read -s" needs to save/restore termios, can't allow ^C
  12797. * to jump out of it.
  12798. */
  12799. again:
  12800. INT_OFF;
  12801. r = shell_builtin_read(&params);
  12802. INT_ON;
  12803. if ((uintptr_t)r == 1 && errno == EINTR) {
  12804. /* To get SIGCHLD: sleep 1 & read x; echo $x
  12805. * Correct behavior is to not exit "read"
  12806. */
  12807. if (pending_sig == 0)
  12808. goto again;
  12809. }
  12810. if ((uintptr_t)r > 1)
  12811. ash_msg_and_raise_error(r);
  12812. return (uintptr_t)r;
  12813. }
  12814. static int FAST_FUNC
  12815. umaskcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  12816. {
  12817. static const char permuser[3] ALIGN1 = "ogu";
  12818. mode_t mask;
  12819. int symbolic_mode = 0;
  12820. while (nextopt("S") != '\0') {
  12821. symbolic_mode = 1;
  12822. }
  12823. INT_OFF;
  12824. mask = umask(0);
  12825. umask(mask);
  12826. INT_ON;
  12827. if (*argptr == NULL) {
  12828. if (symbolic_mode) {
  12829. char buf[sizeof(",u=rwx,g=rwx,o=rwx")];
  12830. char *p = buf;
  12831. int i;
  12832. i = 2;
  12833. for (;;) {
  12834. *p++ = ',';
  12835. *p++ = permuser[i];
  12836. *p++ = '=';
  12837. /* mask is 0..0uuugggooo. i=2 selects uuu bits */
  12838. if (!(mask & 0400)) *p++ = 'r';
  12839. if (!(mask & 0200)) *p++ = 'w';
  12840. if (!(mask & 0100)) *p++ = 'x';
  12841. mask <<= 3;
  12842. if (--i < 0)
  12843. break;
  12844. }
  12845. *p = '\0';
  12846. puts(buf + 1);
  12847. } else {
  12848. out1fmt("%04o\n", mask);
  12849. }
  12850. } else {
  12851. char *modestr = *argptr;
  12852. /* numeric umasks are taken as-is */
  12853. /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
  12854. if (!isdigit(modestr[0]))
  12855. mask ^= 0777;
  12856. mask = bb_parse_mode(modestr, mask);
  12857. if ((unsigned)mask > 0777) {
  12858. ash_msg_and_raise_error("illegal mode: %s", modestr);
  12859. }
  12860. if (!isdigit(modestr[0]))
  12861. mask ^= 0777;
  12862. umask(mask);
  12863. }
  12864. return 0;
  12865. }
  12866. static int FAST_FUNC
  12867. ulimitcmd(int argc UNUSED_PARAM, char **argv)
  12868. {
  12869. return shell_builtin_ulimit(argv);
  12870. }
  12871. /* ============ main() and helpers */
  12872. /*
  12873. * This routine is called when an error or an interrupt occurs in an
  12874. * interactive shell and control is returned to the main command loop
  12875. * but prior to exitshell.
  12876. */
  12877. static void
  12878. exitreset(void)
  12879. {
  12880. /* from eval.c: */
  12881. if (savestatus >= 0) {
  12882. if (exception_type == EXEXIT || evalskip == SKIPFUNCDEF)
  12883. exitstatus = savestatus;
  12884. savestatus = -1;
  12885. }
  12886. evalskip = 0;
  12887. loopnest = 0;
  12888. /* from expand.c: */
  12889. ifsfree();
  12890. /* from redir.c: */
  12891. unwindredir(NULL);
  12892. }
  12893. /*
  12894. * This routine is called when an error or an interrupt occurs in an
  12895. * interactive shell and control is returned to the main command loop.
  12896. * (In dash, this function is auto-generated by build machinery).
  12897. */
  12898. static void
  12899. reset(void)
  12900. {
  12901. /* from input.c: */
  12902. g_parsefile->left_in_buffer = 0;
  12903. g_parsefile->left_in_line = 0; /* clear input buffer */
  12904. popallfiles();
  12905. /* from var.c: */
  12906. unwindlocalvars(NULL);
  12907. }
  12908. /*
  12909. * Called to exit the shell.
  12910. */
  12911. static void
  12912. exitshell(void)
  12913. {
  12914. struct jmploc loc;
  12915. char *p;
  12916. #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
  12917. if (line_input_state)
  12918. save_history(line_input_state);
  12919. #endif
  12920. savestatus = exitstatus;
  12921. TRACE(("pid %d, exitshell(%d)\n", getpid(), savestatus));
  12922. if (setjmp(loc.loc))
  12923. goto out;
  12924. exception_handler = &loc;
  12925. p = trap[0];
  12926. if (p) {
  12927. trap[0] = NULL;
  12928. evalskip = 0;
  12929. evalstring(p, 0);
  12930. evalskip = SKIPFUNCDEF;
  12931. /*free(p); - we'll exit soon */
  12932. }
  12933. out:
  12934. exitreset();
  12935. /* dash wraps setjobctl(0) in "if (setjmp(loc.loc) == 0) {...}".
  12936. * our setjobctl(0) does not panic if tcsetpgrp fails inside it.
  12937. */
  12938. setjobctl(0);
  12939. flush_stdout_stderr();
  12940. _exit(exitstatus);
  12941. /* NOTREACHED */
  12942. }
  12943. /* Don't inline: conserve stack of caller from having our locals too */
  12944. static NOINLINE void
  12945. init(void)
  12946. {
  12947. /* we will never free this */
  12948. basepf.next_to_pgetc = basepf.buf = ckmalloc(IBUFSIZ);
  12949. basepf.linno = 1;
  12950. sigmode[SIGCHLD - 1] = S_DFL; /* ensure we install handler even if it is SIG_IGNed */
  12951. setsignal(SIGCHLD);
  12952. {
  12953. char **envp;
  12954. const char *p;
  12955. initvar();
  12956. for (envp = environ; envp && *envp; envp++) {
  12957. /* Used to have
  12958. * p = endofname(*envp);
  12959. * if (p != *envp && *p == '=') {
  12960. * here to weed out badly-named variables, but this breaks
  12961. * scenarios where people do want them passed to children:
  12962. * import os
  12963. * os.environ["test-test"]="test"
  12964. * if os.fork() == 0:
  12965. * os.execv("ash", [ 'ash', '-c', 'eval $(export -p); echo OK' ]) # fixes this
  12966. * os.execv("ash", [ 'ash', '-c', 'env | grep test-test' ]) # breaks this
  12967. */
  12968. if (strchr(*envp, '=')) {
  12969. setvareq(*envp, VEXPORT|VTEXTFIXED);
  12970. }
  12971. }
  12972. setvareq((char*)defifsvar, VTEXTFIXED);
  12973. setvareq((char*)defoptindvar, VTEXTFIXED);
  12974. setvar0("PPID", utoa(getppid()));
  12975. #if BASH_SHLVL_VAR
  12976. p = lookupvar("SHLVL");
  12977. setvar("SHLVL", utoa((p ? atoi(p) : 0) + 1), VEXPORT);
  12978. #endif
  12979. #if BASH_HOSTNAME_VAR
  12980. if (!lookupvar("HOSTNAME")) {
  12981. struct utsname uts;
  12982. uname(&uts);
  12983. setvar0("HOSTNAME", uts.nodename);
  12984. }
  12985. #endif
  12986. p = lookupvar("PWD");
  12987. if (p) {
  12988. struct stat st1, st2;
  12989. if (p[0] != '/' || stat(p, &st1) || stat(".", &st2)
  12990. || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino
  12991. ) {
  12992. p = NULL;
  12993. }
  12994. }
  12995. setpwd(p, 0);
  12996. }
  12997. }
  12998. //usage:#define ash_trivial_usage
  12999. //usage: "[-/+OPTIONS] [-/+o OPT]... [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS] / -s [ARGS]]"
  13000. //usage:#define ash_full_usage "\n\n"
  13001. //usage: "Unix shell interpreter"
  13002. /*
  13003. * Process the shell command line arguments.
  13004. */
  13005. static int
  13006. procargs(char **argv)
  13007. {
  13008. int i;
  13009. const char *xminusc;
  13010. char **xargv;
  13011. int login_sh;
  13012. xargv = argv;
  13013. login_sh = xargv[0] && xargv[0][0] == '-';
  13014. #if NUM_SCRIPTS > 0
  13015. if (minusc)
  13016. goto setarg0;
  13017. #endif
  13018. arg0 = xargv[0];
  13019. /* if (xargv[0]) - mmm, this is always true! */
  13020. xargv++;
  13021. argptr = xargv;
  13022. for (i = 0; i < NOPTS; i++)
  13023. optlist[i] = 2;
  13024. if (options(&login_sh)) {
  13025. /* it already printed err message */
  13026. raise_exception(EXERROR);
  13027. }
  13028. xargv = argptr;
  13029. xminusc = minusc;
  13030. if (*xargv == NULL) {
  13031. if (xminusc)
  13032. ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
  13033. sflag = 1;
  13034. }
  13035. if (iflag == 2 /* no explicit -i given */
  13036. && sflag == 1 /* -s given (or implied) */
  13037. && !minusc /* bash compat: ash -sc 'echo $-' is not interactive (dash is) */
  13038. && isatty(0) && isatty(1) /* we are on tty */
  13039. ) {
  13040. iflag = 1;
  13041. }
  13042. if (mflag == 2)
  13043. mflag = iflag;
  13044. for (i = 0; i < NOPTS; i++)
  13045. if (optlist[i] == 2)
  13046. optlist[i] = 0;
  13047. #if DEBUG == 2
  13048. debug = 1;
  13049. #endif
  13050. /* POSIX 1003.2: first arg after "-c CMD" is $0, remainder $1... */
  13051. if (xminusc) {
  13052. minusc = *xargv++;
  13053. if (*xargv)
  13054. goto setarg0;
  13055. } else if (!sflag) {
  13056. setinputfile(*xargv, 0);
  13057. setarg0:
  13058. arg0 = *xargv++;
  13059. commandname = arg0;
  13060. }
  13061. shellparam.p = xargv;
  13062. #if ENABLE_ASH_GETOPTS
  13063. shellparam.optind = 1;
  13064. shellparam.optoff = -1;
  13065. #endif
  13066. /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
  13067. while (*xargv) {
  13068. shellparam.nparam++;
  13069. xargv++;
  13070. }
  13071. optschanged();
  13072. return login_sh;
  13073. }
  13074. /*
  13075. * Read /etc/profile, ~/.profile, $ENV.
  13076. */
  13077. static void
  13078. read_profile(const char *name)
  13079. {
  13080. name = expandstr(name, DQSYNTAX);
  13081. if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
  13082. return;
  13083. cmdloop(0);
  13084. popfile();
  13085. }
  13086. #if PROFILE
  13087. static short profile_buf[16384];
  13088. extern int etext();
  13089. #endif
  13090. /*
  13091. * Main routine. We initialize things, parse the arguments, execute
  13092. * profiles if we're a login shell, and then call cmdloop to execute
  13093. * commands. The setjmp call sets up the location to jump to when an
  13094. * exception occurs. When an exception occurs the variable "state"
  13095. * is used to figure out how far we had gotten.
  13096. */
  13097. int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  13098. #if NUM_SCRIPTS > 0
  13099. int ash_main(int argc, char **argv)
  13100. #else
  13101. int ash_main(int argc UNUSED_PARAM, char **argv)
  13102. #endif
  13103. /* note: 'argc' is used only if embedded scripts are enabled */
  13104. {
  13105. volatile smallint state;
  13106. struct jmploc jmploc;
  13107. struct stackmark smark;
  13108. int login_sh;
  13109. /* Initialize global data */
  13110. INIT_G_misc();
  13111. INIT_G_memstack();
  13112. INIT_G_var();
  13113. #if ENABLE_ASH_ALIAS
  13114. INIT_G_alias();
  13115. #endif
  13116. INIT_G_cmdtable();
  13117. #if PROFILE
  13118. monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
  13119. #endif
  13120. state = 0;
  13121. if (setjmp(jmploc.loc)) {
  13122. smallint e;
  13123. smallint s;
  13124. exitreset();
  13125. e = exception_type;
  13126. s = state;
  13127. if (e == EXEND || e == EXEXIT || s == 0 || iflag == 0 || shlvl) {
  13128. exitshell();
  13129. }
  13130. reset();
  13131. if (e == EXINT) {
  13132. newline_and_flush(stderr);
  13133. }
  13134. popstackmark(&smark);
  13135. FORCE_INT_ON; /* enable interrupts */
  13136. if (s == 1)
  13137. goto state1;
  13138. if (s == 2)
  13139. goto state2;
  13140. if (s == 3)
  13141. goto state3;
  13142. goto state4;
  13143. }
  13144. exception_handler = &jmploc;
  13145. rootpid = getpid();
  13146. init();
  13147. setstackmark(&smark);
  13148. #if NUM_SCRIPTS > 0
  13149. if (argc < 0)
  13150. /* Non-NULL minusc tells procargs that an embedded script is being run */
  13151. minusc = get_script_content(-argc - 1);
  13152. #endif
  13153. login_sh = procargs(argv);
  13154. #if DEBUG
  13155. TRACE(("Shell args: "));
  13156. trace_puts_args(argv);
  13157. #endif
  13158. if (login_sh) {
  13159. const char *hp;
  13160. state = 1;
  13161. read_profile("/etc/profile");
  13162. state1:
  13163. state = 2;
  13164. hp = lookupvar("HOME");
  13165. if (hp)
  13166. read_profile("$HOME/.profile");
  13167. }
  13168. state2:
  13169. state = 3;
  13170. if (
  13171. #ifndef linux
  13172. getuid() == geteuid() && getgid() == getegid() &&
  13173. #endif
  13174. iflag
  13175. ) {
  13176. const char *shinit = lookupvar("ENV");
  13177. if (shinit != NULL && *shinit != '\0')
  13178. read_profile(shinit);
  13179. }
  13180. popstackmark(&smark);
  13181. state3:
  13182. state = 4;
  13183. if (minusc) {
  13184. /* evalstring pushes parsefile stack.
  13185. * Ensure we don't falsely claim that 0 (stdin)
  13186. * is one of stacked source fds.
  13187. * Testcase: ash -c 'exec 1>&0' must not complain. */
  13188. // if (!sflag) g_parsefile->pf_fd = -1;
  13189. // ^^ not necessary since now we special-case fd 0
  13190. // in save_fd_on_redirect()
  13191. // dash: evalstring(minusc, sflag ? 0 : EV_EXIT);
  13192. // The above makes
  13193. // ash -sc 'echo $-'
  13194. // continue reading input from stdin after running 'echo'.
  13195. // bash does not do this: it prints "hBcs" and exits.
  13196. evalstring(minusc, EV_EXIT);
  13197. }
  13198. if (sflag || minusc == NULL) {
  13199. #if MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
  13200. if (iflag) {
  13201. const char *hp = lookupvar("HISTFILE");
  13202. if (!hp) {
  13203. hp = lookupvar("HOME");
  13204. if (hp) {
  13205. INT_OFF;
  13206. hp = concat_path_file(hp, ".ash_history");
  13207. setvar0("HISTFILE", hp);
  13208. free((char*)hp);
  13209. INT_ON;
  13210. hp = lookupvar("HISTFILE");
  13211. }
  13212. }
  13213. if (hp)
  13214. line_input_state->hist_file = hp;
  13215. # if ENABLE_FEATURE_SH_HISTFILESIZE
  13216. hp = lookupvar("HISTFILESIZE");
  13217. line_input_state->max_history = size_from_HISTFILESIZE(hp);
  13218. # endif
  13219. }
  13220. #endif
  13221. state4: /* XXX ??? - why isn't this before the "if" statement */
  13222. /* Interactive bash re-enables SIGHUP which is SIG_IGNed on entry.
  13223. * Try:
  13224. * trap '' hup; bash; echo RET # type "kill -hup $$", see SIGHUP having effect
  13225. * trap '' hup; bash -c 'kill -hup $$; echo ALIVE' # here SIGHUP is SIG_IGNed
  13226. */
  13227. signal(SIGHUP, SIG_DFL);
  13228. cmdloop(1);
  13229. }
  13230. #if PROFILE
  13231. monitor(0);
  13232. #endif
  13233. #ifdef GPROF
  13234. {
  13235. extern void _mcleanup(void);
  13236. _mcleanup();
  13237. }
  13238. #endif
  13239. TRACE(("End of main reached\n"));
  13240. exitshell();
  13241. /* NOTREACHED */
  13242. }
  13243. /*-
  13244. * Copyright (c) 1989, 1991, 1993, 1994
  13245. * The Regents of the University of California. All rights reserved.
  13246. *
  13247. * This code is derived from software contributed to Berkeley by
  13248. * Kenneth Almquist.
  13249. *
  13250. * Redistribution and use in source and binary forms, with or without
  13251. * modification, are permitted provided that the following conditions
  13252. * are met:
  13253. * 1. Redistributions of source code must retain the above copyright
  13254. * notice, this list of conditions and the following disclaimer.
  13255. * 2. Redistributions in binary form must reproduce the above copyright
  13256. * notice, this list of conditions and the following disclaimer in the
  13257. * documentation and/or other materials provided with the distribution.
  13258. * 3. Neither the name of the University nor the names of its contributors
  13259. * may be used to endorse or promote products derived from this software
  13260. * without specific prior written permission.
  13261. *
  13262. * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ''AS IS'' AND
  13263. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  13264. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  13265. * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
  13266. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  13267. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  13268. * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  13269. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  13270. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  13271. * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  13272. * SUCH DAMAGE.
  13273. */