ash.c 313 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022
  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 (77 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_JOB_CONTROL
  55. //config: bool "Job control"
  56. //config: default y
  57. //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
  58. //config:
  59. //config:config ASH_ALIAS
  60. //config: bool "Alias support"
  61. //config: default y
  62. //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
  63. //config:
  64. //config:config ASH_RANDOM_SUPPORT
  65. //config: bool "Pseudorandom generator and $RANDOM variable"
  66. //config: default y
  67. //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
  68. //config: help
  69. //config: Enable pseudorandom generator and dynamic variable "$RANDOM".
  70. //config: Each read of "$RANDOM" will generate a new pseudorandom value.
  71. //config: You can reset the generator by using a specified start value.
  72. //config: After "unset RANDOM" the generator will switch off and this
  73. //config: variable will no longer have special treatment.
  74. //config:
  75. //config:config ASH_EXPAND_PRMT
  76. //config: bool "Expand prompt string"
  77. //config: default y
  78. //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
  79. //config: help
  80. //config: $PS# may contain volatile content, such as backquote commands.
  81. //config: This option recreates the prompt string from the environment
  82. //config: variable each time it is displayed.
  83. //config:
  84. //config:config ASH_IDLE_TIMEOUT
  85. //config: bool "Idle timeout variable $TMOUT"
  86. //config: default y
  87. //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
  88. //config: help
  89. //config: Enable bash-like auto-logout after $TMOUT seconds of idle time.
  90. //config:
  91. //config:config ASH_MAIL
  92. //config: bool "Check for new mail in interactive shell"
  93. //config: default y
  94. //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
  95. //config: help
  96. //config: Enable "check for new mail" function:
  97. //config: if set, $MAIL file and $MAILPATH list of files
  98. //config: are checked for mtime changes, and "you have mail"
  99. //config: message is printed if change is detected.
  100. //config:
  101. //config:config ASH_ECHO
  102. //config: bool "echo builtin"
  103. //config: default y
  104. //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
  105. //config:
  106. //config:config ASH_PRINTF
  107. //config: bool "printf builtin"
  108. //config: default y
  109. //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
  110. //config:
  111. //config:config ASH_TEST
  112. //config: bool "test builtin"
  113. //config: default y
  114. //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
  115. //config:
  116. //config:config ASH_HELP
  117. //config: bool "help builtin"
  118. //config: default y
  119. //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
  120. //config:
  121. //config:config ASH_GETOPTS
  122. //config: bool "getopts builtin"
  123. //config: default y
  124. //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
  125. //config:
  126. //config:config ASH_CMDCMD
  127. //config: bool "command builtin"
  128. //config: default y
  129. //config: depends on ASH || SH_IS_ASH || BASH_IS_ASH
  130. //config: help
  131. //config: Enable support for the 'command' builtin, which allows
  132. //config: you to run the specified command or builtin,
  133. //config: even when there is a function with the same name.
  134. //config:
  135. //config:endif # ash options
  136. //applet:IF_ASH(APPLET(ash, BB_DIR_BIN, BB_SUID_DROP))
  137. // APPLET_ODDNAME:name main location suid_type help
  138. //applet:IF_SH_IS_ASH( APPLET_ODDNAME(sh, ash, BB_DIR_BIN, BB_SUID_DROP, ash))
  139. //applet:IF_BASH_IS_ASH(APPLET_ODDNAME(bash, ash, BB_DIR_BIN, BB_SUID_DROP, ash))
  140. //kbuild:lib-$(CONFIG_ASH) += ash.o ash_ptr_hack.o shell_common.o
  141. //kbuild:lib-$(CONFIG_SH_IS_ASH) += ash.o ash_ptr_hack.o shell_common.o
  142. //kbuild:lib-$(CONFIG_BASH_IS_ASH) += ash.o ash_ptr_hack.o shell_common.o
  143. //kbuild:lib-$(CONFIG_ASH_RANDOM_SUPPORT) += random.o
  144. /*
  145. * DEBUG=1 to compile in debugging ('set -o debug' turns on)
  146. * DEBUG=2 to compile in and turn on debugging.
  147. * When debugging is on ("set -o debug" was executed, or DEBUG=2),
  148. * debugging info is written to ./trace, quit signal generates core dump.
  149. */
  150. #define DEBUG 0
  151. /* Tweak debug output verbosity here */
  152. #define DEBUG_TIME 0
  153. #define DEBUG_PID 1
  154. #define DEBUG_SIG 1
  155. #define DEBUG_INTONOFF 0
  156. #define PROFILE 0
  157. #define JOBS ENABLE_ASH_JOB_CONTROL
  158. #include <setjmp.h>
  159. #include <fnmatch.h>
  160. #include <sys/times.h>
  161. #include <sys/utsname.h> /* for setting $HOSTNAME */
  162. #include "busybox.h" /* for applet_names */
  163. /* So far, all bash compat is controlled by one config option */
  164. /* Separate defines document which part of code implements what */
  165. /* function keyword */
  166. #define BASH_FUNCTION ENABLE_ASH_BASH_COMPAT
  167. #define IF_BASH_FUNCTION IF_ASH_BASH_COMPAT
  168. /* &>file */
  169. #define BASH_REDIR_OUTPUT ENABLE_ASH_BASH_COMPAT
  170. #define IF_BASH_REDIR_OUTPUT IF_ASH_BASH_COMPAT
  171. /* $'...' */
  172. #define BASH_DOLLAR_SQUOTE ENABLE_ASH_BASH_COMPAT
  173. #define IF_BASH_DOLLAR_SQUOTE IF_ASH_BASH_COMPAT
  174. #define BASH_PATTERN_SUBST ENABLE_ASH_BASH_COMPAT
  175. #define IF_BASH_PATTERN_SUBST IF_ASH_BASH_COMPAT
  176. #define BASH_SUBSTR ENABLE_ASH_BASH_COMPAT
  177. #define IF_BASH_SUBSTR IF_ASH_BASH_COMPAT
  178. /* [[ EXPR ]] */
  179. #define BASH_TEST2 (ENABLE_ASH_BASH_COMPAT * ENABLE_ASH_TEST)
  180. #define BASH_SOURCE ENABLE_ASH_BASH_COMPAT
  181. #define BASH_PIPEFAIL ENABLE_ASH_BASH_COMPAT
  182. #define BASH_HOSTNAME_VAR ENABLE_ASH_BASH_COMPAT
  183. #define BASH_SHLVL_VAR ENABLE_ASH_BASH_COMPAT
  184. #define BASH_XTRACEFD ENABLE_ASH_BASH_COMPAT
  185. #define BASH_READ_D ENABLE_ASH_BASH_COMPAT
  186. #define IF_BASH_READ_D IF_ASH_BASH_COMPAT
  187. #if defined(__ANDROID_API__) && __ANDROID_API__ <= 24
  188. /* Bionic at least up to version 24 has no glob() */
  189. # undef ENABLE_ASH_INTERNAL_GLOB
  190. # define ENABLE_ASH_INTERNAL_GLOB 1
  191. #endif
  192. #if !ENABLE_ASH_INTERNAL_GLOB && defined(__UCLIBC__)
  193. # error uClibc glob() is buggy, use ASH_INTERNAL_GLOB.
  194. # error The bug is: for "$PWD"/<pattern> ash will escape e.g. dashes in "$PWD"
  195. # error with backslash, even ones which do not need to be: "/a-b" -> "/a\-b"
  196. # error glob() should unbackslash them and match. uClibc does not unbackslash,
  197. # error fails to match dirname, subsequently not expanding <pattern> in it.
  198. // Testcase:
  199. // if (glob("/etc/polkit\\-1", 0, NULL, &pglob)) - this returns 0 on uclibc, no bug
  200. // if (glob("/etc/polkit\\-1/*", 0, NULL, &pglob)) printf("uclibc bug!\n");
  201. #endif
  202. #if !ENABLE_ASH_INTERNAL_GLOB
  203. # include <glob.h>
  204. #endif
  205. #include "unicode.h"
  206. #include "shell_common.h"
  207. #if ENABLE_FEATURE_SH_MATH
  208. # include "math.h"
  209. #else
  210. typedef long arith_t;
  211. # define ARITH_FMT "%ld"
  212. #endif
  213. #if ENABLE_ASH_RANDOM_SUPPORT
  214. # include "random.h"
  215. #else
  216. # define CLEAR_RANDOM_T(rnd) ((void)0)
  217. #endif
  218. #include "NUM_APPLETS.h"
  219. #if NUM_APPLETS == 1
  220. /* STANDALONE does not make sense, and won't compile */
  221. # undef CONFIG_FEATURE_SH_STANDALONE
  222. # undef ENABLE_FEATURE_SH_STANDALONE
  223. # undef IF_FEATURE_SH_STANDALONE
  224. # undef IF_NOT_FEATURE_SH_STANDALONE
  225. # define ENABLE_FEATURE_SH_STANDALONE 0
  226. # define IF_FEATURE_SH_STANDALONE(...)
  227. # define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
  228. #endif
  229. #ifndef PIPE_BUF
  230. # define PIPE_BUF 4096 /* amount of buffering in a pipe */
  231. #endif
  232. #if !BB_MMU
  233. # error "Do not even bother, ash will not run on NOMMU machine"
  234. #endif
  235. /* ============ Hash table sizes. Configurable. */
  236. #define VTABSIZE 39
  237. #define ATABSIZE 39
  238. #define CMDTABLESIZE 31 /* should be prime */
  239. /* ============ Shell options */
  240. static const char *const optletters_optnames[] = {
  241. "e" "errexit",
  242. "f" "noglob",
  243. "I" "ignoreeof",
  244. "i" "interactive",
  245. "m" "monitor",
  246. "n" "noexec",
  247. "s" "stdin",
  248. "x" "xtrace",
  249. "v" "verbose",
  250. "C" "noclobber",
  251. "a" "allexport",
  252. "b" "notify",
  253. "u" "nounset",
  254. "\0" "vi"
  255. #if BASH_PIPEFAIL
  256. ,"\0" "pipefail"
  257. #endif
  258. #if DEBUG
  259. ,"\0" "nolog"
  260. ,"\0" "debug"
  261. #endif
  262. };
  263. #define optletters(n) optletters_optnames[n][0]
  264. #define optnames(n) (optletters_optnames[n] + 1)
  265. enum { NOPTS = ARRAY_SIZE(optletters_optnames) };
  266. /* ============ Misc data */
  267. #define msg_illnum "Illegal number: %s"
  268. /*
  269. * We enclose jmp_buf in a structure so that we can declare pointers to
  270. * jump locations. The global variable handler contains the location to
  271. * jump to when an exception occurs, and the global variable exception_type
  272. * contains a code identifying the exception. To implement nested
  273. * exception handlers, the user should save the value of handler on entry
  274. * to an inner scope, set handler to point to a jmploc structure for the
  275. * inner scope, and restore handler on exit from the scope.
  276. */
  277. struct jmploc {
  278. jmp_buf loc;
  279. };
  280. struct globals_misc {
  281. uint8_t exitstatus; /* exit status of last command */
  282. uint8_t back_exitstatus;/* exit status of backquoted command */
  283. smallint job_warning; /* user was warned about stopped jobs (can be 2, 1 or 0). */
  284. int rootpid; /* pid of main shell */
  285. /* shell level: 0 for the main shell, 1 for its children, and so on */
  286. int shlvl;
  287. #define rootshell (!shlvl)
  288. char *minusc; /* argument to -c option */
  289. char *curdir; // = nullstr; /* current working directory */
  290. char *physdir; // = nullstr; /* physical working directory */
  291. char *arg0; /* value of $0 */
  292. struct jmploc *exception_handler;
  293. volatile int suppress_int; /* counter */
  294. volatile /*sig_atomic_t*/ smallint pending_int; /* 1 = got SIGINT */
  295. volatile /*sig_atomic_t*/ smallint got_sigchld; /* 1 = got SIGCHLD */
  296. volatile /*sig_atomic_t*/ smallint pending_sig; /* last pending signal */
  297. smallint exception_type; /* kind of exception (0..5) */
  298. /* exceptions */
  299. #define EXINT 0 /* SIGINT received */
  300. #define EXERROR 1 /* a generic error */
  301. #define EXEXIT 4 /* exit the shell */
  302. char nullstr[1]; /* zero length string */
  303. char optlist[NOPTS];
  304. #define eflag optlist[0]
  305. #define fflag optlist[1]
  306. #define Iflag optlist[2]
  307. #define iflag optlist[3]
  308. #define mflag optlist[4]
  309. #define nflag optlist[5]
  310. #define sflag optlist[6]
  311. #define xflag optlist[7]
  312. #define vflag optlist[8]
  313. #define Cflag optlist[9]
  314. #define aflag optlist[10]
  315. #define bflag optlist[11]
  316. #define uflag optlist[12]
  317. #define viflag optlist[13]
  318. #if BASH_PIPEFAIL
  319. # define pipefail optlist[14]
  320. #else
  321. # define pipefail 0
  322. #endif
  323. #if DEBUG
  324. # define nolog optlist[14 + BASH_PIPEFAIL]
  325. # define debug optlist[15 + BASH_PIPEFAIL]
  326. #endif
  327. /* trap handler commands */
  328. /*
  329. * Sigmode records the current value of the signal handlers for the various
  330. * modes. A value of zero means that the current handler is not known.
  331. * S_HARD_IGN indicates that the signal was ignored on entry to the shell.
  332. */
  333. char sigmode[NSIG - 1];
  334. #define S_DFL 1 /* default signal handling (SIG_DFL) */
  335. #define S_CATCH 2 /* signal is caught */
  336. #define S_IGN 3 /* signal is ignored (SIG_IGN) */
  337. #define S_HARD_IGN 4 /* signal is ignored permanently (it was SIG_IGN on entry to shell) */
  338. /* indicates specified signal received */
  339. uint8_t gotsig[NSIG - 1]; /* offset by 1: "signal" 0 is meaningless */
  340. uint8_t may_have_traps; /* 0: definitely no traps are set, 1: some traps may be set */
  341. char *trap[NSIG];
  342. char **trap_ptr; /* used only by "trap hack" */
  343. /* Rarely referenced stuff */
  344. #if ENABLE_ASH_RANDOM_SUPPORT
  345. random_t random_gen;
  346. #endif
  347. pid_t backgndpid; /* pid of last background process */
  348. };
  349. extern struct globals_misc *const ash_ptr_to_globals_misc;
  350. #define G_misc (*ash_ptr_to_globals_misc)
  351. #define exitstatus (G_misc.exitstatus )
  352. #define back_exitstatus (G_misc.back_exitstatus )
  353. #define job_warning (G_misc.job_warning)
  354. #define rootpid (G_misc.rootpid )
  355. #define shlvl (G_misc.shlvl )
  356. #define minusc (G_misc.minusc )
  357. #define curdir (G_misc.curdir )
  358. #define physdir (G_misc.physdir )
  359. #define arg0 (G_misc.arg0 )
  360. #define exception_handler (G_misc.exception_handler)
  361. #define exception_type (G_misc.exception_type )
  362. #define suppress_int (G_misc.suppress_int )
  363. #define pending_int (G_misc.pending_int )
  364. #define got_sigchld (G_misc.got_sigchld )
  365. #define pending_sig (G_misc.pending_sig )
  366. #define nullstr (G_misc.nullstr )
  367. #define optlist (G_misc.optlist )
  368. #define sigmode (G_misc.sigmode )
  369. #define gotsig (G_misc.gotsig )
  370. #define may_have_traps (G_misc.may_have_traps )
  371. #define trap (G_misc.trap )
  372. #define trap_ptr (G_misc.trap_ptr )
  373. #define random_gen (G_misc.random_gen )
  374. #define backgndpid (G_misc.backgndpid )
  375. #define INIT_G_misc() do { \
  376. (*(struct globals_misc**)&ash_ptr_to_globals_misc) = xzalloc(sizeof(G_misc)); \
  377. barrier(); \
  378. curdir = nullstr; \
  379. physdir = nullstr; \
  380. trap_ptr = trap; \
  381. } while (0)
  382. /* ============ DEBUG */
  383. #if DEBUG
  384. static void trace_printf(const char *fmt, ...);
  385. static void trace_vprintf(const char *fmt, va_list va);
  386. # define TRACE(param) trace_printf param
  387. # define TRACEV(param) trace_vprintf param
  388. # define close(fd) do { \
  389. int dfd = (fd); \
  390. if (close(dfd) < 0) \
  391. bb_error_msg("bug on %d: closing %d(0x%x)", \
  392. __LINE__, dfd, dfd); \
  393. } while (0)
  394. #else
  395. # define TRACE(param)
  396. # define TRACEV(param)
  397. #endif
  398. /* ============ Utility functions */
  399. #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
  400. #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
  401. static int
  402. isdigit_str9(const char *str)
  403. {
  404. int maxlen = 9 + 1; /* max 9 digits: 999999999 */
  405. while (--maxlen && isdigit(*str))
  406. str++;
  407. return (*str == '\0');
  408. }
  409. static const char *
  410. var_end(const char *var)
  411. {
  412. while (*var)
  413. if (*var++ == '=')
  414. break;
  415. return var;
  416. }
  417. /* ============ Interrupts / exceptions */
  418. static void exitshell(void) NORETURN;
  419. /*
  420. * These macros allow the user to suspend the handling of interrupt signals
  421. * over a period of time. This is similar to SIGHOLD or to sigblock, but
  422. * much more efficient and portable. (But hacking the kernel is so much
  423. * more fun than worrying about efficiency and portability. :-))
  424. */
  425. #if DEBUG_INTONOFF
  426. # define INT_OFF do { \
  427. TRACE(("%s:%d INT_OFF(%d)\n", __func__, __LINE__, suppress_int)); \
  428. suppress_int++; \
  429. barrier(); \
  430. } while (0)
  431. #else
  432. # define INT_OFF do { \
  433. suppress_int++; \
  434. barrier(); \
  435. } while (0)
  436. #endif
  437. /*
  438. * Called to raise an exception. Since C doesn't include exceptions, we
  439. * just do a longjmp to the exception handler. The type of exception is
  440. * stored in the global variable "exception_type".
  441. */
  442. static void raise_exception(int) NORETURN;
  443. static void
  444. raise_exception(int e)
  445. {
  446. #if DEBUG
  447. if (exception_handler == NULL)
  448. abort();
  449. #endif
  450. INT_OFF;
  451. exception_type = e;
  452. longjmp(exception_handler->loc, 1);
  453. }
  454. #if DEBUG
  455. #define raise_exception(e) do { \
  456. TRACE(("raising exception %d on line %d\n", (e), __LINE__)); \
  457. raise_exception(e); \
  458. } while (0)
  459. #endif
  460. /*
  461. * Called when a SIGINT is received. (If the user specifies
  462. * that SIGINT is to be trapped or ignored using the trap builtin, then
  463. * this routine is not called.) Suppressint is nonzero when interrupts
  464. * are held using the INT_OFF macro. (The test for iflag is just
  465. * defensive programming.)
  466. */
  467. static void raise_interrupt(void) NORETURN;
  468. static void
  469. raise_interrupt(void)
  470. {
  471. pending_int = 0;
  472. /* Signal is not automatically unmasked after it is raised,
  473. * do it ourself - unmask all signals */
  474. sigprocmask_allsigs(SIG_UNBLOCK);
  475. /* pending_sig = 0; - now done in signal_handler() */
  476. if (!(rootshell && iflag)) {
  477. /* Kill ourself with SIGINT */
  478. signal(SIGINT, SIG_DFL);
  479. raise(SIGINT);
  480. }
  481. /* bash: ^C even on empty command line sets $? */
  482. exitstatus = SIGINT + 128;
  483. raise_exception(EXINT);
  484. /* NOTREACHED */
  485. }
  486. #if DEBUG
  487. #define raise_interrupt() do { \
  488. TRACE(("raising interrupt on line %d\n", __LINE__)); \
  489. raise_interrupt(); \
  490. } while (0)
  491. #endif
  492. static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
  493. int_on(void)
  494. {
  495. barrier();
  496. if (--suppress_int == 0 && pending_int) {
  497. raise_interrupt();
  498. }
  499. }
  500. #if DEBUG_INTONOFF
  501. # define INT_ON do { \
  502. TRACE(("%s:%d INT_ON(%d)\n", __func__, __LINE__, suppress_int-1)); \
  503. int_on(); \
  504. } while (0)
  505. #else
  506. # define INT_ON int_on()
  507. #endif
  508. static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
  509. force_int_on(void)
  510. {
  511. barrier();
  512. suppress_int = 0;
  513. if (pending_int)
  514. raise_interrupt();
  515. }
  516. #define FORCE_INT_ON force_int_on()
  517. #define SAVE_INT(v) ((v) = suppress_int)
  518. #define RESTORE_INT(v) do { \
  519. barrier(); \
  520. suppress_int = (v); \
  521. if (suppress_int == 0 && pending_int) \
  522. raise_interrupt(); \
  523. } while (0)
  524. /* ============ Stdout/stderr output */
  525. static void
  526. outstr(const char *p, FILE *file)
  527. {
  528. INT_OFF;
  529. fputs(p, file);
  530. INT_ON;
  531. }
  532. static void
  533. flush_stdout_stderr(void)
  534. {
  535. INT_OFF;
  536. fflush_all();
  537. INT_ON;
  538. }
  539. /* Was called outcslow(c,FILE*), but c was always '\n' */
  540. static void
  541. newline_and_flush(FILE *dest)
  542. {
  543. INT_OFF;
  544. putc('\n', dest);
  545. fflush(dest);
  546. INT_ON;
  547. }
  548. static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
  549. static int
  550. out1fmt(const char *fmt, ...)
  551. {
  552. va_list ap;
  553. int r;
  554. INT_OFF;
  555. va_start(ap, fmt);
  556. r = vprintf(fmt, ap);
  557. va_end(ap);
  558. INT_ON;
  559. return r;
  560. }
  561. static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
  562. static int
  563. fmtstr(char *outbuf, size_t length, const char *fmt, ...)
  564. {
  565. va_list ap;
  566. int ret;
  567. INT_OFF;
  568. va_start(ap, fmt);
  569. ret = vsnprintf(outbuf, length, fmt, ap);
  570. va_end(ap);
  571. INT_ON;
  572. return ret;
  573. }
  574. static void
  575. out1str(const char *p)
  576. {
  577. outstr(p, stdout);
  578. }
  579. static void
  580. out2str(const char *p)
  581. {
  582. outstr(p, stderr);
  583. flush_stdout_stderr();
  584. }
  585. /* ============ Parser structures */
  586. /* control characters in argument strings */
  587. #define CTL_FIRST CTLESC
  588. #define CTLESC ((unsigned char)'\201') /* escape next character */
  589. #define CTLVAR ((unsigned char)'\202') /* variable defn */
  590. #define CTLENDVAR ((unsigned char)'\203')
  591. #define CTLBACKQ ((unsigned char)'\204')
  592. #define CTLARI ((unsigned char)'\206') /* arithmetic expression */
  593. #define CTLENDARI ((unsigned char)'\207')
  594. #define CTLQUOTEMARK ((unsigned char)'\210')
  595. #define CTL_LAST CTLQUOTEMARK
  596. /* variable substitution byte (follows CTLVAR) */
  597. #define VSTYPE 0x0f /* type of variable substitution */
  598. #define VSNUL 0x10 /* colon--treat the empty string as unset */
  599. /* values of VSTYPE field */
  600. #define VSNORMAL 0x1 /* normal variable: $var or ${var} */
  601. #define VSMINUS 0x2 /* ${var-text} */
  602. #define VSPLUS 0x3 /* ${var+text} */
  603. #define VSQUESTION 0x4 /* ${var?message} */
  604. #define VSASSIGN 0x5 /* ${var=text} */
  605. #define VSTRIMRIGHT 0x6 /* ${var%pattern} */
  606. #define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
  607. #define VSTRIMLEFT 0x8 /* ${var#pattern} */
  608. #define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
  609. #define VSLENGTH 0xa /* ${#var} */
  610. #if BASH_SUBSTR
  611. #define VSSUBSTR 0xc /* ${var:position:length} */
  612. #endif
  613. #if BASH_PATTERN_SUBST
  614. #define VSREPLACE 0xd /* ${var/pattern/replacement} */
  615. #define VSREPLACEALL 0xe /* ${var//pattern/replacement} */
  616. #endif
  617. static const char dolatstr[] ALIGN1 = {
  618. CTLQUOTEMARK, CTLVAR, VSNORMAL, '@', '=', CTLQUOTEMARK, '\0'
  619. };
  620. #define DOLATSTRLEN 6
  621. #define NCMD 0
  622. #define NPIPE 1
  623. #define NREDIR 2
  624. #define NBACKGND 3
  625. #define NSUBSHELL 4
  626. #define NAND 5
  627. #define NOR 6
  628. #define NSEMI 7
  629. #define NIF 8
  630. #define NWHILE 9
  631. #define NUNTIL 10
  632. #define NFOR 11
  633. #define NCASE 12
  634. #define NCLIST 13
  635. #define NDEFUN 14
  636. #define NARG 15
  637. #define NTO 16
  638. #if BASH_REDIR_OUTPUT
  639. #define NTO2 17
  640. #endif
  641. #define NCLOBBER 18
  642. #define NFROM 19
  643. #define NFROMTO 20
  644. #define NAPPEND 21
  645. #define NTOFD 22
  646. #define NFROMFD 23
  647. #define NHERE 24
  648. #define NXHERE 25
  649. #define NNOT 26
  650. #define N_NUMBER 27
  651. union node;
  652. struct ncmd {
  653. smallint type; /* Nxxxx */
  654. union node *assign;
  655. union node *args;
  656. union node *redirect;
  657. };
  658. struct npipe {
  659. smallint type;
  660. smallint pipe_backgnd;
  661. struct nodelist *cmdlist;
  662. };
  663. struct nredir {
  664. smallint type;
  665. union node *n;
  666. union node *redirect;
  667. };
  668. struct nbinary {
  669. smallint type;
  670. union node *ch1;
  671. union node *ch2;
  672. };
  673. struct nif {
  674. smallint type;
  675. union node *test;
  676. union node *ifpart;
  677. union node *elsepart;
  678. };
  679. struct nfor {
  680. smallint type;
  681. union node *args;
  682. union node *body;
  683. char *var;
  684. };
  685. struct ncase {
  686. smallint type;
  687. union node *expr;
  688. union node *cases;
  689. };
  690. struct nclist {
  691. smallint type;
  692. union node *next;
  693. union node *pattern;
  694. union node *body;
  695. };
  696. struct narg {
  697. smallint type;
  698. union node *next;
  699. char *text;
  700. struct nodelist *backquote;
  701. };
  702. /* nfile and ndup layout must match!
  703. * NTOFD (>&fdnum) uses ndup structure, but we may discover mid-flight
  704. * that it is actually NTO2 (>&file), and change its type.
  705. */
  706. struct nfile {
  707. smallint type;
  708. union node *next;
  709. int fd;
  710. int _unused_dupfd;
  711. union node *fname;
  712. char *expfname;
  713. };
  714. struct ndup {
  715. smallint type;
  716. union node *next;
  717. int fd;
  718. int dupfd;
  719. union node *vname;
  720. char *_unused_expfname;
  721. };
  722. struct nhere {
  723. smallint type;
  724. union node *next;
  725. int fd;
  726. union node *doc;
  727. };
  728. struct nnot {
  729. smallint type;
  730. union node *com;
  731. };
  732. union node {
  733. smallint type;
  734. struct ncmd ncmd;
  735. struct npipe npipe;
  736. struct nredir nredir;
  737. struct nbinary nbinary;
  738. struct nif nif;
  739. struct nfor nfor;
  740. struct ncase ncase;
  741. struct nclist nclist;
  742. struct narg narg;
  743. struct nfile nfile;
  744. struct ndup ndup;
  745. struct nhere nhere;
  746. struct nnot nnot;
  747. };
  748. /*
  749. * NODE_EOF is returned by parsecmd when it encounters an end of file.
  750. * It must be distinct from NULL.
  751. */
  752. #define NODE_EOF ((union node *) -1L)
  753. struct nodelist {
  754. struct nodelist *next;
  755. union node *n;
  756. };
  757. struct funcnode {
  758. int count;
  759. union node n;
  760. };
  761. /*
  762. * Free a parse tree.
  763. */
  764. static void
  765. freefunc(struct funcnode *f)
  766. {
  767. if (f && --f->count < 0)
  768. free(f);
  769. }
  770. /* ============ Debugging output */
  771. #if DEBUG
  772. static FILE *tracefile;
  773. static void
  774. trace_printf(const char *fmt, ...)
  775. {
  776. va_list va;
  777. if (debug != 1)
  778. return;
  779. if (DEBUG_TIME)
  780. fprintf(tracefile, "%u ", (int) time(NULL));
  781. if (DEBUG_PID)
  782. fprintf(tracefile, "[%u] ", (int) getpid());
  783. if (DEBUG_SIG)
  784. fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
  785. va_start(va, fmt);
  786. vfprintf(tracefile, fmt, va);
  787. va_end(va);
  788. }
  789. static void
  790. trace_vprintf(const char *fmt, va_list va)
  791. {
  792. if (debug != 1)
  793. return;
  794. vfprintf(tracefile, fmt, va);
  795. fprintf(tracefile, "\n");
  796. }
  797. static void
  798. trace_puts(const char *s)
  799. {
  800. if (debug != 1)
  801. return;
  802. fputs(s, tracefile);
  803. }
  804. static void
  805. trace_puts_quoted(char *s)
  806. {
  807. char *p;
  808. char c;
  809. if (debug != 1)
  810. return;
  811. putc('"', tracefile);
  812. for (p = s; *p; p++) {
  813. switch ((unsigned char)*p) {
  814. case '\n': c = 'n'; goto backslash;
  815. case '\t': c = 't'; goto backslash;
  816. case '\r': c = 'r'; goto backslash;
  817. case '\"': c = '\"'; goto backslash;
  818. case '\\': c = '\\'; goto backslash;
  819. case CTLESC: c = 'e'; goto backslash;
  820. case CTLVAR: c = 'v'; goto backslash;
  821. case CTLBACKQ: c = 'q'; goto backslash;
  822. backslash:
  823. putc('\\', tracefile);
  824. putc(c, tracefile);
  825. break;
  826. default:
  827. if (*p >= ' ' && *p <= '~')
  828. putc(*p, tracefile);
  829. else {
  830. putc('\\', tracefile);
  831. putc((*p >> 6) & 03, tracefile);
  832. putc((*p >> 3) & 07, tracefile);
  833. putc(*p & 07, tracefile);
  834. }
  835. break;
  836. }
  837. }
  838. putc('"', tracefile);
  839. }
  840. static void
  841. trace_puts_args(char **ap)
  842. {
  843. if (debug != 1)
  844. return;
  845. if (!*ap)
  846. return;
  847. while (1) {
  848. trace_puts_quoted(*ap);
  849. if (!*++ap) {
  850. putc('\n', tracefile);
  851. break;
  852. }
  853. putc(' ', tracefile);
  854. }
  855. }
  856. static void
  857. opentrace(void)
  858. {
  859. char s[100];
  860. #ifdef O_APPEND
  861. int flags;
  862. #endif
  863. if (debug != 1) {
  864. if (tracefile)
  865. fflush(tracefile);
  866. /* leave open because libedit might be using it */
  867. return;
  868. }
  869. strcpy(s, "./trace");
  870. if (tracefile) {
  871. if (!freopen(s, "a", tracefile)) {
  872. fprintf(stderr, "Can't re-open %s\n", s);
  873. debug = 0;
  874. return;
  875. }
  876. } else {
  877. tracefile = fopen(s, "a");
  878. if (tracefile == NULL) {
  879. fprintf(stderr, "Can't open %s\n", s);
  880. debug = 0;
  881. return;
  882. }
  883. }
  884. #ifdef O_APPEND
  885. flags = fcntl(fileno(tracefile), F_GETFL);
  886. if (flags >= 0)
  887. fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
  888. #endif
  889. setlinebuf(tracefile);
  890. fputs("\nTracing started.\n", tracefile);
  891. }
  892. static void
  893. indent(int amount, char *pfx, FILE *fp)
  894. {
  895. int i;
  896. for (i = 0; i < amount; i++) {
  897. if (pfx && i == amount - 1)
  898. fputs(pfx, fp);
  899. putc('\t', fp);
  900. }
  901. }
  902. /* little circular references here... */
  903. static void shtree(union node *n, int ind, char *pfx, FILE *fp);
  904. static void
  905. sharg(union node *arg, FILE *fp)
  906. {
  907. char *p;
  908. struct nodelist *bqlist;
  909. unsigned char subtype;
  910. if (arg->type != NARG) {
  911. out1fmt("<node type %d>\n", arg->type);
  912. abort();
  913. }
  914. bqlist = arg->narg.backquote;
  915. for (p = arg->narg.text; *p; p++) {
  916. switch ((unsigned char)*p) {
  917. case CTLESC:
  918. p++;
  919. putc(*p, fp);
  920. break;
  921. case CTLVAR:
  922. putc('$', fp);
  923. putc('{', fp);
  924. subtype = *++p;
  925. if (subtype == VSLENGTH)
  926. putc('#', fp);
  927. while (*p != '=') {
  928. putc(*p, fp);
  929. p++;
  930. }
  931. if (subtype & VSNUL)
  932. putc(':', fp);
  933. switch (subtype & VSTYPE) {
  934. case VSNORMAL:
  935. putc('}', fp);
  936. break;
  937. case VSMINUS:
  938. putc('-', fp);
  939. break;
  940. case VSPLUS:
  941. putc('+', fp);
  942. break;
  943. case VSQUESTION:
  944. putc('?', fp);
  945. break;
  946. case VSASSIGN:
  947. putc('=', fp);
  948. break;
  949. case VSTRIMLEFT:
  950. putc('#', fp);
  951. break;
  952. case VSTRIMLEFTMAX:
  953. putc('#', fp);
  954. putc('#', fp);
  955. break;
  956. case VSTRIMRIGHT:
  957. putc('%', fp);
  958. break;
  959. case VSTRIMRIGHTMAX:
  960. putc('%', fp);
  961. putc('%', fp);
  962. break;
  963. case VSLENGTH:
  964. break;
  965. default:
  966. out1fmt("<subtype %d>", subtype);
  967. }
  968. break;
  969. case CTLENDVAR:
  970. putc('}', fp);
  971. break;
  972. case CTLBACKQ:
  973. putc('$', fp);
  974. putc('(', fp);
  975. shtree(bqlist->n, -1, NULL, fp);
  976. putc(')', fp);
  977. break;
  978. default:
  979. putc(*p, fp);
  980. break;
  981. }
  982. }
  983. }
  984. static void
  985. shcmd(union node *cmd, FILE *fp)
  986. {
  987. union node *np;
  988. int first;
  989. const char *s;
  990. int dftfd;
  991. first = 1;
  992. for (np = cmd->ncmd.args; np; np = np->narg.next) {
  993. if (!first)
  994. putc(' ', fp);
  995. sharg(np, fp);
  996. first = 0;
  997. }
  998. for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
  999. if (!first)
  1000. putc(' ', fp);
  1001. dftfd = 0;
  1002. switch (np->nfile.type) {
  1003. case NTO: s = ">>"+1; dftfd = 1; break;
  1004. case NCLOBBER: s = ">|"; dftfd = 1; break;
  1005. case NAPPEND: s = ">>"; dftfd = 1; break;
  1006. #if BASH_REDIR_OUTPUT
  1007. case NTO2:
  1008. #endif
  1009. case NTOFD: s = ">&"; dftfd = 1; break;
  1010. case NFROM: s = "<"; break;
  1011. case NFROMFD: s = "<&"; break;
  1012. case NFROMTO: s = "<>"; break;
  1013. default: s = "*error*"; break;
  1014. }
  1015. if (np->nfile.fd != dftfd)
  1016. fprintf(fp, "%d", np->nfile.fd);
  1017. fputs(s, fp);
  1018. if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
  1019. fprintf(fp, "%d", np->ndup.dupfd);
  1020. } else {
  1021. sharg(np->nfile.fname, fp);
  1022. }
  1023. first = 0;
  1024. }
  1025. }
  1026. static void
  1027. shtree(union node *n, int ind, char *pfx, FILE *fp)
  1028. {
  1029. struct nodelist *lp;
  1030. const char *s;
  1031. if (n == NULL)
  1032. return;
  1033. indent(ind, pfx, fp);
  1034. if (n == NODE_EOF) {
  1035. fputs("<EOF>", fp);
  1036. return;
  1037. }
  1038. switch (n->type) {
  1039. case NSEMI:
  1040. s = "; ";
  1041. goto binop;
  1042. case NAND:
  1043. s = " && ";
  1044. goto binop;
  1045. case NOR:
  1046. s = " || ";
  1047. binop:
  1048. shtree(n->nbinary.ch1, ind, NULL, fp);
  1049. /* if (ind < 0) */
  1050. fputs(s, fp);
  1051. shtree(n->nbinary.ch2, ind, NULL, fp);
  1052. break;
  1053. case NCMD:
  1054. shcmd(n, fp);
  1055. if (ind >= 0)
  1056. putc('\n', fp);
  1057. break;
  1058. case NPIPE:
  1059. for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
  1060. shtree(lp->n, 0, NULL, fp);
  1061. if (lp->next)
  1062. fputs(" | ", fp);
  1063. }
  1064. if (n->npipe.pipe_backgnd)
  1065. fputs(" &", fp);
  1066. if (ind >= 0)
  1067. putc('\n', fp);
  1068. break;
  1069. default:
  1070. fprintf(fp, "<node type %d>", n->type);
  1071. if (ind >= 0)
  1072. putc('\n', fp);
  1073. break;
  1074. }
  1075. }
  1076. static void
  1077. showtree(union node *n)
  1078. {
  1079. trace_puts("showtree called\n");
  1080. shtree(n, 1, NULL, stderr);
  1081. }
  1082. #endif /* DEBUG */
  1083. /* ============ Parser data */
  1084. /*
  1085. * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
  1086. */
  1087. struct strlist {
  1088. struct strlist *next;
  1089. char *text;
  1090. };
  1091. struct alias;
  1092. struct strpush {
  1093. struct strpush *prev; /* preceding string on stack */
  1094. char *prev_string;
  1095. int prev_left_in_line;
  1096. #if ENABLE_ASH_ALIAS
  1097. struct alias *ap; /* if push was associated with an alias */
  1098. #endif
  1099. char *string; /* remember the string since it may change */
  1100. /* Remember last two characters for pungetc. */
  1101. int lastc[2];
  1102. /* Number of outstanding calls to pungetc. */
  1103. int unget;
  1104. };
  1105. /*
  1106. * The parsefile structure pointed to by the global variable parsefile
  1107. * contains information about the current file being read.
  1108. */
  1109. struct parsefile {
  1110. struct parsefile *prev; /* preceding file on stack */
  1111. int linno; /* current line */
  1112. int pf_fd; /* file descriptor (or -1 if string) */
  1113. int left_in_line; /* number of chars left in this line */
  1114. int left_in_buffer; /* number of chars left in this buffer past the line */
  1115. char *next_to_pgetc; /* next char in buffer */
  1116. char *buf; /* input buffer */
  1117. struct strpush *strpush; /* for pushing strings at this level */
  1118. struct strpush basestrpush; /* so pushing one is fast */
  1119. /* Remember last two characters for pungetc. */
  1120. int lastc[2];
  1121. /* Number of outstanding calls to pungetc. */
  1122. int unget;
  1123. };
  1124. static struct parsefile basepf; /* top level input file */
  1125. static struct parsefile *g_parsefile = &basepf; /* current input file */
  1126. static int startlinno; /* line # where last token started */
  1127. static char *commandname; /* currently executing command */
  1128. /* ============ Message printing */
  1129. static void
  1130. ash_vmsg(const char *msg, va_list ap)
  1131. {
  1132. fprintf(stderr, "%s: ", arg0);
  1133. if (commandname) {
  1134. if (strcmp(arg0, commandname))
  1135. fprintf(stderr, "%s: ", commandname);
  1136. if (!iflag || g_parsefile->pf_fd > 0)
  1137. fprintf(stderr, "line %d: ", startlinno);
  1138. }
  1139. vfprintf(stderr, msg, ap);
  1140. newline_and_flush(stderr);
  1141. }
  1142. /*
  1143. * Exverror is called to raise the error exception. If the second argument
  1144. * is not NULL then error prints an error message using printf style
  1145. * formatting. It then raises the error exception.
  1146. */
  1147. static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
  1148. static void
  1149. ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
  1150. {
  1151. #if DEBUG
  1152. if (msg) {
  1153. TRACE(("ash_vmsg_and_raise(%d):", cond));
  1154. TRACEV((msg, ap));
  1155. } else
  1156. TRACE(("ash_vmsg_and_raise(%d):NULL\n", cond));
  1157. if (msg)
  1158. #endif
  1159. ash_vmsg(msg, ap);
  1160. flush_stdout_stderr();
  1161. raise_exception(cond);
  1162. /* NOTREACHED */
  1163. }
  1164. static void ash_msg_and_raise_error(const char *, ...) NORETURN;
  1165. static void
  1166. ash_msg_and_raise_error(const char *msg, ...)
  1167. {
  1168. va_list ap;
  1169. exitstatus = 2;
  1170. va_start(ap, msg);
  1171. ash_vmsg_and_raise(EXERROR, msg, ap);
  1172. /* NOTREACHED */
  1173. va_end(ap);
  1174. }
  1175. /*
  1176. * 'fmt' must be a string literal.
  1177. */
  1178. #define ash_msg_and_raise_perror(fmt, ...) ash_msg_and_raise_error(fmt ": "STRERROR_FMT, ##__VA_ARGS__ STRERROR_ERRNO)
  1179. static void raise_error_syntax(const char *) NORETURN;
  1180. static void
  1181. raise_error_syntax(const char *msg)
  1182. {
  1183. ash_msg_and_raise_error("syntax error: %s", msg);
  1184. /* NOTREACHED */
  1185. }
  1186. static void ash_msg_and_raise(int, const char *, ...) NORETURN;
  1187. static void
  1188. ash_msg_and_raise(int cond, const char *msg, ...)
  1189. {
  1190. va_list ap;
  1191. va_start(ap, msg);
  1192. ash_vmsg_and_raise(cond, msg, ap);
  1193. /* NOTREACHED */
  1194. va_end(ap);
  1195. }
  1196. /*
  1197. * error/warning routines for external builtins
  1198. */
  1199. static void
  1200. ash_msg(const char *fmt, ...)
  1201. {
  1202. va_list ap;
  1203. va_start(ap, fmt);
  1204. ash_vmsg(fmt, ap);
  1205. va_end(ap);
  1206. }
  1207. /*
  1208. * Return a string describing an error. The returned string may be a
  1209. * pointer to a static buffer that will be overwritten on the next call.
  1210. * Action describes the operation that got the error.
  1211. */
  1212. static const char *
  1213. errmsg(int e, const char *em)
  1214. {
  1215. if (e == ENOENT || e == ENOTDIR) {
  1216. return em;
  1217. }
  1218. return strerror(e);
  1219. }
  1220. /* ============ Memory allocation */
  1221. #if 0
  1222. /* I consider these wrappers nearly useless:
  1223. * ok, they return you to nearest exception handler, but
  1224. * how much memory do you leak in the process, making
  1225. * memory starvation worse?
  1226. */
  1227. static void *
  1228. ckrealloc(void * p, size_t nbytes)
  1229. {
  1230. p = realloc(p, nbytes);
  1231. if (!p)
  1232. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  1233. return p;
  1234. }
  1235. static void *
  1236. ckmalloc(size_t nbytes)
  1237. {
  1238. return ckrealloc(NULL, nbytes);
  1239. }
  1240. static void *
  1241. ckzalloc(size_t nbytes)
  1242. {
  1243. return memset(ckmalloc(nbytes), 0, nbytes);
  1244. }
  1245. static char *
  1246. ckstrdup(const char *s)
  1247. {
  1248. char *p = strdup(s);
  1249. if (!p)
  1250. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  1251. return p;
  1252. }
  1253. #else
  1254. /* Using bbox equivalents. They exit if out of memory */
  1255. # define ckrealloc xrealloc
  1256. # define ckmalloc xmalloc
  1257. # define ckzalloc xzalloc
  1258. # define ckstrdup xstrdup
  1259. #endif
  1260. /*
  1261. * It appears that grabstackstr() will barf with such alignments
  1262. * because stalloc() will return a string allocated in a new stackblock.
  1263. */
  1264. #define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
  1265. enum {
  1266. /* Most machines require the value returned from malloc to be aligned
  1267. * in some way. The following macro will get this right
  1268. * on many machines. */
  1269. SHELL_SIZE = sizeof(union { int i; char *cp; double d; }) - 1,
  1270. /* Minimum size of a block */
  1271. MINSIZE = SHELL_ALIGN(504),
  1272. };
  1273. struct stack_block {
  1274. struct stack_block *prev;
  1275. char space[MINSIZE];
  1276. };
  1277. struct stackmark {
  1278. struct stack_block *stackp;
  1279. char *stacknxt;
  1280. size_t stacknleft;
  1281. };
  1282. struct globals_memstack {
  1283. struct stack_block *g_stackp; // = &stackbase;
  1284. char *g_stacknxt; // = stackbase.space;
  1285. char *sstrend; // = stackbase.space + MINSIZE;
  1286. size_t g_stacknleft; // = MINSIZE;
  1287. struct stack_block stackbase;
  1288. };
  1289. extern struct globals_memstack *const ash_ptr_to_globals_memstack;
  1290. #define G_memstack (*ash_ptr_to_globals_memstack)
  1291. #define g_stackp (G_memstack.g_stackp )
  1292. #define g_stacknxt (G_memstack.g_stacknxt )
  1293. #define sstrend (G_memstack.sstrend )
  1294. #define g_stacknleft (G_memstack.g_stacknleft)
  1295. #define stackbase (G_memstack.stackbase )
  1296. #define INIT_G_memstack() do { \
  1297. (*(struct globals_memstack**)&ash_ptr_to_globals_memstack) = xzalloc(sizeof(G_memstack)); \
  1298. barrier(); \
  1299. g_stackp = &stackbase; \
  1300. g_stacknxt = stackbase.space; \
  1301. g_stacknleft = MINSIZE; \
  1302. sstrend = stackbase.space + MINSIZE; \
  1303. } while (0)
  1304. #define stackblock() ((void *)g_stacknxt)
  1305. #define stackblocksize() g_stacknleft
  1306. /*
  1307. * Parse trees for commands are allocated in lifo order, so we use a stack
  1308. * to make this more efficient, and also to avoid all sorts of exception
  1309. * handling code to handle interrupts in the middle of a parse.
  1310. *
  1311. * The size 504 was chosen because the Ultrix malloc handles that size
  1312. * well.
  1313. */
  1314. static void *
  1315. stalloc(size_t nbytes)
  1316. {
  1317. char *p;
  1318. size_t aligned;
  1319. aligned = SHELL_ALIGN(nbytes);
  1320. if (aligned > g_stacknleft) {
  1321. size_t len;
  1322. size_t blocksize;
  1323. struct stack_block *sp;
  1324. blocksize = aligned;
  1325. if (blocksize < MINSIZE)
  1326. blocksize = MINSIZE;
  1327. len = sizeof(struct stack_block) - MINSIZE + blocksize;
  1328. if (len < blocksize)
  1329. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  1330. INT_OFF;
  1331. sp = ckmalloc(len);
  1332. sp->prev = g_stackp;
  1333. g_stacknxt = sp->space;
  1334. g_stacknleft = blocksize;
  1335. sstrend = g_stacknxt + blocksize;
  1336. g_stackp = sp;
  1337. INT_ON;
  1338. }
  1339. p = g_stacknxt;
  1340. g_stacknxt += aligned;
  1341. g_stacknleft -= aligned;
  1342. return p;
  1343. }
  1344. static void *
  1345. stzalloc(size_t nbytes)
  1346. {
  1347. return memset(stalloc(nbytes), 0, nbytes);
  1348. }
  1349. static void
  1350. stunalloc(void *p)
  1351. {
  1352. #if DEBUG
  1353. if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
  1354. write(STDERR_FILENO, "stunalloc\n", 10);
  1355. abort();
  1356. }
  1357. #endif
  1358. g_stacknleft += g_stacknxt - (char *)p;
  1359. g_stacknxt = p;
  1360. }
  1361. /*
  1362. * Like strdup but works with the ash stack.
  1363. */
  1364. static char *
  1365. sstrdup(const char *p)
  1366. {
  1367. size_t len = strlen(p) + 1;
  1368. return memcpy(stalloc(len), p, len);
  1369. }
  1370. static inline void
  1371. grabstackblock(size_t len)
  1372. {
  1373. stalloc(len);
  1374. }
  1375. static void
  1376. pushstackmark(struct stackmark *mark, size_t len)
  1377. {
  1378. mark->stackp = g_stackp;
  1379. mark->stacknxt = g_stacknxt;
  1380. mark->stacknleft = g_stacknleft;
  1381. grabstackblock(len);
  1382. }
  1383. static void
  1384. setstackmark(struct stackmark *mark)
  1385. {
  1386. pushstackmark(mark, g_stacknxt == g_stackp->space && g_stackp != &stackbase);
  1387. }
  1388. static void
  1389. popstackmark(struct stackmark *mark)
  1390. {
  1391. struct stack_block *sp;
  1392. if (!mark->stackp)
  1393. return;
  1394. INT_OFF;
  1395. while (g_stackp != mark->stackp) {
  1396. sp = g_stackp;
  1397. g_stackp = sp->prev;
  1398. free(sp);
  1399. }
  1400. g_stacknxt = mark->stacknxt;
  1401. g_stacknleft = mark->stacknleft;
  1402. sstrend = mark->stacknxt + mark->stacknleft;
  1403. INT_ON;
  1404. }
  1405. /*
  1406. * When the parser reads in a string, it wants to stick the string on the
  1407. * stack and only adjust the stack pointer when it knows how big the
  1408. * string is. Stackblock (defined in stack.h) returns a pointer to a block
  1409. * of space on top of the stack and stackblocklen returns the length of
  1410. * this block. Growstackblock will grow this space by at least one byte,
  1411. * possibly moving it (like realloc). Grabstackblock actually allocates the
  1412. * part of the block that has been used.
  1413. */
  1414. static void
  1415. growstackblock(void)
  1416. {
  1417. size_t newlen;
  1418. newlen = g_stacknleft * 2;
  1419. if (newlen < g_stacknleft)
  1420. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  1421. if (newlen < 128)
  1422. newlen += 128;
  1423. if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
  1424. struct stack_block *sp;
  1425. struct stack_block *prevstackp;
  1426. size_t grosslen;
  1427. INT_OFF;
  1428. sp = g_stackp;
  1429. prevstackp = sp->prev;
  1430. grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
  1431. sp = ckrealloc(sp, grosslen);
  1432. sp->prev = prevstackp;
  1433. g_stackp = sp;
  1434. g_stacknxt = sp->space;
  1435. g_stacknleft = newlen;
  1436. sstrend = sp->space + newlen;
  1437. INT_ON;
  1438. } else {
  1439. char *oldspace = g_stacknxt;
  1440. size_t oldlen = g_stacknleft;
  1441. char *p = stalloc(newlen);
  1442. /* free the space we just allocated */
  1443. g_stacknxt = memcpy(p, oldspace, oldlen);
  1444. g_stacknleft += newlen;
  1445. }
  1446. }
  1447. /*
  1448. * The following routines are somewhat easier to use than the above.
  1449. * The user declares a variable of type STACKSTR, which may be declared
  1450. * to be a register. The macro STARTSTACKSTR initializes things. Then
  1451. * the user uses the macro STPUTC to add characters to the string. In
  1452. * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
  1453. * grown as necessary. When the user is done, she can just leave the
  1454. * string there and refer to it using stackblock(). Or she can allocate
  1455. * the space for it using grabstackstr(). If it is necessary to allow
  1456. * someone else to use the stack temporarily and then continue to grow
  1457. * the string, the user should use grabstack to allocate the space, and
  1458. * then call ungrabstr(p) to return to the previous mode of operation.
  1459. *
  1460. * USTPUTC is like STPUTC except that it doesn't check for overflow.
  1461. * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
  1462. * is space for at least one character.
  1463. */
  1464. static void *
  1465. growstackstr(void)
  1466. {
  1467. size_t len = stackblocksize();
  1468. growstackblock();
  1469. return (char *)stackblock() + len;
  1470. }
  1471. /*
  1472. * Called from CHECKSTRSPACE.
  1473. */
  1474. static char *
  1475. makestrspace(size_t newlen, char *p)
  1476. {
  1477. size_t len = p - g_stacknxt;
  1478. size_t size;
  1479. for (;;) {
  1480. size_t nleft;
  1481. size = stackblocksize();
  1482. nleft = size - len;
  1483. if (nleft >= newlen)
  1484. break;
  1485. growstackblock();
  1486. }
  1487. return (char *)stackblock() + len;
  1488. }
  1489. static char *
  1490. stack_nputstr(const char *s, size_t n, char *p)
  1491. {
  1492. p = makestrspace(n, p);
  1493. p = (char *)mempcpy(p, s, n);
  1494. return p;
  1495. }
  1496. static char *
  1497. stack_putstr(const char *s, char *p)
  1498. {
  1499. return stack_nputstr(s, strlen(s), p);
  1500. }
  1501. static char *
  1502. _STPUTC(int c, char *p)
  1503. {
  1504. if (p == sstrend)
  1505. p = growstackstr();
  1506. *p++ = c;
  1507. return p;
  1508. }
  1509. #define STARTSTACKSTR(p) ((p) = stackblock())
  1510. #define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
  1511. #define CHECKSTRSPACE(n, p) do { \
  1512. char *q = (p); \
  1513. size_t l = (n); \
  1514. size_t m = sstrend - q; \
  1515. if (l > m) \
  1516. (p) = makestrspace(l, q); \
  1517. } while (0)
  1518. #define USTPUTC(c, p) (*(p)++ = (c))
  1519. #define STACKSTRNUL(p) do { \
  1520. if ((p) == sstrend) \
  1521. (p) = growstackstr(); \
  1522. *(p) = '\0'; \
  1523. } while (0)
  1524. #define STUNPUTC(p) (--(p))
  1525. #define STTOPC(p) ((p)[-1])
  1526. #define STADJUST(amount, p) ((p) += (amount))
  1527. #define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
  1528. #define ungrabstackstr(s, p) stunalloc(s)
  1529. #define stackstrend() ((void *)sstrend)
  1530. /* ============ String helpers */
  1531. /*
  1532. * prefix -- see if pfx is a prefix of string.
  1533. */
  1534. static char *
  1535. prefix(const char *string, const char *pfx)
  1536. {
  1537. while (*pfx) {
  1538. if (*pfx++ != *string++)
  1539. return NULL;
  1540. }
  1541. return (char *) string;
  1542. }
  1543. /*
  1544. * Check for a valid number. This should be elsewhere.
  1545. */
  1546. static int
  1547. is_number(const char *p)
  1548. {
  1549. do {
  1550. if (!isdigit(*p))
  1551. return 0;
  1552. } while (*++p != '\0');
  1553. return 1;
  1554. }
  1555. /*
  1556. * Convert a string of digits to an integer, printing an error message on
  1557. * failure.
  1558. */
  1559. static int
  1560. number(const char *s)
  1561. {
  1562. if (!is_number(s))
  1563. ash_msg_and_raise_error(msg_illnum, s);
  1564. return atoi(s);
  1565. }
  1566. /*
  1567. * Produce a single quoted string suitable as input to the shell.
  1568. * The return string is allocated on the stack.
  1569. */
  1570. static char *
  1571. single_quote(const char *s)
  1572. {
  1573. char *p;
  1574. STARTSTACKSTR(p);
  1575. do {
  1576. char *q;
  1577. size_t len;
  1578. len = strchrnul(s, '\'') - s;
  1579. q = p = makestrspace(len + 3, p);
  1580. *q++ = '\'';
  1581. q = (char *)mempcpy(q, s, len);
  1582. *q++ = '\'';
  1583. s += len;
  1584. STADJUST(q - p, p);
  1585. if (*s != '\'')
  1586. break;
  1587. len = 0;
  1588. do len++; while (*++s == '\'');
  1589. q = p = makestrspace(len + 3, p);
  1590. *q++ = '"';
  1591. q = (char *)mempcpy(q, s - len, len);
  1592. *q++ = '"';
  1593. STADJUST(q - p, p);
  1594. } while (*s);
  1595. USTPUTC('\0', p);
  1596. return stackblock();
  1597. }
  1598. /*
  1599. * Produce a possibly single quoted string suitable as input to the shell.
  1600. * If quoting was done, the return string is allocated on the stack,
  1601. * otherwise a pointer to the original string is returned.
  1602. */
  1603. static const char *
  1604. maybe_single_quote(const char *s)
  1605. {
  1606. const char *p = s;
  1607. while (*p) {
  1608. /* Assuming ACSII */
  1609. /* quote ctrl_chars space !"#$%&'()* */
  1610. if (*p < '+')
  1611. goto need_quoting;
  1612. /* quote ;<=>? */
  1613. if (*p >= ';' && *p <= '?')
  1614. goto need_quoting;
  1615. /* quote `[\ */
  1616. if (*p == '`')
  1617. goto need_quoting;
  1618. if (*p == '[')
  1619. goto need_quoting;
  1620. if (*p == '\\')
  1621. goto need_quoting;
  1622. /* quote {|}~ DEL and high bytes */
  1623. if (*p > 'z')
  1624. goto need_quoting;
  1625. /* Not quoting these: +,-./ 0-9 :@ A-Z ]^_ a-z */
  1626. /* TODO: maybe avoid quoting % */
  1627. p++;
  1628. }
  1629. return s;
  1630. need_quoting:
  1631. return single_quote(s);
  1632. }
  1633. /* ============ nextopt */
  1634. static char **argptr; /* argument list for builtin commands */
  1635. static char *optionarg; /* set by nextopt (like getopt) */
  1636. static char *optptr; /* used by nextopt */
  1637. /*
  1638. * XXX - should get rid of. Have all builtins use getopt(3).
  1639. * The library getopt must have the BSD extension static variable
  1640. * "optreset", otherwise it can't be used within the shell safely.
  1641. *
  1642. * Standard option processing (a la getopt) for builtin routines.
  1643. * The only argument that is passed to nextopt is the option string;
  1644. * the other arguments are unnecessary. It returns the character,
  1645. * or '\0' on end of input.
  1646. */
  1647. static int
  1648. nextopt(const char *optstring)
  1649. {
  1650. char *p;
  1651. const char *q;
  1652. char c;
  1653. p = optptr;
  1654. if (p == NULL || *p == '\0') {
  1655. /* We ate entire "-param", take next one */
  1656. p = *argptr;
  1657. if (p == NULL)
  1658. return '\0';
  1659. if (*p != '-')
  1660. return '\0';
  1661. if (*++p == '\0') /* just "-" ? */
  1662. return '\0';
  1663. argptr++;
  1664. if (LONE_DASH(p)) /* "--" ? */
  1665. return '\0';
  1666. /* p => next "-param" */
  1667. }
  1668. /* p => some option char in the middle of a "-param" */
  1669. c = *p++;
  1670. for (q = optstring; *q != c;) {
  1671. if (*q == '\0')
  1672. ash_msg_and_raise_error("illegal option -%c", c);
  1673. if (*++q == ':')
  1674. q++;
  1675. }
  1676. if (*++q == ':') {
  1677. if (*p == '\0') {
  1678. p = *argptr++;
  1679. if (p == NULL)
  1680. ash_msg_and_raise_error("no arg for -%c option", c);
  1681. }
  1682. optionarg = p;
  1683. p = NULL;
  1684. }
  1685. optptr = p;
  1686. return c;
  1687. }
  1688. /* ============ Shell variables */
  1689. struct shparam {
  1690. int nparam; /* # of positional parameters (without $0) */
  1691. #if ENABLE_ASH_GETOPTS
  1692. int optind; /* next parameter to be processed by getopts */
  1693. int optoff; /* used by getopts */
  1694. #endif
  1695. unsigned char malloced; /* if parameter list dynamically allocated */
  1696. char **p; /* parameter list */
  1697. };
  1698. /*
  1699. * Free the list of positional parameters.
  1700. */
  1701. static void
  1702. freeparam(volatile struct shparam *param)
  1703. {
  1704. if (param->malloced) {
  1705. char **ap, **ap1;
  1706. ap = ap1 = param->p;
  1707. while (*ap)
  1708. free(*ap++);
  1709. free(ap1);
  1710. }
  1711. }
  1712. #if ENABLE_ASH_GETOPTS
  1713. static void FAST_FUNC getoptsreset(const char *value);
  1714. #endif
  1715. struct var {
  1716. struct var *next; /* next entry in hash list */
  1717. int flags; /* flags are defined above */
  1718. const char *var_text; /* name=value */
  1719. void (*var_func)(const char *) FAST_FUNC; /* function to be called when */
  1720. /* the variable gets set/unset */
  1721. };
  1722. struct localvar {
  1723. struct localvar *next; /* next local variable in list */
  1724. struct var *vp; /* the variable that was made local */
  1725. int flags; /* saved flags */
  1726. const char *text; /* saved text */
  1727. };
  1728. /* flags */
  1729. #define VEXPORT 0x01 /* variable is exported */
  1730. #define VREADONLY 0x02 /* variable cannot be modified */
  1731. #define VSTRFIXED 0x04 /* variable struct is statically allocated */
  1732. #define VTEXTFIXED 0x08 /* text is statically allocated */
  1733. #define VSTACK 0x10 /* text is allocated on the stack */
  1734. #define VUNSET 0x20 /* the variable is not set */
  1735. #define VNOFUNC 0x40 /* don't call the callback function */
  1736. #define VNOSET 0x80 /* do not set variable - just readonly test */
  1737. #define VNOSAVE 0x100 /* when text is on the heap before setvareq */
  1738. #if ENABLE_ASH_RANDOM_SUPPORT
  1739. # define VDYNAMIC 0x200 /* dynamic variable */
  1740. #else
  1741. # define VDYNAMIC 0
  1742. #endif
  1743. /* Need to be before varinit_data[] */
  1744. #if ENABLE_LOCALE_SUPPORT
  1745. static void FAST_FUNC
  1746. change_lc_all(const char *value)
  1747. {
  1748. if (value && *value != '\0')
  1749. setlocale(LC_ALL, value);
  1750. }
  1751. static void FAST_FUNC
  1752. change_lc_ctype(const char *value)
  1753. {
  1754. if (value && *value != '\0')
  1755. setlocale(LC_CTYPE, value);
  1756. }
  1757. #endif
  1758. #if ENABLE_ASH_MAIL
  1759. static void chkmail(void);
  1760. static void changemail(const char *var_value) FAST_FUNC;
  1761. #else
  1762. # define chkmail() ((void)0)
  1763. #endif
  1764. static void changepath(const char *) FAST_FUNC;
  1765. #if ENABLE_ASH_RANDOM_SUPPORT
  1766. static void change_random(const char *) FAST_FUNC;
  1767. #endif
  1768. static const struct {
  1769. int flags;
  1770. const char *var_text;
  1771. void (*var_func)(const char *) FAST_FUNC;
  1772. } varinit_data[] = {
  1773. /*
  1774. * Note: VEXPORT would not work correctly here for NOFORK applets:
  1775. * some environment strings may be constant.
  1776. */
  1777. { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
  1778. #if ENABLE_ASH_MAIL
  1779. { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL" , changemail },
  1780. { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH" , changemail },
  1781. #endif
  1782. { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
  1783. { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
  1784. { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
  1785. { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
  1786. #if ENABLE_ASH_GETOPTS
  1787. { VSTRFIXED|VTEXTFIXED , defoptindvar, getoptsreset },
  1788. #endif
  1789. #if ENABLE_ASH_RANDOM_SUPPORT
  1790. { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM", change_random },
  1791. #endif
  1792. #if ENABLE_LOCALE_SUPPORT
  1793. { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL" , change_lc_all },
  1794. { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE" , change_lc_ctype },
  1795. #endif
  1796. #if ENABLE_FEATURE_EDITING_SAVEHISTORY
  1797. { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE" , NULL },
  1798. #endif
  1799. };
  1800. struct redirtab;
  1801. struct globals_var {
  1802. struct shparam shellparam; /* $@ current positional parameters */
  1803. struct redirtab *redirlist;
  1804. int preverrout_fd; /* stderr fd: usually 2, unless redirect moved it */
  1805. struct var *vartab[VTABSIZE];
  1806. struct var varinit[ARRAY_SIZE(varinit_data)];
  1807. };
  1808. extern struct globals_var *const ash_ptr_to_globals_var;
  1809. #define G_var (*ash_ptr_to_globals_var)
  1810. #define shellparam (G_var.shellparam )
  1811. //#define redirlist (G_var.redirlist )
  1812. #define preverrout_fd (G_var.preverrout_fd)
  1813. #define vartab (G_var.vartab )
  1814. #define varinit (G_var.varinit )
  1815. #define INIT_G_var() do { \
  1816. unsigned i; \
  1817. (*(struct globals_var**)&ash_ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
  1818. barrier(); \
  1819. for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
  1820. varinit[i].flags = varinit_data[i].flags; \
  1821. varinit[i].var_text = varinit_data[i].var_text; \
  1822. varinit[i].var_func = varinit_data[i].var_func; \
  1823. } \
  1824. } while (0)
  1825. #define vifs varinit[0]
  1826. #if ENABLE_ASH_MAIL
  1827. # define vmail (&vifs)[1]
  1828. # define vmpath (&vmail)[1]
  1829. # define vpath (&vmpath)[1]
  1830. #else
  1831. # define vpath (&vifs)[1]
  1832. #endif
  1833. #define vps1 (&vpath)[1]
  1834. #define vps2 (&vps1)[1]
  1835. #define vps4 (&vps2)[1]
  1836. #if ENABLE_ASH_GETOPTS
  1837. # define voptind (&vps4)[1]
  1838. # if ENABLE_ASH_RANDOM_SUPPORT
  1839. # define vrandom (&voptind)[1]
  1840. # endif
  1841. #else
  1842. # if ENABLE_ASH_RANDOM_SUPPORT
  1843. # define vrandom (&vps4)[1]
  1844. # endif
  1845. #endif
  1846. /*
  1847. * The following macros access the values of the above variables.
  1848. * They have to skip over the name. They return the null string
  1849. * for unset variables.
  1850. */
  1851. #define ifsval() (vifs.var_text + 4)
  1852. #define ifsset() ((vifs.flags & VUNSET) == 0)
  1853. #if ENABLE_ASH_MAIL
  1854. # define mailval() (vmail.var_text + 5)
  1855. # define mpathval() (vmpath.var_text + 9)
  1856. # define mpathset() ((vmpath.flags & VUNSET) == 0)
  1857. #endif
  1858. #define pathval() (vpath.var_text + 5)
  1859. #define ps1val() (vps1.var_text + 4)
  1860. #define ps2val() (vps2.var_text + 4)
  1861. #define ps4val() (vps4.var_text + 4)
  1862. #if ENABLE_ASH_GETOPTS
  1863. # define optindval() (voptind.var_text + 7)
  1864. #endif
  1865. #if ENABLE_ASH_GETOPTS
  1866. static void FAST_FUNC
  1867. getoptsreset(const char *value)
  1868. {
  1869. shellparam.optind = 1;
  1870. if (is_number(value))
  1871. shellparam.optind = number(value) ?: 1;
  1872. shellparam.optoff = -1;
  1873. }
  1874. #endif
  1875. /*
  1876. * Compares two strings up to the first = or '\0'. The first
  1877. * string must be terminated by '='; the second may be terminated by
  1878. * either '=' or '\0'.
  1879. */
  1880. static int
  1881. varcmp(const char *p, const char *q)
  1882. {
  1883. int c, d;
  1884. while ((c = *p) == (d = *q)) {
  1885. if (c == '\0' || c == '=')
  1886. goto out;
  1887. p++;
  1888. q++;
  1889. }
  1890. if (c == '=')
  1891. c = '\0';
  1892. if (d == '=')
  1893. d = '\0';
  1894. out:
  1895. return c - d;
  1896. }
  1897. /*
  1898. * Find the appropriate entry in the hash table from the name.
  1899. */
  1900. static struct var **
  1901. hashvar(const char *p)
  1902. {
  1903. unsigned hashval;
  1904. hashval = ((unsigned char) *p) << 4;
  1905. while (*p && *p != '=')
  1906. hashval += (unsigned char) *p++;
  1907. return &vartab[hashval % VTABSIZE];
  1908. }
  1909. static int
  1910. vpcmp(const void *a, const void *b)
  1911. {
  1912. return varcmp(*(const char **)a, *(const char **)b);
  1913. }
  1914. /*
  1915. * This routine initializes the builtin variables.
  1916. */
  1917. static void
  1918. initvar(void)
  1919. {
  1920. struct var *vp;
  1921. struct var *end;
  1922. struct var **vpp;
  1923. /*
  1924. * PS1 depends on uid
  1925. */
  1926. #if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
  1927. vps1.var_text = "PS1=\\w \\$ ";
  1928. #else
  1929. if (!geteuid())
  1930. vps1.var_text = "PS1=# ";
  1931. #endif
  1932. vp = varinit;
  1933. end = vp + ARRAY_SIZE(varinit);
  1934. do {
  1935. vpp = hashvar(vp->var_text);
  1936. vp->next = *vpp;
  1937. *vpp = vp;
  1938. } while (++vp < end);
  1939. }
  1940. static struct var **
  1941. findvar(struct var **vpp, const char *name)
  1942. {
  1943. for (; *vpp; vpp = &(*vpp)->next) {
  1944. if (varcmp((*vpp)->var_text, name) == 0) {
  1945. break;
  1946. }
  1947. }
  1948. return vpp;
  1949. }
  1950. /*
  1951. * Find the value of a variable. Returns NULL if not set.
  1952. */
  1953. static const char* FAST_FUNC
  1954. lookupvar(const char *name)
  1955. {
  1956. struct var *v;
  1957. v = *findvar(hashvar(name), name);
  1958. if (v) {
  1959. #if ENABLE_ASH_RANDOM_SUPPORT
  1960. /*
  1961. * Dynamic variables are implemented roughly the same way they are
  1962. * in bash. Namely, they're "special" so long as they aren't unset.
  1963. * As soon as they're unset, they're no longer dynamic, and dynamic
  1964. * lookup will no longer happen at that point. -- PFM.
  1965. */
  1966. if (v->flags & VDYNAMIC)
  1967. v->var_func(NULL);
  1968. #endif
  1969. if (!(v->flags & VUNSET))
  1970. return var_end(v->var_text);
  1971. }
  1972. return NULL;
  1973. }
  1974. #if ENABLE_UNICODE_SUPPORT
  1975. static void
  1976. reinit_unicode_for_ash(void)
  1977. {
  1978. /* Unicode support should be activated even if LANG is set
  1979. * _during_ shell execution, not only if it was set when
  1980. * shell was started. Therefore, re-check LANG every time:
  1981. */
  1982. if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
  1983. || ENABLE_UNICODE_USING_LOCALE
  1984. ) {
  1985. const char *s = lookupvar("LC_ALL");
  1986. if (!s) s = lookupvar("LC_CTYPE");
  1987. if (!s) s = lookupvar("LANG");
  1988. reinit_unicode(s);
  1989. }
  1990. }
  1991. #else
  1992. # define reinit_unicode_for_ash() ((void)0)
  1993. #endif
  1994. /*
  1995. * Search the environment of a builtin command.
  1996. */
  1997. static ALWAYS_INLINE const char *
  1998. bltinlookup(const char *name)
  1999. {
  2000. return lookupvar(name);
  2001. }
  2002. /*
  2003. * Same as setvar except that the variable and value are passed in
  2004. * the first argument as name=value. Since the first argument will
  2005. * be actually stored in the table, it should not be a string that
  2006. * will go away.
  2007. * Called with interrupts off.
  2008. */
  2009. static struct var *
  2010. setvareq(char *s, int flags)
  2011. {
  2012. struct var *vp, **vpp;
  2013. vpp = hashvar(s);
  2014. flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
  2015. vpp = findvar(vpp, s);
  2016. vp = *vpp;
  2017. if (vp) {
  2018. if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
  2019. const char *n;
  2020. if (flags & VNOSAVE)
  2021. free(s);
  2022. n = vp->var_text;
  2023. exitstatus = 1;
  2024. ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
  2025. }
  2026. if (flags & VNOSET)
  2027. goto out;
  2028. if (vp->var_func && !(flags & VNOFUNC))
  2029. vp->var_func(var_end(s));
  2030. if (!(vp->flags & (VTEXTFIXED|VSTACK)))
  2031. free((char*)vp->var_text);
  2032. if (((flags & (VEXPORT|VREADONLY|VSTRFIXED|VUNSET)) | (vp->flags & VSTRFIXED)) == VUNSET) {
  2033. *vpp = vp->next;
  2034. free(vp);
  2035. out_free:
  2036. if ((flags & (VTEXTFIXED|VSTACK|VNOSAVE)) == VNOSAVE)
  2037. free(s);
  2038. goto out;
  2039. }
  2040. flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
  2041. } else {
  2042. /* variable s is not found */
  2043. if (flags & VNOSET)
  2044. goto out;
  2045. if ((flags & (VEXPORT|VREADONLY|VSTRFIXED|VUNSET)) == VUNSET)
  2046. goto out_free;
  2047. vp = ckzalloc(sizeof(*vp));
  2048. vp->next = *vpp;
  2049. /*vp->func = NULL; - ckzalloc did it */
  2050. *vpp = vp;
  2051. }
  2052. if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
  2053. s = ckstrdup(s);
  2054. vp->var_text = s;
  2055. vp->flags = flags;
  2056. out:
  2057. return vp;
  2058. }
  2059. /*
  2060. * Set the value of a variable. The flags argument is ored with the
  2061. * flags of the variable. If val is NULL, the variable is unset.
  2062. */
  2063. static struct var *
  2064. setvar(const char *name, const char *val, int flags)
  2065. {
  2066. const char *q;
  2067. char *p;
  2068. char *nameeq;
  2069. size_t namelen;
  2070. size_t vallen;
  2071. struct var *vp;
  2072. q = endofname(name);
  2073. p = strchrnul(q, '=');
  2074. namelen = p - name;
  2075. if (!namelen || p != q)
  2076. ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
  2077. vallen = 0;
  2078. if (val == NULL) {
  2079. flags |= VUNSET;
  2080. } else {
  2081. vallen = strlen(val);
  2082. }
  2083. INT_OFF;
  2084. nameeq = ckmalloc(namelen + vallen + 2);
  2085. p = mempcpy(nameeq, name, namelen);
  2086. if (val) {
  2087. *p++ = '=';
  2088. p = mempcpy(p, val, vallen);
  2089. }
  2090. *p = '\0';
  2091. vp = setvareq(nameeq, flags | VNOSAVE);
  2092. INT_ON;
  2093. return vp;
  2094. }
  2095. static void FAST_FUNC
  2096. setvar0(const char *name, const char *val)
  2097. {
  2098. setvar(name, val, 0);
  2099. }
  2100. /*
  2101. * Unset the specified variable.
  2102. */
  2103. static void
  2104. unsetvar(const char *s)
  2105. {
  2106. setvar(s, NULL, 0);
  2107. }
  2108. /*
  2109. * Process a linked list of variable assignments.
  2110. */
  2111. static void
  2112. listsetvar(struct strlist *list_set_var, int flags)
  2113. {
  2114. struct strlist *lp = list_set_var;
  2115. if (!lp)
  2116. return;
  2117. INT_OFF;
  2118. do {
  2119. setvareq(lp->text, flags);
  2120. lp = lp->next;
  2121. } while (lp);
  2122. INT_ON;
  2123. }
  2124. /*
  2125. * Generate a list of variables satisfying the given conditions.
  2126. */
  2127. #if !ENABLE_FEATURE_SH_NOFORK
  2128. # define listvars(on, off, lp, end) listvars(on, off, end)
  2129. #endif
  2130. static char **
  2131. listvars(int on, int off, struct strlist *lp, char ***end)
  2132. {
  2133. struct var **vpp;
  2134. struct var *vp;
  2135. char **ep;
  2136. int mask;
  2137. STARTSTACKSTR(ep);
  2138. vpp = vartab;
  2139. mask = on | off;
  2140. do {
  2141. for (vp = *vpp; vp; vp = vp->next) {
  2142. if ((vp->flags & mask) == on) {
  2143. #if ENABLE_FEATURE_SH_NOFORK
  2144. /* If variable with the same name is both
  2145. * exported and temporarily set for a command:
  2146. * export ZVAR=5
  2147. * ZVAR=6 printenv
  2148. * then "ZVAR=6" will be both in vartab and
  2149. * lp lists. Do not pass it twice to printenv.
  2150. */
  2151. struct strlist *lp1 = lp;
  2152. while (lp1) {
  2153. if (strcmp(lp1->text, vp->var_text) == 0)
  2154. goto skip;
  2155. lp1 = lp1->next;
  2156. }
  2157. #endif
  2158. if (ep == stackstrend())
  2159. ep = growstackstr();
  2160. *ep++ = (char*)vp->var_text;
  2161. #if ENABLE_FEATURE_SH_NOFORK
  2162. skip: ;
  2163. #endif
  2164. }
  2165. }
  2166. } while (++vpp < vartab + VTABSIZE);
  2167. #if ENABLE_FEATURE_SH_NOFORK
  2168. while (lp) {
  2169. if (ep == stackstrend())
  2170. ep = growstackstr();
  2171. *ep++ = lp->text;
  2172. lp = lp->next;
  2173. }
  2174. #endif
  2175. if (ep == stackstrend())
  2176. ep = growstackstr();
  2177. if (end)
  2178. *end = ep;
  2179. *ep++ = NULL;
  2180. return grabstackstr(ep);
  2181. }
  2182. /* ============ Path search helper
  2183. *
  2184. * The variable path (passed by reference) should be set to the start
  2185. * of the path before the first call; path_advance will update
  2186. * this value as it proceeds. Successive calls to path_advance will return
  2187. * the possible path expansions in sequence. If an option (indicated by
  2188. * a percent sign) appears in the path entry then the global variable
  2189. * pathopt will be set to point to it; otherwise pathopt will be set to
  2190. * NULL.
  2191. */
  2192. static const char *pathopt; /* set by path_advance */
  2193. static char *
  2194. path_advance(const char **path, const char *name)
  2195. {
  2196. const char *p;
  2197. char *q;
  2198. const char *start;
  2199. size_t len;
  2200. if (*path == NULL)
  2201. return NULL;
  2202. start = *path;
  2203. for (p = start; *p && *p != ':' && *p != '%'; p++)
  2204. continue;
  2205. len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
  2206. while (stackblocksize() < len)
  2207. growstackblock();
  2208. q = stackblock();
  2209. if (p != start) {
  2210. q = mempcpy(q, start, p - start);
  2211. *q++ = '/';
  2212. }
  2213. strcpy(q, name);
  2214. pathopt = NULL;
  2215. if (*p == '%') {
  2216. pathopt = ++p;
  2217. while (*p && *p != ':')
  2218. p++;
  2219. }
  2220. if (*p == ':')
  2221. *path = p + 1;
  2222. else
  2223. *path = NULL;
  2224. return stalloc(len);
  2225. }
  2226. /* ============ Prompt */
  2227. static smallint doprompt; /* if set, prompt the user */
  2228. static smallint needprompt; /* true if interactive and at start of line */
  2229. #if ENABLE_FEATURE_EDITING
  2230. static line_input_t *line_input_state;
  2231. static const char *cmdedit_prompt;
  2232. static void
  2233. putprompt(const char *s)
  2234. {
  2235. if (ENABLE_ASH_EXPAND_PRMT) {
  2236. free((char*)cmdedit_prompt);
  2237. cmdedit_prompt = ckstrdup(s);
  2238. return;
  2239. }
  2240. cmdedit_prompt = s;
  2241. }
  2242. #else
  2243. static void
  2244. putprompt(const char *s)
  2245. {
  2246. out2str(s);
  2247. }
  2248. #endif
  2249. /* expandstr() needs parsing machinery, so it is far away ahead... */
  2250. static const char *expandstr(const char *ps, int syntax_type);
  2251. /* Values for syntax param */
  2252. #define BASESYNTAX 0 /* not in quotes */
  2253. #define DQSYNTAX 1 /* in double quotes */
  2254. #define SQSYNTAX 2 /* in single quotes */
  2255. #define ARISYNTAX 3 /* in arithmetic */
  2256. #if ENABLE_ASH_EXPAND_PRMT
  2257. # define PSSYNTAX 4 /* prompt. never passed to SIT() */
  2258. #endif
  2259. /* PSSYNTAX expansion is identical to DQSYNTAX, except keeping '\$' as '\$' */
  2260. /*
  2261. * called by editline -- any expansions to the prompt should be added here.
  2262. */
  2263. static void
  2264. setprompt_if(smallint do_set, int whichprompt)
  2265. {
  2266. const char *prompt;
  2267. IF_ASH_EXPAND_PRMT(struct stackmark smark;)
  2268. if (!do_set)
  2269. return;
  2270. needprompt = 0;
  2271. switch (whichprompt) {
  2272. case 1:
  2273. prompt = ps1val();
  2274. break;
  2275. case 2:
  2276. prompt = ps2val();
  2277. break;
  2278. default: /* 0 */
  2279. prompt = nullstr;
  2280. }
  2281. #if ENABLE_ASH_EXPAND_PRMT
  2282. pushstackmark(&smark, stackblocksize());
  2283. putprompt(expandstr(prompt, PSSYNTAX));
  2284. popstackmark(&smark);
  2285. #else
  2286. putprompt(prompt);
  2287. #endif
  2288. }
  2289. /* ============ The cd and pwd commands */
  2290. #define CD_PHYSICAL 1
  2291. #define CD_PRINT 2
  2292. static int
  2293. cdopt(void)
  2294. {
  2295. int flags = 0;
  2296. int i, j;
  2297. j = 'L';
  2298. while ((i = nextopt("LP")) != '\0') {
  2299. if (i != j) {
  2300. flags ^= CD_PHYSICAL;
  2301. j = i;
  2302. }
  2303. }
  2304. return flags;
  2305. }
  2306. /*
  2307. * Update curdir (the name of the current directory) in response to a
  2308. * cd command.
  2309. */
  2310. static const char *
  2311. updatepwd(const char *dir)
  2312. {
  2313. char *new;
  2314. char *p;
  2315. char *cdcomppath;
  2316. const char *lim;
  2317. cdcomppath = sstrdup(dir);
  2318. STARTSTACKSTR(new);
  2319. if (*dir != '/') {
  2320. if (curdir == nullstr)
  2321. return 0;
  2322. new = stack_putstr(curdir, new);
  2323. }
  2324. new = makestrspace(strlen(dir) + 2, new);
  2325. lim = (char *)stackblock() + 1;
  2326. if (*dir != '/') {
  2327. if (new[-1] != '/')
  2328. USTPUTC('/', new);
  2329. if (new > lim && *lim == '/')
  2330. lim++;
  2331. } else {
  2332. USTPUTC('/', new);
  2333. cdcomppath++;
  2334. if (dir[1] == '/' && dir[2] != '/') {
  2335. USTPUTC('/', new);
  2336. cdcomppath++;
  2337. lim++;
  2338. }
  2339. }
  2340. p = strtok(cdcomppath, "/");
  2341. while (p) {
  2342. switch (*p) {
  2343. case '.':
  2344. if (p[1] == '.' && p[2] == '\0') {
  2345. while (new > lim) {
  2346. STUNPUTC(new);
  2347. if (new[-1] == '/')
  2348. break;
  2349. }
  2350. break;
  2351. }
  2352. if (p[1] == '\0')
  2353. break;
  2354. /* fall through */
  2355. default:
  2356. new = stack_putstr(p, new);
  2357. USTPUTC('/', new);
  2358. }
  2359. p = strtok(NULL, "/");
  2360. }
  2361. if (new > lim)
  2362. STUNPUTC(new);
  2363. *new = 0;
  2364. return stackblock();
  2365. }
  2366. /*
  2367. * Find out what the current directory is. If we already know the current
  2368. * directory, this routine returns immediately.
  2369. */
  2370. static char *
  2371. getpwd(void)
  2372. {
  2373. char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
  2374. return dir ? dir : nullstr;
  2375. }
  2376. static void
  2377. setpwd(const char *val, int setold)
  2378. {
  2379. char *oldcur, *dir;
  2380. oldcur = dir = curdir;
  2381. if (setold) {
  2382. setvar("OLDPWD", oldcur, VEXPORT);
  2383. }
  2384. INT_OFF;
  2385. if (physdir != nullstr) {
  2386. if (physdir != oldcur)
  2387. free(physdir);
  2388. physdir = nullstr;
  2389. }
  2390. if (oldcur == val || !val) {
  2391. char *s = getpwd();
  2392. physdir = s;
  2393. if (!val)
  2394. dir = s;
  2395. } else
  2396. dir = ckstrdup(val);
  2397. if (oldcur != dir && oldcur != nullstr) {
  2398. free(oldcur);
  2399. }
  2400. curdir = dir;
  2401. INT_ON;
  2402. setvar("PWD", dir, VEXPORT);
  2403. }
  2404. static void hashcd(void);
  2405. /*
  2406. * Actually do the chdir. We also call hashcd to let other routines
  2407. * know that the current directory has changed.
  2408. */
  2409. static int
  2410. docd(const char *dest, int flags)
  2411. {
  2412. const char *dir = NULL;
  2413. int err;
  2414. TRACE(("docd(\"%s\", %d) called\n", dest, flags));
  2415. INT_OFF;
  2416. if (!(flags & CD_PHYSICAL)) {
  2417. dir = updatepwd(dest);
  2418. if (dir)
  2419. dest = dir;
  2420. }
  2421. err = chdir(dest);
  2422. if (err)
  2423. goto out;
  2424. setpwd(dir, 1);
  2425. hashcd();
  2426. out:
  2427. INT_ON;
  2428. return err;
  2429. }
  2430. static int FAST_FUNC
  2431. cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  2432. {
  2433. const char *dest;
  2434. const char *path;
  2435. const char *p;
  2436. char c;
  2437. struct stat statb;
  2438. int flags;
  2439. flags = cdopt();
  2440. dest = *argptr;
  2441. if (!dest)
  2442. dest = bltinlookup("HOME");
  2443. else if (LONE_DASH(dest)) {
  2444. dest = bltinlookup("OLDPWD");
  2445. flags |= CD_PRINT;
  2446. }
  2447. if (!dest)
  2448. dest = nullstr;
  2449. if (*dest == '/')
  2450. goto step6;
  2451. if (*dest == '.') {
  2452. c = dest[1];
  2453. dotdot:
  2454. switch (c) {
  2455. case '\0':
  2456. case '/':
  2457. goto step6;
  2458. case '.':
  2459. c = dest[2];
  2460. if (c != '.')
  2461. goto dotdot;
  2462. }
  2463. }
  2464. if (!*dest)
  2465. dest = ".";
  2466. path = bltinlookup("CDPATH");
  2467. while (path) {
  2468. c = *path;
  2469. p = path_advance(&path, dest);
  2470. if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
  2471. if (c && c != ':')
  2472. flags |= CD_PRINT;
  2473. docd:
  2474. if (!docd(p, flags))
  2475. goto out;
  2476. goto err;
  2477. }
  2478. }
  2479. step6:
  2480. p = dest;
  2481. goto docd;
  2482. err:
  2483. ash_msg_and_raise_perror("can't cd to %s", dest);
  2484. /* NOTREACHED */
  2485. out:
  2486. if (flags & CD_PRINT)
  2487. out1fmt("%s\n", curdir);
  2488. return 0;
  2489. }
  2490. static int FAST_FUNC
  2491. pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  2492. {
  2493. int flags;
  2494. const char *dir = curdir;
  2495. flags = cdopt();
  2496. if (flags) {
  2497. if (physdir == nullstr)
  2498. setpwd(dir, 0);
  2499. dir = physdir;
  2500. }
  2501. out1fmt("%s\n", dir);
  2502. return 0;
  2503. }
  2504. /* ============ ... */
  2505. #define IBUFSIZ (ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 1024)
  2506. /* Syntax classes */
  2507. #define CWORD 0 /* character is nothing special */
  2508. #define CNL 1 /* newline character */
  2509. #define CBACK 2 /* a backslash character */
  2510. #define CSQUOTE 3 /* single quote */
  2511. #define CDQUOTE 4 /* double quote */
  2512. #define CENDQUOTE 5 /* a terminating quote */
  2513. #define CBQUOTE 6 /* backwards single quote */
  2514. #define CVAR 7 /* a dollar sign */
  2515. #define CENDVAR 8 /* a '}' character */
  2516. #define CLP 9 /* a left paren in arithmetic */
  2517. #define CRP 10 /* a right paren in arithmetic */
  2518. #define CENDFILE 11 /* end of file */
  2519. #define CCTL 12 /* like CWORD, except it must be escaped */
  2520. #define CSPCL 13 /* these terminate a word */
  2521. #define CIGN 14 /* character should be ignored */
  2522. #define PEOF 256
  2523. #if ENABLE_ASH_ALIAS
  2524. # define PEOA 257
  2525. #endif
  2526. #define USE_SIT_FUNCTION ENABLE_ASH_OPTIMIZE_FOR_SIZE
  2527. #if ENABLE_FEATURE_SH_MATH
  2528. # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8) | (d << 12))
  2529. #else
  2530. # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8))
  2531. #endif
  2532. static const uint16_t S_I_T[] ALIGN2 = {
  2533. #if ENABLE_ASH_ALIAS
  2534. SIT_ITEM(CSPCL , CIGN , CIGN , CIGN ), /* 0, PEOA */
  2535. #endif
  2536. SIT_ITEM(CSPCL , CWORD , CWORD, CWORD ), /* 1, ' ' */
  2537. SIT_ITEM(CNL , CNL , CNL , CNL ), /* 2, \n */
  2538. SIT_ITEM(CWORD , CCTL , CCTL , CWORD ), /* 3, !*-/:=?[]~ */
  2539. SIT_ITEM(CDQUOTE , CENDQUOTE, CWORD, CWORD ), /* 4, '"' */
  2540. SIT_ITEM(CVAR , CVAR , CWORD, CVAR ), /* 5, $ */
  2541. SIT_ITEM(CSQUOTE , CWORD , CENDQUOTE, CWORD), /* 6, "'" */
  2542. SIT_ITEM(CSPCL , CWORD , CWORD, CLP ), /* 7, ( */
  2543. SIT_ITEM(CSPCL , CWORD , CWORD, CRP ), /* 8, ) */
  2544. SIT_ITEM(CBACK , CBACK , CCTL , CBACK ), /* 9, \ */
  2545. SIT_ITEM(CBQUOTE , CBQUOTE , CWORD, CBQUOTE), /* 10, ` */
  2546. SIT_ITEM(CENDVAR , CENDVAR , CWORD, CENDVAR), /* 11, } */
  2547. #if !USE_SIT_FUNCTION
  2548. SIT_ITEM(CENDFILE, CENDFILE , CENDFILE, CENDFILE),/* 12, PEOF */
  2549. SIT_ITEM(CWORD , CWORD , CWORD, CWORD ), /* 13, 0-9A-Za-z */
  2550. SIT_ITEM(CCTL , CCTL , CCTL , CCTL ) /* 14, CTLESC ... */
  2551. #endif
  2552. #undef SIT_ITEM
  2553. };
  2554. /* Constants below must match table above */
  2555. enum {
  2556. #if ENABLE_ASH_ALIAS
  2557. CSPCL_CIGN_CIGN_CIGN , /* 0 */
  2558. #endif
  2559. CSPCL_CWORD_CWORD_CWORD , /* 1 */
  2560. CNL_CNL_CNL_CNL , /* 2 */
  2561. CWORD_CCTL_CCTL_CWORD , /* 3 */
  2562. CDQUOTE_CENDQUOTE_CWORD_CWORD , /* 4 */
  2563. CVAR_CVAR_CWORD_CVAR , /* 5 */
  2564. CSQUOTE_CWORD_CENDQUOTE_CWORD , /* 6 */
  2565. CSPCL_CWORD_CWORD_CLP , /* 7 */
  2566. CSPCL_CWORD_CWORD_CRP , /* 8 */
  2567. CBACK_CBACK_CCTL_CBACK , /* 9 */
  2568. CBQUOTE_CBQUOTE_CWORD_CBQUOTE , /* 10 */
  2569. CENDVAR_CENDVAR_CWORD_CENDVAR , /* 11 */
  2570. CENDFILE_CENDFILE_CENDFILE_CENDFILE, /* 12 */
  2571. CWORD_CWORD_CWORD_CWORD , /* 13 */
  2572. CCTL_CCTL_CCTL_CCTL , /* 14 */
  2573. };
  2574. /* c in SIT(c, syntax) must be an *unsigned char* or PEOA or PEOF,
  2575. * caller must ensure proper cast on it if c is *char_ptr!
  2576. */
  2577. #if USE_SIT_FUNCTION
  2578. static int
  2579. SIT(int c, int syntax)
  2580. {
  2581. /* Used to also have '/' in this string: "\t\n !\"$&'()*-/:;<=>?[\\]`|}~" */
  2582. static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-:;<=>?[\\]`|}~";
  2583. /*
  2584. * This causes '/' to be prepended with CTLESC in dquoted string,
  2585. * making "./file"* treated incorrectly because we feed
  2586. * ".\/file*" string to glob(), confusing it (see expandmeta func).
  2587. * The "homegrown" glob implementation is okay with that,
  2588. * but glibc one isn't. With '/' always treated as CWORD,
  2589. * both work fine.
  2590. */
  2591. # if ENABLE_ASH_ALIAS
  2592. static const uint8_t syntax_index_table[] ALIGN1 = {
  2593. 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
  2594. 7, 8, 3, 3,/*3,*/3, 1, 1, /* "()*-/:;<" */
  2595. 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
  2596. 11, 3 /* "}~" */
  2597. };
  2598. # else
  2599. static const uint8_t syntax_index_table[] ALIGN1 = {
  2600. 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
  2601. 6, 7, 2, 2,/*2,*/2, 0, 0, /* "()*-/:;<" */
  2602. 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
  2603. 10, 2 /* "}~" */
  2604. };
  2605. # endif
  2606. const char *s;
  2607. int indx;
  2608. if (c == PEOF)
  2609. return CENDFILE;
  2610. # if ENABLE_ASH_ALIAS
  2611. if (c == PEOA)
  2612. indx = 0;
  2613. else
  2614. # endif
  2615. {
  2616. /* Cast is purely for paranoia here,
  2617. * just in case someone passed signed char to us */
  2618. if ((unsigned char)c >= CTL_FIRST
  2619. && (unsigned char)c <= CTL_LAST
  2620. ) {
  2621. return CCTL;
  2622. }
  2623. s = strchrnul(spec_symbls, c);
  2624. if (*s == '\0')
  2625. return CWORD;
  2626. indx = syntax_index_table[s - spec_symbls];
  2627. }
  2628. return (S_I_T[indx] >> (syntax*4)) & 0xf;
  2629. }
  2630. #else /* !USE_SIT_FUNCTION */
  2631. static const uint8_t syntax_index_table[] ALIGN1 = {
  2632. /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
  2633. /* 0 */ CWORD_CWORD_CWORD_CWORD,
  2634. /* 1 */ CWORD_CWORD_CWORD_CWORD,
  2635. /* 2 */ CWORD_CWORD_CWORD_CWORD,
  2636. /* 3 */ CWORD_CWORD_CWORD_CWORD,
  2637. /* 4 */ CWORD_CWORD_CWORD_CWORD,
  2638. /* 5 */ CWORD_CWORD_CWORD_CWORD,
  2639. /* 6 */ CWORD_CWORD_CWORD_CWORD,
  2640. /* 7 */ CWORD_CWORD_CWORD_CWORD,
  2641. /* 8 */ CWORD_CWORD_CWORD_CWORD,
  2642. /* 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
  2643. /* 10 "\n" */ CNL_CNL_CNL_CNL,
  2644. /* 11 */ CWORD_CWORD_CWORD_CWORD,
  2645. /* 12 */ CWORD_CWORD_CWORD_CWORD,
  2646. /* 13 */ CWORD_CWORD_CWORD_CWORD,
  2647. /* 14 */ CWORD_CWORD_CWORD_CWORD,
  2648. /* 15 */ CWORD_CWORD_CWORD_CWORD,
  2649. /* 16 */ CWORD_CWORD_CWORD_CWORD,
  2650. /* 17 */ CWORD_CWORD_CWORD_CWORD,
  2651. /* 18 */ CWORD_CWORD_CWORD_CWORD,
  2652. /* 19 */ CWORD_CWORD_CWORD_CWORD,
  2653. /* 20 */ CWORD_CWORD_CWORD_CWORD,
  2654. /* 21 */ CWORD_CWORD_CWORD_CWORD,
  2655. /* 22 */ CWORD_CWORD_CWORD_CWORD,
  2656. /* 23 */ CWORD_CWORD_CWORD_CWORD,
  2657. /* 24 */ CWORD_CWORD_CWORD_CWORD,
  2658. /* 25 */ CWORD_CWORD_CWORD_CWORD,
  2659. /* 26 */ CWORD_CWORD_CWORD_CWORD,
  2660. /* 27 */ CWORD_CWORD_CWORD_CWORD,
  2661. /* 28 */ CWORD_CWORD_CWORD_CWORD,
  2662. /* 29 */ CWORD_CWORD_CWORD_CWORD,
  2663. /* 30 */ CWORD_CWORD_CWORD_CWORD,
  2664. /* 31 */ CWORD_CWORD_CWORD_CWORD,
  2665. /* 32 " " */ CSPCL_CWORD_CWORD_CWORD,
  2666. /* 33 "!" */ CWORD_CCTL_CCTL_CWORD,
  2667. /* 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
  2668. /* 35 "#" */ CWORD_CWORD_CWORD_CWORD,
  2669. /* 36 "$" */ CVAR_CVAR_CWORD_CVAR,
  2670. /* 37 "%" */ CWORD_CWORD_CWORD_CWORD,
  2671. /* 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
  2672. /* 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
  2673. /* 40 "(" */ CSPCL_CWORD_CWORD_CLP,
  2674. /* 41 ")" */ CSPCL_CWORD_CWORD_CRP,
  2675. /* 42 "*" */ CWORD_CCTL_CCTL_CWORD,
  2676. /* 43 "+" */ CWORD_CWORD_CWORD_CWORD,
  2677. /* 44 "," */ CWORD_CWORD_CWORD_CWORD,
  2678. /* 45 "-" */ CWORD_CCTL_CCTL_CWORD,
  2679. /* 46 "." */ CWORD_CWORD_CWORD_CWORD,
  2680. /* "/" was CWORD_CCTL_CCTL_CWORD, see comment in SIT() function why this is changed: */
  2681. /* 47 "/" */ CWORD_CWORD_CWORD_CWORD,
  2682. /* 48 "0" */ CWORD_CWORD_CWORD_CWORD,
  2683. /* 49 "1" */ CWORD_CWORD_CWORD_CWORD,
  2684. /* 50 "2" */ CWORD_CWORD_CWORD_CWORD,
  2685. /* 51 "3" */ CWORD_CWORD_CWORD_CWORD,
  2686. /* 52 "4" */ CWORD_CWORD_CWORD_CWORD,
  2687. /* 53 "5" */ CWORD_CWORD_CWORD_CWORD,
  2688. /* 54 "6" */ CWORD_CWORD_CWORD_CWORD,
  2689. /* 55 "7" */ CWORD_CWORD_CWORD_CWORD,
  2690. /* 56 "8" */ CWORD_CWORD_CWORD_CWORD,
  2691. /* 57 "9" */ CWORD_CWORD_CWORD_CWORD,
  2692. /* 58 ":" */ CWORD_CCTL_CCTL_CWORD,
  2693. /* 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
  2694. /* 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
  2695. /* 61 "=" */ CWORD_CCTL_CCTL_CWORD,
  2696. /* 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
  2697. /* 63 "?" */ CWORD_CCTL_CCTL_CWORD,
  2698. /* 64 "@" */ CWORD_CWORD_CWORD_CWORD,
  2699. /* 65 "A" */ CWORD_CWORD_CWORD_CWORD,
  2700. /* 66 "B" */ CWORD_CWORD_CWORD_CWORD,
  2701. /* 67 "C" */ CWORD_CWORD_CWORD_CWORD,
  2702. /* 68 "D" */ CWORD_CWORD_CWORD_CWORD,
  2703. /* 69 "E" */ CWORD_CWORD_CWORD_CWORD,
  2704. /* 70 "F" */ CWORD_CWORD_CWORD_CWORD,
  2705. /* 71 "G" */ CWORD_CWORD_CWORD_CWORD,
  2706. /* 72 "H" */ CWORD_CWORD_CWORD_CWORD,
  2707. /* 73 "I" */ CWORD_CWORD_CWORD_CWORD,
  2708. /* 74 "J" */ CWORD_CWORD_CWORD_CWORD,
  2709. /* 75 "K" */ CWORD_CWORD_CWORD_CWORD,
  2710. /* 76 "L" */ CWORD_CWORD_CWORD_CWORD,
  2711. /* 77 "M" */ CWORD_CWORD_CWORD_CWORD,
  2712. /* 78 "N" */ CWORD_CWORD_CWORD_CWORD,
  2713. /* 79 "O" */ CWORD_CWORD_CWORD_CWORD,
  2714. /* 80 "P" */ CWORD_CWORD_CWORD_CWORD,
  2715. /* 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
  2716. /* 82 "R" */ CWORD_CWORD_CWORD_CWORD,
  2717. /* 83 "S" */ CWORD_CWORD_CWORD_CWORD,
  2718. /* 84 "T" */ CWORD_CWORD_CWORD_CWORD,
  2719. /* 85 "U" */ CWORD_CWORD_CWORD_CWORD,
  2720. /* 86 "V" */ CWORD_CWORD_CWORD_CWORD,
  2721. /* 87 "W" */ CWORD_CWORD_CWORD_CWORD,
  2722. /* 88 "X" */ CWORD_CWORD_CWORD_CWORD,
  2723. /* 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
  2724. /* 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
  2725. /* 91 "[" */ CWORD_CCTL_CCTL_CWORD,
  2726. /* 92 "\" */ CBACK_CBACK_CCTL_CBACK,
  2727. /* 93 "]" */ CWORD_CCTL_CCTL_CWORD,
  2728. /* 94 "^" */ CWORD_CWORD_CWORD_CWORD,
  2729. /* 95 "_" */ CWORD_CWORD_CWORD_CWORD,
  2730. /* 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
  2731. /* 97 "a" */ CWORD_CWORD_CWORD_CWORD,
  2732. /* 98 "b" */ CWORD_CWORD_CWORD_CWORD,
  2733. /* 99 "c" */ CWORD_CWORD_CWORD_CWORD,
  2734. /* 100 "d" */ CWORD_CWORD_CWORD_CWORD,
  2735. /* 101 "e" */ CWORD_CWORD_CWORD_CWORD,
  2736. /* 102 "f" */ CWORD_CWORD_CWORD_CWORD,
  2737. /* 103 "g" */ CWORD_CWORD_CWORD_CWORD,
  2738. /* 104 "h" */ CWORD_CWORD_CWORD_CWORD,
  2739. /* 105 "i" */ CWORD_CWORD_CWORD_CWORD,
  2740. /* 106 "j" */ CWORD_CWORD_CWORD_CWORD,
  2741. /* 107 "k" */ CWORD_CWORD_CWORD_CWORD,
  2742. /* 108 "l" */ CWORD_CWORD_CWORD_CWORD,
  2743. /* 109 "m" */ CWORD_CWORD_CWORD_CWORD,
  2744. /* 110 "n" */ CWORD_CWORD_CWORD_CWORD,
  2745. /* 111 "o" */ CWORD_CWORD_CWORD_CWORD,
  2746. /* 112 "p" */ CWORD_CWORD_CWORD_CWORD,
  2747. /* 113 "q" */ CWORD_CWORD_CWORD_CWORD,
  2748. /* 114 "r" */ CWORD_CWORD_CWORD_CWORD,
  2749. /* 115 "s" */ CWORD_CWORD_CWORD_CWORD,
  2750. /* 116 "t" */ CWORD_CWORD_CWORD_CWORD,
  2751. /* 117 "u" */ CWORD_CWORD_CWORD_CWORD,
  2752. /* 118 "v" */ CWORD_CWORD_CWORD_CWORD,
  2753. /* 119 "w" */ CWORD_CWORD_CWORD_CWORD,
  2754. /* 120 "x" */ CWORD_CWORD_CWORD_CWORD,
  2755. /* 121 "y" */ CWORD_CWORD_CWORD_CWORD,
  2756. /* 122 "z" */ CWORD_CWORD_CWORD_CWORD,
  2757. /* 123 "{" */ CWORD_CWORD_CWORD_CWORD,
  2758. /* 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
  2759. /* 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
  2760. /* 126 "~" */ CWORD_CCTL_CCTL_CWORD,
  2761. /* 127 del */ CWORD_CWORD_CWORD_CWORD,
  2762. /* 128 0x80 */ CWORD_CWORD_CWORD_CWORD,
  2763. /* 129 CTLESC */ CCTL_CCTL_CCTL_CCTL,
  2764. /* 130 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
  2765. /* 131 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
  2766. /* 132 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
  2767. /* 133 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
  2768. /* 134 CTLARI */ CCTL_CCTL_CCTL_CCTL,
  2769. /* 135 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
  2770. /* 136 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
  2771. /* 137 */ CWORD_CWORD_CWORD_CWORD,
  2772. /* 138 */ CWORD_CWORD_CWORD_CWORD,
  2773. /* 139 */ CWORD_CWORD_CWORD_CWORD,
  2774. /* 140 */ CWORD_CWORD_CWORD_CWORD,
  2775. /* 141 */ CWORD_CWORD_CWORD_CWORD,
  2776. /* 142 */ CWORD_CWORD_CWORD_CWORD,
  2777. /* 143 */ CWORD_CWORD_CWORD_CWORD,
  2778. /* 144 */ CWORD_CWORD_CWORD_CWORD,
  2779. /* 145 */ CWORD_CWORD_CWORD_CWORD,
  2780. /* 146 */ CWORD_CWORD_CWORD_CWORD,
  2781. /* 147 */ CWORD_CWORD_CWORD_CWORD,
  2782. /* 148 */ CWORD_CWORD_CWORD_CWORD,
  2783. /* 149 */ CWORD_CWORD_CWORD_CWORD,
  2784. /* 150 */ CWORD_CWORD_CWORD_CWORD,
  2785. /* 151 */ CWORD_CWORD_CWORD_CWORD,
  2786. /* 152 */ CWORD_CWORD_CWORD_CWORD,
  2787. /* 153 */ CWORD_CWORD_CWORD_CWORD,
  2788. /* 154 */ CWORD_CWORD_CWORD_CWORD,
  2789. /* 155 */ CWORD_CWORD_CWORD_CWORD,
  2790. /* 156 */ CWORD_CWORD_CWORD_CWORD,
  2791. /* 157 */ CWORD_CWORD_CWORD_CWORD,
  2792. /* 158 */ CWORD_CWORD_CWORD_CWORD,
  2793. /* 159 */ CWORD_CWORD_CWORD_CWORD,
  2794. /* 160 */ CWORD_CWORD_CWORD_CWORD,
  2795. /* 161 */ CWORD_CWORD_CWORD_CWORD,
  2796. /* 162 */ CWORD_CWORD_CWORD_CWORD,
  2797. /* 163 */ CWORD_CWORD_CWORD_CWORD,
  2798. /* 164 */ CWORD_CWORD_CWORD_CWORD,
  2799. /* 165 */ CWORD_CWORD_CWORD_CWORD,
  2800. /* 166 */ CWORD_CWORD_CWORD_CWORD,
  2801. /* 167 */ CWORD_CWORD_CWORD_CWORD,
  2802. /* 168 */ CWORD_CWORD_CWORD_CWORD,
  2803. /* 169 */ CWORD_CWORD_CWORD_CWORD,
  2804. /* 170 */ CWORD_CWORD_CWORD_CWORD,
  2805. /* 171 */ CWORD_CWORD_CWORD_CWORD,
  2806. /* 172 */ CWORD_CWORD_CWORD_CWORD,
  2807. /* 173 */ CWORD_CWORD_CWORD_CWORD,
  2808. /* 174 */ CWORD_CWORD_CWORD_CWORD,
  2809. /* 175 */ CWORD_CWORD_CWORD_CWORD,
  2810. /* 176 */ CWORD_CWORD_CWORD_CWORD,
  2811. /* 177 */ CWORD_CWORD_CWORD_CWORD,
  2812. /* 178 */ CWORD_CWORD_CWORD_CWORD,
  2813. /* 179 */ CWORD_CWORD_CWORD_CWORD,
  2814. /* 180 */ CWORD_CWORD_CWORD_CWORD,
  2815. /* 181 */ CWORD_CWORD_CWORD_CWORD,
  2816. /* 182 */ CWORD_CWORD_CWORD_CWORD,
  2817. /* 183 */ CWORD_CWORD_CWORD_CWORD,
  2818. /* 184 */ CWORD_CWORD_CWORD_CWORD,
  2819. /* 185 */ CWORD_CWORD_CWORD_CWORD,
  2820. /* 186 */ CWORD_CWORD_CWORD_CWORD,
  2821. /* 187 */ CWORD_CWORD_CWORD_CWORD,
  2822. /* 188 */ CWORD_CWORD_CWORD_CWORD,
  2823. /* 189 */ CWORD_CWORD_CWORD_CWORD,
  2824. /* 190 */ CWORD_CWORD_CWORD_CWORD,
  2825. /* 191 */ CWORD_CWORD_CWORD_CWORD,
  2826. /* 192 */ CWORD_CWORD_CWORD_CWORD,
  2827. /* 193 */ CWORD_CWORD_CWORD_CWORD,
  2828. /* 194 */ CWORD_CWORD_CWORD_CWORD,
  2829. /* 195 */ CWORD_CWORD_CWORD_CWORD,
  2830. /* 196 */ CWORD_CWORD_CWORD_CWORD,
  2831. /* 197 */ CWORD_CWORD_CWORD_CWORD,
  2832. /* 198 */ CWORD_CWORD_CWORD_CWORD,
  2833. /* 199 */ CWORD_CWORD_CWORD_CWORD,
  2834. /* 200 */ CWORD_CWORD_CWORD_CWORD,
  2835. /* 201 */ CWORD_CWORD_CWORD_CWORD,
  2836. /* 202 */ CWORD_CWORD_CWORD_CWORD,
  2837. /* 203 */ CWORD_CWORD_CWORD_CWORD,
  2838. /* 204 */ CWORD_CWORD_CWORD_CWORD,
  2839. /* 205 */ CWORD_CWORD_CWORD_CWORD,
  2840. /* 206 */ CWORD_CWORD_CWORD_CWORD,
  2841. /* 207 */ CWORD_CWORD_CWORD_CWORD,
  2842. /* 208 */ CWORD_CWORD_CWORD_CWORD,
  2843. /* 209 */ CWORD_CWORD_CWORD_CWORD,
  2844. /* 210 */ CWORD_CWORD_CWORD_CWORD,
  2845. /* 211 */ CWORD_CWORD_CWORD_CWORD,
  2846. /* 212 */ CWORD_CWORD_CWORD_CWORD,
  2847. /* 213 */ CWORD_CWORD_CWORD_CWORD,
  2848. /* 214 */ CWORD_CWORD_CWORD_CWORD,
  2849. /* 215 */ CWORD_CWORD_CWORD_CWORD,
  2850. /* 216 */ CWORD_CWORD_CWORD_CWORD,
  2851. /* 217 */ CWORD_CWORD_CWORD_CWORD,
  2852. /* 218 */ CWORD_CWORD_CWORD_CWORD,
  2853. /* 219 */ CWORD_CWORD_CWORD_CWORD,
  2854. /* 220 */ CWORD_CWORD_CWORD_CWORD,
  2855. /* 221 */ CWORD_CWORD_CWORD_CWORD,
  2856. /* 222 */ CWORD_CWORD_CWORD_CWORD,
  2857. /* 223 */ CWORD_CWORD_CWORD_CWORD,
  2858. /* 224 */ CWORD_CWORD_CWORD_CWORD,
  2859. /* 225 */ CWORD_CWORD_CWORD_CWORD,
  2860. /* 226 */ CWORD_CWORD_CWORD_CWORD,
  2861. /* 227 */ CWORD_CWORD_CWORD_CWORD,
  2862. /* 228 */ CWORD_CWORD_CWORD_CWORD,
  2863. /* 229 */ CWORD_CWORD_CWORD_CWORD,
  2864. /* 230 */ CWORD_CWORD_CWORD_CWORD,
  2865. /* 231 */ CWORD_CWORD_CWORD_CWORD,
  2866. /* 232 */ CWORD_CWORD_CWORD_CWORD,
  2867. /* 233 */ CWORD_CWORD_CWORD_CWORD,
  2868. /* 234 */ CWORD_CWORD_CWORD_CWORD,
  2869. /* 235 */ CWORD_CWORD_CWORD_CWORD,
  2870. /* 236 */ CWORD_CWORD_CWORD_CWORD,
  2871. /* 237 */ CWORD_CWORD_CWORD_CWORD,
  2872. /* 238 */ CWORD_CWORD_CWORD_CWORD,
  2873. /* 239 */ CWORD_CWORD_CWORD_CWORD,
  2874. /* 230 */ CWORD_CWORD_CWORD_CWORD,
  2875. /* 241 */ CWORD_CWORD_CWORD_CWORD,
  2876. /* 242 */ CWORD_CWORD_CWORD_CWORD,
  2877. /* 243 */ CWORD_CWORD_CWORD_CWORD,
  2878. /* 244 */ CWORD_CWORD_CWORD_CWORD,
  2879. /* 245 */ CWORD_CWORD_CWORD_CWORD,
  2880. /* 246 */ CWORD_CWORD_CWORD_CWORD,
  2881. /* 247 */ CWORD_CWORD_CWORD_CWORD,
  2882. /* 248 */ CWORD_CWORD_CWORD_CWORD,
  2883. /* 249 */ CWORD_CWORD_CWORD_CWORD,
  2884. /* 250 */ CWORD_CWORD_CWORD_CWORD,
  2885. /* 251 */ CWORD_CWORD_CWORD_CWORD,
  2886. /* 252 */ CWORD_CWORD_CWORD_CWORD,
  2887. /* 253 */ CWORD_CWORD_CWORD_CWORD,
  2888. /* 254 */ CWORD_CWORD_CWORD_CWORD,
  2889. /* 255 */ CWORD_CWORD_CWORD_CWORD,
  2890. /* PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
  2891. # if ENABLE_ASH_ALIAS
  2892. /* PEOA */ CSPCL_CIGN_CIGN_CIGN,
  2893. # endif
  2894. };
  2895. #if 1
  2896. # define SIT(c, syntax) ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf)
  2897. #else /* debug version, caught one signed char bug */
  2898. # define SIT(c, syntax) \
  2899. ({ \
  2900. if ((c) < 0 || (c) > (PEOF + ENABLE_ASH_ALIAS)) \
  2901. bb_error_msg_and_die("line:%d c:%d", __LINE__, (c)); \
  2902. if ((syntax) < 0 || (syntax) > (2 + ENABLE_FEATURE_SH_MATH)) \
  2903. bb_error_msg_and_die("line:%d c:%d", __LINE__, (c)); \
  2904. ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf); \
  2905. })
  2906. #endif
  2907. #endif /* !USE_SIT_FUNCTION */
  2908. /* ============ Alias handling */
  2909. #if ENABLE_ASH_ALIAS
  2910. #define ALIASINUSE 1
  2911. #define ALIASDEAD 2
  2912. struct alias {
  2913. struct alias *next;
  2914. char *name;
  2915. char *val;
  2916. int flag;
  2917. };
  2918. static struct alias **atab; // [ATABSIZE];
  2919. #define INIT_G_alias() do { \
  2920. atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
  2921. } while (0)
  2922. static struct alias **
  2923. __lookupalias(const char *name)
  2924. {
  2925. unsigned int hashval;
  2926. struct alias **app;
  2927. const char *p;
  2928. unsigned int ch;
  2929. p = name;
  2930. ch = (unsigned char)*p;
  2931. hashval = ch << 4;
  2932. while (ch) {
  2933. hashval += ch;
  2934. ch = (unsigned char)*++p;
  2935. }
  2936. app = &atab[hashval % ATABSIZE];
  2937. for (; *app; app = &(*app)->next) {
  2938. if (strcmp(name, (*app)->name) == 0) {
  2939. break;
  2940. }
  2941. }
  2942. return app;
  2943. }
  2944. static struct alias *
  2945. lookupalias(const char *name, int check)
  2946. {
  2947. struct alias *ap = *__lookupalias(name);
  2948. if (check && ap && (ap->flag & ALIASINUSE))
  2949. return NULL;
  2950. return ap;
  2951. }
  2952. static struct alias *
  2953. freealias(struct alias *ap)
  2954. {
  2955. struct alias *next;
  2956. if (ap->flag & ALIASINUSE) {
  2957. ap->flag |= ALIASDEAD;
  2958. return ap;
  2959. }
  2960. next = ap->next;
  2961. free(ap->name);
  2962. free(ap->val);
  2963. free(ap);
  2964. return next;
  2965. }
  2966. static void
  2967. setalias(const char *name, const char *val)
  2968. {
  2969. struct alias *ap, **app;
  2970. app = __lookupalias(name);
  2971. ap = *app;
  2972. INT_OFF;
  2973. if (ap) {
  2974. if (!(ap->flag & ALIASINUSE)) {
  2975. free(ap->val);
  2976. }
  2977. ap->val = ckstrdup(val);
  2978. ap->flag &= ~ALIASDEAD;
  2979. } else {
  2980. /* not found */
  2981. ap = ckzalloc(sizeof(struct alias));
  2982. ap->name = ckstrdup(name);
  2983. ap->val = ckstrdup(val);
  2984. /*ap->flag = 0; - ckzalloc did it */
  2985. /*ap->next = NULL;*/
  2986. *app = ap;
  2987. }
  2988. INT_ON;
  2989. }
  2990. static int
  2991. unalias(const char *name)
  2992. {
  2993. struct alias **app;
  2994. app = __lookupalias(name);
  2995. if (*app) {
  2996. INT_OFF;
  2997. *app = freealias(*app);
  2998. INT_ON;
  2999. return 0;
  3000. }
  3001. return 1;
  3002. }
  3003. static void
  3004. rmaliases(void)
  3005. {
  3006. struct alias *ap, **app;
  3007. int i;
  3008. INT_OFF;
  3009. for (i = 0; i < ATABSIZE; i++) {
  3010. app = &atab[i];
  3011. for (ap = *app; ap; ap = *app) {
  3012. *app = freealias(*app);
  3013. if (ap == *app) {
  3014. app = &ap->next;
  3015. }
  3016. }
  3017. }
  3018. INT_ON;
  3019. }
  3020. static void
  3021. printalias(const struct alias *ap)
  3022. {
  3023. out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
  3024. }
  3025. /*
  3026. * TODO - sort output
  3027. */
  3028. static int FAST_FUNC
  3029. aliascmd(int argc UNUSED_PARAM, char **argv)
  3030. {
  3031. char *n, *v;
  3032. int ret = 0;
  3033. struct alias *ap;
  3034. if (!argv[1]) {
  3035. int i;
  3036. for (i = 0; i < ATABSIZE; i++) {
  3037. for (ap = atab[i]; ap; ap = ap->next) {
  3038. printalias(ap);
  3039. }
  3040. }
  3041. return 0;
  3042. }
  3043. while ((n = *++argv) != NULL) {
  3044. v = strchr(n+1, '=');
  3045. if (v == NULL) { /* n+1: funny ksh stuff */
  3046. ap = *__lookupalias(n);
  3047. if (ap == NULL) {
  3048. fprintf(stderr, "%s: %s not found\n", "alias", n);
  3049. ret = 1;
  3050. } else
  3051. printalias(ap);
  3052. } else {
  3053. *v++ = '\0';
  3054. setalias(n, v);
  3055. }
  3056. }
  3057. return ret;
  3058. }
  3059. static int FAST_FUNC
  3060. unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  3061. {
  3062. int i;
  3063. while (nextopt("a") != '\0') {
  3064. rmaliases();
  3065. return 0;
  3066. }
  3067. for (i = 0; *argptr; argptr++) {
  3068. if (unalias(*argptr)) {
  3069. fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
  3070. i = 1;
  3071. }
  3072. }
  3073. return i;
  3074. }
  3075. #endif /* ASH_ALIAS */
  3076. /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
  3077. #define FORK_FG 0
  3078. #define FORK_BG 1
  3079. #define FORK_NOJOB 2
  3080. /* mode flags for showjob(s) */
  3081. #define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
  3082. #define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
  3083. #define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
  3084. #define SHOW_STDERR 0x08 /* print to stderr (else stdout) */
  3085. /*
  3086. * A job structure contains information about a job. A job is either a
  3087. * single process or a set of processes contained in a pipeline. In the
  3088. * latter case, pidlist will be non-NULL, and will point to a -1 terminated
  3089. * array of pids.
  3090. */
  3091. struct procstat {
  3092. pid_t ps_pid; /* process id */
  3093. int ps_status; /* last process status from wait() */
  3094. char *ps_cmd; /* text of command being run */
  3095. };
  3096. struct job {
  3097. struct procstat ps0; /* status of process */
  3098. struct procstat *ps; /* status or processes when more than one */
  3099. #if JOBS
  3100. int stopstatus; /* status of a stopped job */
  3101. #endif
  3102. unsigned nprocs; /* number of processes */
  3103. #define JOBRUNNING 0 /* at least one proc running */
  3104. #define JOBSTOPPED 1 /* all procs are stopped */
  3105. #define JOBDONE 2 /* all procs are completed */
  3106. unsigned
  3107. state: 8,
  3108. #if JOBS
  3109. sigint: 1, /* job was killed by SIGINT */
  3110. jobctl: 1, /* job running under job control */
  3111. #endif
  3112. waited: 1, /* true if this entry has been waited for */
  3113. used: 1, /* true if this entry is in used */
  3114. changed: 1; /* true if status has changed */
  3115. struct job *prev_job; /* previous job */
  3116. };
  3117. static struct job *makejob(/*union node *,*/ int);
  3118. static int forkshell(struct job *, union node *, int);
  3119. static int waitforjob(struct job *);
  3120. #if !JOBS
  3121. enum { doing_jobctl = 0 };
  3122. #define setjobctl(on) do {} while (0)
  3123. #else
  3124. static smallint doing_jobctl; //references:8
  3125. static void setjobctl(int);
  3126. #endif
  3127. /*
  3128. * Ignore a signal.
  3129. */
  3130. static void
  3131. ignoresig(int signo)
  3132. {
  3133. /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
  3134. if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
  3135. /* No, need to do it */
  3136. signal(signo, SIG_IGN);
  3137. }
  3138. sigmode[signo - 1] = S_HARD_IGN;
  3139. }
  3140. /*
  3141. * Only one usage site - in setsignal()
  3142. */
  3143. static void
  3144. signal_handler(int signo)
  3145. {
  3146. if (signo == SIGCHLD) {
  3147. got_sigchld = 1;
  3148. if (!trap[SIGCHLD])
  3149. return;
  3150. }
  3151. gotsig[signo - 1] = 1;
  3152. pending_sig = signo;
  3153. if (signo == SIGINT && !trap[SIGINT]) {
  3154. if (!suppress_int) {
  3155. pending_sig = 0;
  3156. raise_interrupt(); /* does not return */
  3157. }
  3158. pending_int = 1;
  3159. }
  3160. }
  3161. /*
  3162. * Set the signal handler for the specified signal. The routine figures
  3163. * out what it should be set to.
  3164. */
  3165. static void
  3166. setsignal(int signo)
  3167. {
  3168. char *t;
  3169. char cur_act, new_act;
  3170. struct sigaction act;
  3171. t = trap[signo];
  3172. new_act = S_DFL;
  3173. if (t != NULL) { /* trap for this sig is set */
  3174. new_act = S_CATCH;
  3175. if (t[0] == '\0') /* trap is "": ignore this sig */
  3176. new_act = S_IGN;
  3177. }
  3178. if (rootshell && new_act == S_DFL) {
  3179. switch (signo) {
  3180. case SIGINT:
  3181. if (iflag || minusc || sflag == 0)
  3182. new_act = S_CATCH;
  3183. break;
  3184. case SIGQUIT:
  3185. #if DEBUG
  3186. if (debug)
  3187. break;
  3188. #endif
  3189. /* man bash:
  3190. * "In all cases, bash ignores SIGQUIT. Non-builtin
  3191. * commands run by bash have signal handlers
  3192. * set to the values inherited by the shell
  3193. * from its parent". */
  3194. new_act = S_IGN;
  3195. break;
  3196. case SIGTERM:
  3197. if (iflag)
  3198. new_act = S_IGN;
  3199. break;
  3200. #if JOBS
  3201. case SIGTSTP:
  3202. case SIGTTOU:
  3203. if (mflag)
  3204. new_act = S_IGN;
  3205. break;
  3206. #endif
  3207. }
  3208. }
  3209. /* if !rootshell, we reset SIGQUIT to DFL,
  3210. * whereas we have to restore it to what shell got on entry.
  3211. * This is handled by the fact that if signal was IGNored on entry,
  3212. * then cur_act is S_HARD_IGN and we never change its sigaction
  3213. * (see code below).
  3214. */
  3215. if (signo == SIGCHLD)
  3216. new_act = S_CATCH;
  3217. t = &sigmode[signo - 1];
  3218. cur_act = *t;
  3219. if (cur_act == 0) {
  3220. /* current setting is not yet known */
  3221. if (sigaction(signo, NULL, &act)) {
  3222. /* pretend it worked; maybe we should give a warning,
  3223. * but other shells don't. We don't alter sigmode,
  3224. * so we retry every time.
  3225. * btw, in Linux it never fails. --vda */
  3226. return;
  3227. }
  3228. if (act.sa_handler == SIG_IGN) {
  3229. cur_act = S_HARD_IGN;
  3230. if (mflag
  3231. && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
  3232. ) {
  3233. cur_act = S_IGN; /* don't hard ignore these */
  3234. }
  3235. }
  3236. if (act.sa_handler == SIG_DFL && new_act == S_DFL) {
  3237. /* installing SIG_DFL over SIG_DFL is a no-op */
  3238. /* saves one sigaction call in each "sh -c SCRIPT" invocation */
  3239. *t = S_DFL;
  3240. return;
  3241. }
  3242. }
  3243. if (cur_act == S_HARD_IGN || cur_act == new_act)
  3244. return;
  3245. *t = new_act;
  3246. act.sa_handler = SIG_DFL;
  3247. switch (new_act) {
  3248. case S_CATCH:
  3249. act.sa_handler = signal_handler;
  3250. break;
  3251. case S_IGN:
  3252. act.sa_handler = SIG_IGN;
  3253. break;
  3254. }
  3255. /* flags and mask matter only if !DFL and !IGN, but we do it
  3256. * for all cases for more deterministic behavior:
  3257. */
  3258. act.sa_flags = 0; //TODO: why not SA_RESTART?
  3259. sigfillset(&act.sa_mask);
  3260. sigaction_set(signo, &act);
  3261. }
  3262. /* mode flags for set_curjob */
  3263. #define CUR_DELETE 2
  3264. #define CUR_RUNNING 1
  3265. #define CUR_STOPPED 0
  3266. #if JOBS
  3267. /* pgrp of shell on invocation */
  3268. static int initialpgrp; //references:2
  3269. static int ttyfd = -1; //5
  3270. #endif
  3271. /* array of jobs */
  3272. static struct job *jobtab; //5
  3273. /* size of array */
  3274. static unsigned njobs; //4
  3275. /* current job */
  3276. static struct job *curjob; //lots
  3277. /* number of presumed living untracked jobs */
  3278. static int jobless; //4
  3279. #if 0
  3280. /* Bash has a feature: it restores termios after a successful wait for
  3281. * a foreground job which had at least one stopped or sigkilled member.
  3282. * The probable rationale is that SIGSTOP and SIGKILL can preclude task from
  3283. * properly restoring tty state. Should we do this too?
  3284. * A reproducer: ^Z an interactive python:
  3285. *
  3286. * # python
  3287. * Python 2.7.12 (...)
  3288. * >>> ^Z
  3289. * { python leaves tty in -icanon -echo state. We do survive that... }
  3290. * [1]+ Stopped python
  3291. * { ...however, next program (python #2) does not survive it well: }
  3292. * # python
  3293. * Python 2.7.12 (...)
  3294. * >>> Traceback (most recent call last):
  3295. * { above, I typed "qwerty<CR>", but -echo state is still in effect }
  3296. * File "<stdin>", line 1, in <module>
  3297. * NameError: name 'qwerty' is not defined
  3298. *
  3299. * The implementation below is modeled on bash code and seems to work.
  3300. * However, I'm not sure we should do this. For one: what if I'd fg
  3301. * the stopped python instead? It'll be confused by "restored" tty state.
  3302. */
  3303. static struct termios shell_tty_info;
  3304. static void
  3305. get_tty_state(void)
  3306. {
  3307. if (rootshell && ttyfd >= 0)
  3308. tcgetattr(ttyfd, &shell_tty_info);
  3309. }
  3310. static void
  3311. set_tty_state(void)
  3312. {
  3313. /* if (rootshell) - caller ensures this */
  3314. if (ttyfd >= 0)
  3315. tcsetattr(ttyfd, TCSADRAIN, &shell_tty_info);
  3316. }
  3317. static int
  3318. job_signal_status(struct job *jp)
  3319. {
  3320. int status;
  3321. unsigned i;
  3322. struct procstat *ps = jp->ps;
  3323. for (i = 0; i < jp->nprocs; i++) {
  3324. status = ps[i].ps_status;
  3325. if (WIFSIGNALED(status) || WIFSTOPPED(status))
  3326. return status;
  3327. }
  3328. return 0;
  3329. }
  3330. static void
  3331. restore_tty_if_stopped_or_signaled(struct job *jp)
  3332. {
  3333. //TODO: check what happens if we come from waitforjob() in expbackq()
  3334. if (rootshell) {
  3335. int s = job_signal_status(jp);
  3336. if (s) /* WIFSIGNALED(s) || WIFSTOPPED(s) */
  3337. set_tty_state();
  3338. }
  3339. }
  3340. #else
  3341. # define get_tty_state() ((void)0)
  3342. # define restore_tty_if_stopped_or_signaled(jp) ((void)0)
  3343. #endif
  3344. static void
  3345. set_curjob(struct job *jp, unsigned mode)
  3346. {
  3347. struct job *jp1;
  3348. struct job **jpp, **curp;
  3349. /* first remove from list */
  3350. jpp = curp = &curjob;
  3351. while (1) {
  3352. jp1 = *jpp;
  3353. if (jp1 == jp)
  3354. break;
  3355. jpp = &jp1->prev_job;
  3356. }
  3357. *jpp = jp1->prev_job;
  3358. /* Then re-insert in correct position */
  3359. jpp = curp;
  3360. switch (mode) {
  3361. default:
  3362. #if DEBUG
  3363. abort();
  3364. #endif
  3365. case CUR_DELETE:
  3366. /* job being deleted */
  3367. break;
  3368. case CUR_RUNNING:
  3369. /* newly created job or backgrounded job,
  3370. * put after all stopped jobs.
  3371. */
  3372. while (1) {
  3373. jp1 = *jpp;
  3374. #if JOBS
  3375. if (!jp1 || jp1->state != JOBSTOPPED)
  3376. #endif
  3377. break;
  3378. jpp = &jp1->prev_job;
  3379. }
  3380. /* FALLTHROUGH */
  3381. #if JOBS
  3382. case CUR_STOPPED:
  3383. #endif
  3384. /* newly stopped job - becomes curjob */
  3385. jp->prev_job = *jpp;
  3386. *jpp = jp;
  3387. break;
  3388. }
  3389. }
  3390. #if JOBS || DEBUG
  3391. static int
  3392. jobno(const struct job *jp)
  3393. {
  3394. return jp - jobtab + 1;
  3395. }
  3396. #endif
  3397. /*
  3398. * Convert a job name to a job structure.
  3399. */
  3400. #if !JOBS
  3401. #define getjob(name, getctl) getjob(name)
  3402. #endif
  3403. static struct job *
  3404. getjob(const char *name, int getctl)
  3405. {
  3406. struct job *jp;
  3407. struct job *found;
  3408. const char *err_msg = "%s: no such job";
  3409. unsigned num;
  3410. int c;
  3411. const char *p;
  3412. char *(*match)(const char *, const char *);
  3413. jp = curjob;
  3414. p = name;
  3415. if (!p)
  3416. goto currentjob;
  3417. if (*p != '%')
  3418. goto err;
  3419. c = *++p;
  3420. if (!c)
  3421. goto currentjob;
  3422. if (!p[1]) {
  3423. if (c == '+' || c == '%') {
  3424. currentjob:
  3425. err_msg = "No current job";
  3426. goto check;
  3427. }
  3428. if (c == '-') {
  3429. if (jp)
  3430. jp = jp->prev_job;
  3431. err_msg = "No previous job";
  3432. check:
  3433. if (!jp)
  3434. goto err;
  3435. goto gotit;
  3436. }
  3437. }
  3438. if (is_number(p)) {
  3439. num = atoi(p);
  3440. if (num > 0 && num <= njobs) {
  3441. jp = jobtab + num - 1;
  3442. if (jp->used)
  3443. goto gotit;
  3444. goto err;
  3445. }
  3446. }
  3447. match = prefix;
  3448. if (*p == '?') {
  3449. match = strstr;
  3450. p++;
  3451. }
  3452. found = NULL;
  3453. while (jp) {
  3454. if (match(jp->ps[0].ps_cmd, p)) {
  3455. if (found)
  3456. goto err;
  3457. found = jp;
  3458. err_msg = "%s: ambiguous";
  3459. }
  3460. jp = jp->prev_job;
  3461. }
  3462. if (!found)
  3463. goto err;
  3464. jp = found;
  3465. gotit:
  3466. #if JOBS
  3467. err_msg = "job %s not created under job control";
  3468. if (getctl && jp->jobctl == 0)
  3469. goto err;
  3470. #endif
  3471. return jp;
  3472. err:
  3473. ash_msg_and_raise_error(err_msg, name);
  3474. }
  3475. /*
  3476. * Mark a job structure as unused.
  3477. */
  3478. static void
  3479. freejob(struct job *jp)
  3480. {
  3481. struct procstat *ps;
  3482. int i;
  3483. INT_OFF;
  3484. for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
  3485. if (ps->ps_cmd != nullstr)
  3486. free(ps->ps_cmd);
  3487. }
  3488. if (jp->ps != &jp->ps0)
  3489. free(jp->ps);
  3490. jp->used = 0;
  3491. set_curjob(jp, CUR_DELETE);
  3492. INT_ON;
  3493. }
  3494. #if JOBS
  3495. static void
  3496. xtcsetpgrp(int fd, pid_t pgrp)
  3497. {
  3498. if (tcsetpgrp(fd, pgrp))
  3499. ash_msg_and_raise_perror("can't set tty process group");
  3500. }
  3501. /*
  3502. * Turn job control on and off.
  3503. *
  3504. * Note: This code assumes that the third arg to ioctl is a character
  3505. * pointer, which is true on Berkeley systems but not System V. Since
  3506. * System V doesn't have job control yet, this isn't a problem now.
  3507. *
  3508. * Called with interrupts off.
  3509. */
  3510. static void
  3511. setjobctl(int on)
  3512. {
  3513. int fd;
  3514. int pgrp;
  3515. if (on == doing_jobctl || rootshell == 0)
  3516. return;
  3517. if (on) {
  3518. int ofd;
  3519. ofd = fd = open(_PATH_TTY, O_RDWR);
  3520. if (fd < 0) {
  3521. /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
  3522. * That sometimes helps to acquire controlling tty.
  3523. * Obviously, a workaround for bugs when someone
  3524. * failed to provide a controlling tty to bash! :) */
  3525. fd = 2;
  3526. while (!isatty(fd))
  3527. if (--fd < 0)
  3528. goto out;
  3529. }
  3530. /* fd is a tty at this point */
  3531. fd = fcntl(fd, F_DUPFD, 10);
  3532. if (ofd >= 0) /* if it is "/dev/tty", close. If 0/1/2, don't */
  3533. close(ofd);
  3534. if (fd < 0)
  3535. goto out; /* F_DUPFD failed */
  3536. close_on_exec_on(fd);
  3537. while (1) { /* while we are in the background */
  3538. pgrp = tcgetpgrp(fd);
  3539. if (pgrp < 0) {
  3540. out:
  3541. ash_msg("can't access tty; job control turned off");
  3542. mflag = on = 0;
  3543. goto close;
  3544. }
  3545. if (pgrp == getpgrp())
  3546. break;
  3547. killpg(0, SIGTTIN);
  3548. }
  3549. initialpgrp = pgrp;
  3550. setsignal(SIGTSTP);
  3551. setsignal(SIGTTOU);
  3552. setsignal(SIGTTIN);
  3553. pgrp = rootpid;
  3554. setpgid(0, pgrp);
  3555. xtcsetpgrp(fd, pgrp);
  3556. } else {
  3557. /* turning job control off */
  3558. fd = ttyfd;
  3559. pgrp = initialpgrp;
  3560. /* was xtcsetpgrp, but this can make exiting ash
  3561. * loop forever if pty is already deleted */
  3562. tcsetpgrp(fd, pgrp);
  3563. setpgid(0, pgrp);
  3564. setsignal(SIGTSTP);
  3565. setsignal(SIGTTOU);
  3566. setsignal(SIGTTIN);
  3567. close:
  3568. if (fd >= 0)
  3569. close(fd);
  3570. fd = -1;
  3571. }
  3572. ttyfd = fd;
  3573. doing_jobctl = on;
  3574. }
  3575. static int FAST_FUNC
  3576. killcmd(int argc, char **argv)
  3577. {
  3578. if (argv[1] && strcmp(argv[1], "-l") != 0) {
  3579. int i = 1;
  3580. do {
  3581. if (argv[i][0] == '%') {
  3582. /*
  3583. * "kill %N" - job kill
  3584. * Converting to pgrp / pid kill
  3585. */
  3586. struct job *jp;
  3587. char *dst;
  3588. int j, n;
  3589. jp = getjob(argv[i], 0);
  3590. /*
  3591. * In jobs started under job control, we signal
  3592. * entire process group by kill -PGRP_ID.
  3593. * This happens, f.e., in interactive shell.
  3594. *
  3595. * Otherwise, we signal each child via
  3596. * kill PID1 PID2 PID3.
  3597. * Testcases:
  3598. * sh -c 'sleep 1|sleep 1 & kill %1'
  3599. * sh -c 'true|sleep 2 & sleep 1; kill %1'
  3600. * sh -c 'true|sleep 1 & sleep 2; kill %1'
  3601. */
  3602. n = jp->nprocs; /* can't be 0 (I hope) */
  3603. if (jp->jobctl)
  3604. n = 1;
  3605. dst = alloca(n * sizeof(int)*4);
  3606. argv[i] = dst;
  3607. for (j = 0; j < n; j++) {
  3608. struct procstat *ps = &jp->ps[j];
  3609. /* Skip non-running and not-stopped members
  3610. * (i.e. dead members) of the job
  3611. */
  3612. if (ps->ps_status != -1 && !WIFSTOPPED(ps->ps_status))
  3613. continue;
  3614. /*
  3615. * kill_main has matching code to expect
  3616. * leading space. Needed to not confuse
  3617. * negative pids with "kill -SIGNAL_NO" syntax
  3618. */
  3619. dst += sprintf(dst, jp->jobctl ? " -%u" : " %u", (int)ps->ps_pid);
  3620. }
  3621. *dst = '\0';
  3622. }
  3623. } while (argv[++i]);
  3624. }
  3625. return kill_main(argc, argv);
  3626. }
  3627. static void
  3628. showpipe(struct job *jp /*, FILE *out*/)
  3629. {
  3630. struct procstat *ps;
  3631. struct procstat *psend;
  3632. psend = jp->ps + jp->nprocs;
  3633. for (ps = jp->ps + 1; ps < psend; ps++)
  3634. printf(" | %s", ps->ps_cmd);
  3635. newline_and_flush(stdout);
  3636. flush_stdout_stderr();
  3637. }
  3638. static int
  3639. restartjob(struct job *jp, int mode)
  3640. {
  3641. struct procstat *ps;
  3642. int i;
  3643. int status;
  3644. pid_t pgid;
  3645. INT_OFF;
  3646. if (jp->state == JOBDONE)
  3647. goto out;
  3648. jp->state = JOBRUNNING;
  3649. pgid = jp->ps[0].ps_pid;
  3650. if (mode == FORK_FG) {
  3651. get_tty_state();
  3652. xtcsetpgrp(ttyfd, pgid);
  3653. }
  3654. killpg(pgid, SIGCONT);
  3655. ps = jp->ps;
  3656. i = jp->nprocs;
  3657. do {
  3658. if (WIFSTOPPED(ps->ps_status)) {
  3659. ps->ps_status = -1;
  3660. }
  3661. ps++;
  3662. } while (--i);
  3663. out:
  3664. status = (mode == FORK_FG) ? waitforjob(jp) : 0;
  3665. INT_ON;
  3666. return status;
  3667. }
  3668. static int FAST_FUNC
  3669. fg_bgcmd(int argc UNUSED_PARAM, char **argv)
  3670. {
  3671. struct job *jp;
  3672. int mode;
  3673. int retval;
  3674. mode = (**argv == 'f') ? FORK_FG : FORK_BG;
  3675. nextopt(nullstr);
  3676. argv = argptr;
  3677. do {
  3678. jp = getjob(*argv, 1);
  3679. if (mode == FORK_BG) {
  3680. set_curjob(jp, CUR_RUNNING);
  3681. printf("[%d] ", jobno(jp));
  3682. }
  3683. out1str(jp->ps[0].ps_cmd);
  3684. showpipe(jp /*, stdout*/);
  3685. retval = restartjob(jp, mode);
  3686. } while (*argv && *++argv);
  3687. return retval;
  3688. }
  3689. #endif
  3690. static int
  3691. sprint_status48(char *s, int status, int sigonly)
  3692. {
  3693. int col;
  3694. int st;
  3695. col = 0;
  3696. if (!WIFEXITED(status)) {
  3697. #if JOBS
  3698. if (WIFSTOPPED(status))
  3699. st = WSTOPSIG(status);
  3700. else
  3701. #endif
  3702. st = WTERMSIG(status);
  3703. if (sigonly) {
  3704. if (st == SIGINT || st == SIGPIPE)
  3705. goto out;
  3706. #if JOBS
  3707. if (WIFSTOPPED(status))
  3708. goto out;
  3709. #endif
  3710. }
  3711. st &= 0x7f;
  3712. //TODO: use bbox's get_signame? strsignal adds ~600 bytes to text+rodata
  3713. col = fmtstr(s, 32, strsignal(st));
  3714. if (WCOREDUMP(status)) {
  3715. strcpy(s + col, " (core dumped)");
  3716. col += sizeof(" (core dumped)")-1;
  3717. }
  3718. } else if (!sigonly) {
  3719. st = WEXITSTATUS(status);
  3720. col = fmtstr(s, 16, (st ? "Done(%d)" : "Done"), st);
  3721. }
  3722. out:
  3723. return col;
  3724. }
  3725. static int
  3726. wait_block_or_sig(int *status)
  3727. {
  3728. int pid;
  3729. do {
  3730. sigset_t mask;
  3731. /* Poll all children for changes in their state */
  3732. got_sigchld = 0;
  3733. /* if job control is active, accept stopped processes too */
  3734. pid = waitpid(-1, status, doing_jobctl ? (WNOHANG|WUNTRACED) : WNOHANG);
  3735. if (pid != 0)
  3736. break; /* Error (e.g. EINTR, ECHILD) or pid */
  3737. /* Children exist, but none are ready. Sleep until interesting signal */
  3738. #if 1
  3739. sigfillset(&mask);
  3740. sigprocmask(SIG_SETMASK, &mask, &mask);
  3741. while (!got_sigchld && !pending_sig)
  3742. sigsuspend(&mask);
  3743. sigprocmask(SIG_SETMASK, &mask, NULL);
  3744. #else /* unsafe: a signal can set pending_sig after check, but before pause() */
  3745. while (!got_sigchld && !pending_sig)
  3746. pause();
  3747. #endif
  3748. /* If it was SIGCHLD, poll children again */
  3749. } while (got_sigchld);
  3750. return pid;
  3751. }
  3752. #define DOWAIT_NONBLOCK 0
  3753. #define DOWAIT_BLOCK 1
  3754. #define DOWAIT_BLOCK_OR_SIG 2
  3755. static int
  3756. dowait(int block, struct job *job)
  3757. {
  3758. int pid;
  3759. int status;
  3760. struct job *jp;
  3761. struct job *thisjob = NULL;
  3762. TRACE(("dowait(0x%x) called\n", block));
  3763. /* It's wrong to call waitpid() outside of INT_OFF region:
  3764. * signal can arrive just after syscall return and handler can
  3765. * longjmp away, losing stop/exit notification processing.
  3766. * Thus, for "jobs" builtin, and for waiting for a fg job,
  3767. * we call waitpid() (blocking or non-blocking) inside INT_OFF.
  3768. *
  3769. * However, for "wait" builtin it is wrong to simply call waitpid()
  3770. * in INT_OFF region: "wait" needs to wait for any running job
  3771. * to change state, but should exit on any trap too.
  3772. * In INT_OFF region, a signal just before syscall entry can set
  3773. * pending_sig variables, but we can't check them, and we would
  3774. * either enter a sleeping waitpid() (BUG), or need to busy-loop.
  3775. *
  3776. * Because of this, we run inside INT_OFF, but use a special routine
  3777. * which combines waitpid() and sigsuspend().
  3778. * This is the reason why we need to have a handler for SIGCHLD:
  3779. * SIG_DFL handler does not wake sigsuspend().
  3780. */
  3781. INT_OFF;
  3782. if (block == DOWAIT_BLOCK_OR_SIG) {
  3783. pid = wait_block_or_sig(&status);
  3784. } else {
  3785. int wait_flags = 0;
  3786. if (block == DOWAIT_NONBLOCK)
  3787. wait_flags = WNOHANG;
  3788. /* if job control is active, accept stopped processes too */
  3789. if (doing_jobctl)
  3790. wait_flags |= WUNTRACED;
  3791. /* NB: _not_ safe_waitpid, we need to detect EINTR */
  3792. pid = waitpid(-1, &status, wait_flags);
  3793. }
  3794. TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
  3795. pid, status, errno, strerror(errno)));
  3796. if (pid <= 0)
  3797. goto out;
  3798. thisjob = NULL;
  3799. for (jp = curjob; jp; jp = jp->prev_job) {
  3800. int jobstate;
  3801. struct procstat *ps;
  3802. struct procstat *psend;
  3803. if (jp->state == JOBDONE)
  3804. continue;
  3805. jobstate = JOBDONE;
  3806. ps = jp->ps;
  3807. psend = ps + jp->nprocs;
  3808. do {
  3809. if (ps->ps_pid == pid) {
  3810. TRACE(("Job %d: changing status of proc %d "
  3811. "from 0x%x to 0x%x\n",
  3812. jobno(jp), pid, ps->ps_status, status));
  3813. ps->ps_status = status;
  3814. thisjob = jp;
  3815. }
  3816. if (ps->ps_status == -1)
  3817. jobstate = JOBRUNNING;
  3818. #if JOBS
  3819. if (jobstate == JOBRUNNING)
  3820. continue;
  3821. if (WIFSTOPPED(ps->ps_status)) {
  3822. jp->stopstatus = ps->ps_status;
  3823. jobstate = JOBSTOPPED;
  3824. }
  3825. #endif
  3826. } while (++ps < psend);
  3827. if (!thisjob)
  3828. continue;
  3829. /* Found the job where one of its processes changed its state.
  3830. * Is there at least one live and running process in this job? */
  3831. if (jobstate != JOBRUNNING) {
  3832. /* No. All live processes in the job are stopped
  3833. * (JOBSTOPPED) or there are no live processes (JOBDONE)
  3834. */
  3835. thisjob->changed = 1;
  3836. if (thisjob->state != jobstate) {
  3837. TRACE(("Job %d: changing state from %d to %d\n",
  3838. jobno(thisjob), thisjob->state, jobstate));
  3839. thisjob->state = jobstate;
  3840. #if JOBS
  3841. if (jobstate == JOBSTOPPED)
  3842. set_curjob(thisjob, CUR_STOPPED);
  3843. #endif
  3844. }
  3845. }
  3846. goto out;
  3847. }
  3848. /* The process wasn't found in job list */
  3849. #if JOBS
  3850. if (!WIFSTOPPED(status))
  3851. jobless--;
  3852. #endif
  3853. out:
  3854. INT_ON;
  3855. if (thisjob && thisjob == job) {
  3856. char s[48 + 1];
  3857. int len;
  3858. len = sprint_status48(s, status, 1);
  3859. if (len) {
  3860. s[len] = '\n';
  3861. s[len + 1] = '\0';
  3862. out2str(s);
  3863. }
  3864. }
  3865. return pid;
  3866. }
  3867. #if JOBS
  3868. static void
  3869. showjob(struct job *jp, int mode)
  3870. {
  3871. struct procstat *ps;
  3872. struct procstat *psend;
  3873. int col;
  3874. int indent_col;
  3875. char s[16 + 16 + 48];
  3876. FILE *out = (mode & SHOW_STDERR ? stderr : stdout);
  3877. ps = jp->ps;
  3878. if (mode & SHOW_ONLY_PGID) { /* jobs -p */
  3879. /* just output process (group) id of pipeline */
  3880. fprintf(out, "%d\n", ps->ps_pid);
  3881. return;
  3882. }
  3883. col = fmtstr(s, 16, "[%d] ", jobno(jp));
  3884. indent_col = col;
  3885. if (jp == curjob)
  3886. s[col - 3] = '+';
  3887. else if (curjob && jp == curjob->prev_job)
  3888. s[col - 3] = '-';
  3889. if (mode & SHOW_PIDS)
  3890. col += fmtstr(s + col, 16, "%d ", ps->ps_pid);
  3891. psend = ps + jp->nprocs;
  3892. if (jp->state == JOBRUNNING) {
  3893. strcpy(s + col, "Running");
  3894. col += sizeof("Running") - 1;
  3895. } else {
  3896. int status = psend[-1].ps_status;
  3897. if (jp->state == JOBSTOPPED)
  3898. status = jp->stopstatus;
  3899. col += sprint_status48(s + col, status, 0);
  3900. }
  3901. /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
  3902. /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
  3903. * or prints several "PID | <cmdN>" lines,
  3904. * depending on SHOW_PIDS bit.
  3905. * We do not print status of individual processes
  3906. * between PID and <cmdN>. bash does it, but not very well:
  3907. * first line shows overall job status, not process status,
  3908. * making it impossible to know 1st process status.
  3909. */
  3910. goto start;
  3911. do {
  3912. /* for each process */
  3913. s[0] = '\0';
  3914. col = 33;
  3915. if (mode & SHOW_PIDS)
  3916. col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->ps_pid) - 1;
  3917. start:
  3918. fprintf(out, "%s%*c%s%s",
  3919. s,
  3920. 33 - col >= 0 ? 33 - col : 0, ' ',
  3921. ps == jp->ps ? "" : "| ",
  3922. ps->ps_cmd
  3923. );
  3924. } while (++ps != psend);
  3925. newline_and_flush(out);
  3926. jp->changed = 0;
  3927. if (jp->state == JOBDONE) {
  3928. TRACE(("showjob: freeing job %d\n", jobno(jp)));
  3929. freejob(jp);
  3930. }
  3931. }
  3932. /*
  3933. * Print a list of jobs. If "change" is nonzero, only print jobs whose
  3934. * statuses have changed since the last call to showjobs.
  3935. */
  3936. static void
  3937. showjobs(int mode)
  3938. {
  3939. struct job *jp;
  3940. TRACE(("showjobs(0x%x) called\n", mode));
  3941. /* Handle all finished jobs */
  3942. while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
  3943. continue;
  3944. for (jp = curjob; jp; jp = jp->prev_job) {
  3945. if (!(mode & SHOW_CHANGED) || jp->changed) {
  3946. showjob(jp, mode);
  3947. }
  3948. }
  3949. }
  3950. static int FAST_FUNC
  3951. jobscmd(int argc UNUSED_PARAM, char **argv)
  3952. {
  3953. int mode, m;
  3954. mode = 0;
  3955. while ((m = nextopt("lp")) != '\0') {
  3956. if (m == 'l')
  3957. mode |= SHOW_PIDS;
  3958. else
  3959. mode |= SHOW_ONLY_PGID;
  3960. }
  3961. argv = argptr;
  3962. if (*argv) {
  3963. do
  3964. showjob(getjob(*argv, 0), mode);
  3965. while (*++argv);
  3966. } else {
  3967. showjobs(mode);
  3968. }
  3969. return 0;
  3970. }
  3971. #endif /* JOBS */
  3972. /* Called only on finished or stopped jobs (no members are running) */
  3973. static int
  3974. getstatus(struct job *job)
  3975. {
  3976. int status;
  3977. int retval;
  3978. struct procstat *ps;
  3979. /* Fetch last member's status */
  3980. ps = job->ps + job->nprocs - 1;
  3981. status = ps->ps_status;
  3982. if (pipefail) {
  3983. /* "set -o pipefail" mode: use last _nonzero_ status */
  3984. while (status == 0 && --ps >= job->ps)
  3985. status = ps->ps_status;
  3986. }
  3987. retval = WEXITSTATUS(status);
  3988. if (!WIFEXITED(status)) {
  3989. #if JOBS
  3990. retval = WSTOPSIG(status);
  3991. if (!WIFSTOPPED(status))
  3992. #endif
  3993. {
  3994. /* XXX: limits number of signals */
  3995. retval = WTERMSIG(status);
  3996. #if JOBS
  3997. if (retval == SIGINT)
  3998. job->sigint = 1;
  3999. #endif
  4000. }
  4001. retval += 128;
  4002. }
  4003. TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
  4004. jobno(job), job->nprocs, status, retval));
  4005. return retval;
  4006. }
  4007. static int FAST_FUNC
  4008. waitcmd(int argc UNUSED_PARAM, char **argv)
  4009. {
  4010. struct job *job;
  4011. int retval;
  4012. struct job *jp;
  4013. nextopt(nullstr);
  4014. retval = 0;
  4015. argv = argptr;
  4016. if (!*argv) {
  4017. /* wait for all jobs */
  4018. for (;;) {
  4019. jp = curjob;
  4020. while (1) {
  4021. if (!jp) /* no running procs */
  4022. goto ret;
  4023. if (jp->state == JOBRUNNING)
  4024. break;
  4025. jp->waited = 1;
  4026. jp = jp->prev_job;
  4027. }
  4028. /* man bash:
  4029. * "When bash is waiting for an asynchronous command via
  4030. * the wait builtin, the reception of a signal for which a trap
  4031. * has been set will cause the wait builtin to return immediately
  4032. * with an exit status greater than 128, immediately after which
  4033. * the trap is executed."
  4034. */
  4035. dowait(DOWAIT_BLOCK_OR_SIG, NULL);
  4036. /* if child sends us a signal *and immediately exits*,
  4037. * dowait() returns pid > 0. Check this case,
  4038. * not "if (dowait() < 0)"!
  4039. */
  4040. if (pending_sig)
  4041. goto sigout;
  4042. }
  4043. }
  4044. retval = 127;
  4045. do {
  4046. if (**argv != '%') {
  4047. pid_t pid = number(*argv);
  4048. job = curjob;
  4049. while (1) {
  4050. if (!job)
  4051. goto repeat;
  4052. if (job->ps[job->nprocs - 1].ps_pid == pid)
  4053. break;
  4054. job = job->prev_job;
  4055. }
  4056. } else {
  4057. job = getjob(*argv, 0);
  4058. }
  4059. /* loop until process terminated or stopped */
  4060. while (job->state == JOBRUNNING) {
  4061. dowait(DOWAIT_BLOCK_OR_SIG, NULL);
  4062. if (pending_sig)
  4063. goto sigout;
  4064. }
  4065. job->waited = 1;
  4066. retval = getstatus(job);
  4067. repeat: ;
  4068. } while (*++argv);
  4069. ret:
  4070. return retval;
  4071. sigout:
  4072. retval = 128 + pending_sig;
  4073. return retval;
  4074. }
  4075. static struct job *
  4076. growjobtab(void)
  4077. {
  4078. size_t len;
  4079. ptrdiff_t offset;
  4080. struct job *jp, *jq;
  4081. len = njobs * sizeof(*jp);
  4082. jq = jobtab;
  4083. jp = ckrealloc(jq, len + 4 * sizeof(*jp));
  4084. offset = (char *)jp - (char *)jq;
  4085. if (offset) {
  4086. /* Relocate pointers */
  4087. size_t l = len;
  4088. jq = (struct job *)((char *)jq + l);
  4089. while (l) {
  4090. l -= sizeof(*jp);
  4091. jq--;
  4092. #define joff(p) ((struct job *)((char *)(p) + l))
  4093. #define jmove(p) (p) = (void *)((char *)(p) + offset)
  4094. if (joff(jp)->ps == &jq->ps0)
  4095. jmove(joff(jp)->ps);
  4096. if (joff(jp)->prev_job)
  4097. jmove(joff(jp)->prev_job);
  4098. }
  4099. if (curjob)
  4100. jmove(curjob);
  4101. #undef joff
  4102. #undef jmove
  4103. }
  4104. njobs += 4;
  4105. jobtab = jp;
  4106. jp = (struct job *)((char *)jp + len);
  4107. jq = jp + 3;
  4108. do {
  4109. jq->used = 0;
  4110. } while (--jq >= jp);
  4111. return jp;
  4112. }
  4113. /*
  4114. * Return a new job structure.
  4115. * Called with interrupts off.
  4116. */
  4117. static struct job *
  4118. makejob(/*union node *node,*/ int nprocs)
  4119. {
  4120. int i;
  4121. struct job *jp;
  4122. for (i = njobs, jp = jobtab; ; jp++) {
  4123. if (--i < 0) {
  4124. jp = growjobtab();
  4125. break;
  4126. }
  4127. if (jp->used == 0)
  4128. break;
  4129. if (jp->state != JOBDONE || !jp->waited)
  4130. continue;
  4131. #if JOBS
  4132. if (doing_jobctl)
  4133. continue;
  4134. #endif
  4135. freejob(jp);
  4136. break;
  4137. }
  4138. memset(jp, 0, sizeof(*jp));
  4139. #if JOBS
  4140. /* jp->jobctl is a bitfield.
  4141. * "jp->jobctl |= doing_jobctl" likely to give awful code */
  4142. if (doing_jobctl)
  4143. jp->jobctl = 1;
  4144. #endif
  4145. jp->prev_job = curjob;
  4146. curjob = jp;
  4147. jp->used = 1;
  4148. jp->ps = &jp->ps0;
  4149. if (nprocs > 1) {
  4150. jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
  4151. }
  4152. TRACE(("makejob(%d) returns %%%d\n", nprocs,
  4153. jobno(jp)));
  4154. return jp;
  4155. }
  4156. #if JOBS
  4157. /*
  4158. * Return a string identifying a command (to be printed by the
  4159. * jobs command).
  4160. */
  4161. static char *cmdnextc;
  4162. static void
  4163. cmdputs(const char *s)
  4164. {
  4165. static const char vstype[VSTYPE + 1][3] = {
  4166. "", "}", "-", "+", "?", "=",
  4167. "%", "%%", "#", "##"
  4168. IF_BASH_SUBSTR(, ":")
  4169. IF_BASH_PATTERN_SUBST(, "/", "//")
  4170. };
  4171. const char *p, *str;
  4172. char cc[2];
  4173. char *nextc;
  4174. unsigned char c;
  4175. unsigned char subtype = 0;
  4176. int quoted = 0;
  4177. cc[1] = '\0';
  4178. nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
  4179. p = s;
  4180. while ((c = *p++) != '\0') {
  4181. str = NULL;
  4182. switch (c) {
  4183. case CTLESC:
  4184. c = *p++;
  4185. break;
  4186. case CTLVAR:
  4187. subtype = *p++;
  4188. if ((subtype & VSTYPE) == VSLENGTH)
  4189. str = "${#";
  4190. else
  4191. str = "${";
  4192. goto dostr;
  4193. case CTLENDVAR:
  4194. str = "\"}" + !(quoted & 1);
  4195. quoted >>= 1;
  4196. subtype = 0;
  4197. goto dostr;
  4198. case CTLBACKQ:
  4199. str = "$(...)";
  4200. goto dostr;
  4201. #if ENABLE_FEATURE_SH_MATH
  4202. case CTLARI:
  4203. str = "$((";
  4204. goto dostr;
  4205. case CTLENDARI:
  4206. str = "))";
  4207. goto dostr;
  4208. #endif
  4209. case CTLQUOTEMARK:
  4210. quoted ^= 1;
  4211. c = '"';
  4212. break;
  4213. case '=':
  4214. if (subtype == 0)
  4215. break;
  4216. if ((subtype & VSTYPE) != VSNORMAL)
  4217. quoted <<= 1;
  4218. str = vstype[subtype & VSTYPE];
  4219. if (subtype & VSNUL)
  4220. c = ':';
  4221. else
  4222. goto checkstr;
  4223. break;
  4224. case '\'':
  4225. case '\\':
  4226. case '"':
  4227. case '$':
  4228. /* These can only happen inside quotes */
  4229. cc[0] = c;
  4230. str = cc;
  4231. //FIXME:
  4232. // $ true $$ &
  4233. // $ <cr>
  4234. // [1]+ Done true ${\$} <<=== BUG: ${\$} is not a valid way to write $$ (${$} would be ok)
  4235. c = '\\';
  4236. break;
  4237. default:
  4238. break;
  4239. }
  4240. USTPUTC(c, nextc);
  4241. checkstr:
  4242. if (!str)
  4243. continue;
  4244. dostr:
  4245. while ((c = *str++) != '\0') {
  4246. USTPUTC(c, nextc);
  4247. }
  4248. } /* while *p++ not NUL */
  4249. if (quoted & 1) {
  4250. USTPUTC('"', nextc);
  4251. }
  4252. *nextc = 0;
  4253. cmdnextc = nextc;
  4254. }
  4255. /* cmdtxt() and cmdlist() call each other */
  4256. static void cmdtxt(union node *n);
  4257. static void
  4258. cmdlist(union node *np, int sep)
  4259. {
  4260. for (; np; np = np->narg.next) {
  4261. if (!sep)
  4262. cmdputs(" ");
  4263. cmdtxt(np);
  4264. if (sep && np->narg.next)
  4265. cmdputs(" ");
  4266. }
  4267. }
  4268. static void
  4269. cmdtxt(union node *n)
  4270. {
  4271. union node *np;
  4272. struct nodelist *lp;
  4273. const char *p;
  4274. if (!n)
  4275. return;
  4276. switch (n->type) {
  4277. default:
  4278. #if DEBUG
  4279. abort();
  4280. #endif
  4281. case NPIPE:
  4282. lp = n->npipe.cmdlist;
  4283. for (;;) {
  4284. cmdtxt(lp->n);
  4285. lp = lp->next;
  4286. if (!lp)
  4287. break;
  4288. cmdputs(" | ");
  4289. }
  4290. break;
  4291. case NSEMI:
  4292. p = "; ";
  4293. goto binop;
  4294. case NAND:
  4295. p = " && ";
  4296. goto binop;
  4297. case NOR:
  4298. p = " || ";
  4299. binop:
  4300. cmdtxt(n->nbinary.ch1);
  4301. cmdputs(p);
  4302. n = n->nbinary.ch2;
  4303. goto donode;
  4304. case NREDIR:
  4305. case NBACKGND:
  4306. n = n->nredir.n;
  4307. goto donode;
  4308. case NNOT:
  4309. cmdputs("!");
  4310. n = n->nnot.com;
  4311. donode:
  4312. cmdtxt(n);
  4313. break;
  4314. case NIF:
  4315. cmdputs("if ");
  4316. cmdtxt(n->nif.test);
  4317. cmdputs("; then ");
  4318. if (n->nif.elsepart) {
  4319. cmdtxt(n->nif.ifpart);
  4320. cmdputs("; else ");
  4321. n = n->nif.elsepart;
  4322. } else {
  4323. n = n->nif.ifpart;
  4324. }
  4325. p = "; fi";
  4326. goto dotail;
  4327. case NSUBSHELL:
  4328. cmdputs("(");
  4329. n = n->nredir.n;
  4330. p = ")";
  4331. goto dotail;
  4332. case NWHILE:
  4333. p = "while ";
  4334. goto until;
  4335. case NUNTIL:
  4336. p = "until ";
  4337. until:
  4338. cmdputs(p);
  4339. cmdtxt(n->nbinary.ch1);
  4340. n = n->nbinary.ch2;
  4341. p = "; done";
  4342. dodo:
  4343. cmdputs("; do ");
  4344. dotail:
  4345. cmdtxt(n);
  4346. goto dotail2;
  4347. case NFOR:
  4348. cmdputs("for ");
  4349. cmdputs(n->nfor.var);
  4350. cmdputs(" in ");
  4351. cmdlist(n->nfor.args, 1);
  4352. n = n->nfor.body;
  4353. p = "; done";
  4354. goto dodo;
  4355. case NDEFUN:
  4356. cmdputs(n->narg.text);
  4357. p = "() { ... }";
  4358. goto dotail2;
  4359. case NCMD:
  4360. cmdlist(n->ncmd.args, 1);
  4361. cmdlist(n->ncmd.redirect, 0);
  4362. break;
  4363. case NARG:
  4364. p = n->narg.text;
  4365. dotail2:
  4366. cmdputs(p);
  4367. break;
  4368. case NHERE:
  4369. case NXHERE:
  4370. p = "<<...";
  4371. goto dotail2;
  4372. case NCASE:
  4373. cmdputs("case ");
  4374. cmdputs(n->ncase.expr->narg.text);
  4375. cmdputs(" in ");
  4376. for (np = n->ncase.cases; np; np = np->nclist.next) {
  4377. cmdtxt(np->nclist.pattern);
  4378. cmdputs(") ");
  4379. cmdtxt(np->nclist.body);
  4380. cmdputs(";; ");
  4381. }
  4382. p = "esac";
  4383. goto dotail2;
  4384. case NTO:
  4385. p = ">";
  4386. goto redir;
  4387. case NCLOBBER:
  4388. p = ">|";
  4389. goto redir;
  4390. case NAPPEND:
  4391. p = ">>";
  4392. goto redir;
  4393. #if BASH_REDIR_OUTPUT
  4394. case NTO2:
  4395. #endif
  4396. case NTOFD:
  4397. p = ">&";
  4398. goto redir;
  4399. case NFROM:
  4400. p = "<";
  4401. goto redir;
  4402. case NFROMFD:
  4403. p = "<&";
  4404. goto redir;
  4405. case NFROMTO:
  4406. p = "<>";
  4407. redir:
  4408. cmdputs(utoa(n->nfile.fd));
  4409. cmdputs(p);
  4410. if (n->type == NTOFD || n->type == NFROMFD) {
  4411. if (n->ndup.dupfd >= 0)
  4412. cmdputs(utoa(n->ndup.dupfd));
  4413. else
  4414. cmdputs("-");
  4415. break;
  4416. }
  4417. n = n->nfile.fname;
  4418. goto donode;
  4419. }
  4420. }
  4421. static char *
  4422. commandtext(union node *n)
  4423. {
  4424. char *name;
  4425. STARTSTACKSTR(cmdnextc);
  4426. cmdtxt(n);
  4427. name = stackblock();
  4428. TRACE(("commandtext: name %p, end %p\n", name, cmdnextc));
  4429. return ckstrdup(name);
  4430. }
  4431. #endif /* JOBS */
  4432. /*
  4433. * Fork off a subshell. If we are doing job control, give the subshell its
  4434. * own process group. Jp is a job structure that the job is to be added to.
  4435. * N is the command that will be evaluated by the child. Both jp and n may
  4436. * be NULL. The mode parameter can be one of the following:
  4437. * FORK_FG - Fork off a foreground process.
  4438. * FORK_BG - Fork off a background process.
  4439. * FORK_NOJOB - Like FORK_FG, but don't give the process its own
  4440. * process group even if job control is on.
  4441. *
  4442. * When job control is turned off, background processes have their standard
  4443. * input redirected to /dev/null (except for the second and later processes
  4444. * in a pipeline).
  4445. *
  4446. * Called with interrupts off.
  4447. */
  4448. /*
  4449. * Clear traps on a fork.
  4450. */
  4451. static void
  4452. clear_traps(void)
  4453. {
  4454. char **tp;
  4455. INT_OFF;
  4456. for (tp = trap; tp < &trap[NSIG]; tp++) {
  4457. if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
  4458. if (trap_ptr == trap)
  4459. free(*tp);
  4460. /* else: it "belongs" to trap_ptr vector, don't free */
  4461. *tp = NULL;
  4462. if ((tp - trap) != 0)
  4463. setsignal(tp - trap);
  4464. }
  4465. }
  4466. may_have_traps = 0;
  4467. INT_ON;
  4468. }
  4469. /* Lives far away from here, needed for forkchild */
  4470. static void closescript(void);
  4471. /* Called after fork(), in child */
  4472. /* jp and n are NULL when called by openhere() for heredoc support */
  4473. static NOINLINE void
  4474. forkchild(struct job *jp, union node *n, int mode)
  4475. {
  4476. int oldlvl;
  4477. TRACE(("Child shell %d\n", getpid()));
  4478. oldlvl = shlvl;
  4479. shlvl++;
  4480. /* man bash: "Non-builtin commands run by bash have signal handlers
  4481. * set to the values inherited by the shell from its parent".
  4482. * Do we do it correctly? */
  4483. closescript();
  4484. if (mode == FORK_NOJOB /* is it `xxx` ? */
  4485. && n && n->type == NCMD /* is it single cmd? */
  4486. /* && n->ncmd.args->type == NARG - always true? */
  4487. && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "trap") == 0
  4488. && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
  4489. /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
  4490. ) {
  4491. TRACE(("Trap hack\n"));
  4492. /* Awful hack for `trap` or $(trap).
  4493. *
  4494. * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
  4495. * contains an example where "trap" is executed in a subshell:
  4496. *
  4497. * save_traps=$(trap)
  4498. * ...
  4499. * eval "$save_traps"
  4500. *
  4501. * Standard does not say that "trap" in subshell shall print
  4502. * parent shell's traps. It only says that its output
  4503. * must have suitable form, but then, in the above example
  4504. * (which is not supposed to be normative), it implies that.
  4505. *
  4506. * bash (and probably other shell) does implement it
  4507. * (traps are reset to defaults, but "trap" still shows them),
  4508. * but as a result, "trap" logic is hopelessly messed up:
  4509. *
  4510. * # trap
  4511. * trap -- 'echo Ho' SIGWINCH <--- we have a handler
  4512. * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
  4513. * # true | trap <--- trap is in subshell - no output (ditto)
  4514. * # echo `true | trap` <--- in subshell - output (but traps are reset!)
  4515. * trap -- 'echo Ho' SIGWINCH
  4516. * # echo `(trap)` <--- in subshell in subshell - output
  4517. * trap -- 'echo Ho' SIGWINCH
  4518. * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
  4519. * trap -- 'echo Ho' SIGWINCH
  4520. *
  4521. * The rules when to forget and when to not forget traps
  4522. * get really complex and nonsensical.
  4523. *
  4524. * Our solution: ONLY bare $(trap) or `trap` is special.
  4525. */
  4526. /* Save trap handler strings for trap builtin to print */
  4527. trap_ptr = xmemdup(trap, sizeof(trap));
  4528. /* Fall through into clearing traps */
  4529. }
  4530. clear_traps();
  4531. #if JOBS
  4532. /* do job control only in root shell */
  4533. doing_jobctl = 0;
  4534. if (mode != FORK_NOJOB && jp->jobctl && oldlvl == 0) {
  4535. pid_t pgrp;
  4536. if (jp->nprocs == 0)
  4537. pgrp = getpid();
  4538. else
  4539. pgrp = jp->ps[0].ps_pid;
  4540. /* this can fail because we are doing it in the parent also */
  4541. setpgid(0, pgrp);
  4542. if (mode == FORK_FG)
  4543. xtcsetpgrp(ttyfd, pgrp);
  4544. setsignal(SIGTSTP);
  4545. setsignal(SIGTTOU);
  4546. } else
  4547. #endif
  4548. if (mode == FORK_BG) {
  4549. /* man bash: "When job control is not in effect,
  4550. * asynchronous commands ignore SIGINT and SIGQUIT" */
  4551. ignoresig(SIGINT);
  4552. ignoresig(SIGQUIT);
  4553. if (jp->nprocs == 0) {
  4554. close(0);
  4555. if (open(bb_dev_null, O_RDONLY) != 0)
  4556. ash_msg_and_raise_perror("can't open '%s'", bb_dev_null);
  4557. }
  4558. }
  4559. if (oldlvl == 0) {
  4560. if (iflag) { /* why if iflag only? */
  4561. setsignal(SIGINT);
  4562. setsignal(SIGTERM);
  4563. }
  4564. /* man bash:
  4565. * "In all cases, bash ignores SIGQUIT. Non-builtin
  4566. * commands run by bash have signal handlers
  4567. * set to the values inherited by the shell
  4568. * from its parent".
  4569. * Take care of the second rule: */
  4570. setsignal(SIGQUIT);
  4571. }
  4572. #if JOBS
  4573. if (n && n->type == NCMD
  4574. && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "jobs") == 0
  4575. ) {
  4576. TRACE(("Job hack\n"));
  4577. /* "jobs": we do not want to clear job list for it,
  4578. * instead we remove only _its_ own_ job from job list.
  4579. * This makes "jobs .... | cat" more useful.
  4580. */
  4581. freejob(curjob);
  4582. return;
  4583. }
  4584. #endif
  4585. for (jp = curjob; jp; jp = jp->prev_job)
  4586. freejob(jp);
  4587. jobless = 0;
  4588. }
  4589. /* Called after fork(), in parent */
  4590. #if !JOBS
  4591. #define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
  4592. #endif
  4593. static void
  4594. forkparent(struct job *jp, union node *n, int mode, pid_t pid)
  4595. {
  4596. TRACE(("In parent shell: child = %d\n", pid));
  4597. if (!jp) {
  4598. /* jp is NULL when called by openhere() for heredoc support */
  4599. while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
  4600. continue;
  4601. jobless++;
  4602. return;
  4603. }
  4604. #if JOBS
  4605. if (mode != FORK_NOJOB && jp->jobctl) {
  4606. int pgrp;
  4607. if (jp->nprocs == 0)
  4608. pgrp = pid;
  4609. else
  4610. pgrp = jp->ps[0].ps_pid;
  4611. /* This can fail because we are doing it in the child also */
  4612. setpgid(pid, pgrp);
  4613. }
  4614. #endif
  4615. if (mode == FORK_BG) {
  4616. backgndpid = pid; /* set $! */
  4617. set_curjob(jp, CUR_RUNNING);
  4618. }
  4619. if (jp) {
  4620. struct procstat *ps = &jp->ps[jp->nprocs++];
  4621. ps->ps_pid = pid;
  4622. ps->ps_status = -1;
  4623. ps->ps_cmd = nullstr;
  4624. #if JOBS
  4625. if (doing_jobctl && n)
  4626. ps->ps_cmd = commandtext(n);
  4627. #endif
  4628. }
  4629. }
  4630. /* jp and n are NULL when called by openhere() for heredoc support */
  4631. static int
  4632. forkshell(struct job *jp, union node *n, int mode)
  4633. {
  4634. int pid;
  4635. TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
  4636. pid = fork();
  4637. if (pid < 0) {
  4638. TRACE(("Fork failed, errno=%d", errno));
  4639. if (jp)
  4640. freejob(jp);
  4641. ash_msg_and_raise_perror("can't fork");
  4642. }
  4643. if (pid == 0) {
  4644. CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
  4645. forkchild(jp, n, mode);
  4646. } else {
  4647. forkparent(jp, n, mode, pid);
  4648. }
  4649. return pid;
  4650. }
  4651. /*
  4652. * Wait for job to finish.
  4653. *
  4654. * Under job control we have the problem that while a child process
  4655. * is running interrupts generated by the user are sent to the child
  4656. * but not to the shell. This means that an infinite loop started by
  4657. * an interactive user may be hard to kill. With job control turned off,
  4658. * an interactive user may place an interactive program inside a loop.
  4659. * If the interactive program catches interrupts, the user doesn't want
  4660. * these interrupts to also abort the loop. The approach we take here
  4661. * is to have the shell ignore interrupt signals while waiting for a
  4662. * foreground process to terminate, and then send itself an interrupt
  4663. * signal if the child process was terminated by an interrupt signal.
  4664. * Unfortunately, some programs want to do a bit of cleanup and then
  4665. * exit on interrupt; unless these processes terminate themselves by
  4666. * sending a signal to themselves (instead of calling exit) they will
  4667. * confuse this approach.
  4668. *
  4669. * Called with interrupts off.
  4670. */
  4671. static int
  4672. waitforjob(struct job *jp)
  4673. {
  4674. int st;
  4675. TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
  4676. INT_OFF;
  4677. while (jp->state == JOBRUNNING) {
  4678. /* In non-interactive shells, we _can_ get
  4679. * a keyboard signal here and be EINTRed,
  4680. * but we just loop back, waiting for command to complete.
  4681. *
  4682. * man bash:
  4683. * "If bash is waiting for a command to complete and receives
  4684. * a signal for which a trap has been set, the trap
  4685. * will not be executed until the command completes."
  4686. *
  4687. * Reality is that even if trap is not set, bash
  4688. * will not act on the signal until command completes.
  4689. * Try this. sleep5intoff.c:
  4690. * #include <signal.h>
  4691. * #include <unistd.h>
  4692. * int main() {
  4693. * sigset_t set;
  4694. * sigemptyset(&set);
  4695. * sigaddset(&set, SIGINT);
  4696. * sigaddset(&set, SIGQUIT);
  4697. * sigprocmask(SIG_BLOCK, &set, NULL);
  4698. * sleep(5);
  4699. * return 0;
  4700. * }
  4701. * $ bash -c './sleep5intoff; echo hi'
  4702. * ^C^C^C^C <--- pressing ^C once a second
  4703. * $ _
  4704. * $ bash -c './sleep5intoff; echo hi'
  4705. * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
  4706. * $ _
  4707. */
  4708. dowait(DOWAIT_BLOCK, jp);
  4709. }
  4710. INT_ON;
  4711. st = getstatus(jp);
  4712. #if JOBS
  4713. if (jp->jobctl) {
  4714. xtcsetpgrp(ttyfd, rootpid);
  4715. restore_tty_if_stopped_or_signaled(jp);
  4716. /*
  4717. * This is truly gross.
  4718. * If we're doing job control, then we did a TIOCSPGRP which
  4719. * caused us (the shell) to no longer be in the controlling
  4720. * session -- so we wouldn't have seen any ^C/SIGINT. So, we
  4721. * intuit from the subprocess exit status whether a SIGINT
  4722. * occurred, and if so interrupt ourselves. Yuck. - mycroft
  4723. */
  4724. if (jp->sigint) /* TODO: do the same with all signals */
  4725. raise(SIGINT); /* ... by raise(jp->sig) instead? */
  4726. }
  4727. if (jp->state == JOBDONE)
  4728. #endif
  4729. freejob(jp);
  4730. return st;
  4731. }
  4732. /*
  4733. * return 1 if there are stopped jobs, otherwise 0
  4734. */
  4735. static int
  4736. stoppedjobs(void)
  4737. {
  4738. struct job *jp;
  4739. int retval;
  4740. retval = 0;
  4741. if (job_warning)
  4742. goto out;
  4743. jp = curjob;
  4744. if (jp && jp->state == JOBSTOPPED) {
  4745. out2str("You have stopped jobs.\n");
  4746. job_warning = 2;
  4747. retval++;
  4748. }
  4749. out:
  4750. return retval;
  4751. }
  4752. /*
  4753. * Code for dealing with input/output redirection.
  4754. */
  4755. #undef EMPTY
  4756. #undef CLOSED
  4757. #define EMPTY -2 /* marks an unused slot in redirtab */
  4758. #define CLOSED -1 /* marks a slot of previously-closed fd */
  4759. /*
  4760. * Handle here documents. Normally we fork off a process to write the
  4761. * data to a pipe. If the document is short, we can stuff the data in
  4762. * the pipe without forking.
  4763. */
  4764. /* openhere needs this forward reference */
  4765. static void expandhere(union node *arg, int fd);
  4766. static int
  4767. openhere(union node *redir)
  4768. {
  4769. int pip[2];
  4770. size_t len = 0;
  4771. if (pipe(pip) < 0)
  4772. ash_msg_and_raise_perror("can't create pipe");
  4773. if (redir->type == NHERE) {
  4774. len = strlen(redir->nhere.doc->narg.text);
  4775. if (len <= PIPE_BUF) {
  4776. full_write(pip[1], redir->nhere.doc->narg.text, len);
  4777. goto out;
  4778. }
  4779. }
  4780. if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
  4781. /* child */
  4782. close(pip[0]);
  4783. ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
  4784. ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
  4785. ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
  4786. ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
  4787. signal(SIGPIPE, SIG_DFL);
  4788. if (redir->type == NHERE)
  4789. full_write(pip[1], redir->nhere.doc->narg.text, len);
  4790. else /* NXHERE */
  4791. expandhere(redir->nhere.doc, pip[1]);
  4792. _exit(EXIT_SUCCESS);
  4793. }
  4794. out:
  4795. close(pip[1]);
  4796. return pip[0];
  4797. }
  4798. static int
  4799. openredirect(union node *redir)
  4800. {
  4801. struct stat sb;
  4802. char *fname;
  4803. int f;
  4804. switch (redir->nfile.type) {
  4805. /* Can't happen, our single caller does this itself */
  4806. // case NTOFD:
  4807. // case NFROMFD:
  4808. // return -1;
  4809. case NHERE:
  4810. case NXHERE:
  4811. return openhere(redir);
  4812. }
  4813. /* For N[X]HERE, reading redir->nfile.expfname would touch beyond
  4814. * allocated space. Do it only when we know it is safe.
  4815. */
  4816. fname = redir->nfile.expfname;
  4817. switch (redir->nfile.type) {
  4818. default:
  4819. #if DEBUG
  4820. abort();
  4821. #endif
  4822. case NFROM:
  4823. f = open(fname, O_RDONLY);
  4824. if (f < 0)
  4825. goto eopen;
  4826. break;
  4827. case NFROMTO:
  4828. f = open(fname, O_RDWR|O_CREAT, 0666);
  4829. if (f < 0)
  4830. goto ecreate;
  4831. break;
  4832. case NTO:
  4833. #if BASH_REDIR_OUTPUT
  4834. case NTO2:
  4835. #endif
  4836. /* Take care of noclobber mode. */
  4837. if (Cflag) {
  4838. if (stat(fname, &sb) < 0) {
  4839. f = open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
  4840. if (f < 0)
  4841. goto ecreate;
  4842. } else if (!S_ISREG(sb.st_mode)) {
  4843. f = open(fname, O_WRONLY, 0666);
  4844. if (f < 0)
  4845. goto ecreate;
  4846. if (fstat(f, &sb) < 0 && S_ISREG(sb.st_mode)) {
  4847. close(f);
  4848. errno = EEXIST;
  4849. goto ecreate;
  4850. }
  4851. } else {
  4852. errno = EEXIST;
  4853. goto ecreate;
  4854. }
  4855. break;
  4856. }
  4857. /* FALLTHROUGH */
  4858. case NCLOBBER:
  4859. f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
  4860. if (f < 0)
  4861. goto ecreate;
  4862. break;
  4863. case NAPPEND:
  4864. f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
  4865. if (f < 0)
  4866. goto ecreate;
  4867. break;
  4868. }
  4869. return f;
  4870. ecreate:
  4871. ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
  4872. eopen:
  4873. ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
  4874. }
  4875. /*
  4876. * Copy a file descriptor to be >= 10. Throws exception on error.
  4877. */
  4878. static int
  4879. savefd(int from)
  4880. {
  4881. int newfd;
  4882. int err;
  4883. newfd = fcntl(from, F_DUPFD, 10);
  4884. err = newfd < 0 ? errno : 0;
  4885. if (err != EBADF) {
  4886. if (err)
  4887. ash_msg_and_raise_perror("%d", from);
  4888. close(from);
  4889. fcntl(newfd, F_SETFD, FD_CLOEXEC);
  4890. }
  4891. return newfd;
  4892. }
  4893. static int
  4894. dup2_or_raise(int from, int to)
  4895. {
  4896. int newfd;
  4897. newfd = (from != to) ? dup2(from, to) : to;
  4898. if (newfd < 0) {
  4899. /* Happens when source fd is not open: try "echo >&99" */
  4900. ash_msg_and_raise_perror("%d", from);
  4901. }
  4902. return newfd;
  4903. }
  4904. static int
  4905. fcntl_F_DUPFD(int fd, int avoid_fd)
  4906. {
  4907. int newfd;
  4908. repeat:
  4909. newfd = fcntl(fd, F_DUPFD, avoid_fd + 1);
  4910. if (newfd < 0) {
  4911. if (errno == EBUSY)
  4912. goto repeat;
  4913. if (errno == EINTR)
  4914. goto repeat;
  4915. }
  4916. return newfd;
  4917. }
  4918. static int
  4919. xdup_CLOEXEC_and_close(int fd, int avoid_fd)
  4920. {
  4921. int newfd;
  4922. repeat:
  4923. newfd = fcntl(fd, F_DUPFD, avoid_fd + 1);
  4924. if (newfd < 0) {
  4925. if (errno == EBUSY)
  4926. goto repeat;
  4927. if (errno == EINTR)
  4928. goto repeat;
  4929. /* fd was not open? */
  4930. if (errno == EBADF)
  4931. return fd;
  4932. ash_msg_and_raise_perror("%d", newfd);
  4933. }
  4934. fcntl(newfd, F_SETFD, FD_CLOEXEC);
  4935. close(fd);
  4936. return newfd;
  4937. }
  4938. /* Struct def and variable are moved down to the first usage site */
  4939. struct squirrel {
  4940. int orig_fd;
  4941. int moved_to;
  4942. };
  4943. struct redirtab {
  4944. struct redirtab *next;
  4945. int pair_count;
  4946. struct squirrel two_fd[];
  4947. };
  4948. #define redirlist (G_var.redirlist)
  4949. static void
  4950. add_squirrel_closed(struct redirtab *sq, int fd)
  4951. {
  4952. int i;
  4953. if (!sq)
  4954. return;
  4955. for (i = 0; sq->two_fd[i].orig_fd != EMPTY; i++) {
  4956. /* If we collide with an already moved fd... */
  4957. if (fd == sq->two_fd[i].orig_fd) {
  4958. /* Examples:
  4959. * "echo 3>FILE 3>&- 3>FILE"
  4960. * "echo 3>&- 3>FILE"
  4961. * No need for last redirect to insert
  4962. * another "need to close 3" indicator.
  4963. */
  4964. TRACE(("redirect_fd %d: already moved or closed\n", fd));
  4965. return;
  4966. }
  4967. }
  4968. TRACE(("redirect_fd %d: previous fd was closed\n", fd));
  4969. sq->two_fd[i].orig_fd = fd;
  4970. sq->two_fd[i].moved_to = CLOSED;
  4971. }
  4972. static int
  4973. save_fd_on_redirect(int fd, int avoid_fd, struct redirtab *sq)
  4974. {
  4975. int i, new_fd;
  4976. if (avoid_fd < 9) /* the important case here is that it can be -1 */
  4977. avoid_fd = 9;
  4978. #if JOBS
  4979. if (fd == ttyfd) {
  4980. /* Testcase: "ls -l /proc/$$/fd 10>&-" should work */
  4981. ttyfd = xdup_CLOEXEC_and_close(ttyfd, avoid_fd);
  4982. TRACE(("redirect_fd %d: matches ttyfd, moving it to %d\n", fd, ttyfd));
  4983. return 1; /* "we closed fd" */
  4984. }
  4985. #endif
  4986. /* Are we called from redirect(0)? E.g. redirect
  4987. * in a forked child. No need to save fds,
  4988. * we aren't going to use them anymore, ok to trash.
  4989. */
  4990. if (!sq)
  4991. return 0;
  4992. /* If this one of script's fds? */
  4993. if (fd != 0) {
  4994. struct parsefile *pf = g_parsefile;
  4995. while (pf) {
  4996. /* We skip fd == 0 case because of the following:
  4997. * $ ash # running ash interactively
  4998. * $ . ./script.sh
  4999. * and in script.sh: "exec 9>&0".
  5000. * Even though top-level pf_fd _is_ 0,
  5001. * it's still ok to use it: "read" builtin uses it,
  5002. * why should we cripple "exec" builtin?
  5003. */
  5004. if (fd == pf->pf_fd) {
  5005. pf->pf_fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
  5006. return 1; /* "we closed fd" */
  5007. }
  5008. pf = pf->prev;
  5009. }
  5010. }
  5011. /* Check whether it collides with any open fds (e.g. stdio), save fds as needed */
  5012. /* First: do we collide with some already moved fds? */
  5013. for (i = 0; sq->two_fd[i].orig_fd != EMPTY; i++) {
  5014. /* If we collide with an already moved fd... */
  5015. if (fd == sq->two_fd[i].moved_to) {
  5016. new_fd = fcntl_F_DUPFD(fd, avoid_fd);
  5017. sq->two_fd[i].moved_to = new_fd;
  5018. TRACE(("redirect_fd %d: already busy, moving to %d\n", fd, new_fd));
  5019. if (new_fd < 0) /* what? */
  5020. xfunc_die();
  5021. return 0; /* "we did not close fd" */
  5022. }
  5023. if (fd == sq->two_fd[i].orig_fd) {
  5024. /* Example: echo Hello >/dev/null 1>&2 */
  5025. TRACE(("redirect_fd %d: already moved\n", fd));
  5026. return 0; /* "we did not close fd" */
  5027. }
  5028. }
  5029. /* If this fd is open, we move and remember it; if it's closed, new_fd = CLOSED (-1) */
  5030. new_fd = fcntl_F_DUPFD(fd, avoid_fd);
  5031. TRACE(("redirect_fd %d: previous fd is moved to %d (-1 if it was closed)\n", fd, new_fd));
  5032. if (new_fd < 0) {
  5033. if (errno != EBADF)
  5034. xfunc_die();
  5035. /* new_fd = CLOSED; - already is -1 */
  5036. }
  5037. sq->two_fd[i].moved_to = new_fd;
  5038. sq->two_fd[i].orig_fd = fd;
  5039. /* if we move stderr, let "set -x" code know */
  5040. if (fd == preverrout_fd)
  5041. preverrout_fd = new_fd;
  5042. return 0; /* "we did not close fd" */
  5043. }
  5044. static int
  5045. internally_opened_fd(int fd, struct redirtab *sq)
  5046. {
  5047. int i;
  5048. #if JOBS
  5049. if (fd == ttyfd)
  5050. return 1;
  5051. #endif
  5052. /* If this one of script's fds? */
  5053. if (fd != 0) {
  5054. struct parsefile *pf = g_parsefile;
  5055. while (pf) {
  5056. if (fd == pf->pf_fd)
  5057. return 1;
  5058. pf = pf->prev;
  5059. }
  5060. }
  5061. if (sq) for (i = 0; i < sq->pair_count && sq->two_fd[i].orig_fd != EMPTY; i++) {
  5062. if (fd == sq->two_fd[i].moved_to)
  5063. return 1;
  5064. }
  5065. return 0;
  5066. }
  5067. /*
  5068. * Process a list of redirection commands. If the REDIR_PUSH flag is set,
  5069. * old file descriptors are stashed away so that the redirection can be
  5070. * undone by calling popredir.
  5071. */
  5072. /* flags passed to redirect */
  5073. #define REDIR_PUSH 01 /* save previous values of file descriptors */
  5074. static void
  5075. redirect(union node *redir, int flags)
  5076. {
  5077. struct redirtab *sv;
  5078. if (!redir)
  5079. return;
  5080. sv = NULL;
  5081. INT_OFF;
  5082. if (flags & REDIR_PUSH)
  5083. sv = redirlist;
  5084. do {
  5085. int fd;
  5086. int newfd;
  5087. int close_fd;
  5088. int closed;
  5089. fd = redir->nfile.fd;
  5090. if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
  5091. //bb_error_msg("doing %d > %d", fd, newfd);
  5092. newfd = redir->ndup.dupfd;
  5093. close_fd = -1;
  5094. } else {
  5095. newfd = openredirect(redir); /* always >= 0 */
  5096. if (fd == newfd) {
  5097. /* open() gave us precisely the fd we wanted.
  5098. * This means that this fd was not busy
  5099. * (not opened to anywhere).
  5100. * Remember to close it on restore:
  5101. */
  5102. add_squirrel_closed(sv, fd);
  5103. continue;
  5104. }
  5105. close_fd = newfd;
  5106. }
  5107. if (fd == newfd)
  5108. continue;
  5109. /* if "N>FILE": move newfd to fd */
  5110. /* if "N>&M": dup newfd to fd */
  5111. /* if "N>&-": close fd (newfd is -1) */
  5112. IF_BASH_REDIR_OUTPUT(redirect_more:)
  5113. closed = save_fd_on_redirect(fd, /*avoid:*/ newfd, sv);
  5114. if (newfd == -1) {
  5115. /* "N>&-" means "close me" */
  5116. if (!closed) {
  5117. /* ^^^ optimization: saving may already
  5118. * have closed it. If not... */
  5119. close(fd);
  5120. }
  5121. } else {
  5122. /* if newfd is a script fd or saved fd, simulate EBADF */
  5123. if (internally_opened_fd(newfd, sv)) {
  5124. errno = EBADF;
  5125. ash_msg_and_raise_perror("%d", newfd);
  5126. }
  5127. dup2_or_raise(newfd, fd);
  5128. if (close_fd >= 0) /* "N>FILE" or ">&FILE" or heredoc? */
  5129. close(close_fd);
  5130. #if BASH_REDIR_OUTPUT
  5131. if (redir->nfile.type == NTO2 && fd == 1) {
  5132. /* ">&FILE". we already redirected to 1, now copy 1 to 2 */
  5133. fd = 2;
  5134. newfd = 1;
  5135. close_fd = -1;
  5136. goto redirect_more;
  5137. }
  5138. #endif
  5139. }
  5140. } while ((redir = redir->nfile.next) != NULL);
  5141. INT_ON;
  5142. //dash:#define REDIR_SAVEFD2 03 /* set preverrout */
  5143. #define REDIR_SAVEFD2 0
  5144. // dash has a bug: since REDIR_SAVEFD2=3 and REDIR_PUSH=1, this test
  5145. // triggers for pure REDIR_PUSH too. Thus, this is done almost always,
  5146. // not only for calls with flags containing REDIR_SAVEFD2.
  5147. // We do this unconditionally (see save_fd_on_redirect()).
  5148. //if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
  5149. // preverrout_fd = copied_fd2;
  5150. }
  5151. static int
  5152. redirectsafe(union node *redir, int flags)
  5153. {
  5154. int err;
  5155. volatile int saveint;
  5156. struct jmploc *volatile savehandler = exception_handler;
  5157. struct jmploc jmploc;
  5158. SAVE_INT(saveint);
  5159. /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
  5160. err = setjmp(jmploc.loc); /* was = setjmp(jmploc.loc) * 2; */
  5161. if (!err) {
  5162. exception_handler = &jmploc;
  5163. redirect(redir, flags);
  5164. }
  5165. exception_handler = savehandler;
  5166. if (err && exception_type != EXERROR)
  5167. longjmp(exception_handler->loc, 1);
  5168. RESTORE_INT(saveint);
  5169. return err;
  5170. }
  5171. static struct redirtab*
  5172. pushredir(union node *redir)
  5173. {
  5174. struct redirtab *sv;
  5175. int i;
  5176. if (!redir)
  5177. return redirlist;
  5178. i = 0;
  5179. do {
  5180. i++;
  5181. #if BASH_REDIR_OUTPUT
  5182. if (redir->nfile.type == NTO2)
  5183. i++;
  5184. #endif
  5185. redir = redir->nfile.next;
  5186. } while (redir);
  5187. sv = ckzalloc(sizeof(*sv) + i * sizeof(sv->two_fd[0]));
  5188. sv->pair_count = i;
  5189. while (--i >= 0)
  5190. sv->two_fd[i].orig_fd = sv->two_fd[i].moved_to = EMPTY;
  5191. sv->next = redirlist;
  5192. redirlist = sv;
  5193. return sv->next;
  5194. }
  5195. /*
  5196. * Undo the effects of the last redirection.
  5197. */
  5198. static void
  5199. popredir(int drop)
  5200. {
  5201. struct redirtab *rp;
  5202. int i;
  5203. if (redirlist == NULL)
  5204. return;
  5205. INT_OFF;
  5206. rp = redirlist;
  5207. for (i = 0; i < rp->pair_count; i++) {
  5208. int fd = rp->two_fd[i].orig_fd;
  5209. int copy = rp->two_fd[i].moved_to;
  5210. if (copy == CLOSED) {
  5211. if (!drop)
  5212. close(fd);
  5213. continue;
  5214. }
  5215. if (copy != EMPTY) {
  5216. if (!drop) {
  5217. /*close(fd);*/
  5218. dup2_or_raise(copy, fd);
  5219. }
  5220. close(copy);
  5221. }
  5222. }
  5223. redirlist = rp->next;
  5224. free(rp);
  5225. INT_ON;
  5226. }
  5227. static void
  5228. unwindredir(struct redirtab *stop)
  5229. {
  5230. while (redirlist != stop)
  5231. popredir(/*drop:*/ 0);
  5232. }
  5233. /* ============ Routines to expand arguments to commands
  5234. *
  5235. * We have to deal with backquotes, shell variables, and file metacharacters.
  5236. */
  5237. #if ENABLE_FEATURE_SH_MATH
  5238. static arith_t
  5239. ash_arith(const char *s)
  5240. {
  5241. arith_state_t math_state;
  5242. arith_t result;
  5243. math_state.lookupvar = lookupvar;
  5244. math_state.setvar = setvar0;
  5245. //math_state.endofname = endofname;
  5246. INT_OFF;
  5247. result = arith(&math_state, s);
  5248. if (math_state.errmsg)
  5249. ash_msg_and_raise_error(math_state.errmsg);
  5250. INT_ON;
  5251. return result;
  5252. }
  5253. #endif
  5254. /*
  5255. * expandarg flags
  5256. */
  5257. #define EXP_FULL 0x1 /* perform word splitting & file globbing */
  5258. #define EXP_TILDE 0x2 /* do normal tilde expansion */
  5259. #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
  5260. #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
  5261. /* ^^^^^^^^^^^^^^ this is meant to support constructs such as "cmd >file*.txt"
  5262. * POSIX says for this case:
  5263. * Pathname expansion shall not be performed on the word by a
  5264. * non-interactive shell; an interactive shell may perform it, but shall
  5265. * do so only when the expansion would result in one word.
  5266. * Currently, our code complies to the above rule by never globbing
  5267. * redirection filenames.
  5268. * Bash performs globbing, unless it is non-interactive and in POSIX mode.
  5269. * (this means that on a typical Linux distro, bash almost always
  5270. * performs globbing, and thus diverges from what we do).
  5271. */
  5272. #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
  5273. #define EXP_QPAT 0x20 /* pattern in quoted parameter expansion */
  5274. #define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
  5275. #define EXP_WORD 0x80 /* expand word in parameter expansion */
  5276. #define EXP_QUOTED 0x100 /* expand word in double quotes */
  5277. /*
  5278. * rmescape() flags
  5279. */
  5280. #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
  5281. #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
  5282. #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
  5283. #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
  5284. #define RMESCAPE_SLASH 0x20 /* Stop globbing after slash */
  5285. /* Add CTLESC when necessary. */
  5286. #define QUOTES_ESC (EXP_FULL | EXP_CASE | EXP_QPAT)
  5287. /* Do not skip NUL characters. */
  5288. #define QUOTES_KEEPNUL EXP_TILDE
  5289. /*
  5290. * Structure specifying which parts of the string should be searched
  5291. * for IFS characters.
  5292. */
  5293. struct ifsregion {
  5294. struct ifsregion *next; /* next region in list */
  5295. int begoff; /* offset of start of region */
  5296. int endoff; /* offset of end of region */
  5297. int nulonly; /* search for nul bytes only */
  5298. };
  5299. struct arglist {
  5300. struct strlist *list;
  5301. struct strlist **lastp;
  5302. };
  5303. /* output of current string */
  5304. static char *expdest;
  5305. /* list of back quote expressions */
  5306. static struct nodelist *argbackq;
  5307. /* first struct in list of ifs regions */
  5308. static struct ifsregion ifsfirst;
  5309. /* last struct in list */
  5310. static struct ifsregion *ifslastp;
  5311. /* holds expanded arg list */
  5312. static struct arglist exparg;
  5313. /*
  5314. * Our own itoa().
  5315. * cvtnum() is used even if math support is off (to prepare $? values and such).
  5316. */
  5317. static int
  5318. cvtnum(arith_t num)
  5319. {
  5320. int len;
  5321. /* 32-bit and wider ints require buffer size of bytes*3 (or less) */
  5322. len = sizeof(arith_t) * 3;
  5323. /* If narrower: worst case, 1-byte ints: need 5 bytes: "-127<NUL>" */
  5324. if (sizeof(arith_t) < 4) len += 2;
  5325. expdest = makestrspace(len, expdest);
  5326. len = fmtstr(expdest, len, ARITH_FMT, num);
  5327. STADJUST(len, expdest);
  5328. return len;
  5329. }
  5330. /*
  5331. * Break the argument string into pieces based upon IFS and add the
  5332. * strings to the argument list. The regions of the string to be
  5333. * searched for IFS characters have been stored by recordregion.
  5334. */
  5335. static void
  5336. ifsbreakup(char *string, struct arglist *arglist)
  5337. {
  5338. struct ifsregion *ifsp;
  5339. struct strlist *sp;
  5340. char *start;
  5341. char *p;
  5342. char *q;
  5343. const char *ifs, *realifs;
  5344. int ifsspc;
  5345. int nulonly;
  5346. start = string;
  5347. if (ifslastp != NULL) {
  5348. ifsspc = 0;
  5349. nulonly = 0;
  5350. realifs = ifsset() ? ifsval() : defifs;
  5351. ifsp = &ifsfirst;
  5352. do {
  5353. p = string + ifsp->begoff;
  5354. nulonly = ifsp->nulonly;
  5355. ifs = nulonly ? nullstr : realifs;
  5356. ifsspc = 0;
  5357. while (p < string + ifsp->endoff) {
  5358. q = p;
  5359. if ((unsigned char)*p == CTLESC)
  5360. p++;
  5361. if (!strchr(ifs, *p)) {
  5362. p++;
  5363. continue;
  5364. }
  5365. if (!nulonly)
  5366. ifsspc = (strchr(defifs, *p) != NULL);
  5367. /* Ignore IFS whitespace at start */
  5368. if (q == start && ifsspc) {
  5369. p++;
  5370. start = p;
  5371. continue;
  5372. }
  5373. *q = '\0';
  5374. sp = stzalloc(sizeof(*sp));
  5375. sp->text = start;
  5376. *arglist->lastp = sp;
  5377. arglist->lastp = &sp->next;
  5378. p++;
  5379. if (!nulonly) {
  5380. for (;;) {
  5381. if (p >= string + ifsp->endoff) {
  5382. break;
  5383. }
  5384. q = p;
  5385. if ((unsigned char)*p == CTLESC)
  5386. p++;
  5387. if (strchr(ifs, *p) == NULL) {
  5388. p = q;
  5389. break;
  5390. }
  5391. if (strchr(defifs, *p) == NULL) {
  5392. if (ifsspc) {
  5393. p++;
  5394. ifsspc = 0;
  5395. } else {
  5396. p = q;
  5397. break;
  5398. }
  5399. } else
  5400. p++;
  5401. }
  5402. }
  5403. start = p;
  5404. } /* while */
  5405. ifsp = ifsp->next;
  5406. } while (ifsp != NULL);
  5407. if (nulonly)
  5408. goto add;
  5409. }
  5410. if (!*start)
  5411. return;
  5412. add:
  5413. sp = stzalloc(sizeof(*sp));
  5414. sp->text = start;
  5415. *arglist->lastp = sp;
  5416. arglist->lastp = &sp->next;
  5417. }
  5418. static void
  5419. ifsfree(void)
  5420. {
  5421. struct ifsregion *p = ifsfirst.next;
  5422. if (!p)
  5423. goto out;
  5424. INT_OFF;
  5425. do {
  5426. struct ifsregion *ifsp;
  5427. ifsp = p->next;
  5428. free(p);
  5429. p = ifsp;
  5430. } while (p);
  5431. ifsfirst.next = NULL;
  5432. INT_ON;
  5433. out:
  5434. ifslastp = NULL;
  5435. }
  5436. static size_t
  5437. esclen(const char *start, const char *p)
  5438. {
  5439. size_t esc = 0;
  5440. while (p > start && (unsigned char)*--p == CTLESC) {
  5441. esc++;
  5442. }
  5443. return esc;
  5444. }
  5445. /*
  5446. * Remove any CTLESC characters from a string.
  5447. */
  5448. static char *
  5449. rmescapes(char *str, int flag)
  5450. {
  5451. static const char qchars[] ALIGN1 = {
  5452. IF_BASH_PATTERN_SUBST('/',) CTLESC, CTLQUOTEMARK, '\0' };
  5453. char *p, *q, *r;
  5454. unsigned inquotes;
  5455. unsigned protect_against_glob;
  5456. unsigned globbing;
  5457. IF_BASH_PATTERN_SUBST(unsigned slash = flag & RMESCAPE_SLASH;)
  5458. p = strpbrk(str, qchars IF_BASH_PATTERN_SUBST(+ !slash));
  5459. if (!p)
  5460. return str;
  5461. q = p;
  5462. r = str;
  5463. if (flag & RMESCAPE_ALLOC) {
  5464. size_t len = p - str;
  5465. size_t fulllen = len + strlen(p) + 1;
  5466. if (flag & RMESCAPE_GROW) {
  5467. int strloc = str - (char *)stackblock();
  5468. r = makestrspace(fulllen, expdest);
  5469. /* p and str may be invalidated by makestrspace */
  5470. str = (char *)stackblock() + strloc;
  5471. p = str + len;
  5472. } else if (flag & RMESCAPE_HEAP) {
  5473. r = ckmalloc(fulllen);
  5474. } else {
  5475. r = stalloc(fulllen);
  5476. }
  5477. q = r;
  5478. if (len > 0) {
  5479. q = (char *)mempcpy(q, str, len);
  5480. }
  5481. }
  5482. inquotes = 0;
  5483. globbing = flag & RMESCAPE_GLOB;
  5484. protect_against_glob = globbing;
  5485. while (*p) {
  5486. if ((unsigned char)*p == CTLQUOTEMARK) {
  5487. // Note: both inquotes and protect_against_glob only affect whether
  5488. // CTLESC,<ch> gets converted to <ch> or to \<ch>
  5489. inquotes = ~inquotes;
  5490. p++;
  5491. protect_against_glob = globbing;
  5492. continue;
  5493. }
  5494. if ((unsigned char)*p == CTLESC) {
  5495. p++;
  5496. #if DEBUG
  5497. if (*p == '\0')
  5498. ash_msg_and_raise_error("CTLESC at EOL (shouldn't happen)");
  5499. #endif
  5500. if (protect_against_glob) {
  5501. /*
  5502. * We used to trust glob() and fnmatch() to eat
  5503. * superfluous escapes (\z where z has no
  5504. * special meaning anyway). But this causes
  5505. * bugs such as string of one greek letter rho
  5506. * (unicode-encoded as two bytes "cf,81")
  5507. * getting encoded as "cf,CTLESC,81"
  5508. * and here, converted to "cf,\,81" -
  5509. * which does not go well with some flavors
  5510. * of fnmatch() in unicode locales
  5511. * (for example, glibc <= 2.22).
  5512. *
  5513. * Lets add "\" only on the chars which need it.
  5514. * Testcases for less obvious chars are shown.
  5515. */
  5516. if (*p == '*'
  5517. || *p == '?'
  5518. || *p == '['
  5519. || *p == '\\' /* case '\' in \\ ) echo ok;; *) echo WRONG;; esac */
  5520. || *p == ']' /* case ']' in [a\]] ) echo ok;; *) echo WRONG;; esac */
  5521. || *p == '-' /* case '-' in [a\-c]) echo ok;; *) echo WRONG;; esac */
  5522. || *p == '!' /* case '!' in [\!] ) echo ok;; *) echo WRONG;; esac */
  5523. /* Some libc support [^negate], that's why "^" also needs love */
  5524. || *p == '^' /* case '^' in [\^] ) echo ok;; *) echo WRONG;; esac */
  5525. ) {
  5526. *q++ = '\\';
  5527. }
  5528. }
  5529. } else if (*p == '\\' && !inquotes) {
  5530. /* naked back slash */
  5531. protect_against_glob = 0;
  5532. goto copy;
  5533. }
  5534. #if BASH_PATTERN_SUBST
  5535. else if (*p == '/' && slash) {
  5536. /* stop handling globbing and mark location of slash */
  5537. globbing = slash = 0;
  5538. *p = CTLESC;
  5539. }
  5540. #endif
  5541. protect_against_glob = globbing;
  5542. copy:
  5543. *q++ = *p++;
  5544. }
  5545. *q = '\0';
  5546. if (flag & RMESCAPE_GROW) {
  5547. expdest = r;
  5548. STADJUST(q - r + 1, expdest);
  5549. }
  5550. return r;
  5551. }
  5552. #define pmatch(a, b) !fnmatch((a), (b), 0)
  5553. /*
  5554. * Prepare a pattern for a expmeta (internal glob(3)) call.
  5555. *
  5556. * Returns an stalloced string.
  5557. */
  5558. static char *
  5559. preglob(const char *pattern, int flag)
  5560. {
  5561. return rmescapes((char *)pattern, flag | RMESCAPE_GLOB);
  5562. }
  5563. /*
  5564. * Put a string on the stack.
  5565. */
  5566. static void
  5567. memtodest(const char *p, size_t len, int syntax, int quotes)
  5568. {
  5569. char *q;
  5570. if (!len)
  5571. return;
  5572. q = makestrspace((quotes & QUOTES_ESC) ? len * 2 : len, expdest);
  5573. do {
  5574. unsigned char c = *p++;
  5575. if (c) {
  5576. if (quotes & QUOTES_ESC) {
  5577. int n = SIT(c, syntax);
  5578. if (n == CCTL
  5579. || (((quotes & EXP_FULL) || syntax != BASESYNTAX)
  5580. && n == CBACK
  5581. )
  5582. ) {
  5583. USTPUTC(CTLESC, q);
  5584. }
  5585. }
  5586. } else if (!(quotes & QUOTES_KEEPNUL))
  5587. continue;
  5588. USTPUTC(c, q);
  5589. } while (--len);
  5590. expdest = q;
  5591. }
  5592. static size_t
  5593. strtodest(const char *p, int syntax, int quotes)
  5594. {
  5595. size_t len = strlen(p);
  5596. memtodest(p, len, syntax, quotes);
  5597. return len;
  5598. }
  5599. /*
  5600. * Record the fact that we have to scan this region of the
  5601. * string for IFS characters.
  5602. */
  5603. static void
  5604. recordregion(int start, int end, int nulonly)
  5605. {
  5606. struct ifsregion *ifsp;
  5607. if (ifslastp == NULL) {
  5608. ifsp = &ifsfirst;
  5609. } else {
  5610. INT_OFF;
  5611. ifsp = ckzalloc(sizeof(*ifsp));
  5612. /*ifsp->next = NULL; - ckzalloc did it */
  5613. ifslastp->next = ifsp;
  5614. INT_ON;
  5615. }
  5616. ifslastp = ifsp;
  5617. ifslastp->begoff = start;
  5618. ifslastp->endoff = end;
  5619. ifslastp->nulonly = nulonly;
  5620. }
  5621. static void
  5622. removerecordregions(int endoff)
  5623. {
  5624. if (ifslastp == NULL)
  5625. return;
  5626. if (ifsfirst.endoff > endoff) {
  5627. while (ifsfirst.next) {
  5628. struct ifsregion *ifsp;
  5629. INT_OFF;
  5630. ifsp = ifsfirst.next->next;
  5631. free(ifsfirst.next);
  5632. ifsfirst.next = ifsp;
  5633. INT_ON;
  5634. }
  5635. if (ifsfirst.begoff > endoff) {
  5636. ifslastp = NULL;
  5637. } else {
  5638. ifslastp = &ifsfirst;
  5639. ifsfirst.endoff = endoff;
  5640. }
  5641. return;
  5642. }
  5643. ifslastp = &ifsfirst;
  5644. while (ifslastp->next && ifslastp->next->begoff < endoff)
  5645. ifslastp = ifslastp->next;
  5646. while (ifslastp->next) {
  5647. struct ifsregion *ifsp;
  5648. INT_OFF;
  5649. ifsp = ifslastp->next->next;
  5650. free(ifslastp->next);
  5651. ifslastp->next = ifsp;
  5652. INT_ON;
  5653. }
  5654. if (ifslastp->endoff > endoff)
  5655. ifslastp->endoff = endoff;
  5656. }
  5657. static char *
  5658. exptilde(char *startp, char *p, int flags)
  5659. {
  5660. unsigned char c;
  5661. char *name;
  5662. struct passwd *pw;
  5663. const char *home;
  5664. int quotes = flags & QUOTES_ESC;
  5665. name = p + 1;
  5666. while ((c = *++p) != '\0') {
  5667. switch (c) {
  5668. case CTLESC:
  5669. return startp;
  5670. case CTLQUOTEMARK:
  5671. return startp;
  5672. case ':':
  5673. if (flags & EXP_VARTILDE)
  5674. goto done;
  5675. break;
  5676. case '/':
  5677. case CTLENDVAR:
  5678. goto done;
  5679. }
  5680. }
  5681. done:
  5682. *p = '\0';
  5683. if (*name == '\0') {
  5684. home = lookupvar("HOME");
  5685. } else {
  5686. pw = getpwnam(name);
  5687. if (pw == NULL)
  5688. goto lose;
  5689. home = pw->pw_dir;
  5690. }
  5691. if (!home || !*home)
  5692. goto lose;
  5693. *p = c;
  5694. strtodest(home, SQSYNTAX, quotes);
  5695. return p;
  5696. lose:
  5697. *p = c;
  5698. return startp;
  5699. }
  5700. /*
  5701. * Execute a command inside back quotes. If it's a builtin command, we
  5702. * want to save its output in a block obtained from malloc. Otherwise
  5703. * we fork off a subprocess and get the output of the command via a pipe.
  5704. * Should be called with interrupts off.
  5705. */
  5706. struct backcmd { /* result of evalbackcmd */
  5707. int fd; /* file descriptor to read from */
  5708. int nleft; /* number of chars in buffer */
  5709. char *buf; /* buffer */
  5710. struct job *jp; /* job structure for command */
  5711. };
  5712. /* These forward decls are needed to use "eval" code for backticks handling: */
  5713. /* flags in argument to evaltree */
  5714. #define EV_EXIT 01 /* exit after evaluating tree */
  5715. #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
  5716. static int evaltree(union node *, int);
  5717. /* An evaltree() which is known to never return.
  5718. * Used to use an alias:
  5719. * static int evaltreenr(union node *, int) __attribute__((alias("evaltree"),__noreturn__));
  5720. * but clang was reported to "transfer" noreturn-ness to evaltree() as well.
  5721. */
  5722. static ALWAYS_INLINE NORETURN void
  5723. evaltreenr(union node *n, int flags)
  5724. {
  5725. evaltree(n, flags);
  5726. bb_unreachable(abort());
  5727. /* NOTREACHED */
  5728. }
  5729. static void FAST_FUNC
  5730. evalbackcmd(union node *n, struct backcmd *result)
  5731. {
  5732. int pip[2];
  5733. struct job *jp;
  5734. result->fd = -1;
  5735. result->buf = NULL;
  5736. result->nleft = 0;
  5737. result->jp = NULL;
  5738. if (n == NULL) {
  5739. goto out;
  5740. }
  5741. if (pipe(pip) < 0)
  5742. ash_msg_and_raise_perror("can't create pipe");
  5743. jp = makejob(/*n,*/ 1);
  5744. if (forkshell(jp, n, FORK_NOJOB) == 0) {
  5745. /* child */
  5746. FORCE_INT_ON;
  5747. close(pip[0]);
  5748. if (pip[1] != 1) {
  5749. /*close(1);*/
  5750. dup2_or_raise(pip[1], 1);
  5751. close(pip[1]);
  5752. }
  5753. /* TODO: eflag clearing makes the following not abort:
  5754. * ash -c 'set -e; z=$(false;echo foo); echo $z'
  5755. * which is what bash does (unless it is in POSIX mode).
  5756. * dash deleted "eflag = 0" line in the commit
  5757. * Date: Mon, 28 Jun 2010 17:11:58 +1000
  5758. * [EVAL] Don't clear eflag in evalbackcmd
  5759. * For now, preserve bash-like behavior, it seems to be somewhat more useful:
  5760. */
  5761. eflag = 0;
  5762. ifsfree();
  5763. evaltreenr(n, EV_EXIT);
  5764. /* NOTREACHED */
  5765. }
  5766. /* parent */
  5767. close(pip[1]);
  5768. result->fd = pip[0];
  5769. result->jp = jp;
  5770. out:
  5771. TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
  5772. result->fd, result->buf, result->nleft, result->jp));
  5773. }
  5774. /*
  5775. * Expand stuff in backwards quotes.
  5776. */
  5777. static void
  5778. expbackq(union node *cmd, int flag)
  5779. {
  5780. struct backcmd in;
  5781. int i;
  5782. char buf[128];
  5783. char *p;
  5784. char *dest;
  5785. int startloc;
  5786. int syntax = flag & EXP_QUOTED ? DQSYNTAX : BASESYNTAX;
  5787. struct stackmark smark;
  5788. INT_OFF;
  5789. startloc = expdest - (char *)stackblock();
  5790. pushstackmark(&smark, startloc);
  5791. evalbackcmd(cmd, &in);
  5792. popstackmark(&smark);
  5793. p = in.buf;
  5794. i = in.nleft;
  5795. if (i == 0)
  5796. goto read;
  5797. for (;;) {
  5798. memtodest(p, i, syntax, flag & QUOTES_ESC);
  5799. read:
  5800. if (in.fd < 0)
  5801. break;
  5802. i = nonblock_immune_read(in.fd, buf, sizeof(buf));
  5803. TRACE(("expbackq: read returns %d\n", i));
  5804. if (i <= 0)
  5805. break;
  5806. p = buf;
  5807. }
  5808. free(in.buf);
  5809. if (in.fd >= 0) {
  5810. close(in.fd);
  5811. back_exitstatus = waitforjob(in.jp);
  5812. }
  5813. INT_ON;
  5814. /* Eat all trailing newlines */
  5815. dest = expdest;
  5816. for (; dest > (char *)stackblock() && dest[-1] == '\n';)
  5817. STUNPUTC(dest);
  5818. expdest = dest;
  5819. if (!(flag & EXP_QUOTED))
  5820. recordregion(startloc, dest - (char *)stackblock(), 0);
  5821. TRACE(("evalbackq: size:%d:'%.*s'\n",
  5822. (int)((dest - (char *)stackblock()) - startloc),
  5823. (int)((dest - (char *)stackblock()) - startloc),
  5824. stackblock() + startloc));
  5825. }
  5826. #if ENABLE_FEATURE_SH_MATH
  5827. /*
  5828. * Expand arithmetic expression. Backup to start of expression,
  5829. * evaluate, place result in (backed up) result, adjust string position.
  5830. */
  5831. static void
  5832. expari(int flag)
  5833. {
  5834. char *p, *start;
  5835. int begoff;
  5836. int len;
  5837. /* ifsfree(); */
  5838. /*
  5839. * This routine is slightly over-complicated for
  5840. * efficiency. Next we scan backwards looking for the
  5841. * start of arithmetic.
  5842. */
  5843. start = stackblock();
  5844. p = expdest - 1;
  5845. *p = '\0';
  5846. p--;
  5847. while (1) {
  5848. int esc;
  5849. while ((unsigned char)*p != CTLARI) {
  5850. p--;
  5851. #if DEBUG
  5852. if (p < start) {
  5853. ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
  5854. }
  5855. #endif
  5856. }
  5857. esc = esclen(start, p);
  5858. if (!(esc % 2)) {
  5859. break;
  5860. }
  5861. p -= esc + 1;
  5862. }
  5863. begoff = p - start;
  5864. removerecordregions(begoff);
  5865. expdest = p;
  5866. if (flag & QUOTES_ESC)
  5867. rmescapes(p + 1, 0);
  5868. len = cvtnum(ash_arith(p + 1));
  5869. if (!(flag & EXP_QUOTED))
  5870. recordregion(begoff, begoff + len, 0);
  5871. }
  5872. #endif
  5873. /* argstr needs it */
  5874. static char *evalvar(char *p, int flags);
  5875. /*
  5876. * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
  5877. * characters to allow for further processing. Otherwise treat
  5878. * $@ like $* since no splitting will be performed.
  5879. */
  5880. static void
  5881. argstr(char *p, int flags)
  5882. {
  5883. static const char spclchars[] ALIGN1 = {
  5884. '=',
  5885. ':',
  5886. CTLQUOTEMARK,
  5887. CTLENDVAR,
  5888. CTLESC,
  5889. CTLVAR,
  5890. CTLBACKQ,
  5891. #if ENABLE_FEATURE_SH_MATH
  5892. CTLENDARI,
  5893. #endif
  5894. '\0'
  5895. };
  5896. const char *reject = spclchars;
  5897. int breakall = (flags & (EXP_WORD | EXP_QUOTED)) == EXP_WORD;
  5898. int inquotes;
  5899. size_t length;
  5900. int startloc;
  5901. if (!(flags & EXP_VARTILDE)) {
  5902. reject += 2;
  5903. } else if (flags & EXP_VARTILDE2) {
  5904. reject++;
  5905. }
  5906. inquotes = 0;
  5907. length = 0;
  5908. if (flags & EXP_TILDE) {
  5909. char *q;
  5910. flags &= ~EXP_TILDE;
  5911. tilde:
  5912. q = p;
  5913. if (*q == '~')
  5914. p = exptilde(p, q, flags);
  5915. }
  5916. start:
  5917. startloc = expdest - (char *)stackblock();
  5918. for (;;) {
  5919. unsigned char c;
  5920. length += strcspn(p + length, reject);
  5921. c = p[length];
  5922. if (c) {
  5923. if (!(c & 0x80)
  5924. IF_FEATURE_SH_MATH(|| c == CTLENDARI)
  5925. ) {
  5926. /* c == '=' || c == ':' || c == CTLENDARI */
  5927. length++;
  5928. }
  5929. }
  5930. if (length > 0) {
  5931. int newloc;
  5932. expdest = stack_nputstr(p, length, expdest);
  5933. newloc = expdest - (char *)stackblock();
  5934. if (breakall && !inquotes && newloc > startloc) {
  5935. recordregion(startloc, newloc, 0);
  5936. }
  5937. startloc = newloc;
  5938. }
  5939. p += length + 1;
  5940. length = 0;
  5941. switch (c) {
  5942. case '\0':
  5943. goto breakloop;
  5944. case '=':
  5945. if (flags & EXP_VARTILDE2) {
  5946. p--;
  5947. continue;
  5948. }
  5949. flags |= EXP_VARTILDE2;
  5950. reject++;
  5951. /* fall through */
  5952. case ':':
  5953. /*
  5954. * sort of a hack - expand tildes in variable
  5955. * assignments (after the first '=' and after ':'s).
  5956. */
  5957. if (*--p == '~') {
  5958. goto tilde;
  5959. }
  5960. continue;
  5961. }
  5962. switch (c) {
  5963. case CTLENDVAR: /* ??? */
  5964. goto breakloop;
  5965. case CTLQUOTEMARK:
  5966. inquotes ^= EXP_QUOTED;
  5967. /* "$@" syntax adherence hack */
  5968. if (inquotes && !memcmp(p, dolatstr + 1, DOLATSTRLEN - 1)) {
  5969. p = evalvar(p + 1, flags | inquotes) + 1;
  5970. goto start;
  5971. }
  5972. addquote:
  5973. if (flags & QUOTES_ESC) {
  5974. p--;
  5975. length++;
  5976. startloc++;
  5977. }
  5978. break;
  5979. case CTLESC:
  5980. startloc++;
  5981. length++;
  5982. /*
  5983. * Quoted parameter expansion pattern: remove quote
  5984. * unless inside inner quotes or we have a literal
  5985. * backslash.
  5986. */
  5987. if (((flags | inquotes) & (EXP_QPAT | EXP_QUOTED)) ==
  5988. EXP_QPAT && *p != '\\')
  5989. break;
  5990. goto addquote;
  5991. case CTLVAR:
  5992. TRACE(("argstr: evalvar('%s')\n", p));
  5993. p = evalvar(p, flags | inquotes);
  5994. TRACE(("argstr: evalvar:'%s'\n", (char *)stackblock()));
  5995. goto start;
  5996. case CTLBACKQ:
  5997. expbackq(argbackq->n, flags | inquotes);
  5998. argbackq = argbackq->next;
  5999. goto start;
  6000. #if ENABLE_FEATURE_SH_MATH
  6001. case CTLENDARI:
  6002. p--;
  6003. expari(flags | inquotes);
  6004. goto start;
  6005. #endif
  6006. }
  6007. }
  6008. breakloop: ;
  6009. }
  6010. static char *
  6011. scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM,
  6012. char *pattern, int quotes, int zero)
  6013. {
  6014. char *loc, *loc2;
  6015. char c;
  6016. loc = startp;
  6017. loc2 = rmesc;
  6018. do {
  6019. int match;
  6020. const char *s = loc2;
  6021. c = *loc2;
  6022. if (zero) {
  6023. *loc2 = '\0';
  6024. s = rmesc;
  6025. }
  6026. match = pmatch(pattern, s);
  6027. *loc2 = c;
  6028. if (match)
  6029. return loc;
  6030. if (quotes && (unsigned char)*loc == CTLESC)
  6031. loc++;
  6032. loc++;
  6033. loc2++;
  6034. } while (c);
  6035. return NULL;
  6036. }
  6037. static char *
  6038. scanright(char *startp, char *rmesc, char *rmescend,
  6039. char *pattern, int quotes, int match_at_start)
  6040. {
  6041. #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
  6042. int try2optimize = match_at_start;
  6043. #endif
  6044. int esc = 0;
  6045. char *loc;
  6046. char *loc2;
  6047. /* If we called by "${v/pattern/repl}" or "${v//pattern/repl}":
  6048. * startp="escaped_value_of_v" rmesc="raw_value_of_v"
  6049. * rmescend=""(ptr to NUL in rmesc) pattern="pattern" quotes=match_at_start=1
  6050. * Logic:
  6051. * loc starts at NUL at the end of startp, loc2 starts at the end of rmesc,
  6052. * and on each iteration they go back two/one char until they reach the beginning.
  6053. * We try to find a match in "raw_value_of_v", "raw_value_of_", "raw_value_of" etc.
  6054. */
  6055. /* TODO: document in what other circumstances we are called. */
  6056. for (loc = pattern - 1, loc2 = rmescend; loc >= startp; loc2--) {
  6057. int match;
  6058. char c = *loc2;
  6059. const char *s = loc2;
  6060. if (match_at_start) {
  6061. *loc2 = '\0';
  6062. s = rmesc;
  6063. }
  6064. match = pmatch(pattern, s);
  6065. //bb_error_msg("pmatch(pattern:'%s',s:'%s'):%d", pattern, s, match);
  6066. *loc2 = c;
  6067. if (match)
  6068. return loc;
  6069. #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
  6070. if (try2optimize) {
  6071. /* Maybe we can optimize this:
  6072. * if pattern ends with unescaped *, we can avoid checking
  6073. * shorter strings: if "foo*" doesn't match "raw_value_of_v",
  6074. * it won't match truncated "raw_value_of_" strings too.
  6075. */
  6076. unsigned plen = strlen(pattern);
  6077. /* Does it end with "*"? */
  6078. if (plen != 0 && pattern[--plen] == '*') {
  6079. /* "xxxx*" is not escaped */
  6080. /* "xxx\*" is escaped */
  6081. /* "xx\\*" is not escaped */
  6082. /* "x\\\*" is escaped */
  6083. int slashes = 0;
  6084. while (plen != 0 && pattern[--plen] == '\\')
  6085. slashes++;
  6086. if (!(slashes & 1))
  6087. break; /* ends with unescaped "*" */
  6088. }
  6089. try2optimize = 0;
  6090. }
  6091. #endif
  6092. loc--;
  6093. if (quotes) {
  6094. if (--esc < 0) {
  6095. esc = esclen(startp, loc);
  6096. }
  6097. if (esc % 2) {
  6098. esc--;
  6099. loc--;
  6100. }
  6101. }
  6102. }
  6103. return NULL;
  6104. }
  6105. static void varunset(const char *, const char *, const char *, int) NORETURN;
  6106. static void
  6107. varunset(const char *end, const char *var, const char *umsg, int varflags)
  6108. {
  6109. const char *msg;
  6110. const char *tail;
  6111. tail = nullstr;
  6112. msg = "parameter not set";
  6113. if (umsg) {
  6114. if ((unsigned char)*end == CTLENDVAR) {
  6115. if (varflags & VSNUL)
  6116. tail = " or null";
  6117. } else {
  6118. msg = umsg;
  6119. }
  6120. }
  6121. ash_msg_and_raise_error("%.*s: %s%s", (int)(end - var - 1), var, msg, tail);
  6122. }
  6123. static const char *
  6124. subevalvar(char *p, char *varname, int strloc, int subtype,
  6125. int startloc, int varflags, int flag)
  6126. {
  6127. struct nodelist *saveargbackq = argbackq;
  6128. int quotes = flag & QUOTES_ESC;
  6129. char *startp;
  6130. char *loc;
  6131. char *rmesc, *rmescend;
  6132. char *str;
  6133. int amount, resetloc;
  6134. IF_BASH_PATTERN_SUBST(int workloc;)
  6135. IF_BASH_PATTERN_SUBST(char *repl = NULL;)
  6136. int zero;
  6137. char *(*scan)(char*, char*, char*, char*, int, int);
  6138. //bb_error_msg("subevalvar(p:'%s',varname:'%s',strloc:%d,subtype:%d,startloc:%d,varflags:%x,quotes:%d)",
  6139. // p, varname, strloc, subtype, startloc, varflags, quotes);
  6140. argstr(p, EXP_TILDE | (subtype != VSASSIGN && subtype != VSQUESTION ?
  6141. (flag & (EXP_QUOTED | EXP_QPAT) ? EXP_QPAT : EXP_CASE) : 0)
  6142. );
  6143. STPUTC('\0', expdest);
  6144. argbackq = saveargbackq;
  6145. startp = (char *)stackblock() + startloc;
  6146. switch (subtype) {
  6147. case VSASSIGN:
  6148. setvar0(varname, startp);
  6149. amount = startp - expdest;
  6150. STADJUST(amount, expdest);
  6151. return startp;
  6152. case VSQUESTION:
  6153. varunset(p, varname, startp, varflags);
  6154. /* NOTREACHED */
  6155. #if BASH_SUBSTR
  6156. case VSSUBSTR: {
  6157. int pos, len, orig_len;
  6158. char *colon;
  6159. loc = str = stackblock() + strloc;
  6160. # if !ENABLE_FEATURE_SH_MATH
  6161. # define ash_arith number
  6162. # endif
  6163. /* Read POS in ${var:POS:LEN} */
  6164. colon = strchr(loc, ':');
  6165. if (colon) *colon = '\0';
  6166. pos = ash_arith(loc);
  6167. if (colon) *colon = ':';
  6168. /* Read LEN in ${var:POS:LEN} */
  6169. len = str - startp - 1;
  6170. /* *loc != '\0', guaranteed by parser */
  6171. if (quotes) {
  6172. char *ptr;
  6173. /* Adjust the length by the number of escapes */
  6174. for (ptr = startp; ptr < (str - 1); ptr++) {
  6175. if ((unsigned char)*ptr == CTLESC) {
  6176. len--;
  6177. ptr++;
  6178. }
  6179. }
  6180. }
  6181. orig_len = len;
  6182. if (*loc++ == ':') {
  6183. /* ${var::LEN} */
  6184. len = ash_arith(loc);
  6185. } else {
  6186. /* Skip POS in ${var:POS:LEN} */
  6187. len = orig_len;
  6188. while (*loc && *loc != ':') {
  6189. loc++;
  6190. }
  6191. if (*loc++ == ':') {
  6192. len = ash_arith(loc);
  6193. }
  6194. }
  6195. # undef ash_arith
  6196. if (pos < 0) {
  6197. /* ${VAR:$((-n)):l} starts n chars from the end */
  6198. pos = orig_len + pos;
  6199. }
  6200. if ((unsigned)pos >= orig_len) {
  6201. /* apart from obvious ${VAR:999999:l},
  6202. * covers ${VAR:$((-9999999)):l} - result is ""
  6203. * (bash compat)
  6204. */
  6205. pos = 0;
  6206. len = 0;
  6207. }
  6208. if (len < 0) {
  6209. /* ${VAR:N:-M} sets LEN to strlen()-M */
  6210. len = (orig_len - pos) + len;
  6211. }
  6212. if ((unsigned)len > (orig_len - pos))
  6213. len = orig_len - pos;
  6214. for (str = startp; pos; str++, pos--) {
  6215. if (quotes && (unsigned char)*str == CTLESC)
  6216. str++;
  6217. }
  6218. for (loc = startp; len; len--) {
  6219. if (quotes && (unsigned char)*str == CTLESC)
  6220. *loc++ = *str++;
  6221. *loc++ = *str++;
  6222. }
  6223. *loc = '\0';
  6224. amount = loc - expdest;
  6225. STADJUST(amount, expdest);
  6226. return loc;
  6227. }
  6228. #endif /* BASH_SUBSTR */
  6229. }
  6230. resetloc = expdest - (char *)stackblock();
  6231. #if BASH_PATTERN_SUBST
  6232. /* We'll comeback here if we grow the stack while handling
  6233. * a VSREPLACE or VSREPLACEALL, since our pointers into the
  6234. * stack will need rebasing, and we'll need to remove our work
  6235. * areas each time
  6236. */
  6237. restart:
  6238. #endif
  6239. amount = expdest - ((char *)stackblock() + resetloc);
  6240. STADJUST(-amount, expdest);
  6241. startp = (char *)stackblock() + startloc;
  6242. rmesc = startp;
  6243. rmescend = (char *)stackblock() + strloc;
  6244. if (quotes) {
  6245. rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
  6246. if (rmesc != startp) {
  6247. rmescend = expdest;
  6248. startp = (char *)stackblock() + startloc;
  6249. }
  6250. }
  6251. rmescend--;
  6252. str = (char *)stackblock() + strloc;
  6253. /*
  6254. * Example: v='a\bc'; echo ${v/\\b/_\\_\z_}
  6255. * The result is a_\_z_c (not a\_\_z_c)!
  6256. *
  6257. * The search pattern and replace string treat backslashes differently!
  6258. * RMESCAPE_SLASH causes preglob to work differently on the pattern
  6259. * and string. It's only used on the first call.
  6260. */
  6261. preglob(str, IF_BASH_PATTERN_SUBST(
  6262. (subtype == VSREPLACE || subtype == VSREPLACEALL) && !repl ?
  6263. RMESCAPE_SLASH : ) 0);
  6264. #if BASH_PATTERN_SUBST
  6265. workloc = expdest - (char *)stackblock();
  6266. if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
  6267. int len;
  6268. char *idx, *end;
  6269. if (!repl) {
  6270. repl = strchr(str, CTLESC);
  6271. if (repl)
  6272. *repl++ = '\0';
  6273. else
  6274. repl = nullstr;
  6275. }
  6276. //bb_error_msg("str:'%s' repl:'%s'", str, repl);
  6277. /* If there's no pattern to match, return the expansion unmolested */
  6278. if (str[0] == '\0')
  6279. return NULL;
  6280. len = 0;
  6281. idx = startp;
  6282. end = str - 1;
  6283. while (idx < end) {
  6284. try_to_match:
  6285. loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
  6286. //bb_error_msg("scanright('%s'):'%s'", str, loc);
  6287. if (!loc) {
  6288. /* No match, advance */
  6289. char *restart_detect = stackblock();
  6290. skip_matching:
  6291. STPUTC(*idx, expdest);
  6292. if (quotes && (unsigned char)*idx == CTLESC) {
  6293. idx++;
  6294. len++;
  6295. STPUTC(*idx, expdest);
  6296. }
  6297. if (stackblock() != restart_detect)
  6298. goto restart;
  6299. idx++;
  6300. len++;
  6301. rmesc++;
  6302. /* continue; - prone to quadratic behavior, smarter code: */
  6303. if (idx >= end)
  6304. break;
  6305. if (str[0] == '*') {
  6306. /* Pattern is "*foo". If "*foo" does not match "long_string",
  6307. * it would never match "ong_string" etc, no point in trying.
  6308. */
  6309. goto skip_matching;
  6310. }
  6311. goto try_to_match;
  6312. }
  6313. if (subtype == VSREPLACEALL) {
  6314. while (idx < loc) {
  6315. if (quotes && (unsigned char)*idx == CTLESC)
  6316. idx++;
  6317. idx++;
  6318. rmesc++;
  6319. }
  6320. } else {
  6321. idx = loc;
  6322. }
  6323. //bb_error_msg("repl:'%s'", repl);
  6324. for (loc = (char*)repl; *loc; loc++) {
  6325. char *restart_detect = stackblock();
  6326. if (quotes && *loc == '\\') {
  6327. STPUTC(CTLESC, expdest);
  6328. len++;
  6329. }
  6330. STPUTC(*loc, expdest);
  6331. if (stackblock() != restart_detect)
  6332. goto restart;
  6333. len++;
  6334. }
  6335. if (subtype == VSREPLACE) {
  6336. //bb_error_msg("tail:'%s', quotes:%x", idx, quotes);
  6337. while (*idx) {
  6338. char *restart_detect = stackblock();
  6339. STPUTC(*idx, expdest);
  6340. if (stackblock() != restart_detect)
  6341. goto restart;
  6342. len++;
  6343. idx++;
  6344. }
  6345. break;
  6346. }
  6347. }
  6348. /* We've put the replaced text into a buffer at workloc, now
  6349. * move it to the right place and adjust the stack.
  6350. */
  6351. STPUTC('\0', expdest);
  6352. startp = (char *)stackblock() + startloc;
  6353. memmove(startp, (char *)stackblock() + workloc, len + 1);
  6354. //bb_error_msg("startp:'%s'", startp);
  6355. amount = expdest - (startp + len);
  6356. STADJUST(-amount, expdest);
  6357. return startp;
  6358. }
  6359. #endif /* BASH_PATTERN_SUBST */
  6360. subtype -= VSTRIMRIGHT;
  6361. #if DEBUG
  6362. if (subtype < 0 || subtype > 7)
  6363. abort();
  6364. #endif
  6365. /* zero = (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX) */
  6366. zero = subtype >> 1;
  6367. /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
  6368. scan = (subtype & 1) ^ zero ? scanleft : scanright;
  6369. loc = scan(startp, rmesc, rmescend, str, quotes, zero);
  6370. if (loc) {
  6371. if (zero) {
  6372. memmove(startp, loc, str - loc);
  6373. loc = startp + (str - loc) - 1;
  6374. }
  6375. *loc = '\0';
  6376. amount = loc - expdest;
  6377. STADJUST(amount, expdest);
  6378. }
  6379. return loc;
  6380. }
  6381. /*
  6382. * Add the value of a specialized variable to the stack string.
  6383. * name parameter (examples):
  6384. * ash -c 'echo $1' name:'1='
  6385. * ash -c 'echo $qwe' name:'qwe='
  6386. * ash -c 'echo $$' name:'$='
  6387. * ash -c 'echo ${$}' name:'$='
  6388. * ash -c 'echo ${$##q}' name:'$=q'
  6389. * ash -c 'echo ${#$}' name:'$='
  6390. * note: examples with bad shell syntax:
  6391. * ash -c 'echo ${#$1}' name:'$=1'
  6392. * ash -c 'echo ${#1#}' name:'1=#'
  6393. */
  6394. static NOINLINE ssize_t
  6395. varvalue(char *name, int varflags, int flags, int *quotedp)
  6396. {
  6397. const char *p;
  6398. int num;
  6399. int i;
  6400. ssize_t len = 0;
  6401. int sep;
  6402. int quoted = *quotedp;
  6403. int subtype = varflags & VSTYPE;
  6404. int discard = subtype == VSPLUS || subtype == VSLENGTH;
  6405. int quotes = (discard ? 0 : (flags & QUOTES_ESC)) | QUOTES_KEEPNUL;
  6406. int syntax;
  6407. sep = (flags & EXP_FULL) << CHAR_BIT;
  6408. syntax = quoted ? DQSYNTAX : BASESYNTAX;
  6409. switch (*name) {
  6410. case '$':
  6411. num = rootpid;
  6412. goto numvar;
  6413. case '?':
  6414. num = exitstatus;
  6415. goto numvar;
  6416. case '#':
  6417. num = shellparam.nparam;
  6418. goto numvar;
  6419. case '!':
  6420. num = backgndpid;
  6421. if (num == 0)
  6422. return -1;
  6423. numvar:
  6424. len = cvtnum(num);
  6425. goto check_1char_name;
  6426. case '-':
  6427. expdest = makestrspace(NOPTS, expdest);
  6428. for (i = NOPTS - 1; i >= 0; i--) {
  6429. if (optlist[i]) {
  6430. USTPUTC(optletters(i), expdest);
  6431. len++;
  6432. }
  6433. }
  6434. check_1char_name:
  6435. #if 0
  6436. /* handles cases similar to ${#$1} */
  6437. if (name[2] != '\0')
  6438. raise_error_syntax("bad substitution");
  6439. #endif
  6440. break;
  6441. case '@':
  6442. if (quoted && sep)
  6443. goto param;
  6444. /* fall through */
  6445. case '*': {
  6446. char **ap;
  6447. char sepc;
  6448. if (quoted)
  6449. sep = 0;
  6450. sep |= ifsset() ? ifsval()[0] : ' ';
  6451. param:
  6452. sepc = sep;
  6453. *quotedp = !sepc;
  6454. ap = shellparam.p;
  6455. if (!ap)
  6456. return -1;
  6457. while ((p = *ap++) != NULL) {
  6458. len += strtodest(p, syntax, quotes);
  6459. if (*ap && sep) {
  6460. len++;
  6461. memtodest(&sepc, 1, syntax, quotes);
  6462. }
  6463. }
  6464. break;
  6465. } /* case '*' */
  6466. case '0':
  6467. case '1':
  6468. case '2':
  6469. case '3':
  6470. case '4':
  6471. case '5':
  6472. case '6':
  6473. case '7':
  6474. case '8':
  6475. case '9':
  6476. num = atoi(name); /* number(name) fails on ${N#str} etc */
  6477. if (num < 0 || num > shellparam.nparam)
  6478. return -1;
  6479. p = num ? shellparam.p[num - 1] : arg0;
  6480. goto value;
  6481. default:
  6482. /* NB: name has form "VAR=..." */
  6483. p = lookupvar(name);
  6484. value:
  6485. if (!p)
  6486. return -1;
  6487. len = strtodest(p, syntax, quotes);
  6488. #if ENABLE_UNICODE_SUPPORT
  6489. if (subtype == VSLENGTH && len > 0) {
  6490. reinit_unicode_for_ash();
  6491. if (unicode_status == UNICODE_ON) {
  6492. STADJUST(-len, expdest);
  6493. discard = 0;
  6494. len = unicode_strlen(p);
  6495. }
  6496. }
  6497. #endif
  6498. break;
  6499. }
  6500. if (discard)
  6501. STADJUST(-len, expdest);
  6502. return len;
  6503. }
  6504. /*
  6505. * Expand a variable, and return a pointer to the next character in the
  6506. * input string.
  6507. */
  6508. static char *
  6509. evalvar(char *p, int flag)
  6510. {
  6511. char varflags;
  6512. char subtype;
  6513. int quoted;
  6514. char easy;
  6515. char *var;
  6516. int patloc;
  6517. int startloc;
  6518. ssize_t varlen;
  6519. varflags = (unsigned char) *p++;
  6520. subtype = varflags & VSTYPE;
  6521. if (!subtype)
  6522. raise_error_syntax("bad substitution");
  6523. quoted = flag & EXP_QUOTED;
  6524. var = p;
  6525. easy = (!quoted || (*var == '@' && shellparam.nparam));
  6526. startloc = expdest - (char *)stackblock();
  6527. p = strchr(p, '=') + 1; //TODO: use var_end(p)?
  6528. again:
  6529. varlen = varvalue(var, varflags, flag, &quoted);
  6530. if (varflags & VSNUL)
  6531. varlen--;
  6532. if (subtype == VSPLUS) {
  6533. varlen = -1 - varlen;
  6534. goto vsplus;
  6535. }
  6536. if (subtype == VSMINUS) {
  6537. vsplus:
  6538. if (varlen < 0) {
  6539. argstr(
  6540. p,
  6541. flag | EXP_TILDE | EXP_WORD
  6542. );
  6543. goto end;
  6544. }
  6545. goto record;
  6546. }
  6547. if (subtype == VSASSIGN || subtype == VSQUESTION) {
  6548. if (varlen >= 0)
  6549. goto record;
  6550. subevalvar(p, var, 0, subtype, startloc, varflags,
  6551. flag & ~QUOTES_ESC);
  6552. varflags &= ~VSNUL;
  6553. /*
  6554. * Remove any recorded regions beyond
  6555. * start of variable
  6556. */
  6557. removerecordregions(startloc);
  6558. goto again;
  6559. }
  6560. if (varlen < 0 && uflag)
  6561. varunset(p, var, 0, 0);
  6562. if (subtype == VSLENGTH) {
  6563. cvtnum(varlen > 0 ? varlen : 0);
  6564. goto record;
  6565. }
  6566. if (subtype == VSNORMAL) {
  6567. record:
  6568. if (!easy)
  6569. goto end;
  6570. recordregion(startloc, expdest - (char *)stackblock(), quoted);
  6571. goto end;
  6572. }
  6573. #if DEBUG
  6574. switch (subtype) {
  6575. case VSTRIMLEFT:
  6576. case VSTRIMLEFTMAX:
  6577. case VSTRIMRIGHT:
  6578. case VSTRIMRIGHTMAX:
  6579. #if BASH_SUBSTR
  6580. case VSSUBSTR:
  6581. #endif
  6582. #if BASH_PATTERN_SUBST
  6583. case VSREPLACE:
  6584. case VSREPLACEALL:
  6585. #endif
  6586. break;
  6587. default:
  6588. abort();
  6589. }
  6590. #endif
  6591. if (varlen >= 0) {
  6592. /*
  6593. * Terminate the string and start recording the pattern
  6594. * right after it
  6595. */
  6596. STPUTC('\0', expdest);
  6597. patloc = expdest - (char *)stackblock();
  6598. if (NULL == subevalvar(p, /* varname: */ NULL, patloc, subtype,
  6599. startloc, varflags, flag)) {
  6600. int amount = expdest - (
  6601. (char *)stackblock() + patloc - 1
  6602. );
  6603. STADJUST(-amount, expdest);
  6604. }
  6605. /* Remove any recorded regions beyond start of variable */
  6606. removerecordregions(startloc);
  6607. goto record;
  6608. }
  6609. end:
  6610. if (subtype != VSNORMAL) { /* skip to end of alternative */
  6611. int nesting = 1;
  6612. for (;;) {
  6613. unsigned char c = *p++;
  6614. if (c == CTLESC)
  6615. p++;
  6616. else if (c == CTLBACKQ) {
  6617. if (varlen >= 0)
  6618. argbackq = argbackq->next;
  6619. } else if (c == CTLVAR) {
  6620. if ((*p++ & VSTYPE) != VSNORMAL)
  6621. nesting++;
  6622. } else if (c == CTLENDVAR) {
  6623. if (--nesting == 0)
  6624. break;
  6625. }
  6626. }
  6627. }
  6628. return p;
  6629. }
  6630. /*
  6631. * Add a file name to the list.
  6632. */
  6633. static void
  6634. addfname(const char *name)
  6635. {
  6636. struct strlist *sp;
  6637. sp = stzalloc(sizeof(*sp));
  6638. sp->text = sstrdup(name);
  6639. *exparg.lastp = sp;
  6640. exparg.lastp = &sp->next;
  6641. }
  6642. /* Avoid glob() (and thus, stat() et al) for words like "echo" */
  6643. static int
  6644. hasmeta(const char *p)
  6645. {
  6646. static const char chars[] ALIGN1 = {
  6647. '*', '?', '[', '\\', CTLQUOTEMARK, CTLESC, 0
  6648. };
  6649. for (;;) {
  6650. p = strpbrk(p, chars);
  6651. if (!p)
  6652. break;
  6653. switch ((unsigned char) *p) {
  6654. case CTLQUOTEMARK:
  6655. for (;;) {
  6656. p++;
  6657. if (*p == CTLQUOTEMARK)
  6658. break;
  6659. if (*p == CTLESC)
  6660. p++;
  6661. if (*p == '\0') /* huh? */
  6662. return 0;
  6663. }
  6664. break;
  6665. case '\\':
  6666. case CTLESC:
  6667. p++;
  6668. if (*p == '\0')
  6669. return 0;
  6670. break;
  6671. case '[':
  6672. if (!strchr(p + 1, ']')) {
  6673. /* It's not a properly closed [] pattern,
  6674. * but other metas may follow. Continue checking.
  6675. * my[file* _is_ globbed by bash
  6676. * and matches filenames like "my[file1".
  6677. */
  6678. break;
  6679. }
  6680. /* fallthrough */
  6681. default:
  6682. /* case '*': */
  6683. /* case '?': */
  6684. return 1;
  6685. }
  6686. p++;
  6687. }
  6688. return 0;
  6689. }
  6690. /* If we want to use glob() from libc... */
  6691. #if !ENABLE_ASH_INTERNAL_GLOB
  6692. /* Add the result of glob() to the list */
  6693. static void
  6694. addglob(const glob_t *pglob)
  6695. {
  6696. char **p = pglob->gl_pathv;
  6697. do {
  6698. addfname(*p);
  6699. } while (*++p);
  6700. }
  6701. static void
  6702. expandmeta(struct strlist *str /*, int flag*/)
  6703. {
  6704. /* TODO - EXP_REDIR */
  6705. while (str) {
  6706. char *p;
  6707. glob_t pglob;
  6708. int i;
  6709. if (fflag)
  6710. goto nometa;
  6711. if (!hasmeta(str->text))
  6712. goto nometa;
  6713. INT_OFF;
  6714. p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
  6715. // GLOB_NOMAGIC (GNU): if no *?[ chars in pattern, return it even if no match
  6716. // GLOB_NOCHECK: if no match, return unchanged pattern (sans \* escapes?)
  6717. //
  6718. // glibc 2.24.90 glob(GLOB_NOMAGIC) does not remove backslashes used for escaping:
  6719. // if you pass it "file\?", it returns "file\?", not "file?", if no match.
  6720. // Which means you need to unescape the string, right? Not so fast:
  6721. // if there _is_ a file named "file\?" (with backslash), it is returned
  6722. // as "file\?" too (whichever pattern you used to find it, say, "file*").
  6723. // You DON'T KNOW by looking at the result whether you need to unescape it.
  6724. //
  6725. // Worse, globbing of "file\?" in a directory with two files, "file?" and "file\?",
  6726. // returns "file\?" - which is WRONG: "file\?" pattern matches "file?" file.
  6727. // Without GLOB_NOMAGIC, this works correctly ("file?" is returned as a match).
  6728. // With GLOB_NOMAGIC | GLOB_NOCHECK, this also works correctly.
  6729. // i = glob(p, GLOB_NOMAGIC | GLOB_NOCHECK, NULL, &pglob);
  6730. // i = glob(p, GLOB_NOMAGIC, NULL, &pglob);
  6731. i = glob(p, 0, NULL, &pglob);
  6732. //bb_error_msg("glob('%s'):%d '%s'...", p, i, pglob.gl_pathv ? pglob.gl_pathv[0] : "-");
  6733. if (p != str->text)
  6734. free(p);
  6735. switch (i) {
  6736. case 0:
  6737. #if 0 // glibc 2.24.90 bug? Patterns like "*/file", when match, don't set GLOB_MAGCHAR
  6738. /* GLOB_MAGCHAR is set if *?[ chars were seen (GNU) */
  6739. if (!(pglob.gl_flags & GLOB_MAGCHAR))
  6740. goto nometa2;
  6741. #endif
  6742. addglob(&pglob);
  6743. globfree(&pglob);
  6744. INT_ON;
  6745. break;
  6746. case GLOB_NOMATCH:
  6747. //nometa2:
  6748. globfree(&pglob);
  6749. INT_ON;
  6750. nometa:
  6751. *exparg.lastp = str;
  6752. rmescapes(str->text, 0);
  6753. exparg.lastp = &str->next;
  6754. break;
  6755. default: /* GLOB_NOSPACE */
  6756. globfree(&pglob);
  6757. INT_ON;
  6758. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  6759. }
  6760. str = str->next;
  6761. }
  6762. }
  6763. #else
  6764. /* ENABLE_ASH_INTERNAL_GLOB: Homegrown globbing code. (dash also has both, uses homegrown one.) */
  6765. /*
  6766. * Do metacharacter (i.e. *, ?, [...]) expansion.
  6767. */
  6768. static void
  6769. expmeta(char *expdir, char *enddir, char *name)
  6770. {
  6771. char *p;
  6772. const char *cp;
  6773. char *start;
  6774. char *endname;
  6775. int metaflag;
  6776. struct stat statb;
  6777. DIR *dirp;
  6778. struct dirent *dp;
  6779. int atend;
  6780. int matchdot;
  6781. int esc;
  6782. metaflag = 0;
  6783. start = name;
  6784. for (p = name; esc = 0, *p; p += esc + 1) {
  6785. if (*p == '*' || *p == '?')
  6786. metaflag = 1;
  6787. else if (*p == '[') {
  6788. char *q = p + 1;
  6789. if (*q == '!')
  6790. q++;
  6791. for (;;) {
  6792. if (*q == '\\')
  6793. q++;
  6794. if (*q == '/' || *q == '\0')
  6795. break;
  6796. if (*++q == ']') {
  6797. metaflag = 1;
  6798. break;
  6799. }
  6800. }
  6801. } else {
  6802. if (*p == '\\')
  6803. esc++;
  6804. if (p[esc] == '/') {
  6805. if (metaflag)
  6806. break;
  6807. start = p + esc + 1;
  6808. }
  6809. }
  6810. }
  6811. if (metaflag == 0) { /* we've reached the end of the file name */
  6812. if (enddir != expdir)
  6813. metaflag++;
  6814. p = name;
  6815. do {
  6816. if (*p == '\\')
  6817. p++;
  6818. *enddir++ = *p;
  6819. } while (*p++);
  6820. if (metaflag == 0 || lstat(expdir, &statb) >= 0)
  6821. addfname(expdir);
  6822. return;
  6823. }
  6824. endname = p;
  6825. if (name < start) {
  6826. p = name;
  6827. do {
  6828. if (*p == '\\')
  6829. p++;
  6830. *enddir++ = *p++;
  6831. } while (p < start);
  6832. }
  6833. if (enddir == expdir) {
  6834. cp = ".";
  6835. } else if (enddir == expdir + 1 && *expdir == '/') {
  6836. cp = "/";
  6837. } else {
  6838. cp = expdir;
  6839. enddir[-1] = '\0';
  6840. }
  6841. dirp = opendir(cp);
  6842. if (dirp == NULL)
  6843. return;
  6844. if (enddir != expdir)
  6845. enddir[-1] = '/';
  6846. if (*endname == 0) {
  6847. atend = 1;
  6848. } else {
  6849. atend = 0;
  6850. *endname = '\0';
  6851. endname += esc + 1;
  6852. }
  6853. matchdot = 0;
  6854. p = start;
  6855. if (*p == '\\')
  6856. p++;
  6857. if (*p == '.')
  6858. matchdot++;
  6859. while (!pending_int && (dp = readdir(dirp)) != NULL) {
  6860. if (dp->d_name[0] == '.' && !matchdot)
  6861. continue;
  6862. if (pmatch(start, dp->d_name)) {
  6863. if (atend) {
  6864. strcpy(enddir, dp->d_name);
  6865. addfname(expdir);
  6866. } else {
  6867. for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
  6868. continue;
  6869. p[-1] = '/';
  6870. expmeta(expdir, p, endname);
  6871. }
  6872. }
  6873. }
  6874. closedir(dirp);
  6875. if (!atend)
  6876. endname[-esc - 1] = esc ? '\\' : '/';
  6877. }
  6878. static struct strlist *
  6879. msort(struct strlist *list, int len)
  6880. {
  6881. struct strlist *p, *q = NULL;
  6882. struct strlist **lpp;
  6883. int half;
  6884. int n;
  6885. if (len <= 1)
  6886. return list;
  6887. half = len >> 1;
  6888. p = list;
  6889. for (n = half; --n >= 0;) {
  6890. q = p;
  6891. p = p->next;
  6892. }
  6893. q->next = NULL; /* terminate first half of list */
  6894. q = msort(list, half); /* sort first half of list */
  6895. p = msort(p, len - half); /* sort second half */
  6896. lpp = &list;
  6897. for (;;) {
  6898. #if ENABLE_LOCALE_SUPPORT
  6899. if (strcoll(p->text, q->text) < 0)
  6900. #else
  6901. if (strcmp(p->text, q->text) < 0)
  6902. #endif
  6903. {
  6904. *lpp = p;
  6905. lpp = &p->next;
  6906. p = *lpp;
  6907. if (p == NULL) {
  6908. *lpp = q;
  6909. break;
  6910. }
  6911. } else {
  6912. *lpp = q;
  6913. lpp = &q->next;
  6914. q = *lpp;
  6915. if (q == NULL) {
  6916. *lpp = p;
  6917. break;
  6918. }
  6919. }
  6920. }
  6921. return list;
  6922. }
  6923. /*
  6924. * Sort the results of file name expansion. It calculates the number of
  6925. * strings to sort and then calls msort (short for merge sort) to do the
  6926. * work.
  6927. */
  6928. static struct strlist *
  6929. expsort(struct strlist *str)
  6930. {
  6931. int len;
  6932. struct strlist *sp;
  6933. len = 0;
  6934. for (sp = str; sp; sp = sp->next)
  6935. len++;
  6936. return msort(str, len);
  6937. }
  6938. static void
  6939. expandmeta(struct strlist *str /*, int flag*/)
  6940. {
  6941. /* TODO - EXP_REDIR */
  6942. while (str) {
  6943. char *expdir;
  6944. struct strlist **savelastp;
  6945. struct strlist *sp;
  6946. char *p;
  6947. if (fflag)
  6948. goto nometa;
  6949. if (!hasmeta(str->text))
  6950. goto nometa;
  6951. savelastp = exparg.lastp;
  6952. INT_OFF;
  6953. p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
  6954. {
  6955. int i = strlen(str->text);
  6956. //BUGGY estimation of how long expanded name can be
  6957. expdir = ckmalloc(i < 2048 ? 2048 : i+1);
  6958. }
  6959. expmeta(expdir, expdir, p);
  6960. free(expdir);
  6961. if (p != str->text)
  6962. free(p);
  6963. INT_ON;
  6964. if (exparg.lastp == savelastp) {
  6965. /*
  6966. * no matches
  6967. */
  6968. nometa:
  6969. *exparg.lastp = str;
  6970. rmescapes(str->text, 0);
  6971. exparg.lastp = &str->next;
  6972. } else {
  6973. *exparg.lastp = NULL;
  6974. *savelastp = sp = expsort(*savelastp);
  6975. while (sp->next != NULL)
  6976. sp = sp->next;
  6977. exparg.lastp = &sp->next;
  6978. }
  6979. str = str->next;
  6980. }
  6981. }
  6982. #endif /* ENABLE_ASH_INTERNAL_GLOB */
  6983. /*
  6984. * Perform variable substitution and command substitution on an argument,
  6985. * placing the resulting list of arguments in arglist. If EXP_FULL is true,
  6986. * perform splitting and file name expansion. When arglist is NULL, perform
  6987. * here document expansion.
  6988. */
  6989. static void
  6990. expandarg(union node *arg, struct arglist *arglist, int flag)
  6991. {
  6992. struct strlist *sp;
  6993. char *p;
  6994. argbackq = arg->narg.backquote;
  6995. STARTSTACKSTR(expdest);
  6996. TRACE(("expandarg: argstr('%s',flags:%x)\n", arg->narg.text, flag));
  6997. argstr(arg->narg.text, flag);
  6998. p = _STPUTC('\0', expdest);
  6999. expdest = p - 1;
  7000. if (arglist == NULL) {
  7001. /* here document expanded */
  7002. goto out;
  7003. }
  7004. p = grabstackstr(p);
  7005. TRACE(("expandarg: p:'%s'\n", p));
  7006. exparg.lastp = &exparg.list;
  7007. /*
  7008. * TODO - EXP_REDIR
  7009. */
  7010. if (flag & EXP_FULL) {
  7011. ifsbreakup(p, &exparg);
  7012. *exparg.lastp = NULL;
  7013. exparg.lastp = &exparg.list;
  7014. expandmeta(exparg.list /*, flag*/);
  7015. } else {
  7016. sp = stzalloc(sizeof(*sp));
  7017. sp->text = p;
  7018. *exparg.lastp = sp;
  7019. exparg.lastp = &sp->next;
  7020. }
  7021. *exparg.lastp = NULL;
  7022. if (exparg.list) {
  7023. *arglist->lastp = exparg.list;
  7024. arglist->lastp = exparg.lastp;
  7025. }
  7026. out:
  7027. ifsfree();
  7028. }
  7029. /*
  7030. * Expand shell variables and backquotes inside a here document.
  7031. */
  7032. static void
  7033. expandhere(union node *arg, int fd)
  7034. {
  7035. expandarg(arg, (struct arglist *)NULL, EXP_QUOTED);
  7036. full_write(fd, stackblock(), expdest - (char *)stackblock());
  7037. }
  7038. /*
  7039. * Returns true if the pattern matches the string.
  7040. */
  7041. static int
  7042. patmatch(char *pattern, const char *string)
  7043. {
  7044. char *p = preglob(pattern, 0);
  7045. int r = pmatch(p, string);
  7046. //bb_error_msg("!fnmatch(pattern:'%s',str:'%s',0):%d", p, string, r);
  7047. return r;
  7048. }
  7049. /*
  7050. * See if a pattern matches in a case statement.
  7051. */
  7052. static int
  7053. casematch(union node *pattern, char *val)
  7054. {
  7055. struct stackmark smark;
  7056. int result;
  7057. setstackmark(&smark);
  7058. argbackq = pattern->narg.backquote;
  7059. STARTSTACKSTR(expdest);
  7060. argstr(pattern->narg.text, EXP_TILDE | EXP_CASE);
  7061. STACKSTRNUL(expdest);
  7062. ifsfree();
  7063. result = patmatch(stackblock(), val);
  7064. popstackmark(&smark);
  7065. return result;
  7066. }
  7067. /* ============ find_command */
  7068. struct builtincmd {
  7069. const char *name;
  7070. int (*builtin)(int, char **) FAST_FUNC;
  7071. /* unsigned flags; */
  7072. };
  7073. #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
  7074. /* "regular" builtins always take precedence over commands,
  7075. * regardless of PATH=....%builtin... position */
  7076. #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
  7077. #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
  7078. struct cmdentry {
  7079. smallint cmdtype; /* CMDxxx */
  7080. union param {
  7081. int index;
  7082. /* index >= 0 for commands without path (slashes) */
  7083. /* (TODO: what exactly does the value mean? PATH position?) */
  7084. /* index == -1 for commands with slashes */
  7085. /* index == (-2 - applet_no) for NOFORK applets */
  7086. const struct builtincmd *cmd;
  7087. struct funcnode *func;
  7088. } u;
  7089. };
  7090. /* values of cmdtype */
  7091. #define CMDUNKNOWN -1 /* no entry in table for command */
  7092. #define CMDNORMAL 0 /* command is an executable program */
  7093. #define CMDFUNCTION 1 /* command is a shell function */
  7094. #define CMDBUILTIN 2 /* command is a shell builtin */
  7095. /* action to find_command() */
  7096. #define DO_ERR 0x01 /* prints errors */
  7097. #define DO_ABS 0x02 /* checks absolute paths */
  7098. #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
  7099. #define DO_ALTPATH 0x08 /* using alternate path */
  7100. #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
  7101. static void find_command(char *, struct cmdentry *, int, const char *);
  7102. /* ============ Hashing commands */
  7103. /*
  7104. * When commands are first encountered, they are entered in a hash table.
  7105. * This ensures that a full path search will not have to be done for them
  7106. * on each invocation.
  7107. *
  7108. * We should investigate converting to a linear search, even though that
  7109. * would make the command name "hash" a misnomer.
  7110. */
  7111. struct tblentry {
  7112. struct tblentry *next; /* next entry in hash chain */
  7113. union param param; /* definition of builtin function */
  7114. smallint cmdtype; /* CMDxxx */
  7115. char rehash; /* if set, cd done since entry created */
  7116. char cmdname[1]; /* name of command */
  7117. };
  7118. static struct tblentry **cmdtable;
  7119. #define INIT_G_cmdtable() do { \
  7120. cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
  7121. } while (0)
  7122. static int builtinloc = -1; /* index in path of %builtin, or -1 */
  7123. static void
  7124. tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) const char *cmd, char **argv, char **envp)
  7125. {
  7126. #if ENABLE_FEATURE_SH_STANDALONE
  7127. if (applet_no >= 0) {
  7128. if (APPLET_IS_NOEXEC(applet_no)) {
  7129. clearenv();
  7130. while (*envp)
  7131. putenv(*envp++);
  7132. popredir(/*drop:*/ 1);
  7133. run_noexec_applet_and_exit(applet_no, cmd, argv);
  7134. }
  7135. /* re-exec ourselves with the new arguments */
  7136. execve(bb_busybox_exec_path, argv, envp);
  7137. /* If they called chroot or otherwise made the binary no longer
  7138. * executable, fall through */
  7139. }
  7140. #endif
  7141. repeat:
  7142. #ifdef SYSV
  7143. do {
  7144. execve(cmd, argv, envp);
  7145. } while (errno == EINTR);
  7146. #else
  7147. execve(cmd, argv, envp);
  7148. #endif
  7149. if (cmd != bb_busybox_exec_path && errno == ENOEXEC) {
  7150. /* Run "cmd" as a shell script:
  7151. * http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
  7152. * "If the execve() function fails with ENOEXEC, the shell
  7153. * shall execute a command equivalent to having a shell invoked
  7154. * with the command name as its first operand,
  7155. * with any remaining arguments passed to the new shell"
  7156. *
  7157. * That is, do not use $SHELL, user's shell, or /bin/sh;
  7158. * just call ourselves.
  7159. *
  7160. * Note that bash reads ~80 chars of the file, and if it sees
  7161. * a zero byte before it sees newline, it doesn't try to
  7162. * interpret it, but fails with "cannot execute binary file"
  7163. * message and exit code 126. For one, this prevents attempts
  7164. * to interpret foreign ELF binaries as shell scripts.
  7165. */
  7166. argv[0] = (char*) cmd;
  7167. cmd = bb_busybox_exec_path;
  7168. /* NB: this is only possible because all callers of shellexec()
  7169. * ensure that the argv[-1] slot exists!
  7170. */
  7171. argv--;
  7172. argv[0] = (char*) "ash";
  7173. goto repeat;
  7174. }
  7175. }
  7176. /*
  7177. * Exec a program. Never returns. If you change this routine, you may
  7178. * have to change the find_command routine as well.
  7179. * argv[-1] must exist and be writable! See tryexec() for why.
  7180. */
  7181. static void shellexec(char *prog, char **argv, const char *path, int idx) NORETURN;
  7182. static void shellexec(char *prog, char **argv, const char *path, int idx)
  7183. {
  7184. char *cmdname;
  7185. int e;
  7186. char **envp;
  7187. int exerrno;
  7188. int applet_no = -1; /* used only by FEATURE_SH_STANDALONE */
  7189. envp = listvars(VEXPORT, VUNSET, /*strlist:*/ NULL, /*end:*/ NULL);
  7190. if (strchr(prog, '/') != NULL
  7191. #if ENABLE_FEATURE_SH_STANDALONE
  7192. || (applet_no = find_applet_by_name(prog)) >= 0
  7193. #endif
  7194. ) {
  7195. tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) prog, argv, envp);
  7196. if (applet_no >= 0) {
  7197. /* We tried execing ourself, but it didn't work.
  7198. * Maybe /proc/self/exe doesn't exist?
  7199. * Try $PATH search.
  7200. */
  7201. goto try_PATH;
  7202. }
  7203. e = errno;
  7204. } else {
  7205. try_PATH:
  7206. e = ENOENT;
  7207. while ((cmdname = path_advance(&path, prog)) != NULL) {
  7208. if (--idx < 0 && pathopt == NULL) {
  7209. tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
  7210. if (errno != ENOENT && errno != ENOTDIR)
  7211. e = errno;
  7212. }
  7213. stunalloc(cmdname);
  7214. }
  7215. }
  7216. /* Map to POSIX errors */
  7217. switch (e) {
  7218. case EACCES:
  7219. exerrno = 126;
  7220. break;
  7221. case ENOENT:
  7222. exerrno = 127;
  7223. break;
  7224. default:
  7225. exerrno = 2;
  7226. break;
  7227. }
  7228. exitstatus = exerrno;
  7229. TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
  7230. prog, e, suppress_int));
  7231. ash_msg_and_raise(EXEXIT, "%s: %s", prog, errmsg(e, "not found"));
  7232. /* NOTREACHED */
  7233. }
  7234. static void
  7235. printentry(struct tblentry *cmdp)
  7236. {
  7237. int idx;
  7238. const char *path;
  7239. char *name;
  7240. idx = cmdp->param.index;
  7241. path = pathval();
  7242. do {
  7243. name = path_advance(&path, cmdp->cmdname);
  7244. stunalloc(name);
  7245. } while (--idx >= 0);
  7246. out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
  7247. }
  7248. /*
  7249. * Clear out command entries. The argument specifies the first entry in
  7250. * PATH which has changed.
  7251. */
  7252. static void
  7253. clearcmdentry(int firstchange)
  7254. {
  7255. struct tblentry **tblp;
  7256. struct tblentry **pp;
  7257. struct tblentry *cmdp;
  7258. INT_OFF;
  7259. for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
  7260. pp = tblp;
  7261. while ((cmdp = *pp) != NULL) {
  7262. if ((cmdp->cmdtype == CMDNORMAL &&
  7263. cmdp->param.index >= firstchange)
  7264. || (cmdp->cmdtype == CMDBUILTIN &&
  7265. builtinloc >= firstchange)
  7266. ) {
  7267. *pp = cmdp->next;
  7268. free(cmdp);
  7269. } else {
  7270. pp = &cmdp->next;
  7271. }
  7272. }
  7273. }
  7274. INT_ON;
  7275. }
  7276. /*
  7277. * Locate a command in the command hash table. If "add" is nonzero,
  7278. * add the command to the table if it is not already present. The
  7279. * variable "lastcmdentry" is set to point to the address of the link
  7280. * pointing to the entry, so that delete_cmd_entry can delete the
  7281. * entry.
  7282. *
  7283. * Interrupts must be off if called with add != 0.
  7284. */
  7285. static struct tblentry **lastcmdentry;
  7286. static struct tblentry *
  7287. cmdlookup(const char *name, int add)
  7288. {
  7289. unsigned int hashval;
  7290. const char *p;
  7291. struct tblentry *cmdp;
  7292. struct tblentry **pp;
  7293. p = name;
  7294. hashval = (unsigned char)*p << 4;
  7295. while (*p)
  7296. hashval += (unsigned char)*p++;
  7297. hashval &= 0x7FFF;
  7298. pp = &cmdtable[hashval % CMDTABLESIZE];
  7299. for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
  7300. if (strcmp(cmdp->cmdname, name) == 0)
  7301. break;
  7302. pp = &cmdp->next;
  7303. }
  7304. if (add && cmdp == NULL) {
  7305. cmdp = *pp = ckzalloc(sizeof(struct tblentry)
  7306. + strlen(name)
  7307. /* + 1 - already done because
  7308. * tblentry::cmdname is char[1] */);
  7309. /*cmdp->next = NULL; - ckzalloc did it */
  7310. cmdp->cmdtype = CMDUNKNOWN;
  7311. strcpy(cmdp->cmdname, name);
  7312. }
  7313. lastcmdentry = pp;
  7314. return cmdp;
  7315. }
  7316. /*
  7317. * Delete the command entry returned on the last lookup.
  7318. */
  7319. static void
  7320. delete_cmd_entry(void)
  7321. {
  7322. struct tblentry *cmdp;
  7323. INT_OFF;
  7324. cmdp = *lastcmdentry;
  7325. *lastcmdentry = cmdp->next;
  7326. if (cmdp->cmdtype == CMDFUNCTION)
  7327. freefunc(cmdp->param.func);
  7328. free(cmdp);
  7329. INT_ON;
  7330. }
  7331. /*
  7332. * Add a new command entry, replacing any existing command entry for
  7333. * the same name - except special builtins.
  7334. */
  7335. static void
  7336. addcmdentry(char *name, struct cmdentry *entry)
  7337. {
  7338. struct tblentry *cmdp;
  7339. cmdp = cmdlookup(name, 1);
  7340. if (cmdp->cmdtype == CMDFUNCTION) {
  7341. freefunc(cmdp->param.func);
  7342. }
  7343. cmdp->cmdtype = entry->cmdtype;
  7344. cmdp->param = entry->u;
  7345. cmdp->rehash = 0;
  7346. }
  7347. static int FAST_FUNC
  7348. hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  7349. {
  7350. struct tblentry **pp;
  7351. struct tblentry *cmdp;
  7352. int c;
  7353. struct cmdentry entry;
  7354. char *name;
  7355. if (nextopt("r") != '\0') {
  7356. clearcmdentry(0);
  7357. return 0;
  7358. }
  7359. if (*argptr == NULL) {
  7360. for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
  7361. for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
  7362. if (cmdp->cmdtype == CMDNORMAL)
  7363. printentry(cmdp);
  7364. }
  7365. }
  7366. return 0;
  7367. }
  7368. c = 0;
  7369. while ((name = *argptr) != NULL) {
  7370. cmdp = cmdlookup(name, 0);
  7371. if (cmdp != NULL
  7372. && (cmdp->cmdtype == CMDNORMAL
  7373. || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
  7374. ) {
  7375. delete_cmd_entry();
  7376. }
  7377. find_command(name, &entry, DO_ERR, pathval());
  7378. if (entry.cmdtype == CMDUNKNOWN)
  7379. c = 1;
  7380. argptr++;
  7381. }
  7382. return c;
  7383. }
  7384. /*
  7385. * Called when a cd is done. Marks all commands so the next time they
  7386. * are executed they will be rehashed.
  7387. */
  7388. static void
  7389. hashcd(void)
  7390. {
  7391. struct tblentry **pp;
  7392. struct tblentry *cmdp;
  7393. for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
  7394. for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
  7395. if (cmdp->cmdtype == CMDNORMAL
  7396. || (cmdp->cmdtype == CMDBUILTIN
  7397. && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
  7398. && builtinloc > 0)
  7399. ) {
  7400. cmdp->rehash = 1;
  7401. }
  7402. }
  7403. }
  7404. }
  7405. /*
  7406. * Fix command hash table when PATH changed.
  7407. * Called before PATH is changed. The argument is the new value of PATH;
  7408. * pathval() still returns the old value at this point.
  7409. * Called with interrupts off.
  7410. */
  7411. static void FAST_FUNC
  7412. changepath(const char *new)
  7413. {
  7414. const char *old;
  7415. int firstchange;
  7416. int idx;
  7417. int idx_bltin;
  7418. old = pathval();
  7419. firstchange = 9999; /* assume no change */
  7420. idx = 0;
  7421. idx_bltin = -1;
  7422. for (;;) {
  7423. if (*old != *new) {
  7424. firstchange = idx;
  7425. if ((*old == '\0' && *new == ':')
  7426. || (*old == ':' && *new == '\0')
  7427. ) {
  7428. firstchange++;
  7429. }
  7430. old = new; /* ignore subsequent differences */
  7431. }
  7432. if (*new == '\0')
  7433. break;
  7434. if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
  7435. idx_bltin = idx;
  7436. if (*new == ':')
  7437. idx++;
  7438. new++;
  7439. old++;
  7440. }
  7441. if (builtinloc < 0 && idx_bltin >= 0)
  7442. builtinloc = idx_bltin; /* zap builtins */
  7443. if (builtinloc >= 0 && idx_bltin < 0)
  7444. firstchange = 0;
  7445. clearcmdentry(firstchange);
  7446. builtinloc = idx_bltin;
  7447. }
  7448. enum {
  7449. TEOF,
  7450. TNL,
  7451. TREDIR,
  7452. TWORD,
  7453. TSEMI,
  7454. TBACKGND,
  7455. TAND,
  7456. TOR,
  7457. TPIPE,
  7458. TLP,
  7459. TRP,
  7460. TENDCASE,
  7461. TENDBQUOTE,
  7462. TNOT,
  7463. TCASE,
  7464. TDO,
  7465. TDONE,
  7466. TELIF,
  7467. TELSE,
  7468. TESAC,
  7469. TFI,
  7470. TFOR,
  7471. #if BASH_FUNCTION
  7472. TFUNCTION,
  7473. #endif
  7474. TIF,
  7475. TIN,
  7476. TTHEN,
  7477. TUNTIL,
  7478. TWHILE,
  7479. TBEGIN,
  7480. TEND
  7481. };
  7482. typedef smallint token_id_t;
  7483. /* Nth bit indicates if token marks the end of a list */
  7484. enum {
  7485. tokendlist = 0
  7486. /* 0 */ | (1u << TEOF)
  7487. /* 1 */ | (0u << TNL)
  7488. /* 2 */ | (0u << TREDIR)
  7489. /* 3 */ | (0u << TWORD)
  7490. /* 4 */ | (0u << TSEMI)
  7491. /* 5 */ | (0u << TBACKGND)
  7492. /* 6 */ | (0u << TAND)
  7493. /* 7 */ | (0u << TOR)
  7494. /* 8 */ | (0u << TPIPE)
  7495. /* 9 */ | (0u << TLP)
  7496. /* 10 */ | (1u << TRP)
  7497. /* 11 */ | (1u << TENDCASE)
  7498. /* 12 */ | (1u << TENDBQUOTE)
  7499. /* 13 */ | (0u << TNOT)
  7500. /* 14 */ | (0u << TCASE)
  7501. /* 15 */ | (1u << TDO)
  7502. /* 16 */ | (1u << TDONE)
  7503. /* 17 */ | (1u << TELIF)
  7504. /* 18 */ | (1u << TELSE)
  7505. /* 19 */ | (1u << TESAC)
  7506. /* 20 */ | (1u << TFI)
  7507. /* 21 */ | (0u << TFOR)
  7508. #if BASH_FUNCTION
  7509. /* 22 */ | (0u << TFUNCTION)
  7510. #endif
  7511. /* 23 */ | (0u << TIF)
  7512. /* 24 */ | (0u << TIN)
  7513. /* 25 */ | (1u << TTHEN)
  7514. /* 26 */ | (0u << TUNTIL)
  7515. /* 27 */ | (0u << TWHILE)
  7516. /* 28 */ | (0u << TBEGIN)
  7517. /* 29 */ | (1u << TEND)
  7518. , /* thus far 29 bits used */
  7519. };
  7520. static const char *const tokname_array[] = {
  7521. "end of file",
  7522. "newline",
  7523. "redirection",
  7524. "word",
  7525. ";",
  7526. "&",
  7527. "&&",
  7528. "||",
  7529. "|",
  7530. "(",
  7531. ")",
  7532. ";;",
  7533. "`",
  7534. #define KWDOFFSET 13
  7535. /* the following are keywords */
  7536. "!",
  7537. "case",
  7538. "do",
  7539. "done",
  7540. "elif",
  7541. "else",
  7542. "esac",
  7543. "fi",
  7544. "for",
  7545. #if BASH_FUNCTION
  7546. "function",
  7547. #endif
  7548. "if",
  7549. "in",
  7550. "then",
  7551. "until",
  7552. "while",
  7553. "{",
  7554. "}",
  7555. };
  7556. /* Wrapper around strcmp for qsort/bsearch/... */
  7557. static int
  7558. pstrcmp(const void *a, const void *b)
  7559. {
  7560. return strcmp((char*)a, *(char**)b);
  7561. }
  7562. static const char *const *
  7563. findkwd(const char *s)
  7564. {
  7565. return bsearch(s, tokname_array + KWDOFFSET,
  7566. ARRAY_SIZE(tokname_array) - KWDOFFSET,
  7567. sizeof(tokname_array[0]), pstrcmp);
  7568. }
  7569. /*
  7570. * Locate and print what a word is...
  7571. */
  7572. static int
  7573. describe_command(char *command, const char *path, int describe_command_verbose)
  7574. {
  7575. struct cmdentry entry;
  7576. #if ENABLE_ASH_ALIAS
  7577. const struct alias *ap;
  7578. #endif
  7579. path = path ? path : pathval();
  7580. if (describe_command_verbose) {
  7581. out1str(command);
  7582. }
  7583. /* First look at the keywords */
  7584. if (findkwd(command)) {
  7585. out1str(describe_command_verbose ? " is a shell keyword" : command);
  7586. goto out;
  7587. }
  7588. #if ENABLE_ASH_ALIAS
  7589. /* Then look at the aliases */
  7590. ap = lookupalias(command, 0);
  7591. if (ap != NULL) {
  7592. if (!describe_command_verbose) {
  7593. out1str("alias ");
  7594. printalias(ap);
  7595. return 0;
  7596. }
  7597. out1fmt(" is an alias for %s", ap->val);
  7598. goto out;
  7599. }
  7600. #endif
  7601. /* Brute force */
  7602. find_command(command, &entry, DO_ABS, path);
  7603. switch (entry.cmdtype) {
  7604. case CMDNORMAL: {
  7605. int j = entry.u.index;
  7606. char *p;
  7607. if (j < 0) {
  7608. p = command;
  7609. } else {
  7610. do {
  7611. p = path_advance(&path, command);
  7612. stunalloc(p);
  7613. } while (--j >= 0);
  7614. }
  7615. if (describe_command_verbose) {
  7616. out1fmt(" is %s", p);
  7617. } else {
  7618. out1str(p);
  7619. }
  7620. break;
  7621. }
  7622. case CMDFUNCTION:
  7623. if (describe_command_verbose) {
  7624. out1str(" is a shell function");
  7625. } else {
  7626. out1str(command);
  7627. }
  7628. break;
  7629. case CMDBUILTIN:
  7630. if (describe_command_verbose) {
  7631. out1fmt(" is a %sshell builtin",
  7632. IS_BUILTIN_SPECIAL(entry.u.cmd) ?
  7633. "special " : nullstr
  7634. );
  7635. } else {
  7636. out1str(command);
  7637. }
  7638. break;
  7639. default:
  7640. if (describe_command_verbose) {
  7641. out1str(": not found\n");
  7642. }
  7643. return 127;
  7644. }
  7645. out:
  7646. out1str("\n");
  7647. return 0;
  7648. }
  7649. static int FAST_FUNC
  7650. typecmd(int argc UNUSED_PARAM, char **argv)
  7651. {
  7652. int i = 1;
  7653. int err = 0;
  7654. int verbose = 1;
  7655. /* type -p ... ? (we don't bother checking for 'p') */
  7656. if (argv[1] && argv[1][0] == '-') {
  7657. i++;
  7658. verbose = 0;
  7659. }
  7660. while (argv[i]) {
  7661. err |= describe_command(argv[i++], NULL, verbose);
  7662. }
  7663. return err;
  7664. }
  7665. #if ENABLE_ASH_CMDCMD
  7666. /* Is it "command [-p] PROG ARGS" bltin, no other opts? Return ptr to "PROG" if yes */
  7667. static char **
  7668. parse_command_args(char **argv, const char **path)
  7669. {
  7670. char *cp, c;
  7671. for (;;) {
  7672. cp = *++argv;
  7673. if (!cp)
  7674. return NULL;
  7675. if (*cp++ != '-')
  7676. break;
  7677. c = *cp++;
  7678. if (!c)
  7679. break;
  7680. if (c == '-' && !*cp) {
  7681. if (!*++argv)
  7682. return NULL;
  7683. break;
  7684. }
  7685. do {
  7686. switch (c) {
  7687. case 'p':
  7688. *path = bb_default_path;
  7689. break;
  7690. default:
  7691. /* run 'typecmd' for other options */
  7692. return NULL;
  7693. }
  7694. c = *cp++;
  7695. } while (c);
  7696. }
  7697. return argv;
  7698. }
  7699. static int FAST_FUNC
  7700. commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  7701. {
  7702. char *cmd;
  7703. int c;
  7704. enum {
  7705. VERIFY_BRIEF = 1,
  7706. VERIFY_VERBOSE = 2,
  7707. } verify = 0;
  7708. const char *path = NULL;
  7709. /* "command [-p] PROG ARGS" (that is, without -V or -v)
  7710. * never reaches this function.
  7711. */
  7712. while ((c = nextopt("pvV")) != '\0')
  7713. if (c == 'V')
  7714. verify |= VERIFY_VERBOSE;
  7715. else if (c == 'v')
  7716. /*verify |= VERIFY_BRIEF*/;
  7717. #if DEBUG
  7718. else if (c != 'p')
  7719. abort();
  7720. #endif
  7721. else
  7722. path = bb_default_path;
  7723. /* Mimic bash: just "command -v" doesn't complain, it's a nop */
  7724. cmd = *argptr;
  7725. if (/*verify && */ cmd)
  7726. return describe_command(cmd, path, verify /* - VERIFY_BRIEF*/);
  7727. return 0;
  7728. }
  7729. #endif
  7730. /*static int funcblocksize; // size of structures in function */
  7731. /*static int funcstringsize; // size of strings in node */
  7732. static void *funcblock; /* block to allocate function from */
  7733. static char *funcstring_end; /* end of block to allocate strings from */
  7734. static const uint8_t nodesize[N_NUMBER] ALIGN1 = {
  7735. [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
  7736. [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
  7737. [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
  7738. [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
  7739. [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
  7740. [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
  7741. [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
  7742. [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
  7743. [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
  7744. [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
  7745. [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
  7746. [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
  7747. [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
  7748. [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
  7749. [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
  7750. [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
  7751. [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
  7752. #if BASH_REDIR_OUTPUT
  7753. [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
  7754. #endif
  7755. [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
  7756. [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
  7757. [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
  7758. [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
  7759. [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
  7760. [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
  7761. [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
  7762. [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
  7763. [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
  7764. };
  7765. static int calcsize(int funcblocksize, union node *n);
  7766. static int
  7767. sizenodelist(int funcblocksize, struct nodelist *lp)
  7768. {
  7769. while (lp) {
  7770. funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
  7771. funcblocksize = calcsize(funcblocksize, lp->n);
  7772. lp = lp->next;
  7773. }
  7774. return funcblocksize;
  7775. }
  7776. static int
  7777. calcsize(int funcblocksize, union node *n)
  7778. {
  7779. if (n == NULL)
  7780. return funcblocksize;
  7781. funcblocksize += nodesize[n->type];
  7782. switch (n->type) {
  7783. case NCMD:
  7784. funcblocksize = calcsize(funcblocksize, n->ncmd.redirect);
  7785. funcblocksize = calcsize(funcblocksize, n->ncmd.args);
  7786. funcblocksize = calcsize(funcblocksize, n->ncmd.assign);
  7787. break;
  7788. case NPIPE:
  7789. funcblocksize = sizenodelist(funcblocksize, n->npipe.cmdlist);
  7790. break;
  7791. case NREDIR:
  7792. case NBACKGND:
  7793. case NSUBSHELL:
  7794. funcblocksize = calcsize(funcblocksize, n->nredir.redirect);
  7795. funcblocksize = calcsize(funcblocksize, n->nredir.n);
  7796. break;
  7797. case NAND:
  7798. case NOR:
  7799. case NSEMI:
  7800. case NWHILE:
  7801. case NUNTIL:
  7802. funcblocksize = calcsize(funcblocksize, n->nbinary.ch2);
  7803. funcblocksize = calcsize(funcblocksize, n->nbinary.ch1);
  7804. break;
  7805. case NIF:
  7806. funcblocksize = calcsize(funcblocksize, n->nif.elsepart);
  7807. funcblocksize = calcsize(funcblocksize, n->nif.ifpart);
  7808. funcblocksize = calcsize(funcblocksize, n->nif.test);
  7809. break;
  7810. case NFOR:
  7811. funcblocksize += SHELL_ALIGN(strlen(n->nfor.var) + 1); /* was funcstringsize += ... */
  7812. funcblocksize = calcsize(funcblocksize, n->nfor.body);
  7813. funcblocksize = calcsize(funcblocksize, n->nfor.args);
  7814. break;
  7815. case NCASE:
  7816. funcblocksize = calcsize(funcblocksize, n->ncase.cases);
  7817. funcblocksize = calcsize(funcblocksize, n->ncase.expr);
  7818. break;
  7819. case NCLIST:
  7820. funcblocksize = calcsize(funcblocksize, n->nclist.body);
  7821. funcblocksize = calcsize(funcblocksize, n->nclist.pattern);
  7822. funcblocksize = calcsize(funcblocksize, n->nclist.next);
  7823. break;
  7824. case NDEFUN:
  7825. case NARG:
  7826. funcblocksize = sizenodelist(funcblocksize, n->narg.backquote);
  7827. funcblocksize += SHELL_ALIGN(strlen(n->narg.text) + 1); /* was funcstringsize += ... */
  7828. funcblocksize = calcsize(funcblocksize, n->narg.next);
  7829. break;
  7830. case NTO:
  7831. #if BASH_REDIR_OUTPUT
  7832. case NTO2:
  7833. #endif
  7834. case NCLOBBER:
  7835. case NFROM:
  7836. case NFROMTO:
  7837. case NAPPEND:
  7838. funcblocksize = calcsize(funcblocksize, n->nfile.fname);
  7839. funcblocksize = calcsize(funcblocksize, n->nfile.next);
  7840. break;
  7841. case NTOFD:
  7842. case NFROMFD:
  7843. funcblocksize = calcsize(funcblocksize, n->ndup.vname);
  7844. funcblocksize = calcsize(funcblocksize, n->ndup.next);
  7845. break;
  7846. case NHERE:
  7847. case NXHERE:
  7848. funcblocksize = calcsize(funcblocksize, n->nhere.doc);
  7849. funcblocksize = calcsize(funcblocksize, n->nhere.next);
  7850. break;
  7851. case NNOT:
  7852. funcblocksize = calcsize(funcblocksize, n->nnot.com);
  7853. break;
  7854. };
  7855. return funcblocksize;
  7856. }
  7857. static char *
  7858. nodeckstrdup(char *s)
  7859. {
  7860. funcstring_end -= SHELL_ALIGN(strlen(s) + 1);
  7861. return strcpy(funcstring_end, s);
  7862. }
  7863. static union node *copynode(union node *);
  7864. static struct nodelist *
  7865. copynodelist(struct nodelist *lp)
  7866. {
  7867. struct nodelist *start;
  7868. struct nodelist **lpp;
  7869. lpp = &start;
  7870. while (lp) {
  7871. *lpp = funcblock;
  7872. funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
  7873. (*lpp)->n = copynode(lp->n);
  7874. lp = lp->next;
  7875. lpp = &(*lpp)->next;
  7876. }
  7877. *lpp = NULL;
  7878. return start;
  7879. }
  7880. static union node *
  7881. copynode(union node *n)
  7882. {
  7883. union node *new;
  7884. if (n == NULL)
  7885. return NULL;
  7886. new = funcblock;
  7887. funcblock = (char *) funcblock + nodesize[n->type];
  7888. switch (n->type) {
  7889. case NCMD:
  7890. new->ncmd.redirect = copynode(n->ncmd.redirect);
  7891. new->ncmd.args = copynode(n->ncmd.args);
  7892. new->ncmd.assign = copynode(n->ncmd.assign);
  7893. break;
  7894. case NPIPE:
  7895. new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
  7896. new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
  7897. break;
  7898. case NREDIR:
  7899. case NBACKGND:
  7900. case NSUBSHELL:
  7901. new->nredir.redirect = copynode(n->nredir.redirect);
  7902. new->nredir.n = copynode(n->nredir.n);
  7903. break;
  7904. case NAND:
  7905. case NOR:
  7906. case NSEMI:
  7907. case NWHILE:
  7908. case NUNTIL:
  7909. new->nbinary.ch2 = copynode(n->nbinary.ch2);
  7910. new->nbinary.ch1 = copynode(n->nbinary.ch1);
  7911. break;
  7912. case NIF:
  7913. new->nif.elsepart = copynode(n->nif.elsepart);
  7914. new->nif.ifpart = copynode(n->nif.ifpart);
  7915. new->nif.test = copynode(n->nif.test);
  7916. break;
  7917. case NFOR:
  7918. new->nfor.var = nodeckstrdup(n->nfor.var);
  7919. new->nfor.body = copynode(n->nfor.body);
  7920. new->nfor.args = copynode(n->nfor.args);
  7921. break;
  7922. case NCASE:
  7923. new->ncase.cases = copynode(n->ncase.cases);
  7924. new->ncase.expr = copynode(n->ncase.expr);
  7925. break;
  7926. case NCLIST:
  7927. new->nclist.body = copynode(n->nclist.body);
  7928. new->nclist.pattern = copynode(n->nclist.pattern);
  7929. new->nclist.next = copynode(n->nclist.next);
  7930. break;
  7931. case NDEFUN:
  7932. case NARG:
  7933. new->narg.backquote = copynodelist(n->narg.backquote);
  7934. new->narg.text = nodeckstrdup(n->narg.text);
  7935. new->narg.next = copynode(n->narg.next);
  7936. break;
  7937. case NTO:
  7938. #if BASH_REDIR_OUTPUT
  7939. case NTO2:
  7940. #endif
  7941. case NCLOBBER:
  7942. case NFROM:
  7943. case NFROMTO:
  7944. case NAPPEND:
  7945. new->nfile.fname = copynode(n->nfile.fname);
  7946. new->nfile.fd = n->nfile.fd;
  7947. new->nfile.next = copynode(n->nfile.next);
  7948. break;
  7949. case NTOFD:
  7950. case NFROMFD:
  7951. new->ndup.vname = copynode(n->ndup.vname);
  7952. new->ndup.dupfd = n->ndup.dupfd;
  7953. new->ndup.fd = n->ndup.fd;
  7954. new->ndup.next = copynode(n->ndup.next);
  7955. break;
  7956. case NHERE:
  7957. case NXHERE:
  7958. new->nhere.doc = copynode(n->nhere.doc);
  7959. new->nhere.fd = n->nhere.fd;
  7960. new->nhere.next = copynode(n->nhere.next);
  7961. break;
  7962. case NNOT:
  7963. new->nnot.com = copynode(n->nnot.com);
  7964. break;
  7965. };
  7966. new->type = n->type;
  7967. return new;
  7968. }
  7969. /*
  7970. * Make a copy of a parse tree.
  7971. */
  7972. static struct funcnode *
  7973. copyfunc(union node *n)
  7974. {
  7975. struct funcnode *f;
  7976. size_t blocksize;
  7977. /*funcstringsize = 0;*/
  7978. blocksize = offsetof(struct funcnode, n) + calcsize(0, n);
  7979. f = ckzalloc(blocksize /* + funcstringsize */);
  7980. funcblock = (char *) f + offsetof(struct funcnode, n);
  7981. funcstring_end = (char *) f + blocksize;
  7982. copynode(n);
  7983. /* f->count = 0; - ckzalloc did it */
  7984. return f;
  7985. }
  7986. /*
  7987. * Define a shell function.
  7988. */
  7989. static void
  7990. defun(union node *func)
  7991. {
  7992. struct cmdentry entry;
  7993. INT_OFF;
  7994. entry.cmdtype = CMDFUNCTION;
  7995. entry.u.func = copyfunc(func);
  7996. addcmdentry(func->narg.text, &entry);
  7997. INT_ON;
  7998. }
  7999. /* Reasons for skipping commands (see comment on breakcmd routine) */
  8000. #define SKIPBREAK (1 << 0)
  8001. #define SKIPCONT (1 << 1)
  8002. #define SKIPFUNC (1 << 2)
  8003. static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
  8004. static int skipcount; /* number of levels to skip */
  8005. static int funcnest; /* depth of function calls */
  8006. static int loopnest; /* current loop nesting level */
  8007. /* Forward decl way out to parsing code - dotrap needs it */
  8008. static int evalstring(char *s, int flags);
  8009. /* Called to execute a trap.
  8010. * Single callsite - at the end of evaltree().
  8011. * If we return non-zero, evaltree raises EXEXIT exception.
  8012. *
  8013. * Perhaps we should avoid entering new trap handlers
  8014. * while we are executing a trap handler. [is it a TODO?]
  8015. */
  8016. static void
  8017. dotrap(void)
  8018. {
  8019. uint8_t *g;
  8020. int sig;
  8021. uint8_t last_status;
  8022. if (!pending_sig)
  8023. return;
  8024. last_status = exitstatus;
  8025. pending_sig = 0;
  8026. barrier();
  8027. TRACE(("dotrap entered\n"));
  8028. for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
  8029. char *p;
  8030. if (!*g)
  8031. continue;
  8032. if (evalskip) {
  8033. pending_sig = sig;
  8034. break;
  8035. }
  8036. p = trap[sig];
  8037. /* non-trapped SIGINT is handled separately by raise_interrupt,
  8038. * don't upset it by resetting gotsig[SIGINT-1] */
  8039. if (sig == SIGINT && !p)
  8040. continue;
  8041. TRACE(("sig %d is active, will run handler '%s'\n", sig, p));
  8042. *g = 0;
  8043. if (!p)
  8044. continue;
  8045. evalstring(p, 0);
  8046. }
  8047. exitstatus = last_status;
  8048. TRACE(("dotrap returns\n"));
  8049. }
  8050. /* forward declarations - evaluation is fairly recursive business... */
  8051. static int evalloop(union node *, int);
  8052. static int evalfor(union node *, int);
  8053. static int evalcase(union node *, int);
  8054. static int evalsubshell(union node *, int);
  8055. static void expredir(union node *);
  8056. static int evalpipe(union node *, int);
  8057. static int evalcommand(union node *, int);
  8058. static int evalbltin(const struct builtincmd *, int, char **, int);
  8059. static void prehash(union node *);
  8060. /*
  8061. * Evaluate a parse tree. The value is left in the global variable
  8062. * exitstatus.
  8063. */
  8064. static int
  8065. evaltree(union node *n, int flags)
  8066. {
  8067. int checkexit = 0;
  8068. int (*evalfn)(union node *, int);
  8069. int status = 0;
  8070. if (n == NULL) {
  8071. TRACE(("evaltree(NULL) called\n"));
  8072. goto out;
  8073. }
  8074. TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
  8075. dotrap();
  8076. switch (n->type) {
  8077. default:
  8078. #if DEBUG
  8079. out1fmt("Node type = %d\n", n->type);
  8080. fflush_all();
  8081. break;
  8082. #endif
  8083. case NNOT:
  8084. status = !evaltree(n->nnot.com, EV_TESTED);
  8085. goto setstatus;
  8086. case NREDIR:
  8087. expredir(n->nredir.redirect);
  8088. pushredir(n->nredir.redirect);
  8089. status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
  8090. if (!status) {
  8091. status = evaltree(n->nredir.n, flags & EV_TESTED);
  8092. }
  8093. if (n->nredir.redirect)
  8094. popredir(/*drop:*/ 0);
  8095. goto setstatus;
  8096. case NCMD:
  8097. evalfn = evalcommand;
  8098. checkexit:
  8099. if (eflag && !(flags & EV_TESTED))
  8100. checkexit = ~0;
  8101. goto calleval;
  8102. case NFOR:
  8103. evalfn = evalfor;
  8104. goto calleval;
  8105. case NWHILE:
  8106. case NUNTIL:
  8107. evalfn = evalloop;
  8108. goto calleval;
  8109. case NSUBSHELL:
  8110. case NBACKGND:
  8111. evalfn = evalsubshell;
  8112. goto checkexit;
  8113. case NPIPE:
  8114. evalfn = evalpipe;
  8115. goto checkexit;
  8116. case NCASE:
  8117. evalfn = evalcase;
  8118. goto calleval;
  8119. case NAND:
  8120. case NOR:
  8121. case NSEMI: {
  8122. #if NAND + 1 != NOR
  8123. #error NAND + 1 != NOR
  8124. #endif
  8125. #if NOR + 1 != NSEMI
  8126. #error NOR + 1 != NSEMI
  8127. #endif
  8128. unsigned is_or = n->type - NAND;
  8129. status = evaltree(
  8130. n->nbinary.ch1,
  8131. (flags | ((is_or >> 1) - 1)) & EV_TESTED
  8132. );
  8133. if ((!status) == is_or || evalskip)
  8134. break;
  8135. n = n->nbinary.ch2;
  8136. evaln:
  8137. evalfn = evaltree;
  8138. calleval:
  8139. status = evalfn(n, flags);
  8140. goto setstatus;
  8141. }
  8142. case NIF:
  8143. status = evaltree(n->nif.test, EV_TESTED);
  8144. if (evalskip)
  8145. break;
  8146. if (!status) {
  8147. n = n->nif.ifpart;
  8148. goto evaln;
  8149. }
  8150. if (n->nif.elsepart) {
  8151. n = n->nif.elsepart;
  8152. goto evaln;
  8153. }
  8154. status = 0;
  8155. goto setstatus;
  8156. case NDEFUN:
  8157. defun(n);
  8158. /* Not necessary. To test it:
  8159. * "false; f() { qwerty; }; echo $?" should print 0.
  8160. */
  8161. /* status = 0; */
  8162. setstatus:
  8163. exitstatus = status;
  8164. break;
  8165. }
  8166. out:
  8167. /* Order of checks below is important:
  8168. * signal handlers trigger before exit caused by "set -e".
  8169. */
  8170. dotrap();
  8171. if (checkexit & status)
  8172. raise_exception(EXEXIT);
  8173. if (flags & EV_EXIT)
  8174. raise_exception(EXEXIT);
  8175. TRACE(("leaving evaltree (no interrupts)\n"));
  8176. return exitstatus;
  8177. }
  8178. static int
  8179. skiploop(void)
  8180. {
  8181. int skip = evalskip;
  8182. switch (skip) {
  8183. case 0:
  8184. break;
  8185. case SKIPBREAK:
  8186. case SKIPCONT:
  8187. if (--skipcount <= 0) {
  8188. evalskip = 0;
  8189. break;
  8190. }
  8191. skip = SKIPBREAK;
  8192. break;
  8193. }
  8194. return skip;
  8195. }
  8196. static int
  8197. evalloop(union node *n, int flags)
  8198. {
  8199. int skip;
  8200. int status;
  8201. loopnest++;
  8202. status = 0;
  8203. flags &= EV_TESTED;
  8204. do {
  8205. int i;
  8206. i = evaltree(n->nbinary.ch1, EV_TESTED);
  8207. skip = skiploop();
  8208. if (skip == SKIPFUNC)
  8209. status = i;
  8210. if (skip)
  8211. continue;
  8212. if (n->type != NWHILE)
  8213. i = !i;
  8214. if (i != 0)
  8215. break;
  8216. status = evaltree(n->nbinary.ch2, flags);
  8217. skip = skiploop();
  8218. } while (!(skip & ~SKIPCONT));
  8219. loopnest--;
  8220. return status;
  8221. }
  8222. static int
  8223. evalfor(union node *n, int flags)
  8224. {
  8225. struct arglist arglist;
  8226. union node *argp;
  8227. struct strlist *sp;
  8228. struct stackmark smark;
  8229. int status = 0;
  8230. setstackmark(&smark);
  8231. arglist.list = NULL;
  8232. arglist.lastp = &arglist.list;
  8233. for (argp = n->nfor.args; argp; argp = argp->narg.next) {
  8234. expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
  8235. }
  8236. *arglist.lastp = NULL;
  8237. loopnest++;
  8238. flags &= EV_TESTED;
  8239. for (sp = arglist.list; sp; sp = sp->next) {
  8240. setvar0(n->nfor.var, sp->text);
  8241. status = evaltree(n->nfor.body, flags);
  8242. if (skiploop() & ~SKIPCONT)
  8243. break;
  8244. }
  8245. loopnest--;
  8246. popstackmark(&smark);
  8247. return status;
  8248. }
  8249. static int
  8250. evalcase(union node *n, int flags)
  8251. {
  8252. union node *cp;
  8253. union node *patp;
  8254. struct arglist arglist;
  8255. struct stackmark smark;
  8256. int status = 0;
  8257. setstackmark(&smark);
  8258. arglist.list = NULL;
  8259. arglist.lastp = &arglist.list;
  8260. expandarg(n->ncase.expr, &arglist, EXP_TILDE);
  8261. for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
  8262. for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
  8263. if (casematch(patp, arglist.list->text)) {
  8264. /* Ensure body is non-empty as otherwise
  8265. * EV_EXIT may prevent us from setting the
  8266. * exit status.
  8267. */
  8268. if (evalskip == 0 && cp->nclist.body) {
  8269. status = evaltree(cp->nclist.body, flags);
  8270. }
  8271. goto out;
  8272. }
  8273. }
  8274. }
  8275. out:
  8276. popstackmark(&smark);
  8277. return status;
  8278. }
  8279. /*
  8280. * Kick off a subshell to evaluate a tree.
  8281. */
  8282. static int
  8283. evalsubshell(union node *n, int flags)
  8284. {
  8285. struct job *jp;
  8286. int backgnd = (n->type == NBACKGND); /* FORK_BG(1) if yes, else FORK_FG(0) */
  8287. int status;
  8288. expredir(n->nredir.redirect);
  8289. if (!backgnd && (flags & EV_EXIT) && !may_have_traps)
  8290. goto nofork;
  8291. INT_OFF;
  8292. if (backgnd == FORK_FG)
  8293. get_tty_state();
  8294. jp = makejob(/*n,*/ 1);
  8295. if (forkshell(jp, n, backgnd) == 0) {
  8296. /* child */
  8297. INT_ON;
  8298. flags |= EV_EXIT;
  8299. if (backgnd)
  8300. flags &= ~EV_TESTED;
  8301. nofork:
  8302. redirect(n->nredir.redirect, 0);
  8303. evaltreenr(n->nredir.n, flags);
  8304. /* never returns */
  8305. }
  8306. /* parent */
  8307. status = 0;
  8308. if (backgnd == FORK_FG)
  8309. status = waitforjob(jp);
  8310. INT_ON;
  8311. return status;
  8312. }
  8313. /*
  8314. * Compute the names of the files in a redirection list.
  8315. */
  8316. static void fixredir(union node *, const char *, int);
  8317. static void
  8318. expredir(union node *n)
  8319. {
  8320. union node *redir;
  8321. for (redir = n; redir; redir = redir->nfile.next) {
  8322. struct arglist fn;
  8323. fn.list = NULL;
  8324. fn.lastp = &fn.list;
  8325. switch (redir->type) {
  8326. case NFROMTO:
  8327. case NFROM:
  8328. case NTO:
  8329. #if BASH_REDIR_OUTPUT
  8330. case NTO2:
  8331. #endif
  8332. case NCLOBBER:
  8333. case NAPPEND:
  8334. expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
  8335. TRACE(("expredir expanded to '%s'\n", fn.list->text));
  8336. #if BASH_REDIR_OUTPUT
  8337. store_expfname:
  8338. #endif
  8339. #if 0
  8340. // By the design of stack allocator, the loop of this kind:
  8341. // while true; do while true; do break; done </dev/null; done
  8342. // will look like a memory leak: ash plans to free expfname's
  8343. // of "/dev/null" as soon as it finishes running the loop
  8344. // (in this case, never).
  8345. // This "fix" is wrong:
  8346. if (redir->nfile.expfname)
  8347. stunalloc(redir->nfile.expfname);
  8348. // It results in corrupted state of stacked allocations.
  8349. #endif
  8350. redir->nfile.expfname = fn.list->text;
  8351. break;
  8352. case NFROMFD:
  8353. case NTOFD: /* >& */
  8354. if (redir->ndup.vname) {
  8355. expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
  8356. if (fn.list == NULL)
  8357. ash_msg_and_raise_error("redir error");
  8358. #if BASH_REDIR_OUTPUT
  8359. //FIXME: we used expandarg with different args!
  8360. if (!isdigit_str9(fn.list->text)) {
  8361. /* >&file, not >&fd */
  8362. if (redir->nfile.fd != 1) /* 123>&file - BAD */
  8363. ash_msg_and_raise_error("redir error");
  8364. redir->type = NTO2;
  8365. goto store_expfname;
  8366. }
  8367. #endif
  8368. fixredir(redir, fn.list->text, 1);
  8369. }
  8370. break;
  8371. }
  8372. }
  8373. }
  8374. /*
  8375. * Evaluate a pipeline. All the processes in the pipeline are children
  8376. * of the process creating the pipeline. (This differs from some versions
  8377. * of the shell, which make the last process in a pipeline the parent
  8378. * of all the rest.)
  8379. */
  8380. static int
  8381. evalpipe(union node *n, int flags)
  8382. {
  8383. struct job *jp;
  8384. struct nodelist *lp;
  8385. int pipelen;
  8386. int prevfd;
  8387. int pip[2];
  8388. int status = 0;
  8389. TRACE(("evalpipe(0x%lx) called\n", (long)n));
  8390. pipelen = 0;
  8391. for (lp = n->npipe.cmdlist; lp; lp = lp->next)
  8392. pipelen++;
  8393. flags |= EV_EXIT;
  8394. INT_OFF;
  8395. if (n->npipe.pipe_backgnd == 0)
  8396. get_tty_state();
  8397. jp = makejob(/*n,*/ pipelen);
  8398. prevfd = -1;
  8399. for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
  8400. prehash(lp->n);
  8401. pip[1] = -1;
  8402. if (lp->next) {
  8403. if (pipe(pip) < 0) {
  8404. close(prevfd);
  8405. ash_msg_and_raise_perror("can't create pipe");
  8406. }
  8407. }
  8408. if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
  8409. /* child */
  8410. INT_ON;
  8411. if (pip[1] >= 0) {
  8412. close(pip[0]);
  8413. }
  8414. if (prevfd > 0) {
  8415. dup2(prevfd, 0);
  8416. close(prevfd);
  8417. }
  8418. if (pip[1] > 1) {
  8419. dup2(pip[1], 1);
  8420. close(pip[1]);
  8421. }
  8422. evaltreenr(lp->n, flags);
  8423. /* never returns */
  8424. }
  8425. /* parent */
  8426. if (prevfd >= 0)
  8427. close(prevfd);
  8428. prevfd = pip[0];
  8429. /* Don't want to trigger debugging */
  8430. if (pip[1] != -1)
  8431. close(pip[1]);
  8432. }
  8433. if (n->npipe.pipe_backgnd == 0) {
  8434. status = waitforjob(jp);
  8435. TRACE(("evalpipe: job done exit status %d\n", status));
  8436. }
  8437. INT_ON;
  8438. return status;
  8439. }
  8440. /*
  8441. * Controls whether the shell is interactive or not.
  8442. */
  8443. static void
  8444. setinteractive(int on)
  8445. {
  8446. static smallint is_interactive;
  8447. if (++on == is_interactive)
  8448. return;
  8449. is_interactive = on;
  8450. setsignal(SIGINT);
  8451. setsignal(SIGQUIT);
  8452. setsignal(SIGTERM);
  8453. #if !ENABLE_FEATURE_SH_EXTRA_QUIET
  8454. if (is_interactive > 1) {
  8455. /* Looks like they want an interactive shell */
  8456. static smallint did_banner;
  8457. if (!did_banner) {
  8458. /* note: ash and hush share this string */
  8459. out1fmt("\n\n%s %s\n"
  8460. IF_ASH_HELP("Enter 'help' for a list of built-in commands.\n")
  8461. "\n",
  8462. bb_banner,
  8463. "built-in shell (ash)"
  8464. );
  8465. did_banner = 1;
  8466. }
  8467. }
  8468. #endif
  8469. }
  8470. static void
  8471. optschanged(void)
  8472. {
  8473. #if DEBUG
  8474. opentrace();
  8475. #endif
  8476. setinteractive(iflag);
  8477. setjobctl(mflag);
  8478. #if ENABLE_FEATURE_EDITING_VI
  8479. if (viflag)
  8480. line_input_state->flags |= VI_MODE;
  8481. else
  8482. line_input_state->flags &= ~VI_MODE;
  8483. #else
  8484. viflag = 0; /* forcibly keep the option off */
  8485. #endif
  8486. }
  8487. struct localvar_list {
  8488. struct localvar_list *next;
  8489. struct localvar *lv;
  8490. };
  8491. static struct localvar_list *localvar_stack;
  8492. /*
  8493. * Called after a function returns.
  8494. * Interrupts must be off.
  8495. */
  8496. static void
  8497. poplocalvars(int keep)
  8498. {
  8499. struct localvar_list *ll;
  8500. struct localvar *lvp, *next;
  8501. struct var *vp;
  8502. INT_OFF;
  8503. ll = localvar_stack;
  8504. localvar_stack = ll->next;
  8505. next = ll->lv;
  8506. free(ll);
  8507. while ((lvp = next) != NULL) {
  8508. next = lvp->next;
  8509. vp = lvp->vp;
  8510. TRACE(("poplocalvar %s\n", vp ? vp->var_text : "-"));
  8511. if (keep) {
  8512. int bits = VSTRFIXED;
  8513. if (lvp->flags != VUNSET) {
  8514. if (vp->var_text == lvp->text)
  8515. bits |= VTEXTFIXED;
  8516. else if (!(lvp->flags & (VTEXTFIXED|VSTACK)))
  8517. free((char*)lvp->text);
  8518. }
  8519. vp->flags &= ~bits;
  8520. vp->flags |= (lvp->flags & bits);
  8521. if ((vp->flags &
  8522. (VEXPORT|VREADONLY|VSTRFIXED|VUNSET)) == VUNSET)
  8523. unsetvar(vp->var_text);
  8524. } else if (vp == NULL) { /* $- saved */
  8525. memcpy(optlist, lvp->text, sizeof(optlist));
  8526. free((char*)lvp->text);
  8527. optschanged();
  8528. } else if (lvp->flags == VUNSET) {
  8529. vp->flags &= ~(VSTRFIXED|VREADONLY);
  8530. unsetvar(vp->var_text);
  8531. } else {
  8532. if (vp->var_func)
  8533. vp->var_func(var_end(lvp->text));
  8534. if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
  8535. free((char*)vp->var_text);
  8536. vp->flags = lvp->flags;
  8537. vp->var_text = lvp->text;
  8538. }
  8539. free(lvp);
  8540. }
  8541. INT_ON;
  8542. }
  8543. /*
  8544. * Create a new localvar environment.
  8545. */
  8546. static struct localvar_list *
  8547. pushlocalvars(void)
  8548. {
  8549. struct localvar_list *ll;
  8550. INT_OFF;
  8551. ll = ckzalloc(sizeof(*ll));
  8552. /*ll->lv = NULL; - zalloc did it */
  8553. ll->next = localvar_stack;
  8554. localvar_stack = ll;
  8555. INT_ON;
  8556. return ll->next;
  8557. }
  8558. static void
  8559. unwindlocalvars(struct localvar_list *stop)
  8560. {
  8561. while (localvar_stack != stop)
  8562. poplocalvars(0);
  8563. }
  8564. static int
  8565. evalfun(struct funcnode *func, int argc, char **argv, int flags)
  8566. {
  8567. volatile struct shparam saveparam;
  8568. struct jmploc *volatile savehandler;
  8569. struct jmploc jmploc;
  8570. int e;
  8571. saveparam = shellparam;
  8572. savehandler = exception_handler;
  8573. e = setjmp(jmploc.loc);
  8574. if (e) {
  8575. goto funcdone;
  8576. }
  8577. INT_OFF;
  8578. exception_handler = &jmploc;
  8579. shellparam.malloced = 0;
  8580. func->count++;
  8581. funcnest++;
  8582. INT_ON;
  8583. shellparam.nparam = argc - 1;
  8584. shellparam.p = argv + 1;
  8585. #if ENABLE_ASH_GETOPTS
  8586. shellparam.optind = 1;
  8587. shellparam.optoff = -1;
  8588. #endif
  8589. pushlocalvars();
  8590. evaltree(func->n.narg.next, flags & EV_TESTED);
  8591. poplocalvars(0);
  8592. funcdone:
  8593. INT_OFF;
  8594. funcnest--;
  8595. freefunc(func);
  8596. freeparam(&shellparam);
  8597. shellparam = saveparam;
  8598. exception_handler = savehandler;
  8599. INT_ON;
  8600. evalskip &= ~SKIPFUNC;
  8601. return e;
  8602. }
  8603. /*
  8604. * Make a variable a local variable. When a variable is made local, it's
  8605. * value and flags are saved in a localvar structure. The saved values
  8606. * will be restored when the shell function returns. We handle the name
  8607. * "-" as a special case: it makes changes to "set +-options" local
  8608. * (options will be restored on return from the function).
  8609. */
  8610. static void
  8611. mklocal(char *name)
  8612. {
  8613. struct localvar *lvp;
  8614. struct var **vpp;
  8615. struct var *vp;
  8616. char *eq = strchr(name, '=');
  8617. INT_OFF;
  8618. /* Cater for duplicate "local". Examples:
  8619. * x=0; f() { local x=1; echo $x; local x; echo $x; }; f; echo $x
  8620. * x=0; f() { local x=1; echo $x; local x=2; echo $x; }; f; echo $x
  8621. */
  8622. lvp = localvar_stack->lv;
  8623. while (lvp) {
  8624. if (lvp->vp && varcmp(lvp->vp->var_text, name) == 0) {
  8625. if (eq)
  8626. setvareq(name, 0);
  8627. /* else:
  8628. * it's a duplicate "local VAR" declaration, do nothing
  8629. */
  8630. goto ret;
  8631. }
  8632. lvp = lvp->next;
  8633. }
  8634. lvp = ckzalloc(sizeof(*lvp));
  8635. if (LONE_DASH(name)) {
  8636. char *p;
  8637. p = ckmalloc(sizeof(optlist));
  8638. lvp->text = memcpy(p, optlist, sizeof(optlist));
  8639. vp = NULL;
  8640. } else {
  8641. vpp = hashvar(name);
  8642. vp = *findvar(vpp, name);
  8643. if (vp == NULL) {
  8644. /* variable did not exist yet */
  8645. if (eq)
  8646. vp = setvareq(name, VSTRFIXED);
  8647. else
  8648. vp = setvar(name, NULL, VSTRFIXED);
  8649. lvp->flags = VUNSET;
  8650. } else {
  8651. lvp->text = vp->var_text;
  8652. lvp->flags = vp->flags;
  8653. /* make sure neither "struct var" nor string gets freed
  8654. * during (un)setting:
  8655. */
  8656. vp->flags |= VSTRFIXED|VTEXTFIXED;
  8657. if (eq)
  8658. setvareq(name, 0);
  8659. else
  8660. /* "local VAR" unsets VAR: */
  8661. setvar0(name, NULL);
  8662. }
  8663. }
  8664. lvp->vp = vp;
  8665. lvp->next = localvar_stack->lv;
  8666. localvar_stack->lv = lvp;
  8667. ret:
  8668. INT_ON;
  8669. }
  8670. /*
  8671. * The "local" command.
  8672. */
  8673. static int FAST_FUNC
  8674. localcmd(int argc UNUSED_PARAM, char **argv)
  8675. {
  8676. char *name;
  8677. if (!localvar_stack)
  8678. ash_msg_and_raise_error("not in a function");
  8679. argv = argptr;
  8680. while ((name = *argv++) != NULL) {
  8681. mklocal(name);
  8682. }
  8683. return 0;
  8684. }
  8685. static int FAST_FUNC
  8686. falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  8687. {
  8688. return 1;
  8689. }
  8690. static int FAST_FUNC
  8691. truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  8692. {
  8693. return 0;
  8694. }
  8695. static int FAST_FUNC
  8696. execcmd(int argc UNUSED_PARAM, char **argv)
  8697. {
  8698. optionarg = NULL;
  8699. while (nextopt("a:") != '\0')
  8700. /* nextopt() sets optionarg to "-a ARGV0" */;
  8701. argv = argptr;
  8702. if (argv[0]) {
  8703. char *prog;
  8704. iflag = 0; /* exit on error */
  8705. mflag = 0;
  8706. optschanged();
  8707. /* We should set up signals for "exec CMD"
  8708. * the same way as for "CMD" without "exec".
  8709. * But optschanged->setinteractive->setsignal
  8710. * still thought we are a root shell. Therefore, for example,
  8711. * SIGQUIT is still set to IGN. Fix it:
  8712. */
  8713. shlvl++;
  8714. setsignal(SIGQUIT);
  8715. /*setsignal(SIGTERM); - unnecessary because of iflag=0 */
  8716. /*setsignal(SIGTSTP); - unnecessary because of mflag=0 */
  8717. /*setsignal(SIGTTOU); - unnecessary because of mflag=0 */
  8718. prog = argv[0];
  8719. if (optionarg)
  8720. argv[0] = optionarg;
  8721. shellexec(prog, argv, pathval(), 0);
  8722. /* NOTREACHED */
  8723. }
  8724. return 0;
  8725. }
  8726. /*
  8727. * The return command.
  8728. */
  8729. static int FAST_FUNC
  8730. returncmd(int argc UNUSED_PARAM, char **argv)
  8731. {
  8732. /*
  8733. * If called outside a function, do what ksh does;
  8734. * skip the rest of the file.
  8735. */
  8736. evalskip = SKIPFUNC;
  8737. return argv[1] ? number(argv[1]) : exitstatus;
  8738. }
  8739. /* Forward declarations for builtintab[] */
  8740. static int breakcmd(int, char **) FAST_FUNC;
  8741. static int dotcmd(int, char **) FAST_FUNC;
  8742. static int evalcmd(int, char **, int) FAST_FUNC;
  8743. static int exitcmd(int, char **) FAST_FUNC;
  8744. static int exportcmd(int, char **) FAST_FUNC;
  8745. #if ENABLE_ASH_GETOPTS
  8746. static int getoptscmd(int, char **) FAST_FUNC;
  8747. #endif
  8748. #if ENABLE_ASH_HELP
  8749. static int helpcmd(int, char **) FAST_FUNC;
  8750. #endif
  8751. #if MAX_HISTORY
  8752. static int historycmd(int, char **) FAST_FUNC;
  8753. #endif
  8754. #if ENABLE_FEATURE_SH_MATH
  8755. static int letcmd(int, char **) FAST_FUNC;
  8756. #endif
  8757. static int readcmd(int, char **) FAST_FUNC;
  8758. static int setcmd(int, char **) FAST_FUNC;
  8759. static int shiftcmd(int, char **) FAST_FUNC;
  8760. static int timescmd(int, char **) FAST_FUNC;
  8761. static int trapcmd(int, char **) FAST_FUNC;
  8762. static int umaskcmd(int, char **) FAST_FUNC;
  8763. static int unsetcmd(int, char **) FAST_FUNC;
  8764. static int ulimitcmd(int, char **) FAST_FUNC;
  8765. #define BUILTIN_NOSPEC "0"
  8766. #define BUILTIN_SPECIAL "1"
  8767. #define BUILTIN_REGULAR "2"
  8768. #define BUILTIN_SPEC_REG "3"
  8769. #define BUILTIN_ASSIGN "4"
  8770. #define BUILTIN_SPEC_ASSG "5"
  8771. #define BUILTIN_REG_ASSG "6"
  8772. #define BUILTIN_SPEC_REG_ASSG "7"
  8773. /* Stubs for calling non-FAST_FUNC's */
  8774. #if ENABLE_ASH_ECHO
  8775. static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
  8776. #endif
  8777. #if ENABLE_ASH_PRINTF
  8778. static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
  8779. #endif
  8780. #if ENABLE_ASH_TEST || BASH_TEST2
  8781. static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
  8782. #endif
  8783. /* Keep these in proper order since it is searched via bsearch() */
  8784. static const struct builtincmd builtintab[] = {
  8785. { BUILTIN_SPEC_REG "." , dotcmd },
  8786. { BUILTIN_SPEC_REG ":" , truecmd },
  8787. #if ENABLE_ASH_TEST
  8788. { BUILTIN_REGULAR "[" , testcmd },
  8789. #endif
  8790. #if BASH_TEST2
  8791. { BUILTIN_REGULAR "[[" , testcmd },
  8792. #endif
  8793. #if ENABLE_ASH_ALIAS
  8794. { BUILTIN_REG_ASSG "alias" , aliascmd },
  8795. #endif
  8796. #if JOBS
  8797. { BUILTIN_REGULAR "bg" , fg_bgcmd },
  8798. #endif
  8799. { BUILTIN_SPEC_REG "break" , breakcmd },
  8800. { BUILTIN_REGULAR "cd" , cdcmd },
  8801. { BUILTIN_NOSPEC "chdir" , cdcmd },
  8802. #if ENABLE_ASH_CMDCMD
  8803. { BUILTIN_REGULAR "command" , commandcmd },
  8804. #endif
  8805. { BUILTIN_SPEC_REG "continue", breakcmd },
  8806. #if ENABLE_ASH_ECHO
  8807. { BUILTIN_REGULAR "echo" , echocmd },
  8808. #endif
  8809. { BUILTIN_SPEC_REG "eval" , NULL }, /*evalcmd() has a differing prototype*/
  8810. { BUILTIN_SPEC_REG "exec" , execcmd },
  8811. { BUILTIN_SPEC_REG "exit" , exitcmd },
  8812. { BUILTIN_SPEC_REG_ASSG "export" , exportcmd },
  8813. { BUILTIN_REGULAR "false" , falsecmd },
  8814. #if JOBS
  8815. { BUILTIN_REGULAR "fg" , fg_bgcmd },
  8816. #endif
  8817. #if ENABLE_ASH_GETOPTS
  8818. { BUILTIN_REGULAR "getopts" , getoptscmd },
  8819. #endif
  8820. { BUILTIN_NOSPEC "hash" , hashcmd },
  8821. #if ENABLE_ASH_HELP
  8822. { BUILTIN_NOSPEC "help" , helpcmd },
  8823. #endif
  8824. #if MAX_HISTORY
  8825. { BUILTIN_NOSPEC "history" , historycmd },
  8826. #endif
  8827. #if JOBS
  8828. { BUILTIN_REGULAR "jobs" , jobscmd },
  8829. { BUILTIN_REGULAR "kill" , killcmd },
  8830. #endif
  8831. #if ENABLE_FEATURE_SH_MATH
  8832. { BUILTIN_NOSPEC "let" , letcmd },
  8833. #endif
  8834. { BUILTIN_SPEC_REG_ASSG "local" , localcmd },
  8835. #if ENABLE_ASH_PRINTF
  8836. { BUILTIN_REGULAR "printf" , printfcmd },
  8837. #endif
  8838. { BUILTIN_NOSPEC "pwd" , pwdcmd },
  8839. { BUILTIN_REGULAR "read" , readcmd },
  8840. { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
  8841. { BUILTIN_SPEC_REG "return" , returncmd },
  8842. { BUILTIN_SPEC_REG "set" , setcmd },
  8843. { BUILTIN_SPEC_REG "shift" , shiftcmd },
  8844. #if BASH_SOURCE
  8845. { BUILTIN_SPEC_REG "source" , dotcmd },
  8846. #endif
  8847. #if ENABLE_ASH_TEST
  8848. { BUILTIN_REGULAR "test" , testcmd },
  8849. #endif
  8850. { BUILTIN_SPEC_REG "times" , timescmd },
  8851. { BUILTIN_SPEC_REG "trap" , trapcmd },
  8852. { BUILTIN_REGULAR "true" , truecmd },
  8853. { BUILTIN_NOSPEC "type" , typecmd },
  8854. { BUILTIN_NOSPEC "ulimit" , ulimitcmd },
  8855. { BUILTIN_REGULAR "umask" , umaskcmd },
  8856. #if ENABLE_ASH_ALIAS
  8857. { BUILTIN_REGULAR "unalias" , unaliascmd },
  8858. #endif
  8859. { BUILTIN_SPEC_REG "unset" , unsetcmd },
  8860. { BUILTIN_REGULAR "wait" , waitcmd },
  8861. };
  8862. /* Should match the above table! */
  8863. #define COMMANDCMD (builtintab + \
  8864. /* . : */ 2 + \
  8865. /* [ */ 1 * ENABLE_ASH_TEST + \
  8866. /* [[ */ 1 * BASH_TEST2 + \
  8867. /* alias */ 1 * ENABLE_ASH_ALIAS + \
  8868. /* bg */ 1 * ENABLE_ASH_JOB_CONTROL + \
  8869. /* break cd cddir */ 3)
  8870. #define EVALCMD (COMMANDCMD + \
  8871. /* command */ 1 * ENABLE_ASH_CMDCMD + \
  8872. /* continue */ 1 + \
  8873. /* echo */ 1 * ENABLE_ASH_ECHO + \
  8874. 0)
  8875. #define EXECCMD (EVALCMD + \
  8876. /* eval */ 1)
  8877. /*
  8878. * Search the table of builtin commands.
  8879. */
  8880. static int
  8881. pstrcmp1(const void *a, const void *b)
  8882. {
  8883. return strcmp((char*)a, *(char**)b + 1);
  8884. }
  8885. static struct builtincmd *
  8886. find_builtin(const char *name)
  8887. {
  8888. struct builtincmd *bp;
  8889. bp = bsearch(
  8890. name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
  8891. pstrcmp1
  8892. );
  8893. return bp;
  8894. }
  8895. /*
  8896. * Execute a simple command.
  8897. */
  8898. static int
  8899. isassignment(const char *p)
  8900. {
  8901. const char *q = endofname(p);
  8902. if (p == q)
  8903. return 0;
  8904. return *q == '=';
  8905. }
  8906. static int FAST_FUNC
  8907. bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  8908. {
  8909. /* Preserve exitstatus of a previous possible redirection
  8910. * as POSIX mandates */
  8911. return back_exitstatus;
  8912. }
  8913. static int
  8914. evalcommand(union node *cmd, int flags)
  8915. {
  8916. static const struct builtincmd null_bltin = {
  8917. "\0\0", bltincmd /* why three NULs? */
  8918. };
  8919. struct localvar_list *localvar_stop;
  8920. struct redirtab *redir_stop;
  8921. struct stackmark smark;
  8922. union node *argp;
  8923. struct arglist arglist;
  8924. struct arglist varlist;
  8925. char **argv;
  8926. int argc;
  8927. const struct strlist *sp;
  8928. struct cmdentry cmdentry;
  8929. struct job *jp;
  8930. char *lastarg;
  8931. const char *path;
  8932. int spclbltin;
  8933. int status;
  8934. char **nargv;
  8935. smallint cmd_is_exec;
  8936. /* First expand the arguments. */
  8937. TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
  8938. setstackmark(&smark);
  8939. localvar_stop = pushlocalvars();
  8940. back_exitstatus = 0;
  8941. cmdentry.cmdtype = CMDBUILTIN;
  8942. cmdentry.u.cmd = &null_bltin;
  8943. varlist.lastp = &varlist.list;
  8944. *varlist.lastp = NULL;
  8945. arglist.lastp = &arglist.list;
  8946. *arglist.lastp = NULL;
  8947. argc = 0;
  8948. if (cmd->ncmd.args) {
  8949. struct builtincmd *bcmd;
  8950. smallint pseudovarflag;
  8951. bcmd = find_builtin(cmd->ncmd.args->narg.text);
  8952. pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
  8953. for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
  8954. struct strlist **spp;
  8955. spp = arglist.lastp;
  8956. if (pseudovarflag && isassignment(argp->narg.text))
  8957. expandarg(argp, &arglist, EXP_VARTILDE);
  8958. else
  8959. expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
  8960. for (sp = *spp; sp; sp = sp->next)
  8961. argc++;
  8962. }
  8963. }
  8964. /* Reserve one extra spot at the front for shellexec. */
  8965. nargv = stalloc(sizeof(char *) * (argc + 2));
  8966. argv = ++nargv;
  8967. for (sp = arglist.list; sp; sp = sp->next) {
  8968. TRACE(("evalcommand arg: %s\n", sp->text));
  8969. *nargv++ = sp->text;
  8970. }
  8971. *nargv = NULL;
  8972. lastarg = NULL;
  8973. if (iflag && funcnest == 0 && argc > 0)
  8974. lastarg = nargv[-1];
  8975. expredir(cmd->ncmd.redirect);
  8976. redir_stop = pushredir(cmd->ncmd.redirect);
  8977. preverrout_fd = 2;
  8978. if (BASH_XTRACEFD && xflag) {
  8979. /* NB: bash closes fd == $BASH_XTRACEFD when it is changed.
  8980. * we do not emulate this. We only use its value.
  8981. */
  8982. const char *xtracefd = lookupvar("BASH_XTRACEFD");
  8983. if (xtracefd && is_number(xtracefd))
  8984. preverrout_fd = atoi(xtracefd);
  8985. }
  8986. status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
  8987. path = vpath.var_text;
  8988. for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
  8989. struct strlist **spp;
  8990. char *p;
  8991. spp = varlist.lastp;
  8992. expandarg(argp, &varlist, EXP_VARTILDE);
  8993. mklocal((*spp)->text);
  8994. /*
  8995. * Modify the command lookup path, if a PATH= assignment
  8996. * is present
  8997. */
  8998. p = (*spp)->text;
  8999. if (varcmp(p, path) == 0)
  9000. path = p;
  9001. }
  9002. /* Print the command if xflag is set. */
  9003. if (xflag) {
  9004. const char *pfx = "";
  9005. fdprintf(preverrout_fd, "%s", expandstr(ps4val(), DQSYNTAX));
  9006. sp = varlist.list;
  9007. while (sp) {
  9008. char *varval = sp->text;
  9009. char *eq = strchrnul(varval, '=');
  9010. if (*eq)
  9011. eq++;
  9012. fdprintf(preverrout_fd, "%s%.*s%s",
  9013. pfx,
  9014. (int)(eq - varval), varval,
  9015. maybe_single_quote(eq)
  9016. );
  9017. sp = sp->next;
  9018. pfx = " ";
  9019. }
  9020. sp = arglist.list;
  9021. while (sp) {
  9022. fdprintf(preverrout_fd, "%s%s",
  9023. pfx,
  9024. /* always quote if matches reserved word: */
  9025. findkwd(sp->text)
  9026. ? single_quote(sp->text)
  9027. : maybe_single_quote(sp->text)
  9028. );
  9029. sp = sp->next;
  9030. pfx = " ";
  9031. }
  9032. safe_write(preverrout_fd, "\n", 1);
  9033. }
  9034. cmd_is_exec = 0;
  9035. spclbltin = -1;
  9036. /* Now locate the command. */
  9037. if (argc) {
  9038. int cmd_flag = DO_ERR;
  9039. #if ENABLE_ASH_CMDCMD
  9040. const char *oldpath = path + 5;
  9041. #endif
  9042. path += 5;
  9043. for (;;) {
  9044. find_command(argv[0], &cmdentry, cmd_flag, path);
  9045. if (cmdentry.cmdtype == CMDUNKNOWN) {
  9046. flush_stdout_stderr();
  9047. status = 127;
  9048. goto bail;
  9049. }
  9050. /* implement bltin and command here */
  9051. if (cmdentry.cmdtype != CMDBUILTIN)
  9052. break;
  9053. if (spclbltin < 0)
  9054. spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
  9055. if (cmdentry.u.cmd == EXECCMD)
  9056. cmd_is_exec = 1;
  9057. #if ENABLE_ASH_CMDCMD
  9058. if (cmdentry.u.cmd == COMMANDCMD) {
  9059. path = oldpath;
  9060. nargv = parse_command_args(argv, &path);
  9061. if (!nargv)
  9062. break;
  9063. /* It's "command [-p] PROG ARGS" (that is, no -Vv).
  9064. * nargv => "PROG". path is updated if -p.
  9065. */
  9066. argc -= nargv - argv;
  9067. argv = nargv;
  9068. cmd_flag |= DO_NOFUNC;
  9069. } else
  9070. #endif
  9071. break;
  9072. }
  9073. }
  9074. if (status) {
  9075. bail:
  9076. exitstatus = status;
  9077. /* We have a redirection error. */
  9078. if (spclbltin > 0)
  9079. raise_exception(EXERROR);
  9080. goto out;
  9081. }
  9082. /* Execute the command. */
  9083. switch (cmdentry.cmdtype) {
  9084. default: {
  9085. #if ENABLE_FEATURE_SH_NOFORK && NUM_APPLETS > 1
  9086. /* (1) BUG: if variables are set, we need to fork, or save/restore them
  9087. * around run_nofork_applet() call.
  9088. * (2) Should this check also be done in forkshell()?
  9089. * (perhaps it should, so that "VAR=VAL nofork" at least avoids exec...)
  9090. */
  9091. /* find_command() encodes applet_no as (-2 - applet_no) */
  9092. int applet_no = (- cmdentry.u.index - 2);
  9093. if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
  9094. char **sv_environ;
  9095. INT_OFF;
  9096. sv_environ = environ;
  9097. environ = listvars(VEXPORT, VUNSET, varlist.list, /*end:*/ NULL);
  9098. /*
  9099. * Run <applet>_main().
  9100. * Signals (^C) can't interrupt here.
  9101. * Otherwise we can mangle stdio or malloc internal state.
  9102. * This makes applets which can run for a long time
  9103. * and/or wait for user input ineligible for NOFORK:
  9104. * for example, "yes" or "rm" (rm -i waits for input).
  9105. */
  9106. status = run_nofork_applet(applet_no, argv);
  9107. environ = sv_environ;
  9108. /*
  9109. * Try enabling NOFORK for "yes" applet.
  9110. * ^C _will_ stop it (write returns EINTR),
  9111. * but this causes stdout FILE to be stuck
  9112. * and needing clearerr(). What if other applets
  9113. * also can get EINTRs? Do we need to switch
  9114. * our signals to SA_RESTART?
  9115. */
  9116. /*clearerr(stdout);*/
  9117. INT_ON;
  9118. break;
  9119. }
  9120. #endif
  9121. /* Can we avoid forking? For example, very last command
  9122. * in a script or a subshell does not need forking,
  9123. * we can just exec it.
  9124. */
  9125. if (!(flags & EV_EXIT) || may_have_traps) {
  9126. /* No, forking off a child is necessary */
  9127. INT_OFF;
  9128. get_tty_state();
  9129. jp = makejob(/*cmd,*/ 1);
  9130. if (forkshell(jp, cmd, FORK_FG) != 0) {
  9131. /* parent */
  9132. status = waitforjob(jp);
  9133. INT_ON;
  9134. TRACE(("forked child exited with %d\n", status));
  9135. break;
  9136. }
  9137. /* child */
  9138. FORCE_INT_ON;
  9139. /* fall through to exec'ing external program */
  9140. }
  9141. listsetvar(varlist.list, VEXPORT|VSTACK);
  9142. shellexec(argv[0], argv, path, cmdentry.u.index);
  9143. /* NOTREACHED */
  9144. } /* default */
  9145. case CMDBUILTIN:
  9146. if (spclbltin > 0 || argc == 0) {
  9147. poplocalvars(1);
  9148. if (cmd_is_exec && argc > 1)
  9149. listsetvar(varlist.list, VEXPORT);
  9150. }
  9151. /* Tight loop with builtins only:
  9152. * "while kill -0 $child; do true; done"
  9153. * will never exit even if $child died, unless we do this
  9154. * to reap the zombie and make kill detect that it's gone: */
  9155. dowait(DOWAIT_NONBLOCK, NULL);
  9156. if (evalbltin(cmdentry.u.cmd, argc, argv, flags)) {
  9157. if (exception_type == EXERROR && spclbltin <= 0) {
  9158. FORCE_INT_ON;
  9159. goto readstatus;
  9160. }
  9161. raise:
  9162. longjmp(exception_handler->loc, 1);
  9163. }
  9164. goto readstatus;
  9165. case CMDFUNCTION:
  9166. poplocalvars(1);
  9167. /* See above for the rationale */
  9168. dowait(DOWAIT_NONBLOCK, NULL);
  9169. if (evalfun(cmdentry.u.func, argc, argv, flags))
  9170. goto raise;
  9171. readstatus:
  9172. status = exitstatus;
  9173. break;
  9174. } /* switch */
  9175. out:
  9176. if (cmd->ncmd.redirect)
  9177. popredir(/*drop:*/ cmd_is_exec);
  9178. unwindredir(redir_stop);
  9179. unwindlocalvars(localvar_stop);
  9180. if (lastarg) {
  9181. /* dsl: I think this is intended to be used to support
  9182. * '_' in 'vi' command mode during line editing...
  9183. * However I implemented that within libedit itself.
  9184. */
  9185. setvar0("_", lastarg);
  9186. }
  9187. popstackmark(&smark);
  9188. return status;
  9189. }
  9190. static int
  9191. evalbltin(const struct builtincmd *cmd, int argc, char **argv, int flags)
  9192. {
  9193. char *volatile savecmdname;
  9194. struct jmploc *volatile savehandler;
  9195. struct jmploc jmploc;
  9196. int status;
  9197. int i;
  9198. savecmdname = commandname;
  9199. savehandler = exception_handler;
  9200. i = setjmp(jmploc.loc);
  9201. if (i)
  9202. goto cmddone;
  9203. exception_handler = &jmploc;
  9204. commandname = argv[0];
  9205. argptr = argv + 1;
  9206. optptr = NULL; /* initialize nextopt */
  9207. if (cmd == EVALCMD)
  9208. status = evalcmd(argc, argv, flags);
  9209. else
  9210. status = (*cmd->builtin)(argc, argv);
  9211. flush_stdout_stderr();
  9212. status |= ferror(stdout);
  9213. exitstatus = status;
  9214. cmddone:
  9215. clearerr(stdout);
  9216. commandname = savecmdname;
  9217. exception_handler = savehandler;
  9218. return i;
  9219. }
  9220. static int
  9221. goodname(const char *p)
  9222. {
  9223. return endofname(p)[0] == '\0';
  9224. }
  9225. /*
  9226. * Search for a command. This is called before we fork so that the
  9227. * location of the command will be available in the parent as well as
  9228. * the child. The check for "goodname" is an overly conservative
  9229. * check that the name will not be subject to expansion.
  9230. */
  9231. static void
  9232. prehash(union node *n)
  9233. {
  9234. struct cmdentry entry;
  9235. if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
  9236. find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
  9237. }
  9238. /* ============ Builtin commands
  9239. *
  9240. * Builtin commands whose functions are closely tied to evaluation
  9241. * are implemented here.
  9242. */
  9243. /*
  9244. * Handle break and continue commands. Break, continue, and return are
  9245. * all handled by setting the evalskip flag. The evaluation routines
  9246. * above all check this flag, and if it is set they start skipping
  9247. * commands rather than executing them. The variable skipcount is
  9248. * the number of loops to break/continue, or the number of function
  9249. * levels to return. (The latter is always 1.) It should probably
  9250. * be an error to break out of more loops than exist, but it isn't
  9251. * in the standard shell so we don't make it one here.
  9252. */
  9253. static int FAST_FUNC
  9254. breakcmd(int argc UNUSED_PARAM, char **argv)
  9255. {
  9256. int n = argv[1] ? number(argv[1]) : 1;
  9257. if (n <= 0)
  9258. ash_msg_and_raise_error(msg_illnum, argv[1]);
  9259. if (n > loopnest)
  9260. n = loopnest;
  9261. if (n > 0) {
  9262. evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
  9263. skipcount = n;
  9264. }
  9265. return 0;
  9266. }
  9267. /*
  9268. * This implements the input routines used by the parser.
  9269. */
  9270. enum {
  9271. INPUT_PUSH_FILE = 1,
  9272. INPUT_NOFILE_OK = 2,
  9273. };
  9274. static smallint checkkwd;
  9275. /* values of checkkwd variable */
  9276. #define CHKALIAS 0x1
  9277. #define CHKKWD 0x2
  9278. #define CHKNL 0x4
  9279. #define CHKEOFMARK 0x8
  9280. /*
  9281. * Push a string back onto the input at this current parsefile level.
  9282. * We handle aliases this way.
  9283. */
  9284. #if !ENABLE_ASH_ALIAS
  9285. #define pushstring(s, ap) pushstring(s)
  9286. #endif
  9287. static void
  9288. pushstring(char *s, struct alias *ap)
  9289. {
  9290. struct strpush *sp;
  9291. int len;
  9292. len = strlen(s);
  9293. INT_OFF;
  9294. if (g_parsefile->strpush) {
  9295. sp = ckzalloc(sizeof(*sp));
  9296. sp->prev = g_parsefile->strpush;
  9297. } else {
  9298. sp = &(g_parsefile->basestrpush);
  9299. }
  9300. g_parsefile->strpush = sp;
  9301. sp->prev_string = g_parsefile->next_to_pgetc;
  9302. sp->prev_left_in_line = g_parsefile->left_in_line;
  9303. sp->unget = g_parsefile->unget;
  9304. memcpy(sp->lastc, g_parsefile->lastc, sizeof(sp->lastc));
  9305. #if ENABLE_ASH_ALIAS
  9306. sp->ap = ap;
  9307. if (ap) {
  9308. ap->flag |= ALIASINUSE;
  9309. sp->string = s;
  9310. }
  9311. #endif
  9312. g_parsefile->next_to_pgetc = s;
  9313. g_parsefile->left_in_line = len;
  9314. g_parsefile->unget = 0;
  9315. INT_ON;
  9316. }
  9317. static void
  9318. popstring(void)
  9319. {
  9320. struct strpush *sp = g_parsefile->strpush;
  9321. INT_OFF;
  9322. #if ENABLE_ASH_ALIAS
  9323. if (sp->ap) {
  9324. if (g_parsefile->next_to_pgetc[-1] == ' '
  9325. || g_parsefile->next_to_pgetc[-1] == '\t'
  9326. ) {
  9327. checkkwd |= CHKALIAS;
  9328. }
  9329. if (sp->string != sp->ap->val) {
  9330. free(sp->string);
  9331. }
  9332. sp->ap->flag &= ~ALIASINUSE;
  9333. if (sp->ap->flag & ALIASDEAD) {
  9334. unalias(sp->ap->name);
  9335. }
  9336. }
  9337. #endif
  9338. g_parsefile->next_to_pgetc = sp->prev_string;
  9339. g_parsefile->left_in_line = sp->prev_left_in_line;
  9340. g_parsefile->unget = sp->unget;
  9341. memcpy(g_parsefile->lastc, sp->lastc, sizeof(sp->lastc));
  9342. g_parsefile->strpush = sp->prev;
  9343. if (sp != &(g_parsefile->basestrpush))
  9344. free(sp);
  9345. INT_ON;
  9346. }
  9347. static int
  9348. preadfd(void)
  9349. {
  9350. int nr;
  9351. char *buf = g_parsefile->buf;
  9352. g_parsefile->next_to_pgetc = buf;
  9353. #if ENABLE_FEATURE_EDITING
  9354. retry:
  9355. if (!iflag || g_parsefile->pf_fd != STDIN_FILENO)
  9356. nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
  9357. else {
  9358. # if ENABLE_ASH_IDLE_TIMEOUT
  9359. int timeout = -1;
  9360. if (iflag) {
  9361. const char *tmout_var = lookupvar("TMOUT");
  9362. if (tmout_var) {
  9363. timeout = atoi(tmout_var) * 1000;
  9364. if (timeout <= 0)
  9365. timeout = -1;
  9366. }
  9367. }
  9368. line_input_state->timeout = timeout;
  9369. # endif
  9370. # if ENABLE_FEATURE_TAB_COMPLETION
  9371. line_input_state->path_lookup = pathval();
  9372. # endif
  9373. reinit_unicode_for_ash();
  9374. nr = read_line_input(line_input_state, cmdedit_prompt, buf, IBUFSIZ);
  9375. if (nr == 0) {
  9376. /* ^C pressed, "convert" to SIGINT */
  9377. write(STDOUT_FILENO, "^C", 2);
  9378. if (trap[SIGINT]) {
  9379. buf[0] = '\n';
  9380. buf[1] = '\0';
  9381. raise(SIGINT);
  9382. return 1;
  9383. }
  9384. exitstatus = 128 + SIGINT;
  9385. bb_putchar('\n');
  9386. goto retry;
  9387. }
  9388. if (nr < 0) {
  9389. if (errno == 0) {
  9390. /* Ctrl+D pressed */
  9391. nr = 0;
  9392. }
  9393. # if ENABLE_ASH_IDLE_TIMEOUT
  9394. else if (errno == EAGAIN && timeout > 0) {
  9395. puts("\007timed out waiting for input: auto-logout");
  9396. exitshell();
  9397. }
  9398. # endif
  9399. }
  9400. }
  9401. #else
  9402. nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
  9403. #endif
  9404. #if 0 /* disabled: nonblock_immune_read() handles this problem */
  9405. if (nr < 0) {
  9406. if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
  9407. int flags = fcntl(0, F_GETFL);
  9408. if (flags >= 0 && (flags & O_NONBLOCK)) {
  9409. flags &= ~O_NONBLOCK;
  9410. if (fcntl(0, F_SETFL, flags) >= 0) {
  9411. out2str("sh: turning off NDELAY mode\n");
  9412. goto retry;
  9413. }
  9414. }
  9415. }
  9416. }
  9417. #endif
  9418. return nr;
  9419. }
  9420. /*
  9421. * Refill the input buffer and return the next input character:
  9422. *
  9423. * 1) If a string was pushed back on the input, pop it;
  9424. * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
  9425. * or we are reading from a string so we can't refill the buffer,
  9426. * return EOF.
  9427. * 3) If there is more stuff in this buffer, use it else call read to fill it.
  9428. * 4) Process input up to the next newline, deleting nul characters.
  9429. */
  9430. //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
  9431. #define pgetc_debug(...) ((void)0)
  9432. static int pgetc(void);
  9433. static int
  9434. preadbuffer(void)
  9435. {
  9436. char *q;
  9437. int more;
  9438. if (g_parsefile->strpush) {
  9439. #if ENABLE_ASH_ALIAS
  9440. if (g_parsefile->left_in_line == -1
  9441. && g_parsefile->strpush->ap
  9442. && g_parsefile->next_to_pgetc[-1] != ' '
  9443. && g_parsefile->next_to_pgetc[-1] != '\t'
  9444. ) {
  9445. pgetc_debug("preadbuffer PEOA");
  9446. return PEOA;
  9447. }
  9448. #endif
  9449. popstring();
  9450. return pgetc();
  9451. }
  9452. /* on both branches above g_parsefile->left_in_line < 0.
  9453. * "pgetc" needs refilling.
  9454. */
  9455. /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
  9456. * pungetc() may increment it a few times.
  9457. * Assuming it won't increment it to less than -90.
  9458. */
  9459. if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
  9460. pgetc_debug("preadbuffer PEOF1");
  9461. /* even in failure keep left_in_line and next_to_pgetc
  9462. * in lock step, for correct multi-layer pungetc.
  9463. * left_in_line was decremented before preadbuffer(),
  9464. * must inc next_to_pgetc: */
  9465. g_parsefile->next_to_pgetc++;
  9466. return PEOF;
  9467. }
  9468. more = g_parsefile->left_in_buffer;
  9469. if (more <= 0) {
  9470. flush_stdout_stderr();
  9471. again:
  9472. more = preadfd();
  9473. if (more <= 0) {
  9474. /* don't try reading again */
  9475. g_parsefile->left_in_line = -99;
  9476. pgetc_debug("preadbuffer PEOF2");
  9477. g_parsefile->next_to_pgetc++;
  9478. return PEOF;
  9479. }
  9480. }
  9481. /* Find out where's the end of line.
  9482. * Set g_parsefile->left_in_line
  9483. * and g_parsefile->left_in_buffer acordingly.
  9484. * NUL chars are deleted.
  9485. */
  9486. q = g_parsefile->next_to_pgetc;
  9487. for (;;) {
  9488. char c;
  9489. more--;
  9490. c = *q;
  9491. if (c == '\0') {
  9492. memmove(q, q + 1, more);
  9493. } else {
  9494. q++;
  9495. if (c == '\n') {
  9496. g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
  9497. break;
  9498. }
  9499. }
  9500. if (more <= 0) {
  9501. g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
  9502. if (g_parsefile->left_in_line < 0)
  9503. goto again;
  9504. break;
  9505. }
  9506. }
  9507. g_parsefile->left_in_buffer = more;
  9508. if (vflag) {
  9509. char save = *q;
  9510. *q = '\0';
  9511. out2str(g_parsefile->next_to_pgetc);
  9512. *q = save;
  9513. }
  9514. pgetc_debug("preadbuffer at %d:%p'%s'",
  9515. g_parsefile->left_in_line,
  9516. g_parsefile->next_to_pgetc,
  9517. g_parsefile->next_to_pgetc);
  9518. return (unsigned char)*g_parsefile->next_to_pgetc++;
  9519. }
  9520. static void
  9521. nlprompt(void)
  9522. {
  9523. g_parsefile->linno++;
  9524. setprompt_if(doprompt, 2);
  9525. }
  9526. static void
  9527. nlnoprompt(void)
  9528. {
  9529. g_parsefile->linno++;
  9530. needprompt = doprompt;
  9531. }
  9532. static int
  9533. pgetc(void)
  9534. {
  9535. int c;
  9536. pgetc_debug("pgetc at %d:%p'%s'",
  9537. g_parsefile->left_in_line,
  9538. g_parsefile->next_to_pgetc,
  9539. g_parsefile->next_to_pgetc);
  9540. if (g_parsefile->unget)
  9541. return g_parsefile->lastc[--g_parsefile->unget];
  9542. if (--g_parsefile->left_in_line >= 0)
  9543. c = (unsigned char)*g_parsefile->next_to_pgetc++;
  9544. else
  9545. c = preadbuffer();
  9546. g_parsefile->lastc[1] = g_parsefile->lastc[0];
  9547. g_parsefile->lastc[0] = c;
  9548. return c;
  9549. }
  9550. #if ENABLE_ASH_ALIAS
  9551. static int
  9552. pgetc_without_PEOA(void)
  9553. {
  9554. int c;
  9555. do {
  9556. pgetc_debug("pgetc at %d:%p'%s'",
  9557. g_parsefile->left_in_line,
  9558. g_parsefile->next_to_pgetc,
  9559. g_parsefile->next_to_pgetc);
  9560. c = pgetc();
  9561. } while (c == PEOA);
  9562. return c;
  9563. }
  9564. #else
  9565. # define pgetc_without_PEOA() pgetc()
  9566. #endif
  9567. /*
  9568. * Undo a call to pgetc. Only two characters may be pushed back.
  9569. * PEOF may be pushed back.
  9570. */
  9571. static void
  9572. pungetc(void)
  9573. {
  9574. g_parsefile->unget++;
  9575. }
  9576. /* This one eats backslash+newline */
  9577. static int
  9578. pgetc_eatbnl(void)
  9579. {
  9580. int c;
  9581. while ((c = pgetc()) == '\\') {
  9582. if (pgetc() != '\n') {
  9583. pungetc();
  9584. break;
  9585. }
  9586. nlprompt();
  9587. }
  9588. return c;
  9589. }
  9590. /*
  9591. * To handle the "." command, a stack of input files is used. Pushfile
  9592. * adds a new entry to the stack and popfile restores the previous level.
  9593. */
  9594. static void
  9595. pushfile(void)
  9596. {
  9597. struct parsefile *pf;
  9598. pf = ckzalloc(sizeof(*pf));
  9599. pf->prev = g_parsefile;
  9600. pf->pf_fd = -1;
  9601. /*pf->strpush = NULL; - ckzalloc did it */
  9602. /*pf->basestrpush.prev = NULL;*/
  9603. /*pf->unget = 0;*/
  9604. g_parsefile = pf;
  9605. }
  9606. static void
  9607. popfile(void)
  9608. {
  9609. struct parsefile *pf = g_parsefile;
  9610. if (pf == &basepf)
  9611. return;
  9612. INT_OFF;
  9613. if (pf->pf_fd >= 0)
  9614. close(pf->pf_fd);
  9615. free(pf->buf);
  9616. while (pf->strpush)
  9617. popstring();
  9618. g_parsefile = pf->prev;
  9619. free(pf);
  9620. INT_ON;
  9621. }
  9622. /*
  9623. * Return to top level.
  9624. */
  9625. static void
  9626. popallfiles(void)
  9627. {
  9628. while (g_parsefile != &basepf)
  9629. popfile();
  9630. }
  9631. /*
  9632. * Close the file(s) that the shell is reading commands from. Called
  9633. * after a fork is done.
  9634. */
  9635. static void
  9636. closescript(void)
  9637. {
  9638. popallfiles();
  9639. if (g_parsefile->pf_fd > 0) {
  9640. close(g_parsefile->pf_fd);
  9641. g_parsefile->pf_fd = 0;
  9642. }
  9643. }
  9644. /*
  9645. * Like setinputfile, but takes an open file descriptor. Call this with
  9646. * interrupts off.
  9647. */
  9648. static void
  9649. setinputfd(int fd, int push)
  9650. {
  9651. if (push) {
  9652. pushfile();
  9653. g_parsefile->buf = NULL;
  9654. }
  9655. g_parsefile->pf_fd = fd;
  9656. if (g_parsefile->buf == NULL)
  9657. g_parsefile->buf = ckmalloc(IBUFSIZ);
  9658. g_parsefile->left_in_buffer = 0;
  9659. g_parsefile->left_in_line = 0;
  9660. g_parsefile->linno = 1;
  9661. }
  9662. /*
  9663. * Set the input to take input from a file. If push is set, push the
  9664. * old input onto the stack first.
  9665. */
  9666. static int
  9667. setinputfile(const char *fname, int flags)
  9668. {
  9669. int fd;
  9670. INT_OFF;
  9671. fd = open(fname, O_RDONLY);
  9672. if (fd < 0) {
  9673. if (flags & INPUT_NOFILE_OK)
  9674. goto out;
  9675. exitstatus = 127;
  9676. ash_msg_and_raise_perror("can't open '%s'", fname);
  9677. }
  9678. if (fd < 10)
  9679. fd = savefd(fd);
  9680. else
  9681. close_on_exec_on(fd);
  9682. setinputfd(fd, flags & INPUT_PUSH_FILE);
  9683. out:
  9684. INT_ON;
  9685. return fd;
  9686. }
  9687. /*
  9688. * Like setinputfile, but takes input from a string.
  9689. */
  9690. static void
  9691. setinputstring(char *string)
  9692. {
  9693. INT_OFF;
  9694. pushfile();
  9695. g_parsefile->next_to_pgetc = string;
  9696. g_parsefile->left_in_line = strlen(string);
  9697. g_parsefile->buf = NULL;
  9698. g_parsefile->linno = 1;
  9699. INT_ON;
  9700. }
  9701. /*
  9702. * Routines to check for mail.
  9703. */
  9704. #if ENABLE_ASH_MAIL
  9705. /* Hash of mtimes of mailboxes */
  9706. static unsigned mailtime_hash;
  9707. /* Set if MAIL or MAILPATH is changed. */
  9708. static smallint mail_var_path_changed;
  9709. /*
  9710. * Print appropriate message(s) if mail has arrived.
  9711. * If mail_var_path_changed is set,
  9712. * then the value of MAIL has mail_var_path_changed,
  9713. * so we just update the values.
  9714. */
  9715. static void
  9716. chkmail(void)
  9717. {
  9718. const char *mpath;
  9719. char *p;
  9720. char *q;
  9721. unsigned new_hash;
  9722. struct stackmark smark;
  9723. struct stat statb;
  9724. setstackmark(&smark);
  9725. mpath = mpathset() ? mpathval() : mailval();
  9726. new_hash = 0;
  9727. for (;;) {
  9728. p = path_advance(&mpath, nullstr);
  9729. if (p == NULL)
  9730. break;
  9731. if (*p == '\0')
  9732. continue;
  9733. for (q = p; *q; q++)
  9734. continue;
  9735. #if DEBUG
  9736. if (q[-1] != '/')
  9737. abort();
  9738. #endif
  9739. q[-1] = '\0'; /* delete trailing '/' */
  9740. if (stat(p, &statb) < 0) {
  9741. continue;
  9742. }
  9743. /* Very simplistic "hash": just a sum of all mtimes */
  9744. new_hash += (unsigned)statb.st_mtime;
  9745. }
  9746. if (!mail_var_path_changed && mailtime_hash != new_hash) {
  9747. if (mailtime_hash != 0)
  9748. out2str("you have mail\n");
  9749. mailtime_hash = new_hash;
  9750. }
  9751. mail_var_path_changed = 0;
  9752. popstackmark(&smark);
  9753. }
  9754. static void FAST_FUNC
  9755. changemail(const char *val UNUSED_PARAM)
  9756. {
  9757. mail_var_path_changed = 1;
  9758. }
  9759. #endif /* ASH_MAIL */
  9760. /* ============ ??? */
  9761. /*
  9762. * Set the shell parameters.
  9763. */
  9764. static void
  9765. setparam(char **argv)
  9766. {
  9767. char **newparam;
  9768. char **ap;
  9769. int nparam;
  9770. for (nparam = 0; argv[nparam]; nparam++)
  9771. continue;
  9772. ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
  9773. while (*argv) {
  9774. *ap++ = ckstrdup(*argv++);
  9775. }
  9776. *ap = NULL;
  9777. freeparam(&shellparam);
  9778. shellparam.malloced = 1;
  9779. shellparam.nparam = nparam;
  9780. shellparam.p = newparam;
  9781. #if ENABLE_ASH_GETOPTS
  9782. shellparam.optind = 1;
  9783. shellparam.optoff = -1;
  9784. #endif
  9785. }
  9786. /*
  9787. * Process shell options. The global variable argptr contains a pointer
  9788. * to the argument list; we advance it past the options.
  9789. *
  9790. * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
  9791. * For a non-interactive shell, an error condition encountered
  9792. * by a special built-in ... shall cause the shell to write a diagnostic message
  9793. * to standard error and exit as shown in the following table:
  9794. * Error Special Built-In
  9795. * ...
  9796. * Utility syntax error (option or operand error) Shall exit
  9797. * ...
  9798. * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
  9799. * we see that bash does not do that (set "finishes" with error code 1 instead,
  9800. * and shell continues), and people rely on this behavior!
  9801. * Testcase:
  9802. * set -o barfoo 2>/dev/null
  9803. * echo $?
  9804. *
  9805. * Oh well. Let's mimic that.
  9806. */
  9807. static int
  9808. plus_minus_o(char *name, int val)
  9809. {
  9810. int i;
  9811. if (name) {
  9812. for (i = 0; i < NOPTS; i++) {
  9813. if (strcmp(name, optnames(i)) == 0) {
  9814. optlist[i] = val;
  9815. return 0;
  9816. }
  9817. }
  9818. ash_msg("illegal option %co %s", val ? '-' : '+', name);
  9819. return 1;
  9820. }
  9821. for (i = 0; i < NOPTS; i++) {
  9822. if (val) {
  9823. out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
  9824. } else {
  9825. out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
  9826. }
  9827. }
  9828. return 0;
  9829. }
  9830. static void
  9831. setoption(int flag, int val)
  9832. {
  9833. int i;
  9834. for (i = 0; i < NOPTS; i++) {
  9835. if (optletters(i) == flag) {
  9836. optlist[i] = val;
  9837. return;
  9838. }
  9839. }
  9840. ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
  9841. /* NOTREACHED */
  9842. }
  9843. static int
  9844. options(int cmdline, int *login_sh)
  9845. {
  9846. char *p;
  9847. int val;
  9848. int c;
  9849. if (cmdline)
  9850. minusc = NULL;
  9851. while ((p = *argptr) != NULL) {
  9852. c = *p++;
  9853. if (c != '-' && c != '+')
  9854. break;
  9855. argptr++;
  9856. val = 0; /* val = 0 if c == '+' */
  9857. if (c == '-') {
  9858. val = 1;
  9859. if (p[0] == '\0' || LONE_DASH(p)) {
  9860. if (!cmdline) {
  9861. /* "-" means turn off -x and -v */
  9862. if (p[0] == '\0')
  9863. xflag = vflag = 0;
  9864. /* "--" means reset params */
  9865. else if (*argptr == NULL)
  9866. setparam(argptr);
  9867. }
  9868. break; /* "-" or "--" terminates options */
  9869. }
  9870. }
  9871. /* first char was + or - */
  9872. while ((c = *p++) != '\0') {
  9873. /* bash 3.2 indeed handles -c CMD and +c CMD the same */
  9874. if (c == 'c' && cmdline) {
  9875. minusc = p; /* command is after shell args */
  9876. } else if (c == 'o') {
  9877. if (plus_minus_o(*argptr, val)) {
  9878. /* it already printed err message */
  9879. return 1; /* error */
  9880. }
  9881. if (*argptr)
  9882. argptr++;
  9883. } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
  9884. if (login_sh)
  9885. *login_sh = 1;
  9886. /* bash does not accept +-login, we also won't */
  9887. } else if (cmdline && val && (c == '-')) { /* long options */
  9888. if (strcmp(p, "login") == 0) {
  9889. if (login_sh)
  9890. *login_sh = 1;
  9891. }
  9892. break;
  9893. } else {
  9894. setoption(c, val);
  9895. }
  9896. }
  9897. }
  9898. return 0;
  9899. }
  9900. /*
  9901. * The shift builtin command.
  9902. */
  9903. static int FAST_FUNC
  9904. shiftcmd(int argc UNUSED_PARAM, char **argv)
  9905. {
  9906. int n;
  9907. char **ap1, **ap2;
  9908. n = 1;
  9909. if (argv[1])
  9910. n = number(argv[1]);
  9911. if (n > shellparam.nparam)
  9912. return 1;
  9913. INT_OFF;
  9914. shellparam.nparam -= n;
  9915. for (ap1 = shellparam.p; --n >= 0; ap1++) {
  9916. if (shellparam.malloced)
  9917. free(*ap1);
  9918. }
  9919. ap2 = shellparam.p;
  9920. while ((*ap2++ = *ap1++) != NULL)
  9921. continue;
  9922. #if ENABLE_ASH_GETOPTS
  9923. shellparam.optind = 1;
  9924. shellparam.optoff = -1;
  9925. #endif
  9926. INT_ON;
  9927. return 0;
  9928. }
  9929. /*
  9930. * POSIX requires that 'set' (but not export or readonly) output the
  9931. * variables in lexicographic order - by the locale's collating order (sigh).
  9932. * Maybe we could keep them in an ordered balanced binary tree
  9933. * instead of hashed lists.
  9934. * For now just roll 'em through qsort for printing...
  9935. */
  9936. static int
  9937. showvars(const char *sep_prefix, int on, int off)
  9938. {
  9939. const char *sep;
  9940. char **ep, **epend;
  9941. ep = listvars(on, off, /*strlist:*/ NULL, &epend);
  9942. qsort(ep, epend - ep, sizeof(char *), vpcmp);
  9943. sep = *sep_prefix ? " " : sep_prefix;
  9944. for (; ep < epend; ep++) {
  9945. const char *p;
  9946. const char *q;
  9947. p = endofname(*ep);
  9948. /* Used to have simple "p = strchrnul(*ep, '=')" here instead, but this
  9949. * makes "export -p" to have output not suitable for "eval":
  9950. * import os
  9951. * os.environ["test-test"]="test"
  9952. * if os.fork() == 0:
  9953. * os.execv("ash", [ 'ash', '-c', 'eval $(export -p); echo OK' ]) # fixes this
  9954. * os.execv("ash", [ 'ash', '-c', 'env | grep test-test' ])
  9955. */
  9956. q = nullstr;
  9957. if (*p == '=')
  9958. q = single_quote(++p);
  9959. out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
  9960. }
  9961. return 0;
  9962. }
  9963. /*
  9964. * The set command builtin.
  9965. */
  9966. static int FAST_FUNC
  9967. setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  9968. {
  9969. int retval;
  9970. if (!argv[1])
  9971. return showvars(nullstr, 0, VUNSET);
  9972. INT_OFF;
  9973. retval = options(/*cmdline:*/ 0, NULL);
  9974. if (retval == 0) { /* if no parse error... */
  9975. optschanged();
  9976. if (*argptr != NULL) {
  9977. setparam(argptr);
  9978. }
  9979. }
  9980. INT_ON;
  9981. return retval;
  9982. }
  9983. #if ENABLE_ASH_RANDOM_SUPPORT
  9984. static void FAST_FUNC
  9985. change_random(const char *value)
  9986. {
  9987. uint32_t t;
  9988. if (value == NULL) {
  9989. /* "get", generate */
  9990. t = next_random(&random_gen);
  9991. /* set without recursion */
  9992. setvar(vrandom.var_text, utoa(t), VNOFUNC);
  9993. vrandom.flags &= ~VNOFUNC;
  9994. } else {
  9995. /* set/reset */
  9996. t = strtoul(value, NULL, 10);
  9997. INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
  9998. }
  9999. }
  10000. #endif
  10001. #if ENABLE_ASH_GETOPTS
  10002. static int
  10003. getopts(char *optstr, char *optvar, char **optfirst)
  10004. {
  10005. char *p, *q;
  10006. char c = '?';
  10007. int done = 0;
  10008. char sbuf[2];
  10009. char **optnext;
  10010. int ind = shellparam.optind;
  10011. int off = shellparam.optoff;
  10012. sbuf[1] = '\0';
  10013. shellparam.optind = -1;
  10014. optnext = optfirst + ind - 1;
  10015. if (ind <= 1 || off < 0 || (int)strlen(optnext[-1]) < off)
  10016. p = NULL;
  10017. else
  10018. p = optnext[-1] + off;
  10019. if (p == NULL || *p == '\0') {
  10020. /* Current word is done, advance */
  10021. p = *optnext;
  10022. if (p == NULL || *p != '-' || *++p == '\0') {
  10023. atend:
  10024. unsetvar("OPTARG");
  10025. p = NULL;
  10026. done = 1;
  10027. goto out;
  10028. }
  10029. optnext++;
  10030. if (LONE_DASH(p)) /* check for "--" */
  10031. goto atend;
  10032. }
  10033. c = *p++;
  10034. for (q = optstr; *q != c;) {
  10035. if (*q == '\0') {
  10036. /* OPTERR is a bashism */
  10037. const char *cp = lookupvar("OPTERR");
  10038. if ((cp && LONE_CHAR(cp, '0'))
  10039. || (optstr[0] == ':')
  10040. ) {
  10041. sbuf[0] = c;
  10042. /*sbuf[1] = '\0'; - already is */
  10043. setvar0("OPTARG", sbuf);
  10044. } else {
  10045. fprintf(stderr, "Illegal option -%c\n", c);
  10046. unsetvar("OPTARG");
  10047. }
  10048. c = '?';
  10049. goto out;
  10050. }
  10051. if (*++q == ':')
  10052. q++;
  10053. }
  10054. if (*++q == ':') {
  10055. if (*p == '\0' && (p = *optnext) == NULL) {
  10056. /* OPTERR is a bashism */
  10057. const char *cp = lookupvar("OPTERR");
  10058. if ((cp && LONE_CHAR(cp, '0'))
  10059. || (optstr[0] == ':')
  10060. ) {
  10061. sbuf[0] = c;
  10062. /*sbuf[1] = '\0'; - already is */
  10063. setvar0("OPTARG", sbuf);
  10064. c = ':';
  10065. } else {
  10066. fprintf(stderr, "No arg for -%c option\n", c);
  10067. unsetvar("OPTARG");
  10068. c = '?';
  10069. }
  10070. goto out;
  10071. }
  10072. if (p == *optnext)
  10073. optnext++;
  10074. setvar0("OPTARG", p);
  10075. p = NULL;
  10076. } else
  10077. setvar0("OPTARG", nullstr);
  10078. out:
  10079. ind = optnext - optfirst + 1;
  10080. setvar("OPTIND", itoa(ind), VNOFUNC);
  10081. sbuf[0] = c;
  10082. /*sbuf[1] = '\0'; - already is */
  10083. setvar0(optvar, sbuf);
  10084. shellparam.optoff = p ? p - *(optnext - 1) : -1;
  10085. shellparam.optind = ind;
  10086. return done;
  10087. }
  10088. /*
  10089. * The getopts builtin. Shellparam.optnext points to the next argument
  10090. * to be processed. Shellparam.optptr points to the next character to
  10091. * be processed in the current argument. If shellparam.optnext is NULL,
  10092. * then it's the first time getopts has been called.
  10093. */
  10094. static int FAST_FUNC
  10095. getoptscmd(int argc, char **argv)
  10096. {
  10097. char **optbase;
  10098. if (argc < 3)
  10099. ash_msg_and_raise_error("usage: getopts optstring var [arg]");
  10100. if (argc == 3) {
  10101. optbase = shellparam.p;
  10102. if ((unsigned)shellparam.optind > shellparam.nparam + 1) {
  10103. shellparam.optind = 1;
  10104. shellparam.optoff = -1;
  10105. }
  10106. } else {
  10107. optbase = &argv[3];
  10108. if ((unsigned)shellparam.optind > argc - 2) {
  10109. shellparam.optind = 1;
  10110. shellparam.optoff = -1;
  10111. }
  10112. }
  10113. return getopts(argv[1], argv[2], optbase);
  10114. }
  10115. #endif /* ASH_GETOPTS */
  10116. /* ============ Shell parser */
  10117. struct heredoc {
  10118. struct heredoc *next; /* next here document in list */
  10119. union node *here; /* redirection node */
  10120. char *eofmark; /* string indicating end of input */
  10121. smallint striptabs; /* if set, strip leading tabs */
  10122. };
  10123. static smallint tokpushback; /* last token pushed back */
  10124. static smallint quoteflag; /* set if (part of) last token was quoted */
  10125. static token_id_t lasttoken; /* last token read (integer id Txxx) */
  10126. static struct heredoc *heredoclist; /* list of here documents to read */
  10127. static char *wordtext; /* text of last word returned by readtoken */
  10128. static struct nodelist *backquotelist;
  10129. static union node *redirnode;
  10130. static struct heredoc *heredoc;
  10131. static const char *
  10132. tokname(char *buf, int tok)
  10133. {
  10134. if (tok < TSEMI)
  10135. return tokname_array[tok];
  10136. sprintf(buf, "\"%s\"", tokname_array[tok]);
  10137. return buf;
  10138. }
  10139. /* raise_error_unexpected_syntax:
  10140. * Called when an unexpected token is read during the parse. The argument
  10141. * is the token that is expected, or -1 if more than one type of token can
  10142. * occur at this point.
  10143. */
  10144. static void raise_error_unexpected_syntax(int) NORETURN;
  10145. static void
  10146. raise_error_unexpected_syntax(int token)
  10147. {
  10148. char msg[64];
  10149. char buf[16];
  10150. int l;
  10151. l = sprintf(msg, "unexpected %s", tokname(buf, lasttoken));
  10152. if (token >= 0)
  10153. sprintf(msg + l, " (expecting %s)", tokname(buf, token));
  10154. raise_error_syntax(msg);
  10155. /* NOTREACHED */
  10156. }
  10157. /* parsing is heavily cross-recursive, need these forward decls */
  10158. static union node *andor(void);
  10159. static union node *pipeline(void);
  10160. static union node *parse_command(void);
  10161. static void parseheredoc(void);
  10162. static int peektoken(void);
  10163. static int readtoken(void);
  10164. static union node *
  10165. list(int nlflag)
  10166. {
  10167. union node *n1, *n2, *n3;
  10168. int tok;
  10169. n1 = NULL;
  10170. for (;;) {
  10171. switch (peektoken()) {
  10172. case TNL:
  10173. if (!(nlflag & 1))
  10174. break;
  10175. parseheredoc();
  10176. return n1;
  10177. case TEOF:
  10178. if (!n1 && (nlflag & 1))
  10179. n1 = NODE_EOF;
  10180. parseheredoc();
  10181. return n1;
  10182. }
  10183. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  10184. if (nlflag == 2 && ((1 << peektoken()) & tokendlist))
  10185. return n1;
  10186. nlflag |= 2;
  10187. n2 = andor();
  10188. tok = readtoken();
  10189. if (tok == TBACKGND) {
  10190. if (n2->type == NPIPE) {
  10191. n2->npipe.pipe_backgnd = 1;
  10192. } else {
  10193. if (n2->type != NREDIR) {
  10194. n3 = stzalloc(sizeof(struct nredir));
  10195. n3->nredir.n = n2;
  10196. /*n3->nredir.redirect = NULL; - stzalloc did it */
  10197. n2 = n3;
  10198. }
  10199. n2->type = NBACKGND;
  10200. }
  10201. }
  10202. if (n1 == NULL) {
  10203. n1 = n2;
  10204. } else {
  10205. n3 = stzalloc(sizeof(struct nbinary));
  10206. n3->type = NSEMI;
  10207. n3->nbinary.ch1 = n1;
  10208. n3->nbinary.ch2 = n2;
  10209. n1 = n3;
  10210. }
  10211. switch (tok) {
  10212. case TNL:
  10213. case TEOF:
  10214. tokpushback = 1;
  10215. /* fall through */
  10216. case TBACKGND:
  10217. case TSEMI:
  10218. break;
  10219. default:
  10220. if ((nlflag & 1))
  10221. raise_error_unexpected_syntax(-1);
  10222. tokpushback = 1;
  10223. return n1;
  10224. }
  10225. }
  10226. }
  10227. static union node *
  10228. andor(void)
  10229. {
  10230. union node *n1, *n2, *n3;
  10231. int t;
  10232. n1 = pipeline();
  10233. for (;;) {
  10234. t = readtoken();
  10235. if (t == TAND) {
  10236. t = NAND;
  10237. } else if (t == TOR) {
  10238. t = NOR;
  10239. } else {
  10240. tokpushback = 1;
  10241. return n1;
  10242. }
  10243. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  10244. n2 = pipeline();
  10245. n3 = stzalloc(sizeof(struct nbinary));
  10246. n3->type = t;
  10247. n3->nbinary.ch1 = n1;
  10248. n3->nbinary.ch2 = n2;
  10249. n1 = n3;
  10250. }
  10251. }
  10252. static union node *
  10253. pipeline(void)
  10254. {
  10255. union node *n1, *n2, *pipenode;
  10256. struct nodelist *lp, *prev;
  10257. int negate;
  10258. negate = 0;
  10259. TRACE(("pipeline: entered\n"));
  10260. if (readtoken() == TNOT) {
  10261. negate = !negate;
  10262. checkkwd = CHKKWD | CHKALIAS;
  10263. } else
  10264. tokpushback = 1;
  10265. n1 = parse_command();
  10266. if (readtoken() == TPIPE) {
  10267. pipenode = stzalloc(sizeof(struct npipe));
  10268. pipenode->type = NPIPE;
  10269. /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
  10270. lp = stzalloc(sizeof(struct nodelist));
  10271. pipenode->npipe.cmdlist = lp;
  10272. lp->n = n1;
  10273. do {
  10274. prev = lp;
  10275. lp = stzalloc(sizeof(struct nodelist));
  10276. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  10277. lp->n = parse_command();
  10278. prev->next = lp;
  10279. } while (readtoken() == TPIPE);
  10280. lp->next = NULL;
  10281. n1 = pipenode;
  10282. }
  10283. tokpushback = 1;
  10284. if (negate) {
  10285. n2 = stzalloc(sizeof(struct nnot));
  10286. n2->type = NNOT;
  10287. n2->nnot.com = n1;
  10288. return n2;
  10289. }
  10290. return n1;
  10291. }
  10292. static union node *
  10293. makename(void)
  10294. {
  10295. union node *n;
  10296. n = stzalloc(sizeof(struct narg));
  10297. n->type = NARG;
  10298. /*n->narg.next = NULL; - stzalloc did it */
  10299. n->narg.text = wordtext;
  10300. n->narg.backquote = backquotelist;
  10301. return n;
  10302. }
  10303. static void
  10304. fixredir(union node *n, const char *text, int err)
  10305. {
  10306. int fd;
  10307. TRACE(("Fix redir %s %d\n", text, err));
  10308. if (!err)
  10309. n->ndup.vname = NULL;
  10310. fd = bb_strtou(text, NULL, 10);
  10311. if (!errno && fd >= 0)
  10312. n->ndup.dupfd = fd;
  10313. else if (LONE_DASH(text))
  10314. n->ndup.dupfd = -1;
  10315. else {
  10316. if (err)
  10317. raise_error_syntax("bad fd number");
  10318. n->ndup.vname = makename();
  10319. }
  10320. }
  10321. static void
  10322. parsefname(void)
  10323. {
  10324. union node *n = redirnode;
  10325. if (n->type == NHERE)
  10326. checkkwd = CHKEOFMARK;
  10327. if (readtoken() != TWORD)
  10328. raise_error_unexpected_syntax(-1);
  10329. if (n->type == NHERE) {
  10330. struct heredoc *here = heredoc;
  10331. struct heredoc *p;
  10332. if (quoteflag == 0)
  10333. n->type = NXHERE;
  10334. TRACE(("Here document %d\n", n->type));
  10335. rmescapes(wordtext, 0);
  10336. here->eofmark = wordtext;
  10337. here->next = NULL;
  10338. if (heredoclist == NULL)
  10339. heredoclist = here;
  10340. else {
  10341. for (p = heredoclist; p->next; p = p->next)
  10342. continue;
  10343. p->next = here;
  10344. }
  10345. } else if (n->type == NTOFD || n->type == NFROMFD) {
  10346. fixredir(n, wordtext, 0);
  10347. } else {
  10348. n->nfile.fname = makename();
  10349. }
  10350. }
  10351. static union node *
  10352. simplecmd(void)
  10353. {
  10354. union node *args, **app;
  10355. union node *n = NULL;
  10356. union node *vars, **vpp;
  10357. union node **rpp, *redir;
  10358. int savecheckkwd;
  10359. #if BASH_TEST2
  10360. smallint double_brackets_flag = 0;
  10361. #endif
  10362. IF_BASH_FUNCTION(smallint function_flag = 0;)
  10363. args = NULL;
  10364. app = &args;
  10365. vars = NULL;
  10366. vpp = &vars;
  10367. redir = NULL;
  10368. rpp = &redir;
  10369. savecheckkwd = CHKALIAS;
  10370. for (;;) {
  10371. int t;
  10372. checkkwd = savecheckkwd;
  10373. t = readtoken();
  10374. switch (t) {
  10375. #if BASH_FUNCTION
  10376. case TFUNCTION:
  10377. if (peektoken() != TWORD)
  10378. raise_error_unexpected_syntax(TWORD);
  10379. function_flag = 1;
  10380. break;
  10381. #endif
  10382. #if BASH_TEST2
  10383. case TAND: /* "&&" */
  10384. case TOR: /* "||" */
  10385. if (!double_brackets_flag) {
  10386. tokpushback = 1;
  10387. goto out;
  10388. }
  10389. wordtext = (char *) (t == TAND ? "-a" : "-o");
  10390. #endif
  10391. case TWORD:
  10392. n = stzalloc(sizeof(struct narg));
  10393. n->type = NARG;
  10394. /*n->narg.next = NULL; - stzalloc did it */
  10395. n->narg.text = wordtext;
  10396. #if BASH_TEST2
  10397. if (strcmp("[[", wordtext) == 0)
  10398. double_brackets_flag = 1;
  10399. else if (strcmp("]]", wordtext) == 0)
  10400. double_brackets_flag = 0;
  10401. #endif
  10402. n->narg.backquote = backquotelist;
  10403. if (savecheckkwd && isassignment(wordtext)) {
  10404. *vpp = n;
  10405. vpp = &n->narg.next;
  10406. } else {
  10407. *app = n;
  10408. app = &n->narg.next;
  10409. savecheckkwd = 0;
  10410. }
  10411. #if BASH_FUNCTION
  10412. if (function_flag) {
  10413. checkkwd = CHKNL | CHKKWD;
  10414. switch (peektoken()) {
  10415. case TBEGIN:
  10416. case TIF:
  10417. case TCASE:
  10418. case TUNTIL:
  10419. case TWHILE:
  10420. case TFOR:
  10421. goto do_func;
  10422. case TLP:
  10423. function_flag = 0;
  10424. break;
  10425. case TWORD:
  10426. if (strcmp("[[", wordtext) == 0)
  10427. goto do_func;
  10428. /* fall through */
  10429. default:
  10430. raise_error_unexpected_syntax(-1);
  10431. }
  10432. }
  10433. #endif
  10434. break;
  10435. case TREDIR:
  10436. *rpp = n = redirnode;
  10437. rpp = &n->nfile.next;
  10438. parsefname(); /* read name of redirection file */
  10439. break;
  10440. case TLP:
  10441. IF_BASH_FUNCTION(do_func:)
  10442. if (args && app == &args->narg.next
  10443. && !vars && !redir
  10444. ) {
  10445. struct builtincmd *bcmd;
  10446. const char *name;
  10447. /* We have a function */
  10448. if (IF_BASH_FUNCTION(!function_flag &&) readtoken() != TRP)
  10449. raise_error_unexpected_syntax(TRP);
  10450. name = n->narg.text;
  10451. if (!goodname(name)
  10452. || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
  10453. ) {
  10454. raise_error_syntax("bad function name");
  10455. }
  10456. n->type = NDEFUN;
  10457. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  10458. n->narg.next = parse_command();
  10459. return n;
  10460. }
  10461. IF_BASH_FUNCTION(function_flag = 0;)
  10462. /* fall through */
  10463. default:
  10464. tokpushback = 1;
  10465. goto out;
  10466. }
  10467. }
  10468. out:
  10469. *app = NULL;
  10470. *vpp = NULL;
  10471. *rpp = NULL;
  10472. n = stzalloc(sizeof(struct ncmd));
  10473. n->type = NCMD;
  10474. n->ncmd.args = args;
  10475. n->ncmd.assign = vars;
  10476. n->ncmd.redirect = redir;
  10477. return n;
  10478. }
  10479. static union node *
  10480. parse_command(void)
  10481. {
  10482. union node *n1, *n2;
  10483. union node *ap, **app;
  10484. union node *cp, **cpp;
  10485. union node *redir, **rpp;
  10486. union node **rpp2;
  10487. int t;
  10488. redir = NULL;
  10489. rpp2 = &redir;
  10490. switch (readtoken()) {
  10491. default:
  10492. raise_error_unexpected_syntax(-1);
  10493. /* NOTREACHED */
  10494. case TIF:
  10495. n1 = stzalloc(sizeof(struct nif));
  10496. n1->type = NIF;
  10497. n1->nif.test = list(0);
  10498. if (readtoken() != TTHEN)
  10499. raise_error_unexpected_syntax(TTHEN);
  10500. n1->nif.ifpart = list(0);
  10501. n2 = n1;
  10502. while (readtoken() == TELIF) {
  10503. n2->nif.elsepart = stzalloc(sizeof(struct nif));
  10504. n2 = n2->nif.elsepart;
  10505. n2->type = NIF;
  10506. n2->nif.test = list(0);
  10507. if (readtoken() != TTHEN)
  10508. raise_error_unexpected_syntax(TTHEN);
  10509. n2->nif.ifpart = list(0);
  10510. }
  10511. if (lasttoken == TELSE)
  10512. n2->nif.elsepart = list(0);
  10513. else {
  10514. n2->nif.elsepart = NULL;
  10515. tokpushback = 1;
  10516. }
  10517. t = TFI;
  10518. break;
  10519. case TWHILE:
  10520. case TUNTIL: {
  10521. int got;
  10522. n1 = stzalloc(sizeof(struct nbinary));
  10523. n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
  10524. n1->nbinary.ch1 = list(0);
  10525. got = readtoken();
  10526. if (got != TDO) {
  10527. TRACE(("expecting DO got '%s' %s\n", tokname_array[got],
  10528. got == TWORD ? wordtext : ""));
  10529. raise_error_unexpected_syntax(TDO);
  10530. }
  10531. n1->nbinary.ch2 = list(0);
  10532. t = TDONE;
  10533. break;
  10534. }
  10535. case TFOR:
  10536. if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
  10537. raise_error_syntax("bad for loop variable");
  10538. n1 = stzalloc(sizeof(struct nfor));
  10539. n1->type = NFOR;
  10540. n1->nfor.var = wordtext;
  10541. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  10542. if (readtoken() == TIN) {
  10543. app = &ap;
  10544. while (readtoken() == TWORD) {
  10545. n2 = stzalloc(sizeof(struct narg));
  10546. n2->type = NARG;
  10547. /*n2->narg.next = NULL; - stzalloc did it */
  10548. n2->narg.text = wordtext;
  10549. n2->narg.backquote = backquotelist;
  10550. *app = n2;
  10551. app = &n2->narg.next;
  10552. }
  10553. *app = NULL;
  10554. n1->nfor.args = ap;
  10555. if (lasttoken != TNL && lasttoken != TSEMI)
  10556. raise_error_unexpected_syntax(-1);
  10557. } else {
  10558. n2 = stzalloc(sizeof(struct narg));
  10559. n2->type = NARG;
  10560. /*n2->narg.next = NULL; - stzalloc did it */
  10561. n2->narg.text = (char *)dolatstr;
  10562. /*n2->narg.backquote = NULL;*/
  10563. n1->nfor.args = n2;
  10564. /*
  10565. * Newline or semicolon here is optional (but note
  10566. * that the original Bourne shell only allowed NL).
  10567. */
  10568. if (lasttoken != TSEMI)
  10569. tokpushback = 1;
  10570. }
  10571. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  10572. if (readtoken() != TDO)
  10573. raise_error_unexpected_syntax(TDO);
  10574. n1->nfor.body = list(0);
  10575. t = TDONE;
  10576. break;
  10577. case TCASE:
  10578. n1 = stzalloc(sizeof(struct ncase));
  10579. n1->type = NCASE;
  10580. if (readtoken() != TWORD)
  10581. raise_error_unexpected_syntax(TWORD);
  10582. n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
  10583. n2->type = NARG;
  10584. /*n2->narg.next = NULL; - stzalloc did it */
  10585. n2->narg.text = wordtext;
  10586. n2->narg.backquote = backquotelist;
  10587. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  10588. if (readtoken() != TIN)
  10589. raise_error_unexpected_syntax(TIN);
  10590. cpp = &n1->ncase.cases;
  10591. next_case:
  10592. checkkwd = CHKNL | CHKKWD;
  10593. t = readtoken();
  10594. while (t != TESAC) {
  10595. if (lasttoken == TLP)
  10596. readtoken();
  10597. *cpp = cp = stzalloc(sizeof(struct nclist));
  10598. cp->type = NCLIST;
  10599. app = &cp->nclist.pattern;
  10600. for (;;) {
  10601. *app = ap = stzalloc(sizeof(struct narg));
  10602. ap->type = NARG;
  10603. /*ap->narg.next = NULL; - stzalloc did it */
  10604. ap->narg.text = wordtext;
  10605. ap->narg.backquote = backquotelist;
  10606. if (readtoken() != TPIPE)
  10607. break;
  10608. app = &ap->narg.next;
  10609. readtoken();
  10610. }
  10611. //ap->narg.next = NULL;
  10612. if (lasttoken != TRP)
  10613. raise_error_unexpected_syntax(TRP);
  10614. cp->nclist.body = list(2);
  10615. cpp = &cp->nclist.next;
  10616. checkkwd = CHKNL | CHKKWD;
  10617. t = readtoken();
  10618. if (t != TESAC) {
  10619. if (t != TENDCASE)
  10620. raise_error_unexpected_syntax(TENDCASE);
  10621. goto next_case;
  10622. }
  10623. }
  10624. *cpp = NULL;
  10625. goto redir;
  10626. case TLP:
  10627. n1 = stzalloc(sizeof(struct nredir));
  10628. n1->type = NSUBSHELL;
  10629. n1->nredir.n = list(0);
  10630. /*n1->nredir.redirect = NULL; - stzalloc did it */
  10631. t = TRP;
  10632. break;
  10633. case TBEGIN:
  10634. n1 = list(0);
  10635. t = TEND;
  10636. break;
  10637. IF_BASH_FUNCTION(case TFUNCTION:)
  10638. case TWORD:
  10639. case TREDIR:
  10640. tokpushback = 1;
  10641. return simplecmd();
  10642. }
  10643. if (readtoken() != t)
  10644. raise_error_unexpected_syntax(t);
  10645. redir:
  10646. /* Now check for redirection which may follow command */
  10647. checkkwd = CHKKWD | CHKALIAS;
  10648. rpp = rpp2;
  10649. while (readtoken() == TREDIR) {
  10650. *rpp = n2 = redirnode;
  10651. rpp = &n2->nfile.next;
  10652. parsefname();
  10653. }
  10654. tokpushback = 1;
  10655. *rpp = NULL;
  10656. if (redir) {
  10657. if (n1->type != NSUBSHELL) {
  10658. n2 = stzalloc(sizeof(struct nredir));
  10659. n2->type = NREDIR;
  10660. n2->nredir.n = n1;
  10661. n1 = n2;
  10662. }
  10663. n1->nredir.redirect = redir;
  10664. }
  10665. return n1;
  10666. }
  10667. #if BASH_DOLLAR_SQUOTE
  10668. static int
  10669. decode_dollar_squote(void)
  10670. {
  10671. static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
  10672. int c, cnt;
  10673. char *p;
  10674. char buf[4];
  10675. c = pgetc();
  10676. p = strchr(C_escapes, c);
  10677. if (p) {
  10678. buf[0] = c;
  10679. p = buf;
  10680. cnt = 3;
  10681. if ((unsigned char)(c - '0') <= 7) { /* \ooo */
  10682. do {
  10683. c = pgetc();
  10684. *++p = c;
  10685. } while ((unsigned char)(c - '0') <= 7 && --cnt);
  10686. pungetc();
  10687. } else if (c == 'x') { /* \xHH */
  10688. do {
  10689. c = pgetc();
  10690. *++p = c;
  10691. } while (isxdigit(c) && --cnt);
  10692. pungetc();
  10693. if (cnt == 3) { /* \x but next char is "bad" */
  10694. c = 'x';
  10695. goto unrecognized;
  10696. }
  10697. } else { /* simple seq like \\ or \t */
  10698. p++;
  10699. }
  10700. *p = '\0';
  10701. p = buf;
  10702. c = bb_process_escape_sequence((void*)&p);
  10703. } else { /* unrecognized "\z": print both chars unless ' or " */
  10704. if (c != '\'' && c != '"') {
  10705. unrecognized:
  10706. c |= 0x100; /* "please encode \, then me" */
  10707. }
  10708. }
  10709. return c;
  10710. }
  10711. #endif
  10712. /* Used by expandstr to get here-doc like behaviour. */
  10713. #define FAKEEOFMARK ((char*)(uintptr_t)1)
  10714. static ALWAYS_INLINE int
  10715. realeofmark(const char *eofmark)
  10716. {
  10717. return eofmark && eofmark != FAKEEOFMARK;
  10718. }
  10719. /*
  10720. * If eofmark is NULL, read a word or a redirection symbol. If eofmark
  10721. * is not NULL, read a here document. In the latter case, eofmark is the
  10722. * word which marks the end of the document and striptabs is true if
  10723. * leading tabs should be stripped from the document. The argument c
  10724. * is the first character of the input token or document.
  10725. *
  10726. * Because C does not have internal subroutines, I have simulated them
  10727. * using goto's to implement the subroutine linkage. The following macros
  10728. * will run code that appears at the end of readtoken1.
  10729. */
  10730. #define CHECKEND() {goto checkend; checkend_return:;}
  10731. #define PARSEREDIR() {goto parseredir; parseredir_return:;}
  10732. #define PARSESUB() {goto parsesub; parsesub_return:;}
  10733. #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
  10734. #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
  10735. #define PARSEARITH() {goto parsearith; parsearith_return:;}
  10736. static int
  10737. readtoken1(int c, int syntax, char *eofmark, int striptabs)
  10738. {
  10739. /* NB: syntax parameter fits into smallint */
  10740. /* c parameter is an unsigned char or PEOF or PEOA */
  10741. char *out;
  10742. size_t len;
  10743. struct nodelist *bqlist;
  10744. smallint quotef;
  10745. smallint dblquote;
  10746. smallint oldstyle;
  10747. IF_FEATURE_SH_MATH(smallint prevsyntax;) /* syntax before arithmetic */
  10748. smallint pssyntax; /* we are expanding a prompt string */
  10749. int varnest; /* levels of variables expansion */
  10750. IF_FEATURE_SH_MATH(int arinest;) /* levels of arithmetic expansion */
  10751. IF_FEATURE_SH_MATH(int parenlevel;) /* levels of parens in arithmetic */
  10752. int dqvarnest; /* levels of variables expansion within double quotes */
  10753. IF_BASH_DOLLAR_SQUOTE(smallint bash_dollar_squote = 0;)
  10754. startlinno = g_parsefile->linno;
  10755. bqlist = NULL;
  10756. quotef = 0;
  10757. IF_FEATURE_SH_MATH(prevsyntax = 0;)
  10758. #if ENABLE_ASH_EXPAND_PRMT
  10759. pssyntax = (syntax == PSSYNTAX);
  10760. if (pssyntax)
  10761. syntax = DQSYNTAX;
  10762. #else
  10763. pssyntax = 0; /* constant */
  10764. #endif
  10765. dblquote = (syntax == DQSYNTAX);
  10766. varnest = 0;
  10767. IF_FEATURE_SH_MATH(arinest = 0;)
  10768. IF_FEATURE_SH_MATH(parenlevel = 0;)
  10769. dqvarnest = 0;
  10770. STARTSTACKSTR(out);
  10771. loop:
  10772. /* For each line, until end of word */
  10773. CHECKEND(); /* set c to PEOF if at end of here document */
  10774. for (;;) { /* until end of line or end of word */
  10775. CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
  10776. switch (SIT(c, syntax)) {
  10777. case CNL: /* '\n' */
  10778. if (syntax == BASESYNTAX)
  10779. goto endword; /* exit outer loop */
  10780. USTPUTC(c, out);
  10781. nlprompt();
  10782. c = pgetc();
  10783. goto loop; /* continue outer loop */
  10784. case CWORD:
  10785. USTPUTC(c, out);
  10786. break;
  10787. case CCTL:
  10788. #if BASH_DOLLAR_SQUOTE
  10789. if (c == '\\' && bash_dollar_squote) {
  10790. c = decode_dollar_squote();
  10791. if (c == '\0') {
  10792. /* skip $'\000', $'\x00' (like bash) */
  10793. break;
  10794. }
  10795. if (c & 0x100) {
  10796. /* Unknown escape. Encode as '\z' */
  10797. c = (unsigned char)c;
  10798. if (eofmark == NULL || dblquote)
  10799. USTPUTC(CTLESC, out);
  10800. USTPUTC('\\', out);
  10801. }
  10802. }
  10803. #endif
  10804. if (eofmark == NULL || dblquote)
  10805. USTPUTC(CTLESC, out);
  10806. USTPUTC(c, out);
  10807. break;
  10808. case CBACK: /* backslash */
  10809. c = pgetc_without_PEOA();
  10810. if (c == PEOF) {
  10811. USTPUTC(CTLESC, out);
  10812. USTPUTC('\\', out);
  10813. pungetc();
  10814. } else if (c == '\n') {
  10815. nlprompt();
  10816. } else {
  10817. if (pssyntax && c == '$') {
  10818. USTPUTC(CTLESC, out);
  10819. USTPUTC('\\', out);
  10820. }
  10821. /* Backslash is retained if we are in "str" and next char isn't special */
  10822. if (dblquote
  10823. && c != '\\'
  10824. && c != '`'
  10825. && c != '$'
  10826. && (c != '"' || eofmark != NULL)
  10827. ) {
  10828. USTPUTC('\\', out);
  10829. }
  10830. USTPUTC(CTLESC, out);
  10831. USTPUTC(c, out);
  10832. quotef = 1;
  10833. }
  10834. break;
  10835. case CSQUOTE:
  10836. syntax = SQSYNTAX;
  10837. quotemark:
  10838. if (eofmark == NULL) {
  10839. USTPUTC(CTLQUOTEMARK, out);
  10840. }
  10841. break;
  10842. case CDQUOTE:
  10843. syntax = DQSYNTAX;
  10844. dblquote = 1;
  10845. goto quotemark;
  10846. case CENDQUOTE:
  10847. IF_BASH_DOLLAR_SQUOTE(bash_dollar_squote = 0;)
  10848. if (eofmark != NULL && varnest == 0) {
  10849. USTPUTC(c, out);
  10850. } else {
  10851. if (dqvarnest == 0) {
  10852. syntax = BASESYNTAX;
  10853. dblquote = 0;
  10854. }
  10855. quotef = 1;
  10856. goto quotemark;
  10857. }
  10858. break;
  10859. case CVAR: /* '$' */
  10860. PARSESUB(); /* parse substitution */
  10861. break;
  10862. case CENDVAR: /* '}' */
  10863. if (varnest > 0) {
  10864. varnest--;
  10865. if (dqvarnest > 0) {
  10866. dqvarnest--;
  10867. }
  10868. c = CTLENDVAR;
  10869. }
  10870. USTPUTC(c, out);
  10871. break;
  10872. #if ENABLE_FEATURE_SH_MATH
  10873. case CLP: /* '(' in arithmetic */
  10874. parenlevel++;
  10875. USTPUTC(c, out);
  10876. break;
  10877. case CRP: /* ')' in arithmetic */
  10878. if (parenlevel > 0) {
  10879. parenlevel--;
  10880. } else {
  10881. if (pgetc_eatbnl() == ')') {
  10882. c = CTLENDARI;
  10883. if (--arinest == 0) {
  10884. syntax = prevsyntax;
  10885. }
  10886. } else {
  10887. /*
  10888. * unbalanced parens
  10889. * (don't 2nd guess - no error)
  10890. */
  10891. pungetc();
  10892. }
  10893. }
  10894. USTPUTC(c, out);
  10895. break;
  10896. #endif
  10897. case CBQUOTE: /* '`' */
  10898. PARSEBACKQOLD();
  10899. break;
  10900. case CENDFILE:
  10901. goto endword; /* exit outer loop */
  10902. case CIGN:
  10903. break;
  10904. default:
  10905. if (varnest == 0) {
  10906. #if BASH_REDIR_OUTPUT
  10907. if (c == '&') {
  10908. //Can't call pgetc_eatbnl() here, this requires three-deep pungetc()
  10909. if (pgetc() == '>')
  10910. c = 0x100 + '>'; /* flag &> */
  10911. pungetc();
  10912. }
  10913. #endif
  10914. goto endword; /* exit outer loop */
  10915. }
  10916. IF_ASH_ALIAS(if (c != PEOA))
  10917. USTPUTC(c, out);
  10918. }
  10919. c = pgetc();
  10920. } /* for (;;) */
  10921. endword:
  10922. #if ENABLE_FEATURE_SH_MATH
  10923. if (syntax == ARISYNTAX)
  10924. raise_error_syntax("missing '))'");
  10925. #endif
  10926. if (syntax != BASESYNTAX && eofmark == NULL)
  10927. raise_error_syntax("unterminated quoted string");
  10928. if (varnest != 0) {
  10929. startlinno = g_parsefile->linno;
  10930. /* { */
  10931. raise_error_syntax("missing '}'");
  10932. }
  10933. USTPUTC('\0', out);
  10934. len = out - (char *)stackblock();
  10935. out = stackblock();
  10936. if (eofmark == NULL) {
  10937. if ((c == '>' || c == '<' IF_BASH_REDIR_OUTPUT( || c == 0x100 + '>'))
  10938. && quotef == 0
  10939. ) {
  10940. if (isdigit_str9(out)) {
  10941. PARSEREDIR(); /* passed as params: out, c */
  10942. lasttoken = TREDIR;
  10943. return lasttoken;
  10944. }
  10945. /* else: non-number X seen, interpret it
  10946. * as "NNNX>file" = "NNNX >file" */
  10947. }
  10948. pungetc();
  10949. }
  10950. quoteflag = quotef;
  10951. backquotelist = bqlist;
  10952. grabstackblock(len);
  10953. wordtext = out;
  10954. lasttoken = TWORD;
  10955. return lasttoken;
  10956. /* end of readtoken routine */
  10957. /*
  10958. * Check to see whether we are at the end of the here document. When this
  10959. * is called, c is set to the first character of the next input line. If
  10960. * we are at the end of the here document, this routine sets the c to PEOF.
  10961. */
  10962. checkend: {
  10963. if (realeofmark(eofmark)) {
  10964. int markloc;
  10965. char *p;
  10966. #if ENABLE_ASH_ALIAS
  10967. if (c == PEOA)
  10968. c = pgetc_without_PEOA();
  10969. #endif
  10970. if (striptabs) {
  10971. while (c == '\t') {
  10972. c = pgetc_without_PEOA();
  10973. }
  10974. }
  10975. markloc = out - (char *)stackblock();
  10976. for (p = eofmark; STPUTC(c, out), *p; p++) {
  10977. if (c != *p)
  10978. goto more_heredoc;
  10979. c = pgetc_without_PEOA();
  10980. }
  10981. if (c == '\n' || c == PEOF) {
  10982. c = PEOF;
  10983. g_parsefile->linno++;
  10984. needprompt = doprompt;
  10985. } else {
  10986. int len_here;
  10987. more_heredoc:
  10988. p = (char *)stackblock() + markloc + 1;
  10989. len_here = out - p;
  10990. if (len_here) {
  10991. len_here -= (c >= PEOF);
  10992. c = p[-1];
  10993. if (len_here) {
  10994. char *str;
  10995. str = alloca(len_here + 1);
  10996. *(char *)mempcpy(str, p, len_here) = '\0';
  10997. pushstring(str, NULL);
  10998. }
  10999. }
  11000. }
  11001. STADJUST((char *)stackblock() + markloc - out, out);
  11002. }
  11003. goto checkend_return;
  11004. }
  11005. /*
  11006. * Parse a redirection operator. The variable "out" points to a string
  11007. * specifying the fd to be redirected. The variable "c" contains the
  11008. * first character of the redirection operator.
  11009. */
  11010. parseredir: {
  11011. /* out is already checked to be a valid number or "" */
  11012. int fd = (*out == '\0' ? -1 : atoi(out));
  11013. union node *np;
  11014. np = stzalloc(sizeof(struct nfile));
  11015. if (c == '>') {
  11016. np->nfile.fd = 1;
  11017. c = pgetc();
  11018. if (c == '>')
  11019. np->type = NAPPEND;
  11020. else if (c == '|')
  11021. np->type = NCLOBBER;
  11022. else if (c == '&')
  11023. np->type = NTOFD;
  11024. /* it also can be NTO2 (>&file), but we can't figure it out yet */
  11025. else {
  11026. np->type = NTO;
  11027. pungetc();
  11028. }
  11029. }
  11030. #if BASH_REDIR_OUTPUT
  11031. else if (c == 0x100 + '>') { /* this flags &> redirection */
  11032. np->nfile.fd = 1;
  11033. pgetc(); /* this is '>', no need to check */
  11034. np->type = NTO2;
  11035. }
  11036. #endif
  11037. else { /* c == '<' */
  11038. /*np->nfile.fd = 0; - stzalloc did it */
  11039. c = pgetc();
  11040. switch (c) {
  11041. case '<':
  11042. if (sizeof(struct nfile) != sizeof(struct nhere)) {
  11043. np = stzalloc(sizeof(struct nhere));
  11044. /*np->nfile.fd = 0; - stzalloc did it */
  11045. }
  11046. np->type = NHERE;
  11047. heredoc = stzalloc(sizeof(struct heredoc));
  11048. heredoc->here = np;
  11049. c = pgetc();
  11050. if (c == '-') {
  11051. heredoc->striptabs = 1;
  11052. } else {
  11053. /*heredoc->striptabs = 0; - stzalloc did it */
  11054. pungetc();
  11055. }
  11056. break;
  11057. case '&':
  11058. np->type = NFROMFD;
  11059. break;
  11060. case '>':
  11061. np->type = NFROMTO;
  11062. break;
  11063. default:
  11064. np->type = NFROM;
  11065. pungetc();
  11066. break;
  11067. }
  11068. }
  11069. if (fd >= 0)
  11070. np->nfile.fd = fd;
  11071. redirnode = np;
  11072. goto parseredir_return;
  11073. }
  11074. /*
  11075. * Parse a substitution. At this point, we have read the dollar sign
  11076. * and nothing else.
  11077. */
  11078. /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
  11079. * (assuming ascii char codes, as the original implementation did) */
  11080. #define is_special(c) \
  11081. (((unsigned)(c) - 33 < 32) \
  11082. && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
  11083. parsesub: {
  11084. unsigned char subtype;
  11085. int typeloc;
  11086. c = pgetc_eatbnl();
  11087. if ((checkkwd & CHKEOFMARK)
  11088. || c > 255 /* PEOA or PEOF */
  11089. || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
  11090. ) {
  11091. #if BASH_DOLLAR_SQUOTE
  11092. if (syntax != DQSYNTAX && c == '\'')
  11093. bash_dollar_squote = 1;
  11094. else
  11095. #endif
  11096. USTPUTC('$', out);
  11097. pungetc();
  11098. } else if (c == '(') {
  11099. /* $(command) or $((arith)) */
  11100. if (pgetc_eatbnl() == '(') {
  11101. #if ENABLE_FEATURE_SH_MATH
  11102. PARSEARITH();
  11103. #else
  11104. raise_error_syntax("support for $((arith)) is disabled");
  11105. #endif
  11106. } else {
  11107. pungetc();
  11108. PARSEBACKQNEW();
  11109. }
  11110. } else {
  11111. /* $VAR, $<specialchar>, ${...}, or PEOA/PEOF */
  11112. USTPUTC(CTLVAR, out);
  11113. typeloc = out - (char *)stackblock();
  11114. STADJUST(1, out);
  11115. subtype = VSNORMAL;
  11116. if (c == '{') {
  11117. c = pgetc_eatbnl();
  11118. subtype = 0;
  11119. }
  11120. varname:
  11121. if (is_name(c)) {
  11122. /* $[{[#]]NAME[}] */
  11123. do {
  11124. STPUTC(c, out);
  11125. c = pgetc_eatbnl();
  11126. } while (is_in_name(c));
  11127. } else if (isdigit(c)) {
  11128. /* $[{[#]]NUM[}] */
  11129. do {
  11130. STPUTC(c, out);
  11131. c = pgetc_eatbnl();
  11132. } while (isdigit(c));
  11133. } else {
  11134. /* $[{[#]]<specialchar>[}] */
  11135. int cc = c;
  11136. c = pgetc_eatbnl();
  11137. if (!subtype && cc == '#') {
  11138. subtype = VSLENGTH;
  11139. if (c == '_' || isalnum(c))
  11140. goto varname;
  11141. cc = c;
  11142. c = pgetc_eatbnl();
  11143. if (cc == '}' || c != '}') {
  11144. pungetc();
  11145. subtype = 0;
  11146. c = cc;
  11147. cc = '#';
  11148. }
  11149. }
  11150. if (!is_special(cc)) {
  11151. if (subtype == VSLENGTH)
  11152. subtype = 0;
  11153. goto badsub;
  11154. }
  11155. USTPUTC(cc, out);
  11156. }
  11157. if (c != '}' && subtype == VSLENGTH) {
  11158. /* ${#VAR didn't end with } */
  11159. goto badsub;
  11160. }
  11161. if (subtype == 0) {
  11162. static const char types[] ALIGN1 = "}-+?=";
  11163. /* ${VAR...} but not $VAR or ${#VAR} */
  11164. /* c == first char after VAR */
  11165. switch (c) {
  11166. case ':':
  11167. c = pgetc_eatbnl();
  11168. #if BASH_SUBSTR
  11169. /* This check is only needed to not misinterpret
  11170. * ${VAR:-WORD}, ${VAR:+WORD}, ${VAR:=WORD}, ${VAR:?WORD}
  11171. * constructs.
  11172. */
  11173. if (!strchr(types, c)) {
  11174. subtype = VSSUBSTR;
  11175. pungetc();
  11176. break; /* "goto badsub" is bigger (!) */
  11177. }
  11178. #endif
  11179. subtype = VSNUL;
  11180. /*FALLTHROUGH*/
  11181. default: {
  11182. const char *p = strchr(types, c);
  11183. if (p == NULL)
  11184. break;
  11185. subtype |= p - types + VSNORMAL;
  11186. break;
  11187. }
  11188. case '%':
  11189. case '#': {
  11190. int cc = c;
  11191. subtype = (c == '#' ? VSTRIMLEFT : VSTRIMRIGHT);
  11192. c = pgetc_eatbnl();
  11193. if (c != cc)
  11194. goto badsub;
  11195. subtype++;
  11196. break;
  11197. }
  11198. #if BASH_PATTERN_SUBST
  11199. case '/':
  11200. /* ${v/[/]pattern/repl} */
  11201. //TODO: encode pattern and repl separately.
  11202. // Currently ${v/$var_with_slash/repl} is horribly broken
  11203. subtype = VSREPLACE;
  11204. c = pgetc_eatbnl();
  11205. if (c != '/')
  11206. goto badsub;
  11207. subtype++; /* VSREPLACEALL */
  11208. break;
  11209. #endif
  11210. }
  11211. } else {
  11212. badsub:
  11213. pungetc();
  11214. }
  11215. ((unsigned char *)stackblock())[typeloc] = subtype;
  11216. if (subtype != VSNORMAL) {
  11217. varnest++;
  11218. if (dblquote)
  11219. dqvarnest++;
  11220. }
  11221. STPUTC('=', out);
  11222. }
  11223. goto parsesub_return;
  11224. }
  11225. /*
  11226. * Called to parse command substitutions. Newstyle is set if the command
  11227. * is enclosed inside $(...); nlpp is a pointer to the head of the linked
  11228. * list of commands (passed by reference), and savelen is the number of
  11229. * characters on the top of the stack which must be preserved.
  11230. */
  11231. parsebackq: {
  11232. struct nodelist **nlpp;
  11233. union node *n;
  11234. char *str;
  11235. size_t savelen;
  11236. smallint saveprompt = 0;
  11237. str = NULL;
  11238. savelen = out - (char *)stackblock();
  11239. if (savelen > 0) {
  11240. /*
  11241. * FIXME: this can allocate very large block on stack and SEGV.
  11242. * Example:
  11243. * echo "..<100kbytes>..`true` $(true) `true` ..."
  11244. * allocates 100kb for every command subst. With about
  11245. * a hundred command substitutions stack overflows.
  11246. * With larger prepended string, SEGV happens sooner.
  11247. */
  11248. str = alloca(savelen);
  11249. memcpy(str, stackblock(), savelen);
  11250. }
  11251. if (oldstyle) {
  11252. /* We must read until the closing backquote, giving special
  11253. * treatment to some slashes, and then push the string and
  11254. * reread it as input, interpreting it normally.
  11255. */
  11256. char *pout;
  11257. size_t psavelen;
  11258. char *pstr;
  11259. STARTSTACKSTR(pout);
  11260. for (;;) {
  11261. int pc;
  11262. setprompt_if(needprompt, 2);
  11263. pc = pgetc();
  11264. switch (pc) {
  11265. case '`':
  11266. goto done;
  11267. case '\\':
  11268. pc = pgetc();
  11269. if (pc == '\n') {
  11270. nlprompt();
  11271. /*
  11272. * If eating a newline, avoid putting
  11273. * the newline into the new character
  11274. * stream (via the STPUTC after the
  11275. * switch).
  11276. */
  11277. continue;
  11278. }
  11279. if (pc != '\\' && pc != '`' && pc != '$'
  11280. && (!dblquote || pc != '"')
  11281. ) {
  11282. STPUTC('\\', pout);
  11283. }
  11284. if (pc <= 255 /* not PEOA or PEOF */) {
  11285. break;
  11286. }
  11287. /* fall through */
  11288. case PEOF:
  11289. IF_ASH_ALIAS(case PEOA:)
  11290. startlinno = g_parsefile->linno;
  11291. raise_error_syntax("EOF in backquote substitution");
  11292. case '\n':
  11293. nlnoprompt();
  11294. break;
  11295. default:
  11296. break;
  11297. }
  11298. STPUTC(pc, pout);
  11299. }
  11300. done:
  11301. STPUTC('\0', pout);
  11302. psavelen = pout - (char *)stackblock();
  11303. if (psavelen > 0) {
  11304. pstr = grabstackstr(pout);
  11305. setinputstring(pstr);
  11306. }
  11307. }
  11308. nlpp = &bqlist;
  11309. while (*nlpp)
  11310. nlpp = &(*nlpp)->next;
  11311. *nlpp = stzalloc(sizeof(**nlpp));
  11312. /* (*nlpp)->next = NULL; - stzalloc did it */
  11313. if (oldstyle) {
  11314. saveprompt = doprompt;
  11315. doprompt = 0;
  11316. }
  11317. n = list(2);
  11318. if (oldstyle)
  11319. doprompt = saveprompt;
  11320. else if (readtoken() != TRP)
  11321. raise_error_unexpected_syntax(TRP);
  11322. (*nlpp)->n = n;
  11323. if (oldstyle) {
  11324. /*
  11325. * Start reading from old file again, ignoring any pushed back
  11326. * tokens left from the backquote parsing
  11327. */
  11328. popfile();
  11329. tokpushback = 0;
  11330. }
  11331. while (stackblocksize() <= savelen)
  11332. growstackblock();
  11333. STARTSTACKSTR(out);
  11334. if (str) {
  11335. memcpy(out, str, savelen);
  11336. STADJUST(savelen, out);
  11337. }
  11338. USTPUTC(CTLBACKQ, out);
  11339. if (oldstyle)
  11340. goto parsebackq_oldreturn;
  11341. goto parsebackq_newreturn;
  11342. }
  11343. #if ENABLE_FEATURE_SH_MATH
  11344. /*
  11345. * Parse an arithmetic expansion (indicate start of one and set state)
  11346. */
  11347. parsearith: {
  11348. if (++arinest == 1) {
  11349. prevsyntax = syntax;
  11350. syntax = ARISYNTAX;
  11351. }
  11352. USTPUTC(CTLARI, out);
  11353. goto parsearith_return;
  11354. }
  11355. #endif
  11356. } /* end of readtoken */
  11357. /*
  11358. * Read the next input token.
  11359. * If the token is a word, we set backquotelist to the list of cmds in
  11360. * backquotes. We set quoteflag to true if any part of the word was
  11361. * quoted.
  11362. * If the token is TREDIR, then we set redirnode to a structure containing
  11363. * the redirection.
  11364. * In all cases, the variable startlinno is set to the number of the line
  11365. * on which the token starts.
  11366. *
  11367. * [Change comment: here documents and internal procedures]
  11368. * [Readtoken shouldn't have any arguments. Perhaps we should make the
  11369. * word parsing code into a separate routine. In this case, readtoken
  11370. * doesn't need to have any internal procedures, but parseword does.
  11371. * We could also make parseoperator in essence the main routine, and
  11372. * have parseword (readtoken1?) handle both words and redirection.]
  11373. */
  11374. #define NEW_xxreadtoken
  11375. #ifdef NEW_xxreadtoken
  11376. /* singles must be first! */
  11377. static const char xxreadtoken_chars[7] ALIGN1 = {
  11378. '\n', '(', ')', /* singles */
  11379. '&', '|', ';', /* doubles */
  11380. 0
  11381. };
  11382. #define xxreadtoken_singles 3
  11383. #define xxreadtoken_doubles 3
  11384. static const char xxreadtoken_tokens[] ALIGN1 = {
  11385. TNL, TLP, TRP, /* only single occurrence allowed */
  11386. TBACKGND, TPIPE, TSEMI, /* if single occurrence */
  11387. TEOF, /* corresponds to trailing nul */
  11388. TAND, TOR, TENDCASE /* if double occurrence */
  11389. };
  11390. static int
  11391. xxreadtoken(void)
  11392. {
  11393. int c;
  11394. if (tokpushback) {
  11395. tokpushback = 0;
  11396. return lasttoken;
  11397. }
  11398. setprompt_if(needprompt, 2);
  11399. startlinno = g_parsefile->linno;
  11400. for (;;) { /* until token or start of word found */
  11401. c = pgetc();
  11402. if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
  11403. continue;
  11404. if (c == '#') {
  11405. while ((c = pgetc()) != '\n' && c != PEOF)
  11406. continue;
  11407. pungetc();
  11408. } else if (c == '\\') {
  11409. if (pgetc() != '\n') {
  11410. pungetc();
  11411. break; /* return readtoken1(...) */
  11412. }
  11413. nlprompt();
  11414. } else {
  11415. const char *p;
  11416. p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
  11417. if (c != PEOF) {
  11418. if (c == '\n') {
  11419. nlnoprompt();
  11420. }
  11421. p = strchr(xxreadtoken_chars, c);
  11422. if (p == NULL)
  11423. break; /* return readtoken1(...) */
  11424. if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
  11425. int cc = pgetc();
  11426. if (cc == c) { /* double occurrence? */
  11427. p += xxreadtoken_doubles + 1;
  11428. } else {
  11429. pungetc();
  11430. #if BASH_REDIR_OUTPUT
  11431. if (c == '&' && cc == '>') /* &> */
  11432. break; /* return readtoken1(...) */
  11433. #endif
  11434. }
  11435. }
  11436. }
  11437. lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
  11438. return lasttoken;
  11439. }
  11440. } /* for (;;) */
  11441. return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
  11442. }
  11443. #else /* old xxreadtoken */
  11444. #define RETURN(token) return lasttoken = token
  11445. static int
  11446. xxreadtoken(void)
  11447. {
  11448. int c;
  11449. if (tokpushback) {
  11450. tokpushback = 0;
  11451. return lasttoken;
  11452. }
  11453. setprompt_if(needprompt, 2);
  11454. startlinno = g_parsefile->linno;
  11455. for (;;) { /* until token or start of word found */
  11456. c = pgetc();
  11457. switch (c) {
  11458. case ' ': case '\t':
  11459. IF_ASH_ALIAS(case PEOA:)
  11460. continue;
  11461. case '#':
  11462. while ((c = pgetc()) != '\n' && c != PEOF)
  11463. continue;
  11464. pungetc();
  11465. continue;
  11466. case '\\':
  11467. if (pgetc() == '\n') {
  11468. nlprompt();
  11469. continue;
  11470. }
  11471. pungetc();
  11472. goto breakloop;
  11473. case '\n':
  11474. nlnoprompt();
  11475. RETURN(TNL);
  11476. case PEOF:
  11477. RETURN(TEOF);
  11478. case '&':
  11479. if (pgetc() == '&')
  11480. RETURN(TAND);
  11481. pungetc();
  11482. RETURN(TBACKGND);
  11483. case '|':
  11484. if (pgetc() == '|')
  11485. RETURN(TOR);
  11486. pungetc();
  11487. RETURN(TPIPE);
  11488. case ';':
  11489. if (pgetc() == ';')
  11490. RETURN(TENDCASE);
  11491. pungetc();
  11492. RETURN(TSEMI);
  11493. case '(':
  11494. RETURN(TLP);
  11495. case ')':
  11496. RETURN(TRP);
  11497. default:
  11498. goto breakloop;
  11499. }
  11500. }
  11501. breakloop:
  11502. return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
  11503. #undef RETURN
  11504. }
  11505. #endif /* old xxreadtoken */
  11506. static int
  11507. readtoken(void)
  11508. {
  11509. int t;
  11510. int kwd = checkkwd;
  11511. #if DEBUG
  11512. smallint alreadyseen = tokpushback;
  11513. #endif
  11514. #if ENABLE_ASH_ALIAS
  11515. top:
  11516. #endif
  11517. t = xxreadtoken();
  11518. /*
  11519. * eat newlines
  11520. */
  11521. if (kwd & CHKNL) {
  11522. while (t == TNL) {
  11523. parseheredoc();
  11524. t = xxreadtoken();
  11525. }
  11526. }
  11527. if (t != TWORD || quoteflag) {
  11528. goto out;
  11529. }
  11530. /*
  11531. * check for keywords
  11532. */
  11533. if (kwd & CHKKWD) {
  11534. const char *const *pp;
  11535. pp = findkwd(wordtext);
  11536. if (pp) {
  11537. lasttoken = t = pp - tokname_array;
  11538. TRACE(("keyword '%s' recognized\n", tokname_array[t]));
  11539. goto out;
  11540. }
  11541. }
  11542. if (checkkwd & CHKALIAS) {
  11543. #if ENABLE_ASH_ALIAS
  11544. struct alias *ap;
  11545. ap = lookupalias(wordtext, 1);
  11546. if (ap != NULL) {
  11547. if (*ap->val) {
  11548. pushstring(ap->val, ap);
  11549. }
  11550. goto top;
  11551. }
  11552. #endif
  11553. }
  11554. out:
  11555. checkkwd = 0;
  11556. #if DEBUG
  11557. if (!alreadyseen)
  11558. TRACE(("token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
  11559. else
  11560. TRACE(("reread token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
  11561. #endif
  11562. return t;
  11563. }
  11564. static int
  11565. peektoken(void)
  11566. {
  11567. int t;
  11568. t = readtoken();
  11569. tokpushback = 1;
  11570. return t;
  11571. }
  11572. /*
  11573. * Read and parse a command. Returns NODE_EOF on end of file.
  11574. * (NULL is a valid parse tree indicating a blank line.)
  11575. */
  11576. static union node *
  11577. parsecmd(int interact)
  11578. {
  11579. tokpushback = 0;
  11580. checkkwd = 0;
  11581. heredoclist = 0;
  11582. doprompt = interact;
  11583. setprompt_if(doprompt, doprompt);
  11584. needprompt = 0;
  11585. return list(1);
  11586. }
  11587. /*
  11588. * Input any here documents.
  11589. */
  11590. static void
  11591. parseheredoc(void)
  11592. {
  11593. struct heredoc *here;
  11594. union node *n;
  11595. here = heredoclist;
  11596. heredoclist = NULL;
  11597. while (here) {
  11598. setprompt_if(needprompt, 2);
  11599. readtoken1(pgetc(), here->here->type == NHERE ? SQSYNTAX : DQSYNTAX,
  11600. here->eofmark, here->striptabs);
  11601. n = stzalloc(sizeof(struct narg));
  11602. n->narg.type = NARG;
  11603. /*n->narg.next = NULL; - stzalloc did it */
  11604. n->narg.text = wordtext;
  11605. n->narg.backquote = backquotelist;
  11606. here->here->nhere.doc = n;
  11607. here = here->next;
  11608. }
  11609. }
  11610. static const char *
  11611. expandstr(const char *ps, int syntax_type)
  11612. {
  11613. union node n;
  11614. int saveprompt;
  11615. /* XXX Fix (char *) cast. */
  11616. setinputstring((char *)ps);
  11617. saveprompt = doprompt;
  11618. doprompt = 0;
  11619. /* readtoken1() might die horribly.
  11620. * Try a prompt with syntactically wrong command:
  11621. * PS1='$(date "+%H:%M:%S) > '
  11622. */
  11623. {
  11624. volatile int saveint;
  11625. struct jmploc *volatile savehandler = exception_handler;
  11626. struct jmploc jmploc;
  11627. SAVE_INT(saveint);
  11628. if (setjmp(jmploc.loc) == 0) {
  11629. exception_handler = &jmploc;
  11630. readtoken1(pgetc(), syntax_type, FAKEEOFMARK, 0);
  11631. }
  11632. exception_handler = savehandler;
  11633. RESTORE_INT(saveint);
  11634. }
  11635. doprompt = saveprompt;
  11636. popfile();
  11637. n.narg.type = NARG;
  11638. n.narg.next = NULL;
  11639. n.narg.text = wordtext;
  11640. n.narg.backquote = backquotelist;
  11641. expandarg(&n, NULL, EXP_QUOTED);
  11642. return stackblock();
  11643. }
  11644. static inline int
  11645. parser_eof(void)
  11646. {
  11647. return tokpushback && lasttoken == TEOF;
  11648. }
  11649. /*
  11650. * Execute a command or commands contained in a string.
  11651. */
  11652. static int
  11653. evalstring(char *s, int flags)
  11654. {
  11655. struct jmploc *volatile savehandler;
  11656. struct jmploc jmploc;
  11657. int ex;
  11658. union node *n;
  11659. struct stackmark smark;
  11660. int status;
  11661. s = sstrdup(s);
  11662. setinputstring(s);
  11663. setstackmark(&smark);
  11664. status = 0;
  11665. /* On exception inside execution loop, we must popfile().
  11666. * Try interactively:
  11667. * readonly a=a
  11668. * command eval "a=b" # throws "is read only" error
  11669. * "command BLTIN" is not supposed to abort (even in non-interactive use).
  11670. * But if we skip popfile(), we hit EOF in eval's string, and exit.
  11671. */
  11672. savehandler = exception_handler;
  11673. ex = setjmp(jmploc.loc);
  11674. if (ex)
  11675. goto out;
  11676. exception_handler = &jmploc;
  11677. while ((n = parsecmd(0)) != NODE_EOF) {
  11678. int i;
  11679. i = evaltree(n, flags & ~(parser_eof() ? 0 : EV_EXIT));
  11680. if (n)
  11681. status = i;
  11682. popstackmark(&smark);
  11683. if (evalskip)
  11684. break;
  11685. }
  11686. out:
  11687. popstackmark(&smark);
  11688. popfile();
  11689. stunalloc(s);
  11690. exception_handler = savehandler;
  11691. if (ex)
  11692. longjmp(exception_handler->loc, ex);
  11693. return status;
  11694. }
  11695. /*
  11696. * The eval command.
  11697. */
  11698. static int FAST_FUNC
  11699. evalcmd(int argc UNUSED_PARAM, char **argv, int flags)
  11700. {
  11701. char *p;
  11702. char *concat;
  11703. if (argv[1]) {
  11704. p = argv[1];
  11705. argv += 2;
  11706. if (argv[0]) {
  11707. STARTSTACKSTR(concat);
  11708. for (;;) {
  11709. concat = stack_putstr(p, concat);
  11710. p = *argv++;
  11711. if (p == NULL)
  11712. break;
  11713. STPUTC(' ', concat);
  11714. }
  11715. STPUTC('\0', concat);
  11716. p = grabstackstr(concat);
  11717. }
  11718. return evalstring(p, flags & EV_TESTED);
  11719. }
  11720. return 0;
  11721. }
  11722. /*
  11723. * Read and execute commands.
  11724. * "Top" is nonzero for the top level command loop;
  11725. * it turns on prompting if the shell is interactive.
  11726. */
  11727. static int
  11728. cmdloop(int top)
  11729. {
  11730. union node *n;
  11731. struct stackmark smark;
  11732. int inter;
  11733. int status = 0;
  11734. int numeof = 0;
  11735. TRACE(("cmdloop(%d) called\n", top));
  11736. for (;;) {
  11737. int skip;
  11738. setstackmark(&smark);
  11739. #if JOBS
  11740. if (doing_jobctl)
  11741. showjobs(SHOW_CHANGED|SHOW_STDERR);
  11742. #endif
  11743. inter = 0;
  11744. if (iflag && top) {
  11745. inter++;
  11746. chkmail();
  11747. }
  11748. n = parsecmd(inter);
  11749. #if DEBUG
  11750. if (DEBUG > 2 && debug && (n != NODE_EOF))
  11751. showtree(n);
  11752. #endif
  11753. if (n == NODE_EOF) {
  11754. if (!top || numeof >= 50)
  11755. break;
  11756. if (!stoppedjobs()) {
  11757. if (!Iflag)
  11758. break;
  11759. out2str("\nUse \"exit\" to leave shell.\n");
  11760. }
  11761. numeof++;
  11762. } else if (nflag == 0) {
  11763. int i;
  11764. /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
  11765. job_warning >>= 1;
  11766. numeof = 0;
  11767. i = evaltree(n, 0);
  11768. if (n)
  11769. status = i;
  11770. }
  11771. popstackmark(&smark);
  11772. skip = evalskip;
  11773. if (skip) {
  11774. evalskip &= ~SKIPFUNC;
  11775. break;
  11776. }
  11777. }
  11778. return status;
  11779. }
  11780. /*
  11781. * Take commands from a file. To be compatible we should do a path
  11782. * search for the file, which is necessary to find sub-commands.
  11783. */
  11784. static char *
  11785. find_dot_file(char *name)
  11786. {
  11787. char *fullname;
  11788. const char *path = pathval();
  11789. struct stat statb;
  11790. /* don't try this for absolute or relative paths */
  11791. if (strchr(name, '/'))
  11792. return name;
  11793. while ((fullname = path_advance(&path, name)) != NULL) {
  11794. if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
  11795. /*
  11796. * Don't bother freeing here, since it will
  11797. * be freed by the caller.
  11798. */
  11799. return fullname;
  11800. }
  11801. if (fullname != name)
  11802. stunalloc(fullname);
  11803. }
  11804. /* not found in the PATH */
  11805. ash_msg_and_raise_error("%s: not found", name);
  11806. /* NOTREACHED */
  11807. }
  11808. static int FAST_FUNC
  11809. dotcmd(int argc_ UNUSED_PARAM, char **argv_ UNUSED_PARAM)
  11810. {
  11811. /* "false; . empty_file; echo $?" should print 0, not 1: */
  11812. int status = 0;
  11813. char *fullname;
  11814. char **argv;
  11815. char *args_need_save;
  11816. volatile struct shparam saveparam;
  11817. //???
  11818. // struct strlist *sp;
  11819. // for (sp = cmdenviron; sp; sp = sp->next)
  11820. // setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
  11821. nextopt(nullstr); /* handle possible "--" */
  11822. argv = argptr;
  11823. if (!argv[0]) {
  11824. /* bash says: "bash: .: filename argument required" */
  11825. return 2; /* bash compat */
  11826. }
  11827. /* This aborts if file isn't found, which is POSIXly correct.
  11828. * bash returns exitcode 1 instead.
  11829. */
  11830. fullname = find_dot_file(argv[0]);
  11831. argv++;
  11832. args_need_save = argv[0];
  11833. if (args_need_save) { /* ". FILE ARGS", and ARGS are not empty */
  11834. int argc;
  11835. saveparam = shellparam;
  11836. shellparam.malloced = 0;
  11837. argc = 1;
  11838. while (argv[argc])
  11839. argc++;
  11840. shellparam.nparam = argc;
  11841. shellparam.p = argv;
  11842. };
  11843. /* This aborts if file can't be opened, which is POSIXly correct.
  11844. * bash returns exitcode 1 instead.
  11845. */
  11846. setinputfile(fullname, INPUT_PUSH_FILE);
  11847. commandname = fullname;
  11848. status = cmdloop(0);
  11849. popfile();
  11850. if (args_need_save) {
  11851. freeparam(&shellparam);
  11852. shellparam = saveparam;
  11853. };
  11854. return status;
  11855. }
  11856. static int FAST_FUNC
  11857. exitcmd(int argc UNUSED_PARAM, char **argv)
  11858. {
  11859. if (stoppedjobs())
  11860. return 0;
  11861. if (argv[1])
  11862. exitstatus = number(argv[1]);
  11863. raise_exception(EXEXIT);
  11864. /* NOTREACHED */
  11865. }
  11866. /*
  11867. * Read a file containing shell functions.
  11868. */
  11869. static void
  11870. readcmdfile(char *name)
  11871. {
  11872. setinputfile(name, INPUT_PUSH_FILE);
  11873. cmdloop(0);
  11874. popfile();
  11875. }
  11876. /* ============ find_command inplementation */
  11877. /*
  11878. * Resolve a command name. If you change this routine, you may have to
  11879. * change the shellexec routine as well.
  11880. */
  11881. static void
  11882. find_command(char *name, struct cmdentry *entry, int act, const char *path)
  11883. {
  11884. struct tblentry *cmdp;
  11885. int idx;
  11886. int prev;
  11887. char *fullname;
  11888. struct stat statb;
  11889. int e;
  11890. int updatetbl;
  11891. struct builtincmd *bcmd;
  11892. /* If name contains a slash, don't use PATH or hash table */
  11893. if (strchr(name, '/') != NULL) {
  11894. entry->u.index = -1;
  11895. if (act & DO_ABS) {
  11896. while (stat(name, &statb) < 0) {
  11897. #ifdef SYSV
  11898. if (errno == EINTR)
  11899. continue;
  11900. #endif
  11901. entry->cmdtype = CMDUNKNOWN;
  11902. return;
  11903. }
  11904. }
  11905. entry->cmdtype = CMDNORMAL;
  11906. return;
  11907. }
  11908. /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
  11909. updatetbl = (path == pathval());
  11910. if (!updatetbl) {
  11911. act |= DO_ALTPATH;
  11912. if (strstr(path, "%builtin") != NULL)
  11913. act |= DO_ALTBLTIN;
  11914. }
  11915. /* If name is in the table, check answer will be ok */
  11916. cmdp = cmdlookup(name, 0);
  11917. if (cmdp != NULL) {
  11918. int bit;
  11919. switch (cmdp->cmdtype) {
  11920. default:
  11921. #if DEBUG
  11922. abort();
  11923. #endif
  11924. case CMDNORMAL:
  11925. bit = DO_ALTPATH;
  11926. break;
  11927. case CMDFUNCTION:
  11928. bit = DO_NOFUNC;
  11929. break;
  11930. case CMDBUILTIN:
  11931. bit = DO_ALTBLTIN;
  11932. break;
  11933. }
  11934. if (act & bit) {
  11935. updatetbl = 0;
  11936. cmdp = NULL;
  11937. } else if (cmdp->rehash == 0)
  11938. /* if not invalidated by cd, we're done */
  11939. goto success;
  11940. }
  11941. /* If %builtin not in path, check for builtin next */
  11942. bcmd = find_builtin(name);
  11943. if (bcmd) {
  11944. if (IS_BUILTIN_REGULAR(bcmd))
  11945. goto builtin_success;
  11946. if (act & DO_ALTPATH) {
  11947. if (!(act & DO_ALTBLTIN))
  11948. goto builtin_success;
  11949. } else if (builtinloc <= 0) {
  11950. goto builtin_success;
  11951. }
  11952. }
  11953. #if ENABLE_FEATURE_SH_STANDALONE
  11954. {
  11955. int applet_no = find_applet_by_name(name);
  11956. if (applet_no >= 0) {
  11957. entry->cmdtype = CMDNORMAL;
  11958. entry->u.index = -2 - applet_no;
  11959. return;
  11960. }
  11961. }
  11962. #endif
  11963. /* We have to search path. */
  11964. prev = -1; /* where to start */
  11965. if (cmdp && cmdp->rehash) { /* doing a rehash */
  11966. if (cmdp->cmdtype == CMDBUILTIN)
  11967. prev = builtinloc;
  11968. else
  11969. prev = cmdp->param.index;
  11970. }
  11971. e = ENOENT;
  11972. idx = -1;
  11973. loop:
  11974. while ((fullname = path_advance(&path, name)) != NULL) {
  11975. stunalloc(fullname);
  11976. /* NB: code below will still use fullname
  11977. * despite it being "unallocated" */
  11978. idx++;
  11979. if (pathopt) {
  11980. if (prefix(pathopt, "builtin")) {
  11981. if (bcmd)
  11982. goto builtin_success;
  11983. continue;
  11984. }
  11985. if ((act & DO_NOFUNC)
  11986. || !prefix(pathopt, "func")
  11987. ) { /* ignore unimplemented options */
  11988. continue;
  11989. }
  11990. }
  11991. /* if rehash, don't redo absolute path names */
  11992. if (fullname[0] == '/' && idx <= prev) {
  11993. if (idx < prev)
  11994. continue;
  11995. TRACE(("searchexec \"%s\": no change\n", name));
  11996. goto success;
  11997. }
  11998. while (stat(fullname, &statb) < 0) {
  11999. #ifdef SYSV
  12000. if (errno == EINTR)
  12001. continue;
  12002. #endif
  12003. if (errno != ENOENT && errno != ENOTDIR)
  12004. e = errno;
  12005. goto loop;
  12006. }
  12007. e = EACCES; /* if we fail, this will be the error */
  12008. if (!S_ISREG(statb.st_mode))
  12009. continue;
  12010. if (pathopt) { /* this is a %func directory */
  12011. stalloc(strlen(fullname) + 1);
  12012. /* NB: stalloc will return space pointed by fullname
  12013. * (because we don't have any intervening allocations
  12014. * between stunalloc above and this stalloc) */
  12015. readcmdfile(fullname);
  12016. cmdp = cmdlookup(name, 0);
  12017. if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
  12018. ash_msg_and_raise_error("%s not defined in %s", name, fullname);
  12019. stunalloc(fullname);
  12020. goto success;
  12021. }
  12022. TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
  12023. if (!updatetbl) {
  12024. entry->cmdtype = CMDNORMAL;
  12025. entry->u.index = idx;
  12026. return;
  12027. }
  12028. INT_OFF;
  12029. cmdp = cmdlookup(name, 1);
  12030. cmdp->cmdtype = CMDNORMAL;
  12031. cmdp->param.index = idx;
  12032. INT_ON;
  12033. goto success;
  12034. }
  12035. /* We failed. If there was an entry for this command, delete it */
  12036. if (cmdp && updatetbl)
  12037. delete_cmd_entry();
  12038. if (act & DO_ERR)
  12039. ash_msg("%s: %s", name, errmsg(e, "not found"));
  12040. entry->cmdtype = CMDUNKNOWN;
  12041. return;
  12042. builtin_success:
  12043. if (!updatetbl) {
  12044. entry->cmdtype = CMDBUILTIN;
  12045. entry->u.cmd = bcmd;
  12046. return;
  12047. }
  12048. INT_OFF;
  12049. cmdp = cmdlookup(name, 1);
  12050. cmdp->cmdtype = CMDBUILTIN;
  12051. cmdp->param.cmd = bcmd;
  12052. INT_ON;
  12053. success:
  12054. cmdp->rehash = 0;
  12055. entry->cmdtype = cmdp->cmdtype;
  12056. entry->u = cmdp->param;
  12057. }
  12058. /*
  12059. * The trap builtin.
  12060. */
  12061. static int FAST_FUNC
  12062. trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  12063. {
  12064. char *action;
  12065. char **ap;
  12066. int signo, exitcode;
  12067. nextopt(nullstr);
  12068. ap = argptr;
  12069. if (!*ap) {
  12070. for (signo = 0; signo < NSIG; signo++) {
  12071. char *tr = trap_ptr[signo];
  12072. if (tr) {
  12073. /* note: bash adds "SIG", but only if invoked
  12074. * as "bash". If called as "sh", or if set -o posix,
  12075. * then it prints short signal names.
  12076. * We are printing short names: */
  12077. out1fmt("trap -- %s %s\n",
  12078. single_quote(tr),
  12079. get_signame(signo));
  12080. /* trap_ptr != trap only if we are in special-cased `trap` code.
  12081. * In this case, we will exit very soon, no need to free(). */
  12082. /* if (trap_ptr != trap && tp[0]) */
  12083. /* free(tr); */
  12084. }
  12085. }
  12086. /*
  12087. if (trap_ptr != trap) {
  12088. free(trap_ptr);
  12089. trap_ptr = trap;
  12090. }
  12091. */
  12092. return 0;
  12093. }
  12094. /* Why the second check?
  12095. * "trap NUM [sig2]..." is the same as "trap - NUM [sig2]..."
  12096. * In this case, NUM is signal no, not an action.
  12097. */
  12098. action = NULL;
  12099. if (ap[1] && !is_number(ap[0]))
  12100. action = *ap++;
  12101. exitcode = 0;
  12102. while (*ap) {
  12103. signo = get_signum(*ap);
  12104. if (signo < 0) {
  12105. /* Mimic bash message exactly */
  12106. ash_msg("%s: invalid signal specification", *ap);
  12107. exitcode = 1;
  12108. goto next;
  12109. }
  12110. INT_OFF;
  12111. if (action) {
  12112. if (LONE_DASH(action))
  12113. action = NULL;
  12114. else {
  12115. if (action[0]) /* not NULL and not "" and not "-" */
  12116. may_have_traps = 1;
  12117. action = ckstrdup(action);
  12118. }
  12119. }
  12120. free(trap[signo]);
  12121. trap[signo] = action;
  12122. if (signo != 0)
  12123. setsignal(signo);
  12124. INT_ON;
  12125. next:
  12126. ap++;
  12127. }
  12128. return exitcode;
  12129. }
  12130. /* ============ Builtins */
  12131. #if ENABLE_ASH_HELP
  12132. static int FAST_FUNC
  12133. helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  12134. {
  12135. unsigned col;
  12136. unsigned i;
  12137. out1fmt(
  12138. "Built-in commands:\n"
  12139. "------------------\n");
  12140. for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
  12141. col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
  12142. builtintab[i].name + 1);
  12143. if (col > 60) {
  12144. out1fmt("\n");
  12145. col = 0;
  12146. }
  12147. }
  12148. # if ENABLE_FEATURE_SH_STANDALONE
  12149. {
  12150. const char *a = applet_names;
  12151. while (*a) {
  12152. col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
  12153. if (col > 60) {
  12154. out1fmt("\n");
  12155. col = 0;
  12156. }
  12157. while (*a++ != '\0')
  12158. continue;
  12159. }
  12160. }
  12161. # endif
  12162. newline_and_flush(stdout);
  12163. return EXIT_SUCCESS;
  12164. }
  12165. #endif
  12166. #if MAX_HISTORY
  12167. static int FAST_FUNC
  12168. historycmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  12169. {
  12170. show_history(line_input_state);
  12171. return EXIT_SUCCESS;
  12172. }
  12173. #endif
  12174. /*
  12175. * The export and readonly commands.
  12176. */
  12177. static int FAST_FUNC
  12178. exportcmd(int argc UNUSED_PARAM, char **argv)
  12179. {
  12180. struct var *vp;
  12181. char *name;
  12182. const char *p;
  12183. char **aptr;
  12184. char opt;
  12185. int flag;
  12186. int flag_off;
  12187. /* "readonly" in bash accepts, but ignores -n.
  12188. * We do the same: it saves a conditional in nextopt's param.
  12189. */
  12190. flag_off = 0;
  12191. while ((opt = nextopt("np")) != '\0') {
  12192. if (opt == 'n')
  12193. flag_off = VEXPORT;
  12194. }
  12195. flag = VEXPORT;
  12196. if (argv[0][0] == 'r') {
  12197. flag = VREADONLY;
  12198. flag_off = 0; /* readonly ignores -n */
  12199. }
  12200. flag_off = ~flag_off;
  12201. /*if (opt_p_not_specified) - bash doesn't check this. Try "export -p NAME" */
  12202. {
  12203. aptr = argptr;
  12204. name = *aptr;
  12205. if (name) {
  12206. do {
  12207. p = strchr(name, '=');
  12208. if (p != NULL) {
  12209. p++;
  12210. } else {
  12211. vp = *findvar(hashvar(name), name);
  12212. if (vp) {
  12213. vp->flags = ((vp->flags | flag) & flag_off);
  12214. continue;
  12215. }
  12216. }
  12217. setvar(name, p, (flag & flag_off));
  12218. } while ((name = *++aptr) != NULL);
  12219. return 0;
  12220. }
  12221. }
  12222. /* No arguments. Show the list of exported or readonly vars.
  12223. * -n is ignored.
  12224. */
  12225. showvars(argv[0], flag, 0);
  12226. return 0;
  12227. }
  12228. /*
  12229. * Delete a function if it exists.
  12230. */
  12231. static void
  12232. unsetfunc(const char *name)
  12233. {
  12234. struct tblentry *cmdp;
  12235. cmdp = cmdlookup(name, 0);
  12236. if (cmdp != NULL && cmdp->cmdtype == CMDFUNCTION)
  12237. delete_cmd_entry();
  12238. }
  12239. /*
  12240. * The unset builtin command. We unset the function before we unset the
  12241. * variable to allow a function to be unset when there is a readonly variable
  12242. * with the same name.
  12243. */
  12244. static int FAST_FUNC
  12245. unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  12246. {
  12247. char **ap;
  12248. int i;
  12249. int flag = 0;
  12250. while ((i = nextopt("vf")) != 0) {
  12251. flag = i;
  12252. }
  12253. for (ap = argptr; *ap; ap++) {
  12254. if (flag != 'f') {
  12255. unsetvar(*ap);
  12256. continue;
  12257. }
  12258. if (flag != 'v')
  12259. unsetfunc(*ap);
  12260. }
  12261. return 0;
  12262. }
  12263. static const unsigned char timescmd_str[] ALIGN1 = {
  12264. ' ', offsetof(struct tms, tms_utime),
  12265. '\n', offsetof(struct tms, tms_stime),
  12266. ' ', offsetof(struct tms, tms_cutime),
  12267. '\n', offsetof(struct tms, tms_cstime),
  12268. 0
  12269. };
  12270. static int FAST_FUNC
  12271. timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  12272. {
  12273. unsigned clk_tck;
  12274. const unsigned char *p;
  12275. struct tms buf;
  12276. clk_tck = bb_clk_tck();
  12277. times(&buf);
  12278. p = timescmd_str;
  12279. do {
  12280. unsigned sec, frac;
  12281. unsigned long t;
  12282. t = *(clock_t *)(((char *) &buf) + p[1]);
  12283. sec = t / clk_tck;
  12284. frac = t % clk_tck;
  12285. out1fmt("%um%u.%03us%c",
  12286. sec / 60, sec % 60,
  12287. (frac * 1000) / clk_tck,
  12288. p[0]);
  12289. p += 2;
  12290. } while (*p);
  12291. return 0;
  12292. }
  12293. #if ENABLE_FEATURE_SH_MATH
  12294. /*
  12295. * The let builtin. Partially stolen from GNU Bash, the Bourne Again SHell.
  12296. * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
  12297. *
  12298. * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
  12299. */
  12300. static int FAST_FUNC
  12301. letcmd(int argc UNUSED_PARAM, char **argv)
  12302. {
  12303. arith_t i;
  12304. argv++;
  12305. if (!*argv)
  12306. ash_msg_and_raise_error("expression expected");
  12307. do {
  12308. i = ash_arith(*argv);
  12309. } while (*++argv);
  12310. return !i;
  12311. }
  12312. #endif
  12313. /*
  12314. * The read builtin. Options:
  12315. * -r Do not interpret '\' specially
  12316. * -s Turn off echo (tty only)
  12317. * -n NCHARS Read NCHARS max
  12318. * -p PROMPT Display PROMPT on stderr (if input is from tty)
  12319. * -t SECONDS Timeout after SECONDS (tty or pipe only)
  12320. * -u FD Read from given FD instead of fd 0
  12321. * -d DELIM End on DELIM char, not newline
  12322. * This uses unbuffered input, which may be avoidable in some cases.
  12323. * TODO: bash also has:
  12324. * -a ARRAY Read into array[0],[1],etc
  12325. * -e Use line editing (tty only)
  12326. */
  12327. static int FAST_FUNC
  12328. readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  12329. {
  12330. char *opt_n = NULL;
  12331. char *opt_p = NULL;
  12332. char *opt_t = NULL;
  12333. char *opt_u = NULL;
  12334. char *opt_d = NULL; /* optimized out if !BASH */
  12335. int read_flags = 0;
  12336. const char *r;
  12337. int i;
  12338. while ((i = nextopt("p:u:rt:n:sd:")) != '\0') {
  12339. switch (i) {
  12340. case 'p':
  12341. opt_p = optionarg;
  12342. break;
  12343. case 'n':
  12344. opt_n = optionarg;
  12345. break;
  12346. case 's':
  12347. read_flags |= BUILTIN_READ_SILENT;
  12348. break;
  12349. case 't':
  12350. opt_t = optionarg;
  12351. break;
  12352. case 'r':
  12353. read_flags |= BUILTIN_READ_RAW;
  12354. break;
  12355. case 'u':
  12356. opt_u = optionarg;
  12357. break;
  12358. #if BASH_READ_D
  12359. case 'd':
  12360. opt_d = optionarg;
  12361. break;
  12362. #endif
  12363. default:
  12364. break;
  12365. }
  12366. }
  12367. /* "read -s" needs to save/restore termios, can't allow ^C
  12368. * to jump out of it.
  12369. */
  12370. again:
  12371. INT_OFF;
  12372. r = shell_builtin_read(setvar0,
  12373. argptr,
  12374. bltinlookup("IFS"), /* can be NULL */
  12375. read_flags,
  12376. opt_n,
  12377. opt_p,
  12378. opt_t,
  12379. opt_u,
  12380. opt_d
  12381. );
  12382. INT_ON;
  12383. if ((uintptr_t)r == 1 && errno == EINTR) {
  12384. /* To get SIGCHLD: sleep 1 & read x; echo $x
  12385. * Correct behavior is to not exit "read"
  12386. */
  12387. if (pending_sig == 0)
  12388. goto again;
  12389. }
  12390. if ((uintptr_t)r > 1)
  12391. ash_msg_and_raise_error(r);
  12392. return (uintptr_t)r;
  12393. }
  12394. static int FAST_FUNC
  12395. umaskcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  12396. {
  12397. static const char permuser[3] ALIGN1 = "ogu";
  12398. mode_t mask;
  12399. int symbolic_mode = 0;
  12400. while (nextopt("S") != '\0') {
  12401. symbolic_mode = 1;
  12402. }
  12403. INT_OFF;
  12404. mask = umask(0);
  12405. umask(mask);
  12406. INT_ON;
  12407. if (*argptr == NULL) {
  12408. if (symbolic_mode) {
  12409. char buf[sizeof(",u=rwx,g=rwx,o=rwx")];
  12410. char *p = buf;
  12411. int i;
  12412. i = 2;
  12413. for (;;) {
  12414. *p++ = ',';
  12415. *p++ = permuser[i];
  12416. *p++ = '=';
  12417. /* mask is 0..0uuugggooo. i=2 selects uuu bits */
  12418. if (!(mask & 0400)) *p++ = 'r';
  12419. if (!(mask & 0200)) *p++ = 'w';
  12420. if (!(mask & 0100)) *p++ = 'x';
  12421. mask <<= 3;
  12422. if (--i < 0)
  12423. break;
  12424. }
  12425. *p = '\0';
  12426. puts(buf + 1);
  12427. } else {
  12428. out1fmt("%04o\n", mask);
  12429. }
  12430. } else {
  12431. char *modestr = *argptr;
  12432. /* numeric umasks are taken as-is */
  12433. /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
  12434. if (!isdigit(modestr[0]))
  12435. mask ^= 0777;
  12436. mask = bb_parse_mode(modestr, mask);
  12437. if ((unsigned)mask > 0777) {
  12438. ash_msg_and_raise_error("illegal mode: %s", modestr);
  12439. }
  12440. if (!isdigit(modestr[0]))
  12441. mask ^= 0777;
  12442. umask(mask);
  12443. }
  12444. return 0;
  12445. }
  12446. static int FAST_FUNC
  12447. ulimitcmd(int argc UNUSED_PARAM, char **argv)
  12448. {
  12449. return shell_builtin_ulimit(argv);
  12450. }
  12451. /* ============ main() and helpers */
  12452. /*
  12453. * Called to exit the shell.
  12454. */
  12455. static void
  12456. exitshell(void)
  12457. {
  12458. struct jmploc loc;
  12459. char *p;
  12460. int status;
  12461. #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
  12462. save_history(line_input_state);
  12463. #endif
  12464. status = exitstatus;
  12465. TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
  12466. if (setjmp(loc.loc)) {
  12467. if (exception_type == EXEXIT)
  12468. status = exitstatus;
  12469. goto out;
  12470. }
  12471. exception_handler = &loc;
  12472. p = trap[0];
  12473. if (p) {
  12474. trap[0] = NULL;
  12475. evalskip = 0;
  12476. evalstring(p, 0);
  12477. /*free(p); - we'll exit soon */
  12478. }
  12479. out:
  12480. /* dash wraps setjobctl(0) in "if (setjmp(loc.loc) == 0) {...}".
  12481. * our setjobctl(0) does not panic if tcsetpgrp fails inside it.
  12482. */
  12483. setjobctl(0);
  12484. flush_stdout_stderr();
  12485. _exit(status);
  12486. /* NOTREACHED */
  12487. }
  12488. /* Don't inline: conserve stack of caller from having our locals too */
  12489. static NOINLINE void
  12490. init(void)
  12491. {
  12492. /* we will never free this */
  12493. basepf.next_to_pgetc = basepf.buf = ckmalloc(IBUFSIZ);
  12494. basepf.linno = 1;
  12495. sigmode[SIGCHLD - 1] = S_DFL; /* ensure we install handler even if it is SIG_IGNed */
  12496. setsignal(SIGCHLD);
  12497. /* bash re-enables SIGHUP which is SIG_IGNed on entry.
  12498. * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
  12499. */
  12500. signal(SIGHUP, SIG_DFL);
  12501. {
  12502. char **envp;
  12503. const char *p;
  12504. initvar();
  12505. for (envp = environ; envp && *envp; envp++) {
  12506. /* Used to have
  12507. * p = endofname(*envp);
  12508. * if (p != *envp && *p == '=') {
  12509. * here to weed out badly-named variables, but this breaks
  12510. * scenarios where people do want them passed to children:
  12511. * import os
  12512. * os.environ["test-test"]="test"
  12513. * if os.fork() == 0:
  12514. * os.execv("ash", [ 'ash', '-c', 'eval $(export -p); echo OK' ]) # fixes this
  12515. * os.execv("ash", [ 'ash', '-c', 'env | grep test-test' ]) # breaks this
  12516. */
  12517. if (strchr(*envp, '=')) {
  12518. setvareq(*envp, VEXPORT|VTEXTFIXED);
  12519. }
  12520. }
  12521. setvareq((char*)defoptindvar, VTEXTFIXED);
  12522. setvar0("PPID", utoa(getppid()));
  12523. #if BASH_SHLVL_VAR
  12524. p = lookupvar("SHLVL");
  12525. setvar("SHLVL", utoa((p ? atoi(p) : 0) + 1), VEXPORT);
  12526. #endif
  12527. #if BASH_HOSTNAME_VAR
  12528. if (!lookupvar("HOSTNAME")) {
  12529. struct utsname uts;
  12530. uname(&uts);
  12531. setvar0("HOSTNAME", uts.nodename);
  12532. }
  12533. #endif
  12534. p = lookupvar("PWD");
  12535. if (p) {
  12536. struct stat st1, st2;
  12537. if (p[0] != '/' || stat(p, &st1) || stat(".", &st2)
  12538. || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino
  12539. ) {
  12540. p = NULL;
  12541. }
  12542. }
  12543. setpwd(p, 0);
  12544. }
  12545. }
  12546. //usage:#define ash_trivial_usage
  12547. //usage: "[-/+OPTIONS] [-/+o OPT]... [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS]]"
  12548. //usage:#define ash_full_usage "\n\n"
  12549. //usage: "Unix shell interpreter"
  12550. /*
  12551. * Process the shell command line arguments.
  12552. */
  12553. static int
  12554. procargs(char **argv)
  12555. {
  12556. int i;
  12557. const char *xminusc;
  12558. char **xargv;
  12559. int login_sh;
  12560. xargv = argv;
  12561. login_sh = xargv[0] && xargv[0][0] == '-';
  12562. arg0 = xargv[0];
  12563. /* if (xargv[0]) - mmm, this is always true! */
  12564. xargv++;
  12565. for (i = 0; i < NOPTS; i++)
  12566. optlist[i] = 2;
  12567. argptr = xargv;
  12568. if (options(/*cmdline:*/ 1, &login_sh)) {
  12569. /* it already printed err message */
  12570. raise_exception(EXERROR);
  12571. }
  12572. xargv = argptr;
  12573. xminusc = minusc;
  12574. if (*xargv == NULL) {
  12575. if (xminusc)
  12576. ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
  12577. sflag = 1;
  12578. }
  12579. if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
  12580. iflag = 1;
  12581. if (mflag == 2)
  12582. mflag = iflag;
  12583. for (i = 0; i < NOPTS; i++)
  12584. if (optlist[i] == 2)
  12585. optlist[i] = 0;
  12586. #if DEBUG == 2
  12587. debug = 1;
  12588. #endif
  12589. /* POSIX 1003.2: first arg after "-c CMD" is $0, remainder $1... */
  12590. if (xminusc) {
  12591. minusc = *xargv++;
  12592. if (*xargv)
  12593. goto setarg0;
  12594. } else if (!sflag) {
  12595. setinputfile(*xargv, 0);
  12596. setarg0:
  12597. arg0 = *xargv++;
  12598. commandname = arg0;
  12599. }
  12600. shellparam.p = xargv;
  12601. #if ENABLE_ASH_GETOPTS
  12602. shellparam.optind = 1;
  12603. shellparam.optoff = -1;
  12604. #endif
  12605. /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
  12606. while (*xargv) {
  12607. shellparam.nparam++;
  12608. xargv++;
  12609. }
  12610. optschanged();
  12611. return login_sh;
  12612. }
  12613. /*
  12614. * Read /etc/profile, ~/.profile, $ENV.
  12615. */
  12616. static void
  12617. read_profile(const char *name)
  12618. {
  12619. name = expandstr(name, DQSYNTAX);
  12620. if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
  12621. return;
  12622. cmdloop(0);
  12623. popfile();
  12624. }
  12625. /*
  12626. * This routine is called when an error or an interrupt occurs in an
  12627. * interactive shell and control is returned to the main command loop.
  12628. * (In dash, this function is auto-generated by build machinery).
  12629. */
  12630. static void
  12631. reset(void)
  12632. {
  12633. /* from eval.c: */
  12634. evalskip = 0;
  12635. loopnest = 0;
  12636. /* from expand.c: */
  12637. ifsfree();
  12638. /* from input.c: */
  12639. g_parsefile->left_in_buffer = 0;
  12640. g_parsefile->left_in_line = 0; /* clear input buffer */
  12641. popallfiles();
  12642. /* from redir.c: */
  12643. unwindredir(NULL);
  12644. /* from var.c: */
  12645. unwindlocalvars(NULL);
  12646. }
  12647. #if PROFILE
  12648. static short profile_buf[16384];
  12649. extern int etext();
  12650. #endif
  12651. /*
  12652. * Main routine. We initialize things, parse the arguments, execute
  12653. * profiles if we're a login shell, and then call cmdloop to execute
  12654. * commands. The setjmp call sets up the location to jump to when an
  12655. * exception occurs. When an exception occurs the variable "state"
  12656. * is used to figure out how far we had gotten.
  12657. */
  12658. int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  12659. int ash_main(int argc UNUSED_PARAM, char **argv)
  12660. {
  12661. volatile smallint state;
  12662. struct jmploc jmploc;
  12663. struct stackmark smark;
  12664. int login_sh;
  12665. /* Initialize global data */
  12666. INIT_G_misc();
  12667. INIT_G_memstack();
  12668. INIT_G_var();
  12669. #if ENABLE_ASH_ALIAS
  12670. INIT_G_alias();
  12671. #endif
  12672. INIT_G_cmdtable();
  12673. #if PROFILE
  12674. monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
  12675. #endif
  12676. #if ENABLE_FEATURE_EDITING
  12677. line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
  12678. #endif
  12679. state = 0;
  12680. if (setjmp(jmploc.loc)) {
  12681. smallint e;
  12682. smallint s;
  12683. reset();
  12684. e = exception_type;
  12685. s = state;
  12686. if (e == EXEXIT || s == 0 || iflag == 0 || shlvl) {
  12687. exitshell();
  12688. }
  12689. if (e == EXINT) {
  12690. newline_and_flush(stderr);
  12691. }
  12692. popstackmark(&smark);
  12693. FORCE_INT_ON; /* enable interrupts */
  12694. if (s == 1)
  12695. goto state1;
  12696. if (s == 2)
  12697. goto state2;
  12698. if (s == 3)
  12699. goto state3;
  12700. goto state4;
  12701. }
  12702. exception_handler = &jmploc;
  12703. rootpid = getpid();
  12704. init();
  12705. setstackmark(&smark);
  12706. login_sh = procargs(argv);
  12707. #if DEBUG
  12708. TRACE(("Shell args: "));
  12709. trace_puts_args(argv);
  12710. #endif
  12711. if (login_sh) {
  12712. const char *hp;
  12713. state = 1;
  12714. read_profile("/etc/profile");
  12715. state1:
  12716. state = 2;
  12717. hp = lookupvar("HOME");
  12718. if (hp)
  12719. read_profile("$HOME/.profile");
  12720. }
  12721. state2:
  12722. state = 3;
  12723. if (
  12724. #ifndef linux
  12725. getuid() == geteuid() && getgid() == getegid() &&
  12726. #endif
  12727. iflag
  12728. ) {
  12729. const char *shinit = lookupvar("ENV");
  12730. if (shinit != NULL && *shinit != '\0')
  12731. read_profile(shinit);
  12732. }
  12733. popstackmark(&smark);
  12734. state3:
  12735. state = 4;
  12736. if (minusc) {
  12737. /* evalstring pushes parsefile stack.
  12738. * Ensure we don't falsely claim that 0 (stdin)
  12739. * is one of stacked source fds.
  12740. * Testcase: ash -c 'exec 1>&0' must not complain. */
  12741. // if (!sflag) g_parsefile->pf_fd = -1;
  12742. // ^^ not necessary since now we special-case fd 0
  12743. // in save_fd_on_redirect()
  12744. evalstring(minusc, sflag ? 0 : EV_EXIT);
  12745. }
  12746. if (sflag || minusc == NULL) {
  12747. #if MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
  12748. if (iflag) {
  12749. const char *hp = lookupvar("HISTFILE");
  12750. if (!hp) {
  12751. hp = lookupvar("HOME");
  12752. if (hp) {
  12753. INT_OFF;
  12754. hp = concat_path_file(hp, ".ash_history");
  12755. setvar0("HISTFILE", hp);
  12756. free((char*)hp);
  12757. INT_ON;
  12758. hp = lookupvar("HISTFILE");
  12759. }
  12760. }
  12761. if (hp)
  12762. line_input_state->hist_file = hp;
  12763. # if ENABLE_FEATURE_SH_HISTFILESIZE
  12764. hp = lookupvar("HISTFILESIZE");
  12765. line_input_state->max_history = size_from_HISTFILESIZE(hp);
  12766. # endif
  12767. }
  12768. #endif
  12769. state4: /* XXX ??? - why isn't this before the "if" statement */
  12770. cmdloop(1);
  12771. }
  12772. #if PROFILE
  12773. monitor(0);
  12774. #endif
  12775. #ifdef GPROF
  12776. {
  12777. extern void _mcleanup(void);
  12778. _mcleanup();
  12779. }
  12780. #endif
  12781. TRACE(("End of main reached\n"));
  12782. exitshell();
  12783. /* NOTREACHED */
  12784. }
  12785. /*-
  12786. * Copyright (c) 1989, 1991, 1993, 1994
  12787. * The Regents of the University of California. All rights reserved.
  12788. *
  12789. * This code is derived from software contributed to Berkeley by
  12790. * Kenneth Almquist.
  12791. *
  12792. * Redistribution and use in source and binary forms, with or without
  12793. * modification, are permitted provided that the following conditions
  12794. * are met:
  12795. * 1. Redistributions of source code must retain the above copyright
  12796. * notice, this list of conditions and the following disclaimer.
  12797. * 2. Redistributions in binary form must reproduce the above copyright
  12798. * notice, this list of conditions and the following disclaimer in the
  12799. * documentation and/or other materials provided with the distribution.
  12800. * 3. Neither the name of the University nor the names of its contributors
  12801. * may be used to endorse or promote products derived from this software
  12802. * without specific prior written permission.
  12803. *
  12804. * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ''AS IS'' AND
  12805. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  12806. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  12807. * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
  12808. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  12809. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  12810. * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  12811. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  12812. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  12813. * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  12814. * SUCH DAMAGE.
  12815. */