ash.c 313 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028
  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 F_DUPFD_CLOEXEC
  230. # define F_DUPFD_CLOEXEC F_DUPFD
  231. #endif
  232. #ifndef PIPE_BUF
  233. # define PIPE_BUF 4096 /* amount of buffering in a pipe */
  234. #endif
  235. #if !BB_MMU
  236. # error "Do not even bother, ash will not run on NOMMU machine"
  237. #endif
  238. /* ============ Hash table sizes. Configurable. */
  239. #define VTABSIZE 39
  240. #define ATABSIZE 39
  241. #define CMDTABLESIZE 31 /* should be prime */
  242. /* ============ Shell options */
  243. static const char *const optletters_optnames[] = {
  244. "e" "errexit",
  245. "f" "noglob",
  246. "I" "ignoreeof",
  247. "i" "interactive",
  248. "m" "monitor",
  249. "n" "noexec",
  250. "s" "stdin",
  251. "x" "xtrace",
  252. "v" "verbose",
  253. "C" "noclobber",
  254. "a" "allexport",
  255. "b" "notify",
  256. "u" "nounset",
  257. "\0" "vi"
  258. #if BASH_PIPEFAIL
  259. ,"\0" "pipefail"
  260. #endif
  261. #if DEBUG
  262. ,"\0" "nolog"
  263. ,"\0" "debug"
  264. #endif
  265. };
  266. #define optletters(n) optletters_optnames[n][0]
  267. #define optnames(n) (optletters_optnames[n] + 1)
  268. enum { NOPTS = ARRAY_SIZE(optletters_optnames) };
  269. /* ============ Misc data */
  270. #define msg_illnum "Illegal number: %s"
  271. /*
  272. * We enclose jmp_buf in a structure so that we can declare pointers to
  273. * jump locations. The global variable handler contains the location to
  274. * jump to when an exception occurs, and the global variable exception_type
  275. * contains a code identifying the exception. To implement nested
  276. * exception handlers, the user should save the value of handler on entry
  277. * to an inner scope, set handler to point to a jmploc structure for the
  278. * inner scope, and restore handler on exit from the scope.
  279. */
  280. struct jmploc {
  281. jmp_buf loc;
  282. };
  283. struct globals_misc {
  284. uint8_t exitstatus; /* exit status of last command */
  285. uint8_t back_exitstatus;/* exit status of backquoted command */
  286. smallint job_warning; /* user was warned about stopped jobs (can be 2, 1 or 0). */
  287. int rootpid; /* pid of main shell */
  288. /* shell level: 0 for the main shell, 1 for its children, and so on */
  289. int shlvl;
  290. #define rootshell (!shlvl)
  291. char *minusc; /* argument to -c option */
  292. char *curdir; // = nullstr; /* current working directory */
  293. char *physdir; // = nullstr; /* physical working directory */
  294. char *arg0; /* value of $0 */
  295. struct jmploc *exception_handler;
  296. volatile int suppress_int; /* counter */
  297. volatile /*sig_atomic_t*/ smallint pending_int; /* 1 = got SIGINT */
  298. volatile /*sig_atomic_t*/ smallint got_sigchld; /* 1 = got SIGCHLD */
  299. volatile /*sig_atomic_t*/ smallint pending_sig; /* last pending signal */
  300. smallint exception_type; /* kind of exception (0..5) */
  301. /* exceptions */
  302. #define EXINT 0 /* SIGINT received */
  303. #define EXERROR 1 /* a generic error */
  304. #define EXEXIT 4 /* exit the shell */
  305. char nullstr[1]; /* zero length string */
  306. char optlist[NOPTS];
  307. #define eflag optlist[0]
  308. #define fflag optlist[1]
  309. #define Iflag optlist[2]
  310. #define iflag optlist[3]
  311. #define mflag optlist[4]
  312. #define nflag optlist[5]
  313. #define sflag optlist[6]
  314. #define xflag optlist[7]
  315. #define vflag optlist[8]
  316. #define Cflag optlist[9]
  317. #define aflag optlist[10]
  318. #define bflag optlist[11]
  319. #define uflag optlist[12]
  320. #define viflag optlist[13]
  321. #if BASH_PIPEFAIL
  322. # define pipefail optlist[14]
  323. #else
  324. # define pipefail 0
  325. #endif
  326. #if DEBUG
  327. # define nolog optlist[14 + BASH_PIPEFAIL]
  328. # define debug optlist[15 + BASH_PIPEFAIL]
  329. #endif
  330. /* trap handler commands */
  331. /*
  332. * Sigmode records the current value of the signal handlers for the various
  333. * modes. A value of zero means that the current handler is not known.
  334. * S_HARD_IGN indicates that the signal was ignored on entry to the shell.
  335. */
  336. char sigmode[NSIG - 1];
  337. #define S_DFL 1 /* default signal handling (SIG_DFL) */
  338. #define S_CATCH 2 /* signal is caught */
  339. #define S_IGN 3 /* signal is ignored (SIG_IGN) */
  340. #define S_HARD_IGN 4 /* signal is ignored permanently (it was SIG_IGN on entry to shell) */
  341. /* indicates specified signal received */
  342. uint8_t gotsig[NSIG - 1]; /* offset by 1: "signal" 0 is meaningless */
  343. uint8_t may_have_traps; /* 0: definitely no traps are set, 1: some traps may be set */
  344. char *trap[NSIG];
  345. char **trap_ptr; /* used only by "trap hack" */
  346. /* Rarely referenced stuff */
  347. #if ENABLE_ASH_RANDOM_SUPPORT
  348. random_t random_gen;
  349. #endif
  350. pid_t backgndpid; /* pid of last background process */
  351. };
  352. extern struct globals_misc *const ash_ptr_to_globals_misc;
  353. #define G_misc (*ash_ptr_to_globals_misc)
  354. #define exitstatus (G_misc.exitstatus )
  355. #define back_exitstatus (G_misc.back_exitstatus )
  356. #define job_warning (G_misc.job_warning)
  357. #define rootpid (G_misc.rootpid )
  358. #define shlvl (G_misc.shlvl )
  359. #define minusc (G_misc.minusc )
  360. #define curdir (G_misc.curdir )
  361. #define physdir (G_misc.physdir )
  362. #define arg0 (G_misc.arg0 )
  363. #define exception_handler (G_misc.exception_handler)
  364. #define exception_type (G_misc.exception_type )
  365. #define suppress_int (G_misc.suppress_int )
  366. #define pending_int (G_misc.pending_int )
  367. #define got_sigchld (G_misc.got_sigchld )
  368. #define pending_sig (G_misc.pending_sig )
  369. #define nullstr (G_misc.nullstr )
  370. #define optlist (G_misc.optlist )
  371. #define sigmode (G_misc.sigmode )
  372. #define gotsig (G_misc.gotsig )
  373. #define may_have_traps (G_misc.may_have_traps )
  374. #define trap (G_misc.trap )
  375. #define trap_ptr (G_misc.trap_ptr )
  376. #define random_gen (G_misc.random_gen )
  377. #define backgndpid (G_misc.backgndpid )
  378. #define INIT_G_misc() do { \
  379. (*(struct globals_misc**)&ash_ptr_to_globals_misc) = xzalloc(sizeof(G_misc)); \
  380. barrier(); \
  381. curdir = nullstr; \
  382. physdir = nullstr; \
  383. trap_ptr = trap; \
  384. } while (0)
  385. /* ============ DEBUG */
  386. #if DEBUG
  387. static void trace_printf(const char *fmt, ...);
  388. static void trace_vprintf(const char *fmt, va_list va);
  389. # define TRACE(param) trace_printf param
  390. # define TRACEV(param) trace_vprintf param
  391. # define close(fd) do { \
  392. int dfd = (fd); \
  393. if (close(dfd) < 0) \
  394. bb_error_msg("bug on %d: closing %d(0x%x)", \
  395. __LINE__, dfd, dfd); \
  396. } while (0)
  397. #else
  398. # define TRACE(param)
  399. # define TRACEV(param)
  400. #endif
  401. /* ============ Utility functions */
  402. #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
  403. #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
  404. static int
  405. isdigit_str9(const char *str)
  406. {
  407. int maxlen = 9 + 1; /* max 9 digits: 999999999 */
  408. while (--maxlen && isdigit(*str))
  409. str++;
  410. return (*str == '\0');
  411. }
  412. static const char *
  413. var_end(const char *var)
  414. {
  415. while (*var)
  416. if (*var++ == '=')
  417. break;
  418. return var;
  419. }
  420. /* ============ Interrupts / exceptions */
  421. static void exitshell(void) NORETURN;
  422. /*
  423. * These macros allow the user to suspend the handling of interrupt signals
  424. * over a period of time. This is similar to SIGHOLD or to sigblock, but
  425. * much more efficient and portable. (But hacking the kernel is so much
  426. * more fun than worrying about efficiency and portability. :-))
  427. */
  428. #if DEBUG_INTONOFF
  429. # define INT_OFF do { \
  430. TRACE(("%s:%d INT_OFF(%d)\n", __func__, __LINE__, suppress_int)); \
  431. suppress_int++; \
  432. barrier(); \
  433. } while (0)
  434. #else
  435. # define INT_OFF do { \
  436. suppress_int++; \
  437. barrier(); \
  438. } while (0)
  439. #endif
  440. /*
  441. * Called to raise an exception. Since C doesn't include exceptions, we
  442. * just do a longjmp to the exception handler. The type of exception is
  443. * stored in the global variable "exception_type".
  444. */
  445. static void raise_exception(int) NORETURN;
  446. static void
  447. raise_exception(int e)
  448. {
  449. #if DEBUG
  450. if (exception_handler == NULL)
  451. abort();
  452. #endif
  453. INT_OFF;
  454. exception_type = e;
  455. longjmp(exception_handler->loc, 1);
  456. }
  457. #if DEBUG
  458. #define raise_exception(e) do { \
  459. TRACE(("raising exception %d on line %d\n", (e), __LINE__)); \
  460. raise_exception(e); \
  461. } while (0)
  462. #endif
  463. /*
  464. * Called when a SIGINT is received. (If the user specifies
  465. * that SIGINT is to be trapped or ignored using the trap builtin, then
  466. * this routine is not called.) Suppressint is nonzero when interrupts
  467. * are held using the INT_OFF macro. (The test for iflag is just
  468. * defensive programming.)
  469. */
  470. static void raise_interrupt(void) NORETURN;
  471. static void
  472. raise_interrupt(void)
  473. {
  474. pending_int = 0;
  475. /* Signal is not automatically unmasked after it is raised,
  476. * do it ourself - unmask all signals */
  477. sigprocmask_allsigs(SIG_UNBLOCK);
  478. /* pending_sig = 0; - now done in signal_handler() */
  479. if (!(rootshell && iflag)) {
  480. /* Kill ourself with SIGINT */
  481. signal(SIGINT, SIG_DFL);
  482. raise(SIGINT);
  483. }
  484. /* bash: ^C even on empty command line sets $? */
  485. exitstatus = SIGINT + 128;
  486. raise_exception(EXINT);
  487. /* NOTREACHED */
  488. }
  489. #if DEBUG
  490. #define raise_interrupt() do { \
  491. TRACE(("raising interrupt on line %d\n", __LINE__)); \
  492. raise_interrupt(); \
  493. } while (0)
  494. #endif
  495. static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
  496. int_on(void)
  497. {
  498. barrier();
  499. if (--suppress_int == 0 && pending_int) {
  500. raise_interrupt();
  501. }
  502. }
  503. #if DEBUG_INTONOFF
  504. # define INT_ON do { \
  505. TRACE(("%s:%d INT_ON(%d)\n", __func__, __LINE__, suppress_int-1)); \
  506. int_on(); \
  507. } while (0)
  508. #else
  509. # define INT_ON int_on()
  510. #endif
  511. static IF_ASH_OPTIMIZE_FOR_SIZE(inline) void
  512. force_int_on(void)
  513. {
  514. barrier();
  515. suppress_int = 0;
  516. if (pending_int)
  517. raise_interrupt();
  518. }
  519. #define FORCE_INT_ON force_int_on()
  520. #define SAVE_INT(v) ((v) = suppress_int)
  521. #define RESTORE_INT(v) do { \
  522. barrier(); \
  523. suppress_int = (v); \
  524. if (suppress_int == 0 && pending_int) \
  525. raise_interrupt(); \
  526. } while (0)
  527. /* ============ Stdout/stderr output */
  528. static void
  529. outstr(const char *p, FILE *file)
  530. {
  531. INT_OFF;
  532. fputs(p, file);
  533. INT_ON;
  534. }
  535. static void
  536. flush_stdout_stderr(void)
  537. {
  538. INT_OFF;
  539. fflush_all();
  540. INT_ON;
  541. }
  542. /* Was called outcslow(c,FILE*), but c was always '\n' */
  543. static void
  544. newline_and_flush(FILE *dest)
  545. {
  546. INT_OFF;
  547. putc('\n', dest);
  548. fflush(dest);
  549. INT_ON;
  550. }
  551. static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
  552. static int
  553. out1fmt(const char *fmt, ...)
  554. {
  555. va_list ap;
  556. int r;
  557. INT_OFF;
  558. va_start(ap, fmt);
  559. r = vprintf(fmt, ap);
  560. va_end(ap);
  561. INT_ON;
  562. return r;
  563. }
  564. static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
  565. static int
  566. fmtstr(char *outbuf, size_t length, const char *fmt, ...)
  567. {
  568. va_list ap;
  569. int ret;
  570. INT_OFF;
  571. va_start(ap, fmt);
  572. ret = vsnprintf(outbuf, length, fmt, ap);
  573. va_end(ap);
  574. INT_ON;
  575. return ret;
  576. }
  577. static void
  578. out1str(const char *p)
  579. {
  580. outstr(p, stdout);
  581. }
  582. static void
  583. out2str(const char *p)
  584. {
  585. outstr(p, stderr);
  586. flush_stdout_stderr();
  587. }
  588. /* ============ Parser structures */
  589. /* control characters in argument strings */
  590. #define CTL_FIRST CTLESC
  591. #define CTLESC ((unsigned char)'\201') /* escape next character */
  592. #define CTLVAR ((unsigned char)'\202') /* variable defn */
  593. #define CTLENDVAR ((unsigned char)'\203')
  594. #define CTLBACKQ ((unsigned char)'\204')
  595. #define CTLARI ((unsigned char)'\206') /* arithmetic expression */
  596. #define CTLENDARI ((unsigned char)'\207')
  597. #define CTLQUOTEMARK ((unsigned char)'\210')
  598. #define CTL_LAST CTLQUOTEMARK
  599. /* variable substitution byte (follows CTLVAR) */
  600. #define VSTYPE 0x0f /* type of variable substitution */
  601. #define VSNUL 0x10 /* colon--treat the empty string as unset */
  602. /* values of VSTYPE field */
  603. #define VSNORMAL 0x1 /* normal variable: $var or ${var} */
  604. #define VSMINUS 0x2 /* ${var-text} */
  605. #define VSPLUS 0x3 /* ${var+text} */
  606. #define VSQUESTION 0x4 /* ${var?message} */
  607. #define VSASSIGN 0x5 /* ${var=text} */
  608. #define VSTRIMRIGHT 0x6 /* ${var%pattern} */
  609. #define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
  610. #define VSTRIMLEFT 0x8 /* ${var#pattern} */
  611. #define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
  612. #define VSLENGTH 0xa /* ${#var} */
  613. #if BASH_SUBSTR
  614. #define VSSUBSTR 0xc /* ${var:position:length} */
  615. #endif
  616. #if BASH_PATTERN_SUBST
  617. #define VSREPLACE 0xd /* ${var/pattern/replacement} */
  618. #define VSREPLACEALL 0xe /* ${var//pattern/replacement} */
  619. #endif
  620. static const char dolatstr[] ALIGN1 = {
  621. CTLQUOTEMARK, CTLVAR, VSNORMAL, '@', '=', CTLQUOTEMARK, '\0'
  622. };
  623. #define DOLATSTRLEN 6
  624. #define NCMD 0
  625. #define NPIPE 1
  626. #define NREDIR 2
  627. #define NBACKGND 3
  628. #define NSUBSHELL 4
  629. #define NAND 5
  630. #define NOR 6
  631. #define NSEMI 7
  632. #define NIF 8
  633. #define NWHILE 9
  634. #define NUNTIL 10
  635. #define NFOR 11
  636. #define NCASE 12
  637. #define NCLIST 13
  638. #define NDEFUN 14
  639. #define NARG 15
  640. #define NTO 16
  641. #if BASH_REDIR_OUTPUT
  642. #define NTO2 17
  643. #endif
  644. #define NCLOBBER 18
  645. #define NFROM 19
  646. #define NFROMTO 20
  647. #define NAPPEND 21
  648. #define NTOFD 22
  649. #define NFROMFD 23
  650. #define NHERE 24
  651. #define NXHERE 25
  652. #define NNOT 26
  653. #define N_NUMBER 27
  654. union node;
  655. struct ncmd {
  656. smallint type; /* Nxxxx */
  657. union node *assign;
  658. union node *args;
  659. union node *redirect;
  660. };
  661. struct npipe {
  662. smallint type;
  663. smallint pipe_backgnd;
  664. struct nodelist *cmdlist;
  665. };
  666. struct nredir {
  667. smallint type;
  668. union node *n;
  669. union node *redirect;
  670. };
  671. struct nbinary {
  672. smallint type;
  673. union node *ch1;
  674. union node *ch2;
  675. };
  676. struct nif {
  677. smallint type;
  678. union node *test;
  679. union node *ifpart;
  680. union node *elsepart;
  681. };
  682. struct nfor {
  683. smallint type;
  684. union node *args;
  685. union node *body;
  686. char *var;
  687. };
  688. struct ncase {
  689. smallint type;
  690. union node *expr;
  691. union node *cases;
  692. };
  693. struct nclist {
  694. smallint type;
  695. union node *next;
  696. union node *pattern;
  697. union node *body;
  698. };
  699. struct narg {
  700. smallint type;
  701. union node *next;
  702. char *text;
  703. struct nodelist *backquote;
  704. };
  705. /* nfile and ndup layout must match!
  706. * NTOFD (>&fdnum) uses ndup structure, but we may discover mid-flight
  707. * that it is actually NTO2 (>&file), and change its type.
  708. */
  709. struct nfile {
  710. smallint type;
  711. union node *next;
  712. int fd;
  713. int _unused_dupfd;
  714. union node *fname;
  715. char *expfname;
  716. };
  717. struct ndup {
  718. smallint type;
  719. union node *next;
  720. int fd;
  721. int dupfd;
  722. union node *vname;
  723. char *_unused_expfname;
  724. };
  725. struct nhere {
  726. smallint type;
  727. union node *next;
  728. int fd;
  729. union node *doc;
  730. };
  731. struct nnot {
  732. smallint type;
  733. union node *com;
  734. };
  735. union node {
  736. smallint type;
  737. struct ncmd ncmd;
  738. struct npipe npipe;
  739. struct nredir nredir;
  740. struct nbinary nbinary;
  741. struct nif nif;
  742. struct nfor nfor;
  743. struct ncase ncase;
  744. struct nclist nclist;
  745. struct narg narg;
  746. struct nfile nfile;
  747. struct ndup ndup;
  748. struct nhere nhere;
  749. struct nnot nnot;
  750. };
  751. /*
  752. * NODE_EOF is returned by parsecmd when it encounters an end of file.
  753. * It must be distinct from NULL.
  754. */
  755. #define NODE_EOF ((union node *) -1L)
  756. struct nodelist {
  757. struct nodelist *next;
  758. union node *n;
  759. };
  760. struct funcnode {
  761. int count;
  762. union node n;
  763. };
  764. /*
  765. * Free a parse tree.
  766. */
  767. static void
  768. freefunc(struct funcnode *f)
  769. {
  770. if (f && --f->count < 0)
  771. free(f);
  772. }
  773. /* ============ Debugging output */
  774. #if DEBUG
  775. static FILE *tracefile;
  776. static void
  777. trace_printf(const char *fmt, ...)
  778. {
  779. va_list va;
  780. if (debug != 1)
  781. return;
  782. if (DEBUG_TIME)
  783. fprintf(tracefile, "%u ", (int) time(NULL));
  784. if (DEBUG_PID)
  785. fprintf(tracefile, "[%u] ", (int) getpid());
  786. if (DEBUG_SIG)
  787. fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
  788. va_start(va, fmt);
  789. vfprintf(tracefile, fmt, va);
  790. va_end(va);
  791. }
  792. static void
  793. trace_vprintf(const char *fmt, va_list va)
  794. {
  795. if (debug != 1)
  796. return;
  797. vfprintf(tracefile, fmt, va);
  798. fprintf(tracefile, "\n");
  799. }
  800. static void
  801. trace_puts(const char *s)
  802. {
  803. if (debug != 1)
  804. return;
  805. fputs(s, tracefile);
  806. }
  807. static void
  808. trace_puts_quoted(char *s)
  809. {
  810. char *p;
  811. char c;
  812. if (debug != 1)
  813. return;
  814. putc('"', tracefile);
  815. for (p = s; *p; p++) {
  816. switch ((unsigned char)*p) {
  817. case '\n': c = 'n'; goto backslash;
  818. case '\t': c = 't'; goto backslash;
  819. case '\r': c = 'r'; goto backslash;
  820. case '\"': c = '\"'; goto backslash;
  821. case '\\': c = '\\'; goto backslash;
  822. case CTLESC: c = 'e'; goto backslash;
  823. case CTLVAR: c = 'v'; goto backslash;
  824. case CTLBACKQ: c = 'q'; goto backslash;
  825. backslash:
  826. putc('\\', tracefile);
  827. putc(c, tracefile);
  828. break;
  829. default:
  830. if (*p >= ' ' && *p <= '~')
  831. putc(*p, tracefile);
  832. else {
  833. putc('\\', tracefile);
  834. putc((*p >> 6) & 03, tracefile);
  835. putc((*p >> 3) & 07, tracefile);
  836. putc(*p & 07, tracefile);
  837. }
  838. break;
  839. }
  840. }
  841. putc('"', tracefile);
  842. }
  843. static void
  844. trace_puts_args(char **ap)
  845. {
  846. if (debug != 1)
  847. return;
  848. if (!*ap)
  849. return;
  850. while (1) {
  851. trace_puts_quoted(*ap);
  852. if (!*++ap) {
  853. putc('\n', tracefile);
  854. break;
  855. }
  856. putc(' ', tracefile);
  857. }
  858. }
  859. static void
  860. opentrace(void)
  861. {
  862. char s[100];
  863. #ifdef O_APPEND
  864. int flags;
  865. #endif
  866. if (debug != 1) {
  867. if (tracefile)
  868. fflush(tracefile);
  869. /* leave open because libedit might be using it */
  870. return;
  871. }
  872. strcpy(s, "./trace");
  873. if (tracefile) {
  874. if (!freopen(s, "a", tracefile)) {
  875. fprintf(stderr, "Can't re-open %s\n", s);
  876. debug = 0;
  877. return;
  878. }
  879. } else {
  880. tracefile = fopen(s, "a");
  881. if (tracefile == NULL) {
  882. fprintf(stderr, "Can't open %s\n", s);
  883. debug = 0;
  884. return;
  885. }
  886. }
  887. #ifdef O_APPEND
  888. flags = fcntl(fileno(tracefile), F_GETFL);
  889. if (flags >= 0)
  890. fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
  891. #endif
  892. setlinebuf(tracefile);
  893. fputs("\nTracing started.\n", tracefile);
  894. }
  895. static void
  896. indent(int amount, char *pfx, FILE *fp)
  897. {
  898. int i;
  899. for (i = 0; i < amount; i++) {
  900. if (pfx && i == amount - 1)
  901. fputs(pfx, fp);
  902. putc('\t', fp);
  903. }
  904. }
  905. /* little circular references here... */
  906. static void shtree(union node *n, int ind, char *pfx, FILE *fp);
  907. static void
  908. sharg(union node *arg, FILE *fp)
  909. {
  910. char *p;
  911. struct nodelist *bqlist;
  912. unsigned char subtype;
  913. if (arg->type != NARG) {
  914. out1fmt("<node type %d>\n", arg->type);
  915. abort();
  916. }
  917. bqlist = arg->narg.backquote;
  918. for (p = arg->narg.text; *p; p++) {
  919. switch ((unsigned char)*p) {
  920. case CTLESC:
  921. p++;
  922. putc(*p, fp);
  923. break;
  924. case CTLVAR:
  925. putc('$', fp);
  926. putc('{', fp);
  927. subtype = *++p;
  928. if (subtype == VSLENGTH)
  929. putc('#', fp);
  930. while (*p != '=') {
  931. putc(*p, fp);
  932. p++;
  933. }
  934. if (subtype & VSNUL)
  935. putc(':', fp);
  936. switch (subtype & VSTYPE) {
  937. case VSNORMAL:
  938. putc('}', fp);
  939. break;
  940. case VSMINUS:
  941. putc('-', fp);
  942. break;
  943. case VSPLUS:
  944. putc('+', fp);
  945. break;
  946. case VSQUESTION:
  947. putc('?', fp);
  948. break;
  949. case VSASSIGN:
  950. putc('=', fp);
  951. break;
  952. case VSTRIMLEFT:
  953. putc('#', fp);
  954. break;
  955. case VSTRIMLEFTMAX:
  956. putc('#', fp);
  957. putc('#', fp);
  958. break;
  959. case VSTRIMRIGHT:
  960. putc('%', fp);
  961. break;
  962. case VSTRIMRIGHTMAX:
  963. putc('%', fp);
  964. putc('%', fp);
  965. break;
  966. case VSLENGTH:
  967. break;
  968. default:
  969. out1fmt("<subtype %d>", subtype);
  970. }
  971. break;
  972. case CTLENDVAR:
  973. putc('}', fp);
  974. break;
  975. case CTLBACKQ:
  976. putc('$', fp);
  977. putc('(', fp);
  978. shtree(bqlist->n, -1, NULL, fp);
  979. putc(')', fp);
  980. break;
  981. default:
  982. putc(*p, fp);
  983. break;
  984. }
  985. }
  986. }
  987. static void
  988. shcmd(union node *cmd, FILE *fp)
  989. {
  990. union node *np;
  991. int first;
  992. const char *s;
  993. int dftfd;
  994. first = 1;
  995. for (np = cmd->ncmd.args; np; np = np->narg.next) {
  996. if (!first)
  997. putc(' ', fp);
  998. sharg(np, fp);
  999. first = 0;
  1000. }
  1001. for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
  1002. if (!first)
  1003. putc(' ', fp);
  1004. dftfd = 0;
  1005. switch (np->nfile.type) {
  1006. case NTO: s = ">>"+1; dftfd = 1; break;
  1007. case NCLOBBER: s = ">|"; dftfd = 1; break;
  1008. case NAPPEND: s = ">>"; dftfd = 1; break;
  1009. #if BASH_REDIR_OUTPUT
  1010. case NTO2:
  1011. #endif
  1012. case NTOFD: s = ">&"; dftfd = 1; break;
  1013. case NFROM: s = "<"; break;
  1014. case NFROMFD: s = "<&"; break;
  1015. case NFROMTO: s = "<>"; break;
  1016. default: s = "*error*"; break;
  1017. }
  1018. if (np->nfile.fd != dftfd)
  1019. fprintf(fp, "%d", np->nfile.fd);
  1020. fputs(s, fp);
  1021. if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
  1022. fprintf(fp, "%d", np->ndup.dupfd);
  1023. } else {
  1024. sharg(np->nfile.fname, fp);
  1025. }
  1026. first = 0;
  1027. }
  1028. }
  1029. static void
  1030. shtree(union node *n, int ind, char *pfx, FILE *fp)
  1031. {
  1032. struct nodelist *lp;
  1033. const char *s;
  1034. if (n == NULL)
  1035. return;
  1036. indent(ind, pfx, fp);
  1037. if (n == NODE_EOF) {
  1038. fputs("<EOF>", fp);
  1039. return;
  1040. }
  1041. switch (n->type) {
  1042. case NSEMI:
  1043. s = "; ";
  1044. goto binop;
  1045. case NAND:
  1046. s = " && ";
  1047. goto binop;
  1048. case NOR:
  1049. s = " || ";
  1050. binop:
  1051. shtree(n->nbinary.ch1, ind, NULL, fp);
  1052. /* if (ind < 0) */
  1053. fputs(s, fp);
  1054. shtree(n->nbinary.ch2, ind, NULL, fp);
  1055. break;
  1056. case NCMD:
  1057. shcmd(n, fp);
  1058. if (ind >= 0)
  1059. putc('\n', fp);
  1060. break;
  1061. case NPIPE:
  1062. for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
  1063. shtree(lp->n, 0, NULL, fp);
  1064. if (lp->next)
  1065. fputs(" | ", fp);
  1066. }
  1067. if (n->npipe.pipe_backgnd)
  1068. fputs(" &", fp);
  1069. if (ind >= 0)
  1070. putc('\n', fp);
  1071. break;
  1072. default:
  1073. fprintf(fp, "<node type %d>", n->type);
  1074. if (ind >= 0)
  1075. putc('\n', fp);
  1076. break;
  1077. }
  1078. }
  1079. static void
  1080. showtree(union node *n)
  1081. {
  1082. trace_puts("showtree called\n");
  1083. shtree(n, 1, NULL, stderr);
  1084. }
  1085. #endif /* DEBUG */
  1086. /* ============ Parser data */
  1087. /*
  1088. * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
  1089. */
  1090. struct strlist {
  1091. struct strlist *next;
  1092. char *text;
  1093. };
  1094. struct alias;
  1095. struct strpush {
  1096. struct strpush *prev; /* preceding string on stack */
  1097. char *prev_string;
  1098. int prev_left_in_line;
  1099. #if ENABLE_ASH_ALIAS
  1100. struct alias *ap; /* if push was associated with an alias */
  1101. #endif
  1102. char *string; /* remember the string since it may change */
  1103. /* Remember last two characters for pungetc. */
  1104. int lastc[2];
  1105. /* Number of outstanding calls to pungetc. */
  1106. int unget;
  1107. };
  1108. /*
  1109. * The parsefile structure pointed to by the global variable parsefile
  1110. * contains information about the current file being read.
  1111. */
  1112. struct parsefile {
  1113. struct parsefile *prev; /* preceding file on stack */
  1114. int linno; /* current line */
  1115. int pf_fd; /* file descriptor (or -1 if string) */
  1116. int left_in_line; /* number of chars left in this line */
  1117. int left_in_buffer; /* number of chars left in this buffer past the line */
  1118. char *next_to_pgetc; /* next char in buffer */
  1119. char *buf; /* input buffer */
  1120. struct strpush *strpush; /* for pushing strings at this level */
  1121. struct strpush basestrpush; /* so pushing one is fast */
  1122. /* Remember last two characters for pungetc. */
  1123. int lastc[2];
  1124. /* Number of outstanding calls to pungetc. */
  1125. int unget;
  1126. };
  1127. static struct parsefile basepf; /* top level input file */
  1128. static struct parsefile *g_parsefile = &basepf; /* current input file */
  1129. static int startlinno; /* line # where last token started */
  1130. static char *commandname; /* currently executing command */
  1131. /* ============ Message printing */
  1132. static void
  1133. ash_vmsg(const char *msg, va_list ap)
  1134. {
  1135. fprintf(stderr, "%s: ", arg0);
  1136. if (commandname) {
  1137. if (strcmp(arg0, commandname))
  1138. fprintf(stderr, "%s: ", commandname);
  1139. if (!iflag || g_parsefile->pf_fd > 0)
  1140. fprintf(stderr, "line %d: ", startlinno);
  1141. }
  1142. vfprintf(stderr, msg, ap);
  1143. newline_and_flush(stderr);
  1144. }
  1145. /*
  1146. * Exverror is called to raise the error exception. If the second argument
  1147. * is not NULL then error prints an error message using printf style
  1148. * formatting. It then raises the error exception.
  1149. */
  1150. static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
  1151. static void
  1152. ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
  1153. {
  1154. #if DEBUG
  1155. if (msg) {
  1156. TRACE(("ash_vmsg_and_raise(%d):", cond));
  1157. TRACEV((msg, ap));
  1158. } else
  1159. TRACE(("ash_vmsg_and_raise(%d):NULL\n", cond));
  1160. if (msg)
  1161. #endif
  1162. ash_vmsg(msg, ap);
  1163. flush_stdout_stderr();
  1164. raise_exception(cond);
  1165. /* NOTREACHED */
  1166. }
  1167. static void ash_msg_and_raise_error(const char *, ...) NORETURN;
  1168. static void
  1169. ash_msg_and_raise_error(const char *msg, ...)
  1170. {
  1171. va_list ap;
  1172. exitstatus = 2;
  1173. va_start(ap, msg);
  1174. ash_vmsg_and_raise(EXERROR, msg, ap);
  1175. /* NOTREACHED */
  1176. va_end(ap);
  1177. }
  1178. /*
  1179. * 'fmt' must be a string literal.
  1180. */
  1181. #define ash_msg_and_raise_perror(fmt, ...) ash_msg_and_raise_error(fmt ": "STRERROR_FMT, ##__VA_ARGS__ STRERROR_ERRNO)
  1182. static void raise_error_syntax(const char *) NORETURN;
  1183. static void
  1184. raise_error_syntax(const char *msg)
  1185. {
  1186. ash_msg_and_raise_error("syntax error: %s", msg);
  1187. /* NOTREACHED */
  1188. }
  1189. static void ash_msg_and_raise(int, const char *, ...) NORETURN;
  1190. static void
  1191. ash_msg_and_raise(int cond, const char *msg, ...)
  1192. {
  1193. va_list ap;
  1194. va_start(ap, msg);
  1195. ash_vmsg_and_raise(cond, msg, ap);
  1196. /* NOTREACHED */
  1197. va_end(ap);
  1198. }
  1199. /*
  1200. * error/warning routines for external builtins
  1201. */
  1202. static void
  1203. ash_msg(const char *fmt, ...)
  1204. {
  1205. va_list ap;
  1206. va_start(ap, fmt);
  1207. ash_vmsg(fmt, ap);
  1208. va_end(ap);
  1209. }
  1210. /*
  1211. * Return a string describing an error. The returned string may be a
  1212. * pointer to a static buffer that will be overwritten on the next call.
  1213. * Action describes the operation that got the error.
  1214. */
  1215. static const char *
  1216. errmsg(int e, const char *em)
  1217. {
  1218. if (e == ENOENT || e == ENOTDIR) {
  1219. return em;
  1220. }
  1221. return strerror(e);
  1222. }
  1223. /* ============ Memory allocation */
  1224. #if 0
  1225. /* I consider these wrappers nearly useless:
  1226. * ok, they return you to nearest exception handler, but
  1227. * how much memory do you leak in the process, making
  1228. * memory starvation worse?
  1229. */
  1230. static void *
  1231. ckrealloc(void * p, size_t nbytes)
  1232. {
  1233. p = realloc(p, nbytes);
  1234. if (!p)
  1235. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  1236. return p;
  1237. }
  1238. static void *
  1239. ckmalloc(size_t nbytes)
  1240. {
  1241. return ckrealloc(NULL, nbytes);
  1242. }
  1243. static void *
  1244. ckzalloc(size_t nbytes)
  1245. {
  1246. return memset(ckmalloc(nbytes), 0, nbytes);
  1247. }
  1248. static char *
  1249. ckstrdup(const char *s)
  1250. {
  1251. char *p = strdup(s);
  1252. if (!p)
  1253. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  1254. return p;
  1255. }
  1256. #else
  1257. /* Using bbox equivalents. They exit if out of memory */
  1258. # define ckrealloc xrealloc
  1259. # define ckmalloc xmalloc
  1260. # define ckzalloc xzalloc
  1261. # define ckstrdup xstrdup
  1262. #endif
  1263. /*
  1264. * It appears that grabstackstr() will barf with such alignments
  1265. * because stalloc() will return a string allocated in a new stackblock.
  1266. */
  1267. #define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
  1268. enum {
  1269. /* Most machines require the value returned from malloc to be aligned
  1270. * in some way. The following macro will get this right
  1271. * on many machines. */
  1272. SHELL_SIZE = sizeof(union { int i; char *cp; double d; }) - 1,
  1273. /* Minimum size of a block */
  1274. MINSIZE = SHELL_ALIGN(504),
  1275. };
  1276. struct stack_block {
  1277. struct stack_block *prev;
  1278. char space[MINSIZE];
  1279. };
  1280. struct stackmark {
  1281. struct stack_block *stackp;
  1282. char *stacknxt;
  1283. size_t stacknleft;
  1284. };
  1285. struct globals_memstack {
  1286. struct stack_block *g_stackp; // = &stackbase;
  1287. char *g_stacknxt; // = stackbase.space;
  1288. char *sstrend; // = stackbase.space + MINSIZE;
  1289. size_t g_stacknleft; // = MINSIZE;
  1290. struct stack_block stackbase;
  1291. };
  1292. extern struct globals_memstack *const ash_ptr_to_globals_memstack;
  1293. #define G_memstack (*ash_ptr_to_globals_memstack)
  1294. #define g_stackp (G_memstack.g_stackp )
  1295. #define g_stacknxt (G_memstack.g_stacknxt )
  1296. #define sstrend (G_memstack.sstrend )
  1297. #define g_stacknleft (G_memstack.g_stacknleft)
  1298. #define stackbase (G_memstack.stackbase )
  1299. #define INIT_G_memstack() do { \
  1300. (*(struct globals_memstack**)&ash_ptr_to_globals_memstack) = xzalloc(sizeof(G_memstack)); \
  1301. barrier(); \
  1302. g_stackp = &stackbase; \
  1303. g_stacknxt = stackbase.space; \
  1304. g_stacknleft = MINSIZE; \
  1305. sstrend = stackbase.space + MINSIZE; \
  1306. } while (0)
  1307. #define stackblock() ((void *)g_stacknxt)
  1308. #define stackblocksize() g_stacknleft
  1309. /*
  1310. * Parse trees for commands are allocated in lifo order, so we use a stack
  1311. * to make this more efficient, and also to avoid all sorts of exception
  1312. * handling code to handle interrupts in the middle of a parse.
  1313. *
  1314. * The size 504 was chosen because the Ultrix malloc handles that size
  1315. * well.
  1316. */
  1317. static void *
  1318. stalloc(size_t nbytes)
  1319. {
  1320. char *p;
  1321. size_t aligned;
  1322. aligned = SHELL_ALIGN(nbytes);
  1323. if (aligned > g_stacknleft) {
  1324. size_t len;
  1325. size_t blocksize;
  1326. struct stack_block *sp;
  1327. blocksize = aligned;
  1328. if (blocksize < MINSIZE)
  1329. blocksize = MINSIZE;
  1330. len = sizeof(struct stack_block) - MINSIZE + blocksize;
  1331. if (len < blocksize)
  1332. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  1333. INT_OFF;
  1334. sp = ckmalloc(len);
  1335. sp->prev = g_stackp;
  1336. g_stacknxt = sp->space;
  1337. g_stacknleft = blocksize;
  1338. sstrend = g_stacknxt + blocksize;
  1339. g_stackp = sp;
  1340. INT_ON;
  1341. }
  1342. p = g_stacknxt;
  1343. g_stacknxt += aligned;
  1344. g_stacknleft -= aligned;
  1345. return p;
  1346. }
  1347. static void *
  1348. stzalloc(size_t nbytes)
  1349. {
  1350. return memset(stalloc(nbytes), 0, nbytes);
  1351. }
  1352. static void
  1353. stunalloc(void *p)
  1354. {
  1355. #if DEBUG
  1356. if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
  1357. write(STDERR_FILENO, "stunalloc\n", 10);
  1358. abort();
  1359. }
  1360. #endif
  1361. g_stacknleft += g_stacknxt - (char *)p;
  1362. g_stacknxt = p;
  1363. }
  1364. /*
  1365. * Like strdup but works with the ash stack.
  1366. */
  1367. static char *
  1368. sstrdup(const char *p)
  1369. {
  1370. size_t len = strlen(p) + 1;
  1371. return memcpy(stalloc(len), p, len);
  1372. }
  1373. static inline void
  1374. grabstackblock(size_t len)
  1375. {
  1376. stalloc(len);
  1377. }
  1378. static void
  1379. pushstackmark(struct stackmark *mark, size_t len)
  1380. {
  1381. mark->stackp = g_stackp;
  1382. mark->stacknxt = g_stacknxt;
  1383. mark->stacknleft = g_stacknleft;
  1384. grabstackblock(len);
  1385. }
  1386. static void
  1387. setstackmark(struct stackmark *mark)
  1388. {
  1389. pushstackmark(mark, g_stacknxt == g_stackp->space && g_stackp != &stackbase);
  1390. }
  1391. static void
  1392. popstackmark(struct stackmark *mark)
  1393. {
  1394. struct stack_block *sp;
  1395. if (!mark->stackp)
  1396. return;
  1397. INT_OFF;
  1398. while (g_stackp != mark->stackp) {
  1399. sp = g_stackp;
  1400. g_stackp = sp->prev;
  1401. free(sp);
  1402. }
  1403. g_stacknxt = mark->stacknxt;
  1404. g_stacknleft = mark->stacknleft;
  1405. sstrend = mark->stacknxt + mark->stacknleft;
  1406. INT_ON;
  1407. }
  1408. /*
  1409. * When the parser reads in a string, it wants to stick the string on the
  1410. * stack and only adjust the stack pointer when it knows how big the
  1411. * string is. Stackblock (defined in stack.h) returns a pointer to a block
  1412. * of space on top of the stack and stackblocklen returns the length of
  1413. * this block. Growstackblock will grow this space by at least one byte,
  1414. * possibly moving it (like realloc). Grabstackblock actually allocates the
  1415. * part of the block that has been used.
  1416. */
  1417. static void
  1418. growstackblock(void)
  1419. {
  1420. size_t newlen;
  1421. newlen = g_stacknleft * 2;
  1422. if (newlen < g_stacknleft)
  1423. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  1424. if (newlen < 128)
  1425. newlen += 128;
  1426. if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
  1427. struct stack_block *sp;
  1428. struct stack_block *prevstackp;
  1429. size_t grosslen;
  1430. INT_OFF;
  1431. sp = g_stackp;
  1432. prevstackp = sp->prev;
  1433. grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
  1434. sp = ckrealloc(sp, grosslen);
  1435. sp->prev = prevstackp;
  1436. g_stackp = sp;
  1437. g_stacknxt = sp->space;
  1438. g_stacknleft = newlen;
  1439. sstrend = sp->space + newlen;
  1440. INT_ON;
  1441. } else {
  1442. char *oldspace = g_stacknxt;
  1443. size_t oldlen = g_stacknleft;
  1444. char *p = stalloc(newlen);
  1445. /* free the space we just allocated */
  1446. g_stacknxt = memcpy(p, oldspace, oldlen);
  1447. g_stacknleft += newlen;
  1448. }
  1449. }
  1450. /*
  1451. * The following routines are somewhat easier to use than the above.
  1452. * The user declares a variable of type STACKSTR, which may be declared
  1453. * to be a register. The macro STARTSTACKSTR initializes things. Then
  1454. * the user uses the macro STPUTC to add characters to the string. In
  1455. * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
  1456. * grown as necessary. When the user is done, she can just leave the
  1457. * string there and refer to it using stackblock(). Or she can allocate
  1458. * the space for it using grabstackstr(). If it is necessary to allow
  1459. * someone else to use the stack temporarily and then continue to grow
  1460. * the string, the user should use grabstack to allocate the space, and
  1461. * then call ungrabstr(p) to return to the previous mode of operation.
  1462. *
  1463. * USTPUTC is like STPUTC except that it doesn't check for overflow.
  1464. * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
  1465. * is space for at least one character.
  1466. */
  1467. static void *
  1468. growstackstr(void)
  1469. {
  1470. size_t len = stackblocksize();
  1471. growstackblock();
  1472. return (char *)stackblock() + len;
  1473. }
  1474. /*
  1475. * Called from CHECKSTRSPACE.
  1476. */
  1477. static char *
  1478. makestrspace(size_t newlen, char *p)
  1479. {
  1480. size_t len = p - g_stacknxt;
  1481. size_t size;
  1482. for (;;) {
  1483. size_t nleft;
  1484. size = stackblocksize();
  1485. nleft = size - len;
  1486. if (nleft >= newlen)
  1487. break;
  1488. growstackblock();
  1489. }
  1490. return (char *)stackblock() + len;
  1491. }
  1492. static char *
  1493. stack_nputstr(const char *s, size_t n, char *p)
  1494. {
  1495. p = makestrspace(n, p);
  1496. p = (char *)mempcpy(p, s, n);
  1497. return p;
  1498. }
  1499. static char *
  1500. stack_putstr(const char *s, char *p)
  1501. {
  1502. return stack_nputstr(s, strlen(s), p);
  1503. }
  1504. static char *
  1505. _STPUTC(int c, char *p)
  1506. {
  1507. if (p == sstrend)
  1508. p = growstackstr();
  1509. *p++ = c;
  1510. return p;
  1511. }
  1512. #define STARTSTACKSTR(p) ((p) = stackblock())
  1513. #define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
  1514. #define CHECKSTRSPACE(n, p) do { \
  1515. char *q = (p); \
  1516. size_t l = (n); \
  1517. size_t m = sstrend - q; \
  1518. if (l > m) \
  1519. (p) = makestrspace(l, q); \
  1520. } while (0)
  1521. #define USTPUTC(c, p) (*(p)++ = (c))
  1522. #define STACKSTRNUL(p) do { \
  1523. if ((p) == sstrend) \
  1524. (p) = growstackstr(); \
  1525. *(p) = '\0'; \
  1526. } while (0)
  1527. #define STUNPUTC(p) (--(p))
  1528. #define STTOPC(p) ((p)[-1])
  1529. #define STADJUST(amount, p) ((p) += (amount))
  1530. #define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
  1531. #define ungrabstackstr(s, p) stunalloc(s)
  1532. #define stackstrend() ((void *)sstrend)
  1533. /* ============ String helpers */
  1534. /*
  1535. * prefix -- see if pfx is a prefix of string.
  1536. */
  1537. static char *
  1538. prefix(const char *string, const char *pfx)
  1539. {
  1540. while (*pfx) {
  1541. if (*pfx++ != *string++)
  1542. return NULL;
  1543. }
  1544. return (char *) string;
  1545. }
  1546. /*
  1547. * Check for a valid number. This should be elsewhere.
  1548. */
  1549. static int
  1550. is_number(const char *p)
  1551. {
  1552. do {
  1553. if (!isdigit(*p))
  1554. return 0;
  1555. } while (*++p != '\0');
  1556. return 1;
  1557. }
  1558. /*
  1559. * Convert a string of digits to an integer, printing an error message on
  1560. * failure.
  1561. */
  1562. static int
  1563. number(const char *s)
  1564. {
  1565. if (!is_number(s))
  1566. ash_msg_and_raise_error(msg_illnum, s);
  1567. return atoi(s);
  1568. }
  1569. /*
  1570. * Produce a single quoted string suitable as input to the shell.
  1571. * The return string is allocated on the stack.
  1572. */
  1573. static char *
  1574. single_quote(const char *s)
  1575. {
  1576. char *p;
  1577. STARTSTACKSTR(p);
  1578. do {
  1579. char *q;
  1580. size_t len;
  1581. len = strchrnul(s, '\'') - s;
  1582. q = p = makestrspace(len + 3, p);
  1583. *q++ = '\'';
  1584. q = (char *)mempcpy(q, s, len);
  1585. *q++ = '\'';
  1586. s += len;
  1587. STADJUST(q - p, p);
  1588. if (*s != '\'')
  1589. break;
  1590. len = 0;
  1591. do len++; while (*++s == '\'');
  1592. q = p = makestrspace(len + 3, p);
  1593. *q++ = '"';
  1594. q = (char *)mempcpy(q, s - len, len);
  1595. *q++ = '"';
  1596. STADJUST(q - p, p);
  1597. } while (*s);
  1598. USTPUTC('\0', p);
  1599. return stackblock();
  1600. }
  1601. /*
  1602. * Produce a possibly single quoted string suitable as input to the shell.
  1603. * If quoting was done, the return string is allocated on the stack,
  1604. * otherwise a pointer to the original string is returned.
  1605. */
  1606. static const char *
  1607. maybe_single_quote(const char *s)
  1608. {
  1609. const char *p = s;
  1610. while (*p) {
  1611. /* Assuming ACSII */
  1612. /* quote ctrl_chars space !"#$%&'()* */
  1613. if (*p < '+')
  1614. goto need_quoting;
  1615. /* quote ;<=>? */
  1616. if (*p >= ';' && *p <= '?')
  1617. goto need_quoting;
  1618. /* quote `[\ */
  1619. if (*p == '`')
  1620. goto need_quoting;
  1621. if (*p == '[')
  1622. goto need_quoting;
  1623. if (*p == '\\')
  1624. goto need_quoting;
  1625. /* quote {|}~ DEL and high bytes */
  1626. if (*p > 'z')
  1627. goto need_quoting;
  1628. /* Not quoting these: +,-./ 0-9 :@ A-Z ]^_ a-z */
  1629. /* TODO: maybe avoid quoting % */
  1630. p++;
  1631. }
  1632. return s;
  1633. need_quoting:
  1634. return single_quote(s);
  1635. }
  1636. /* ============ nextopt */
  1637. static char **argptr; /* argument list for builtin commands */
  1638. static char *optionarg; /* set by nextopt (like getopt) */
  1639. static char *optptr; /* used by nextopt */
  1640. /*
  1641. * XXX - should get rid of. Have all builtins use getopt(3).
  1642. * The library getopt must have the BSD extension static variable
  1643. * "optreset", otherwise it can't be used within the shell safely.
  1644. *
  1645. * Standard option processing (a la getopt) for builtin routines.
  1646. * The only argument that is passed to nextopt is the option string;
  1647. * the other arguments are unnecessary. It returns the character,
  1648. * or '\0' on end of input.
  1649. */
  1650. static int
  1651. nextopt(const char *optstring)
  1652. {
  1653. char *p;
  1654. const char *q;
  1655. char c;
  1656. p = optptr;
  1657. if (p == NULL || *p == '\0') {
  1658. /* We ate entire "-param", take next one */
  1659. p = *argptr;
  1660. if (p == NULL)
  1661. return '\0';
  1662. if (*p != '-')
  1663. return '\0';
  1664. if (*++p == '\0') /* just "-" ? */
  1665. return '\0';
  1666. argptr++;
  1667. if (LONE_DASH(p)) /* "--" ? */
  1668. return '\0';
  1669. /* p => next "-param" */
  1670. }
  1671. /* p => some option char in the middle of a "-param" */
  1672. c = *p++;
  1673. for (q = optstring; *q != c;) {
  1674. if (*q == '\0')
  1675. ash_msg_and_raise_error("illegal option -%c", c);
  1676. if (*++q == ':')
  1677. q++;
  1678. }
  1679. if (*++q == ':') {
  1680. if (*p == '\0') {
  1681. p = *argptr++;
  1682. if (p == NULL)
  1683. ash_msg_and_raise_error("no arg for -%c option", c);
  1684. }
  1685. optionarg = p;
  1686. p = NULL;
  1687. }
  1688. optptr = p;
  1689. return c;
  1690. }
  1691. /* ============ Shell variables */
  1692. struct shparam {
  1693. int nparam; /* # of positional parameters (without $0) */
  1694. #if ENABLE_ASH_GETOPTS
  1695. int optind; /* next parameter to be processed by getopts */
  1696. int optoff; /* used by getopts */
  1697. #endif
  1698. unsigned char malloced; /* if parameter list dynamically allocated */
  1699. char **p; /* parameter list */
  1700. };
  1701. /*
  1702. * Free the list of positional parameters.
  1703. */
  1704. static void
  1705. freeparam(volatile struct shparam *param)
  1706. {
  1707. if (param->malloced) {
  1708. char **ap, **ap1;
  1709. ap = ap1 = param->p;
  1710. while (*ap)
  1711. free(*ap++);
  1712. free(ap1);
  1713. }
  1714. }
  1715. #if ENABLE_ASH_GETOPTS
  1716. static void FAST_FUNC getoptsreset(const char *value);
  1717. #endif
  1718. struct var {
  1719. struct var *next; /* next entry in hash list */
  1720. int flags; /* flags are defined above */
  1721. const char *var_text; /* name=value */
  1722. void (*var_func)(const char *) FAST_FUNC; /* function to be called when */
  1723. /* the variable gets set/unset */
  1724. };
  1725. struct localvar {
  1726. struct localvar *next; /* next local variable in list */
  1727. struct var *vp; /* the variable that was made local */
  1728. int flags; /* saved flags */
  1729. const char *text; /* saved text */
  1730. };
  1731. /* flags */
  1732. #define VEXPORT 0x01 /* variable is exported */
  1733. #define VREADONLY 0x02 /* variable cannot be modified */
  1734. #define VSTRFIXED 0x04 /* variable struct is statically allocated */
  1735. #define VTEXTFIXED 0x08 /* text is statically allocated */
  1736. #define VSTACK 0x10 /* text is allocated on the stack */
  1737. #define VUNSET 0x20 /* the variable is not set */
  1738. #define VNOFUNC 0x40 /* don't call the callback function */
  1739. #define VNOSET 0x80 /* do not set variable - just readonly test */
  1740. #define VNOSAVE 0x100 /* when text is on the heap before setvareq */
  1741. #if ENABLE_ASH_RANDOM_SUPPORT
  1742. # define VDYNAMIC 0x200 /* dynamic variable */
  1743. #else
  1744. # define VDYNAMIC 0
  1745. #endif
  1746. /* Need to be before varinit_data[] */
  1747. #if ENABLE_LOCALE_SUPPORT
  1748. static void FAST_FUNC
  1749. change_lc_all(const char *value)
  1750. {
  1751. if (value && *value != '\0')
  1752. setlocale(LC_ALL, value);
  1753. }
  1754. static void FAST_FUNC
  1755. change_lc_ctype(const char *value)
  1756. {
  1757. if (value && *value != '\0')
  1758. setlocale(LC_CTYPE, value);
  1759. }
  1760. #endif
  1761. #if ENABLE_ASH_MAIL
  1762. static void chkmail(void);
  1763. static void changemail(const char *var_value) FAST_FUNC;
  1764. #else
  1765. # define chkmail() ((void)0)
  1766. #endif
  1767. static void changepath(const char *) FAST_FUNC;
  1768. #if ENABLE_ASH_RANDOM_SUPPORT
  1769. static void change_random(const char *) FAST_FUNC;
  1770. #endif
  1771. static const struct {
  1772. int flags;
  1773. const char *var_text;
  1774. void (*var_func)(const char *) FAST_FUNC;
  1775. } varinit_data[] = {
  1776. /*
  1777. * Note: VEXPORT would not work correctly here for NOFORK applets:
  1778. * some environment strings may be constant.
  1779. */
  1780. { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
  1781. #if ENABLE_ASH_MAIL
  1782. { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL" , changemail },
  1783. { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH" , changemail },
  1784. #endif
  1785. { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
  1786. { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
  1787. { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
  1788. { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
  1789. #if ENABLE_ASH_GETOPTS
  1790. { VSTRFIXED|VTEXTFIXED , defoptindvar, getoptsreset },
  1791. #endif
  1792. #if ENABLE_ASH_RANDOM_SUPPORT
  1793. { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM", change_random },
  1794. #endif
  1795. #if ENABLE_LOCALE_SUPPORT
  1796. { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL" , change_lc_all },
  1797. { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE" , change_lc_ctype },
  1798. #endif
  1799. #if ENABLE_FEATURE_EDITING_SAVEHISTORY
  1800. { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE" , NULL },
  1801. #endif
  1802. };
  1803. struct redirtab;
  1804. struct globals_var {
  1805. struct shparam shellparam; /* $@ current positional parameters */
  1806. struct redirtab *redirlist;
  1807. int preverrout_fd; /* stderr fd: usually 2, unless redirect moved it */
  1808. struct var *vartab[VTABSIZE];
  1809. struct var varinit[ARRAY_SIZE(varinit_data)];
  1810. };
  1811. extern struct globals_var *const ash_ptr_to_globals_var;
  1812. #define G_var (*ash_ptr_to_globals_var)
  1813. #define shellparam (G_var.shellparam )
  1814. //#define redirlist (G_var.redirlist )
  1815. #define preverrout_fd (G_var.preverrout_fd)
  1816. #define vartab (G_var.vartab )
  1817. #define varinit (G_var.varinit )
  1818. #define INIT_G_var() do { \
  1819. unsigned i; \
  1820. (*(struct globals_var**)&ash_ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
  1821. barrier(); \
  1822. for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
  1823. varinit[i].flags = varinit_data[i].flags; \
  1824. varinit[i].var_text = varinit_data[i].var_text; \
  1825. varinit[i].var_func = varinit_data[i].var_func; \
  1826. } \
  1827. } while (0)
  1828. #define vifs varinit[0]
  1829. #if ENABLE_ASH_MAIL
  1830. # define vmail (&vifs)[1]
  1831. # define vmpath (&vmail)[1]
  1832. # define vpath (&vmpath)[1]
  1833. #else
  1834. # define vpath (&vifs)[1]
  1835. #endif
  1836. #define vps1 (&vpath)[1]
  1837. #define vps2 (&vps1)[1]
  1838. #define vps4 (&vps2)[1]
  1839. #if ENABLE_ASH_GETOPTS
  1840. # define voptind (&vps4)[1]
  1841. # if ENABLE_ASH_RANDOM_SUPPORT
  1842. # define vrandom (&voptind)[1]
  1843. # endif
  1844. #else
  1845. # if ENABLE_ASH_RANDOM_SUPPORT
  1846. # define vrandom (&vps4)[1]
  1847. # endif
  1848. #endif
  1849. /*
  1850. * The following macros access the values of the above variables.
  1851. * They have to skip over the name. They return the null string
  1852. * for unset variables.
  1853. */
  1854. #define ifsval() (vifs.var_text + 4)
  1855. #define ifsset() ((vifs.flags & VUNSET) == 0)
  1856. #if ENABLE_ASH_MAIL
  1857. # define mailval() (vmail.var_text + 5)
  1858. # define mpathval() (vmpath.var_text + 9)
  1859. # define mpathset() ((vmpath.flags & VUNSET) == 0)
  1860. #endif
  1861. #define pathval() (vpath.var_text + 5)
  1862. #define ps1val() (vps1.var_text + 4)
  1863. #define ps2val() (vps2.var_text + 4)
  1864. #define ps4val() (vps4.var_text + 4)
  1865. #if ENABLE_ASH_GETOPTS
  1866. # define optindval() (voptind.var_text + 7)
  1867. #endif
  1868. #if ENABLE_ASH_GETOPTS
  1869. static void FAST_FUNC
  1870. getoptsreset(const char *value)
  1871. {
  1872. shellparam.optind = 1;
  1873. if (is_number(value))
  1874. shellparam.optind = number(value) ?: 1;
  1875. shellparam.optoff = -1;
  1876. }
  1877. #endif
  1878. /*
  1879. * Compares two strings up to the first = or '\0'. The first
  1880. * string must be terminated by '='; the second may be terminated by
  1881. * either '=' or '\0'.
  1882. */
  1883. static int
  1884. varcmp(const char *p, const char *q)
  1885. {
  1886. int c, d;
  1887. while ((c = *p) == (d = *q)) {
  1888. if (c == '\0' || c == '=')
  1889. goto out;
  1890. p++;
  1891. q++;
  1892. }
  1893. if (c == '=')
  1894. c = '\0';
  1895. if (d == '=')
  1896. d = '\0';
  1897. out:
  1898. return c - d;
  1899. }
  1900. /*
  1901. * Find the appropriate entry in the hash table from the name.
  1902. */
  1903. static struct var **
  1904. hashvar(const char *p)
  1905. {
  1906. unsigned hashval;
  1907. hashval = ((unsigned char) *p) << 4;
  1908. while (*p && *p != '=')
  1909. hashval += (unsigned char) *p++;
  1910. return &vartab[hashval % VTABSIZE];
  1911. }
  1912. static int
  1913. vpcmp(const void *a, const void *b)
  1914. {
  1915. return varcmp(*(const char **)a, *(const char **)b);
  1916. }
  1917. /*
  1918. * This routine initializes the builtin variables.
  1919. */
  1920. static void
  1921. initvar(void)
  1922. {
  1923. struct var *vp;
  1924. struct var *end;
  1925. struct var **vpp;
  1926. /*
  1927. * PS1 depends on uid
  1928. */
  1929. #if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
  1930. vps1.var_text = "PS1=\\w \\$ ";
  1931. #else
  1932. if (!geteuid())
  1933. vps1.var_text = "PS1=# ";
  1934. #endif
  1935. vp = varinit;
  1936. end = vp + ARRAY_SIZE(varinit);
  1937. do {
  1938. vpp = hashvar(vp->var_text);
  1939. vp->next = *vpp;
  1940. *vpp = vp;
  1941. } while (++vp < end);
  1942. }
  1943. static struct var **
  1944. findvar(struct var **vpp, const char *name)
  1945. {
  1946. for (; *vpp; vpp = &(*vpp)->next) {
  1947. if (varcmp((*vpp)->var_text, name) == 0) {
  1948. break;
  1949. }
  1950. }
  1951. return vpp;
  1952. }
  1953. /*
  1954. * Find the value of a variable. Returns NULL if not set.
  1955. */
  1956. static const char* FAST_FUNC
  1957. lookupvar(const char *name)
  1958. {
  1959. struct var *v;
  1960. v = *findvar(hashvar(name), name);
  1961. if (v) {
  1962. #if ENABLE_ASH_RANDOM_SUPPORT
  1963. /*
  1964. * Dynamic variables are implemented roughly the same way they are
  1965. * in bash. Namely, they're "special" so long as they aren't unset.
  1966. * As soon as they're unset, they're no longer dynamic, and dynamic
  1967. * lookup will no longer happen at that point. -- PFM.
  1968. */
  1969. if (v->flags & VDYNAMIC)
  1970. v->var_func(NULL);
  1971. #endif
  1972. if (!(v->flags & VUNSET))
  1973. return var_end(v->var_text);
  1974. }
  1975. return NULL;
  1976. }
  1977. #if ENABLE_UNICODE_SUPPORT
  1978. static void
  1979. reinit_unicode_for_ash(void)
  1980. {
  1981. /* Unicode support should be activated even if LANG is set
  1982. * _during_ shell execution, not only if it was set when
  1983. * shell was started. Therefore, re-check LANG every time:
  1984. */
  1985. if (ENABLE_FEATURE_CHECK_UNICODE_IN_ENV
  1986. || ENABLE_UNICODE_USING_LOCALE
  1987. ) {
  1988. const char *s = lookupvar("LC_ALL");
  1989. if (!s) s = lookupvar("LC_CTYPE");
  1990. if (!s) s = lookupvar("LANG");
  1991. reinit_unicode(s);
  1992. }
  1993. }
  1994. #else
  1995. # define reinit_unicode_for_ash() ((void)0)
  1996. #endif
  1997. /*
  1998. * Search the environment of a builtin command.
  1999. */
  2000. static ALWAYS_INLINE const char *
  2001. bltinlookup(const char *name)
  2002. {
  2003. return lookupvar(name);
  2004. }
  2005. /*
  2006. * Same as setvar except that the variable and value are passed in
  2007. * the first argument as name=value. Since the first argument will
  2008. * be actually stored in the table, it should not be a string that
  2009. * will go away.
  2010. * Called with interrupts off.
  2011. */
  2012. static struct var *
  2013. setvareq(char *s, int flags)
  2014. {
  2015. struct var *vp, **vpp;
  2016. vpp = hashvar(s);
  2017. flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
  2018. vpp = findvar(vpp, s);
  2019. vp = *vpp;
  2020. if (vp) {
  2021. if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
  2022. const char *n;
  2023. if (flags & VNOSAVE)
  2024. free(s);
  2025. n = vp->var_text;
  2026. exitstatus = 1;
  2027. ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
  2028. }
  2029. if (flags & VNOSET)
  2030. goto out;
  2031. if (vp->var_func && !(flags & VNOFUNC))
  2032. vp->var_func(var_end(s));
  2033. if (!(vp->flags & (VTEXTFIXED|VSTACK)))
  2034. free((char*)vp->var_text);
  2035. if (((flags & (VEXPORT|VREADONLY|VSTRFIXED|VUNSET)) | (vp->flags & VSTRFIXED)) == VUNSET) {
  2036. *vpp = vp->next;
  2037. free(vp);
  2038. out_free:
  2039. if ((flags & (VTEXTFIXED|VSTACK|VNOSAVE)) == VNOSAVE)
  2040. free(s);
  2041. goto out;
  2042. }
  2043. flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
  2044. } else {
  2045. /* variable s is not found */
  2046. if (flags & VNOSET)
  2047. goto out;
  2048. if ((flags & (VEXPORT|VREADONLY|VSTRFIXED|VUNSET)) == VUNSET)
  2049. goto out_free;
  2050. vp = ckzalloc(sizeof(*vp));
  2051. vp->next = *vpp;
  2052. /*vp->func = NULL; - ckzalloc did it */
  2053. *vpp = vp;
  2054. }
  2055. if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
  2056. s = ckstrdup(s);
  2057. vp->var_text = s;
  2058. vp->flags = flags;
  2059. out:
  2060. return vp;
  2061. }
  2062. /*
  2063. * Set the value of a variable. The flags argument is ored with the
  2064. * flags of the variable. If val is NULL, the variable is unset.
  2065. */
  2066. static struct var *
  2067. setvar(const char *name, const char *val, int flags)
  2068. {
  2069. const char *q;
  2070. char *p;
  2071. char *nameeq;
  2072. size_t namelen;
  2073. size_t vallen;
  2074. struct var *vp;
  2075. q = endofname(name);
  2076. p = strchrnul(q, '=');
  2077. namelen = p - name;
  2078. if (!namelen || p != q)
  2079. ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
  2080. vallen = 0;
  2081. if (val == NULL) {
  2082. flags |= VUNSET;
  2083. } else {
  2084. vallen = strlen(val);
  2085. }
  2086. INT_OFF;
  2087. nameeq = ckmalloc(namelen + vallen + 2);
  2088. p = mempcpy(nameeq, name, namelen);
  2089. if (val) {
  2090. *p++ = '=';
  2091. p = mempcpy(p, val, vallen);
  2092. }
  2093. *p = '\0';
  2094. vp = setvareq(nameeq, flags | VNOSAVE);
  2095. INT_ON;
  2096. return vp;
  2097. }
  2098. static void FAST_FUNC
  2099. setvar0(const char *name, const char *val)
  2100. {
  2101. setvar(name, val, 0);
  2102. }
  2103. /*
  2104. * Unset the specified variable.
  2105. */
  2106. static void
  2107. unsetvar(const char *s)
  2108. {
  2109. setvar(s, NULL, 0);
  2110. }
  2111. /*
  2112. * Process a linked list of variable assignments.
  2113. */
  2114. static void
  2115. listsetvar(struct strlist *list_set_var, int flags)
  2116. {
  2117. struct strlist *lp = list_set_var;
  2118. if (!lp)
  2119. return;
  2120. INT_OFF;
  2121. do {
  2122. setvareq(lp->text, flags);
  2123. lp = lp->next;
  2124. } while (lp);
  2125. INT_ON;
  2126. }
  2127. /*
  2128. * Generate a list of variables satisfying the given conditions.
  2129. */
  2130. #if !ENABLE_FEATURE_SH_NOFORK
  2131. # define listvars(on, off, lp, end) listvars(on, off, end)
  2132. #endif
  2133. static char **
  2134. listvars(int on, int off, struct strlist *lp, char ***end)
  2135. {
  2136. struct var **vpp;
  2137. struct var *vp;
  2138. char **ep;
  2139. int mask;
  2140. STARTSTACKSTR(ep);
  2141. vpp = vartab;
  2142. mask = on | off;
  2143. do {
  2144. for (vp = *vpp; vp; vp = vp->next) {
  2145. if ((vp->flags & mask) == on) {
  2146. #if ENABLE_FEATURE_SH_NOFORK
  2147. /* If variable with the same name is both
  2148. * exported and temporarily set for a command:
  2149. * export ZVAR=5
  2150. * ZVAR=6 printenv
  2151. * then "ZVAR=6" will be both in vartab and
  2152. * lp lists. Do not pass it twice to printenv.
  2153. */
  2154. struct strlist *lp1 = lp;
  2155. while (lp1) {
  2156. if (strcmp(lp1->text, vp->var_text) == 0)
  2157. goto skip;
  2158. lp1 = lp1->next;
  2159. }
  2160. #endif
  2161. if (ep == stackstrend())
  2162. ep = growstackstr();
  2163. *ep++ = (char*)vp->var_text;
  2164. #if ENABLE_FEATURE_SH_NOFORK
  2165. skip: ;
  2166. #endif
  2167. }
  2168. }
  2169. } while (++vpp < vartab + VTABSIZE);
  2170. #if ENABLE_FEATURE_SH_NOFORK
  2171. while (lp) {
  2172. if (ep == stackstrend())
  2173. ep = growstackstr();
  2174. *ep++ = lp->text;
  2175. lp = lp->next;
  2176. }
  2177. #endif
  2178. if (ep == stackstrend())
  2179. ep = growstackstr();
  2180. if (end)
  2181. *end = ep;
  2182. *ep++ = NULL;
  2183. return grabstackstr(ep);
  2184. }
  2185. /* ============ Path search helper
  2186. *
  2187. * The variable path (passed by reference) should be set to the start
  2188. * of the path before the first call; path_advance will update
  2189. * this value as it proceeds. Successive calls to path_advance will return
  2190. * the possible path expansions in sequence. If an option (indicated by
  2191. * a percent sign) appears in the path entry then the global variable
  2192. * pathopt will be set to point to it; otherwise pathopt will be set to
  2193. * NULL.
  2194. */
  2195. static const char *pathopt; /* set by path_advance */
  2196. static char *
  2197. path_advance(const char **path, const char *name)
  2198. {
  2199. const char *p;
  2200. char *q;
  2201. const char *start;
  2202. size_t len;
  2203. if (*path == NULL)
  2204. return NULL;
  2205. start = *path;
  2206. for (p = start; *p && *p != ':' && *p != '%'; p++)
  2207. continue;
  2208. len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
  2209. while (stackblocksize() < len)
  2210. growstackblock();
  2211. q = stackblock();
  2212. if (p != start) {
  2213. q = mempcpy(q, start, p - start);
  2214. *q++ = '/';
  2215. }
  2216. strcpy(q, name);
  2217. pathopt = NULL;
  2218. if (*p == '%') {
  2219. pathopt = ++p;
  2220. while (*p && *p != ':')
  2221. p++;
  2222. }
  2223. if (*p == ':')
  2224. *path = p + 1;
  2225. else
  2226. *path = NULL;
  2227. return stalloc(len);
  2228. }
  2229. /* ============ Prompt */
  2230. static smallint doprompt; /* if set, prompt the user */
  2231. static smallint needprompt; /* true if interactive and at start of line */
  2232. #if ENABLE_FEATURE_EDITING
  2233. static line_input_t *line_input_state;
  2234. static const char *cmdedit_prompt;
  2235. static void
  2236. putprompt(const char *s)
  2237. {
  2238. if (ENABLE_ASH_EXPAND_PRMT) {
  2239. free((char*)cmdedit_prompt);
  2240. cmdedit_prompt = ckstrdup(s);
  2241. return;
  2242. }
  2243. cmdedit_prompt = s;
  2244. }
  2245. #else
  2246. static void
  2247. putprompt(const char *s)
  2248. {
  2249. out2str(s);
  2250. }
  2251. #endif
  2252. /* expandstr() needs parsing machinery, so it is far away ahead... */
  2253. static const char *expandstr(const char *ps, int syntax_type);
  2254. /* Values for syntax param */
  2255. #define BASESYNTAX 0 /* not in quotes */
  2256. #define DQSYNTAX 1 /* in double quotes */
  2257. #define SQSYNTAX 2 /* in single quotes */
  2258. #define ARISYNTAX 3 /* in arithmetic */
  2259. #if ENABLE_ASH_EXPAND_PRMT
  2260. # define PSSYNTAX 4 /* prompt. never passed to SIT() */
  2261. #endif
  2262. /* PSSYNTAX expansion is identical to DQSYNTAX, except keeping '\$' as '\$' */
  2263. /*
  2264. * called by editline -- any expansions to the prompt should be added here.
  2265. */
  2266. static void
  2267. setprompt_if(smallint do_set, int whichprompt)
  2268. {
  2269. const char *prompt;
  2270. IF_ASH_EXPAND_PRMT(struct stackmark smark;)
  2271. if (!do_set)
  2272. return;
  2273. needprompt = 0;
  2274. switch (whichprompt) {
  2275. case 1:
  2276. prompt = ps1val();
  2277. break;
  2278. case 2:
  2279. prompt = ps2val();
  2280. break;
  2281. default: /* 0 */
  2282. prompt = nullstr;
  2283. }
  2284. #if ENABLE_ASH_EXPAND_PRMT
  2285. pushstackmark(&smark, stackblocksize());
  2286. putprompt(expandstr(prompt, PSSYNTAX));
  2287. popstackmark(&smark);
  2288. #else
  2289. putprompt(prompt);
  2290. #endif
  2291. }
  2292. /* ============ The cd and pwd commands */
  2293. #define CD_PHYSICAL 1
  2294. #define CD_PRINT 2
  2295. static int
  2296. cdopt(void)
  2297. {
  2298. int flags = 0;
  2299. int i, j;
  2300. j = 'L';
  2301. while ((i = nextopt("LP")) != '\0') {
  2302. if (i != j) {
  2303. flags ^= CD_PHYSICAL;
  2304. j = i;
  2305. }
  2306. }
  2307. return flags;
  2308. }
  2309. /*
  2310. * Update curdir (the name of the current directory) in response to a
  2311. * cd command.
  2312. */
  2313. static const char *
  2314. updatepwd(const char *dir)
  2315. {
  2316. char *new;
  2317. char *p;
  2318. char *cdcomppath;
  2319. const char *lim;
  2320. cdcomppath = sstrdup(dir);
  2321. STARTSTACKSTR(new);
  2322. if (*dir != '/') {
  2323. if (curdir == nullstr)
  2324. return 0;
  2325. new = stack_putstr(curdir, new);
  2326. }
  2327. new = makestrspace(strlen(dir) + 2, new);
  2328. lim = (char *)stackblock() + 1;
  2329. if (*dir != '/') {
  2330. if (new[-1] != '/')
  2331. USTPUTC('/', new);
  2332. if (new > lim && *lim == '/')
  2333. lim++;
  2334. } else {
  2335. USTPUTC('/', new);
  2336. cdcomppath++;
  2337. if (dir[1] == '/' && dir[2] != '/') {
  2338. USTPUTC('/', new);
  2339. cdcomppath++;
  2340. lim++;
  2341. }
  2342. }
  2343. p = strtok(cdcomppath, "/");
  2344. while (p) {
  2345. switch (*p) {
  2346. case '.':
  2347. if (p[1] == '.' && p[2] == '\0') {
  2348. while (new > lim) {
  2349. STUNPUTC(new);
  2350. if (new[-1] == '/')
  2351. break;
  2352. }
  2353. break;
  2354. }
  2355. if (p[1] == '\0')
  2356. break;
  2357. /* fall through */
  2358. default:
  2359. new = stack_putstr(p, new);
  2360. USTPUTC('/', new);
  2361. }
  2362. p = strtok(NULL, "/");
  2363. }
  2364. if (new > lim)
  2365. STUNPUTC(new);
  2366. *new = 0;
  2367. return stackblock();
  2368. }
  2369. /*
  2370. * Find out what the current directory is. If we already know the current
  2371. * directory, this routine returns immediately.
  2372. */
  2373. static char *
  2374. getpwd(void)
  2375. {
  2376. char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
  2377. return dir ? dir : nullstr;
  2378. }
  2379. static void
  2380. setpwd(const char *val, int setold)
  2381. {
  2382. char *oldcur, *dir;
  2383. oldcur = dir = curdir;
  2384. if (setold) {
  2385. setvar("OLDPWD", oldcur, VEXPORT);
  2386. }
  2387. INT_OFF;
  2388. if (physdir != nullstr) {
  2389. if (physdir != oldcur)
  2390. free(physdir);
  2391. physdir = nullstr;
  2392. }
  2393. if (oldcur == val || !val) {
  2394. char *s = getpwd();
  2395. physdir = s;
  2396. if (!val)
  2397. dir = s;
  2398. } else
  2399. dir = ckstrdup(val);
  2400. if (oldcur != dir && oldcur != nullstr) {
  2401. free(oldcur);
  2402. }
  2403. curdir = dir;
  2404. INT_ON;
  2405. setvar("PWD", dir, VEXPORT);
  2406. }
  2407. static void hashcd(void);
  2408. /*
  2409. * Actually do the chdir. We also call hashcd to let other routines
  2410. * know that the current directory has changed.
  2411. */
  2412. static int
  2413. docd(const char *dest, int flags)
  2414. {
  2415. const char *dir = NULL;
  2416. int err;
  2417. TRACE(("docd(\"%s\", %d) called\n", dest, flags));
  2418. INT_OFF;
  2419. if (!(flags & CD_PHYSICAL)) {
  2420. dir = updatepwd(dest);
  2421. if (dir)
  2422. dest = dir;
  2423. }
  2424. err = chdir(dest);
  2425. if (err)
  2426. goto out;
  2427. setpwd(dir, 1);
  2428. hashcd();
  2429. out:
  2430. INT_ON;
  2431. return err;
  2432. }
  2433. static int FAST_FUNC
  2434. cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  2435. {
  2436. const char *dest;
  2437. const char *path;
  2438. const char *p;
  2439. char c;
  2440. struct stat statb;
  2441. int flags;
  2442. flags = cdopt();
  2443. dest = *argptr;
  2444. if (!dest)
  2445. dest = bltinlookup("HOME");
  2446. else if (LONE_DASH(dest)) {
  2447. dest = bltinlookup("OLDPWD");
  2448. flags |= CD_PRINT;
  2449. }
  2450. if (!dest)
  2451. dest = nullstr;
  2452. if (*dest == '/')
  2453. goto step6;
  2454. if (*dest == '.') {
  2455. c = dest[1];
  2456. dotdot:
  2457. switch (c) {
  2458. case '\0':
  2459. case '/':
  2460. goto step6;
  2461. case '.':
  2462. c = dest[2];
  2463. if (c != '.')
  2464. goto dotdot;
  2465. }
  2466. }
  2467. if (!*dest)
  2468. dest = ".";
  2469. path = bltinlookup("CDPATH");
  2470. while (path) {
  2471. c = *path;
  2472. p = path_advance(&path, dest);
  2473. if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
  2474. if (c && c != ':')
  2475. flags |= CD_PRINT;
  2476. docd:
  2477. if (!docd(p, flags))
  2478. goto out;
  2479. goto err;
  2480. }
  2481. }
  2482. step6:
  2483. p = dest;
  2484. goto docd;
  2485. err:
  2486. ash_msg_and_raise_perror("can't cd to %s", dest);
  2487. /* NOTREACHED */
  2488. out:
  2489. if (flags & CD_PRINT)
  2490. out1fmt("%s\n", curdir);
  2491. return 0;
  2492. }
  2493. static int FAST_FUNC
  2494. pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  2495. {
  2496. int flags;
  2497. const char *dir = curdir;
  2498. flags = cdopt();
  2499. if (flags) {
  2500. if (physdir == nullstr)
  2501. setpwd(dir, 0);
  2502. dir = physdir;
  2503. }
  2504. out1fmt("%s\n", dir);
  2505. return 0;
  2506. }
  2507. /* ============ ... */
  2508. #define IBUFSIZ (ENABLE_FEATURE_EDITING ? CONFIG_FEATURE_EDITING_MAX_LEN : 1024)
  2509. /* Syntax classes */
  2510. #define CWORD 0 /* character is nothing special */
  2511. #define CNL 1 /* newline character */
  2512. #define CBACK 2 /* a backslash character */
  2513. #define CSQUOTE 3 /* single quote */
  2514. #define CDQUOTE 4 /* double quote */
  2515. #define CENDQUOTE 5 /* a terminating quote */
  2516. #define CBQUOTE 6 /* backwards single quote */
  2517. #define CVAR 7 /* a dollar sign */
  2518. #define CENDVAR 8 /* a '}' character */
  2519. #define CLP 9 /* a left paren in arithmetic */
  2520. #define CRP 10 /* a right paren in arithmetic */
  2521. #define CENDFILE 11 /* end of file */
  2522. #define CCTL 12 /* like CWORD, except it must be escaped */
  2523. #define CSPCL 13 /* these terminate a word */
  2524. #define CIGN 14 /* character should be ignored */
  2525. #define PEOF 256
  2526. #if ENABLE_ASH_ALIAS
  2527. # define PEOA 257
  2528. #endif
  2529. #define USE_SIT_FUNCTION ENABLE_ASH_OPTIMIZE_FOR_SIZE
  2530. #if ENABLE_FEATURE_SH_MATH
  2531. # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8) | (d << 12))
  2532. #else
  2533. # define SIT_ITEM(a,b,c,d) (a | (b << 4) | (c << 8))
  2534. #endif
  2535. static const uint16_t S_I_T[] ALIGN2 = {
  2536. #if ENABLE_ASH_ALIAS
  2537. SIT_ITEM(CSPCL , CIGN , CIGN , CIGN ), /* 0, PEOA */
  2538. #endif
  2539. SIT_ITEM(CSPCL , CWORD , CWORD, CWORD ), /* 1, ' ' */
  2540. SIT_ITEM(CNL , CNL , CNL , CNL ), /* 2, \n */
  2541. SIT_ITEM(CWORD , CCTL , CCTL , CWORD ), /* 3, !*-/:=?[]~ */
  2542. SIT_ITEM(CDQUOTE , CENDQUOTE, CWORD, CWORD ), /* 4, '"' */
  2543. SIT_ITEM(CVAR , CVAR , CWORD, CVAR ), /* 5, $ */
  2544. SIT_ITEM(CSQUOTE , CWORD , CENDQUOTE, CWORD), /* 6, "'" */
  2545. SIT_ITEM(CSPCL , CWORD , CWORD, CLP ), /* 7, ( */
  2546. SIT_ITEM(CSPCL , CWORD , CWORD, CRP ), /* 8, ) */
  2547. SIT_ITEM(CBACK , CBACK , CCTL , CBACK ), /* 9, \ */
  2548. SIT_ITEM(CBQUOTE , CBQUOTE , CWORD, CBQUOTE), /* 10, ` */
  2549. SIT_ITEM(CENDVAR , CENDVAR , CWORD, CENDVAR), /* 11, } */
  2550. #if !USE_SIT_FUNCTION
  2551. SIT_ITEM(CENDFILE, CENDFILE , CENDFILE, CENDFILE),/* 12, PEOF */
  2552. SIT_ITEM(CWORD , CWORD , CWORD, CWORD ), /* 13, 0-9A-Za-z */
  2553. SIT_ITEM(CCTL , CCTL , CCTL , CCTL ) /* 14, CTLESC ... */
  2554. #endif
  2555. #undef SIT_ITEM
  2556. };
  2557. /* Constants below must match table above */
  2558. enum {
  2559. #if ENABLE_ASH_ALIAS
  2560. CSPCL_CIGN_CIGN_CIGN , /* 0 */
  2561. #endif
  2562. CSPCL_CWORD_CWORD_CWORD , /* 1 */
  2563. CNL_CNL_CNL_CNL , /* 2 */
  2564. CWORD_CCTL_CCTL_CWORD , /* 3 */
  2565. CDQUOTE_CENDQUOTE_CWORD_CWORD , /* 4 */
  2566. CVAR_CVAR_CWORD_CVAR , /* 5 */
  2567. CSQUOTE_CWORD_CENDQUOTE_CWORD , /* 6 */
  2568. CSPCL_CWORD_CWORD_CLP , /* 7 */
  2569. CSPCL_CWORD_CWORD_CRP , /* 8 */
  2570. CBACK_CBACK_CCTL_CBACK , /* 9 */
  2571. CBQUOTE_CBQUOTE_CWORD_CBQUOTE , /* 10 */
  2572. CENDVAR_CENDVAR_CWORD_CENDVAR , /* 11 */
  2573. CENDFILE_CENDFILE_CENDFILE_CENDFILE, /* 12 */
  2574. CWORD_CWORD_CWORD_CWORD , /* 13 */
  2575. CCTL_CCTL_CCTL_CCTL , /* 14 */
  2576. };
  2577. /* c in SIT(c, syntax) must be an *unsigned char* or PEOA or PEOF,
  2578. * caller must ensure proper cast on it if c is *char_ptr!
  2579. */
  2580. #if USE_SIT_FUNCTION
  2581. static int
  2582. SIT(int c, int syntax)
  2583. {
  2584. /* Used to also have '/' in this string: "\t\n !\"$&'()*-/:;<=>?[\\]`|}~" */
  2585. static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-:;<=>?[\\]`|}~";
  2586. /*
  2587. * This causes '/' to be prepended with CTLESC in dquoted string,
  2588. * making "./file"* treated incorrectly because we feed
  2589. * ".\/file*" string to glob(), confusing it (see expandmeta func).
  2590. * The "homegrown" glob implementation is okay with that,
  2591. * but glibc one isn't. With '/' always treated as CWORD,
  2592. * both work fine.
  2593. */
  2594. # if ENABLE_ASH_ALIAS
  2595. static const uint8_t syntax_index_table[] ALIGN1 = {
  2596. 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
  2597. 7, 8, 3, 3,/*3,*/3, 1, 1, /* "()*-/:;<" */
  2598. 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
  2599. 11, 3 /* "}~" */
  2600. };
  2601. # else
  2602. static const uint8_t syntax_index_table[] ALIGN1 = {
  2603. 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
  2604. 6, 7, 2, 2,/*2,*/2, 0, 0, /* "()*-/:;<" */
  2605. 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
  2606. 10, 2 /* "}~" */
  2607. };
  2608. # endif
  2609. const char *s;
  2610. int indx;
  2611. if (c == PEOF)
  2612. return CENDFILE;
  2613. # if ENABLE_ASH_ALIAS
  2614. if (c == PEOA)
  2615. indx = 0;
  2616. else
  2617. # endif
  2618. {
  2619. /* Cast is purely for paranoia here,
  2620. * just in case someone passed signed char to us */
  2621. if ((unsigned char)c >= CTL_FIRST
  2622. && (unsigned char)c <= CTL_LAST
  2623. ) {
  2624. return CCTL;
  2625. }
  2626. s = strchrnul(spec_symbls, c);
  2627. if (*s == '\0')
  2628. return CWORD;
  2629. indx = syntax_index_table[s - spec_symbls];
  2630. }
  2631. return (S_I_T[indx] >> (syntax*4)) & 0xf;
  2632. }
  2633. #else /* !USE_SIT_FUNCTION */
  2634. static const uint8_t syntax_index_table[] ALIGN1 = {
  2635. /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
  2636. /* 0 */ CWORD_CWORD_CWORD_CWORD,
  2637. /* 1 */ CWORD_CWORD_CWORD_CWORD,
  2638. /* 2 */ CWORD_CWORD_CWORD_CWORD,
  2639. /* 3 */ CWORD_CWORD_CWORD_CWORD,
  2640. /* 4 */ CWORD_CWORD_CWORD_CWORD,
  2641. /* 5 */ CWORD_CWORD_CWORD_CWORD,
  2642. /* 6 */ CWORD_CWORD_CWORD_CWORD,
  2643. /* 7 */ CWORD_CWORD_CWORD_CWORD,
  2644. /* 8 */ CWORD_CWORD_CWORD_CWORD,
  2645. /* 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
  2646. /* 10 "\n" */ CNL_CNL_CNL_CNL,
  2647. /* 11 */ CWORD_CWORD_CWORD_CWORD,
  2648. /* 12 */ CWORD_CWORD_CWORD_CWORD,
  2649. /* 13 */ CWORD_CWORD_CWORD_CWORD,
  2650. /* 14 */ CWORD_CWORD_CWORD_CWORD,
  2651. /* 15 */ CWORD_CWORD_CWORD_CWORD,
  2652. /* 16 */ CWORD_CWORD_CWORD_CWORD,
  2653. /* 17 */ CWORD_CWORD_CWORD_CWORD,
  2654. /* 18 */ CWORD_CWORD_CWORD_CWORD,
  2655. /* 19 */ CWORD_CWORD_CWORD_CWORD,
  2656. /* 20 */ CWORD_CWORD_CWORD_CWORD,
  2657. /* 21 */ CWORD_CWORD_CWORD_CWORD,
  2658. /* 22 */ CWORD_CWORD_CWORD_CWORD,
  2659. /* 23 */ CWORD_CWORD_CWORD_CWORD,
  2660. /* 24 */ CWORD_CWORD_CWORD_CWORD,
  2661. /* 25 */ CWORD_CWORD_CWORD_CWORD,
  2662. /* 26 */ CWORD_CWORD_CWORD_CWORD,
  2663. /* 27 */ CWORD_CWORD_CWORD_CWORD,
  2664. /* 28 */ CWORD_CWORD_CWORD_CWORD,
  2665. /* 29 */ CWORD_CWORD_CWORD_CWORD,
  2666. /* 30 */ CWORD_CWORD_CWORD_CWORD,
  2667. /* 31 */ CWORD_CWORD_CWORD_CWORD,
  2668. /* 32 " " */ CSPCL_CWORD_CWORD_CWORD,
  2669. /* 33 "!" */ CWORD_CCTL_CCTL_CWORD,
  2670. /* 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
  2671. /* 35 "#" */ CWORD_CWORD_CWORD_CWORD,
  2672. /* 36 "$" */ CVAR_CVAR_CWORD_CVAR,
  2673. /* 37 "%" */ CWORD_CWORD_CWORD_CWORD,
  2674. /* 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
  2675. /* 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
  2676. /* 40 "(" */ CSPCL_CWORD_CWORD_CLP,
  2677. /* 41 ")" */ CSPCL_CWORD_CWORD_CRP,
  2678. /* 42 "*" */ CWORD_CCTL_CCTL_CWORD,
  2679. /* 43 "+" */ CWORD_CWORD_CWORD_CWORD,
  2680. /* 44 "," */ CWORD_CWORD_CWORD_CWORD,
  2681. /* 45 "-" */ CWORD_CCTL_CCTL_CWORD,
  2682. /* 46 "." */ CWORD_CWORD_CWORD_CWORD,
  2683. /* "/" was CWORD_CCTL_CCTL_CWORD, see comment in SIT() function why this is changed: */
  2684. /* 47 "/" */ CWORD_CWORD_CWORD_CWORD,
  2685. /* 48 "0" */ CWORD_CWORD_CWORD_CWORD,
  2686. /* 49 "1" */ CWORD_CWORD_CWORD_CWORD,
  2687. /* 50 "2" */ CWORD_CWORD_CWORD_CWORD,
  2688. /* 51 "3" */ CWORD_CWORD_CWORD_CWORD,
  2689. /* 52 "4" */ CWORD_CWORD_CWORD_CWORD,
  2690. /* 53 "5" */ CWORD_CWORD_CWORD_CWORD,
  2691. /* 54 "6" */ CWORD_CWORD_CWORD_CWORD,
  2692. /* 55 "7" */ CWORD_CWORD_CWORD_CWORD,
  2693. /* 56 "8" */ CWORD_CWORD_CWORD_CWORD,
  2694. /* 57 "9" */ CWORD_CWORD_CWORD_CWORD,
  2695. /* 58 ":" */ CWORD_CCTL_CCTL_CWORD,
  2696. /* 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
  2697. /* 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
  2698. /* 61 "=" */ CWORD_CCTL_CCTL_CWORD,
  2699. /* 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
  2700. /* 63 "?" */ CWORD_CCTL_CCTL_CWORD,
  2701. /* 64 "@" */ CWORD_CWORD_CWORD_CWORD,
  2702. /* 65 "A" */ CWORD_CWORD_CWORD_CWORD,
  2703. /* 66 "B" */ CWORD_CWORD_CWORD_CWORD,
  2704. /* 67 "C" */ CWORD_CWORD_CWORD_CWORD,
  2705. /* 68 "D" */ CWORD_CWORD_CWORD_CWORD,
  2706. /* 69 "E" */ CWORD_CWORD_CWORD_CWORD,
  2707. /* 70 "F" */ CWORD_CWORD_CWORD_CWORD,
  2708. /* 71 "G" */ CWORD_CWORD_CWORD_CWORD,
  2709. /* 72 "H" */ CWORD_CWORD_CWORD_CWORD,
  2710. /* 73 "I" */ CWORD_CWORD_CWORD_CWORD,
  2711. /* 74 "J" */ CWORD_CWORD_CWORD_CWORD,
  2712. /* 75 "K" */ CWORD_CWORD_CWORD_CWORD,
  2713. /* 76 "L" */ CWORD_CWORD_CWORD_CWORD,
  2714. /* 77 "M" */ CWORD_CWORD_CWORD_CWORD,
  2715. /* 78 "N" */ CWORD_CWORD_CWORD_CWORD,
  2716. /* 79 "O" */ CWORD_CWORD_CWORD_CWORD,
  2717. /* 80 "P" */ CWORD_CWORD_CWORD_CWORD,
  2718. /* 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
  2719. /* 82 "R" */ CWORD_CWORD_CWORD_CWORD,
  2720. /* 83 "S" */ CWORD_CWORD_CWORD_CWORD,
  2721. /* 84 "T" */ CWORD_CWORD_CWORD_CWORD,
  2722. /* 85 "U" */ CWORD_CWORD_CWORD_CWORD,
  2723. /* 86 "V" */ CWORD_CWORD_CWORD_CWORD,
  2724. /* 87 "W" */ CWORD_CWORD_CWORD_CWORD,
  2725. /* 88 "X" */ CWORD_CWORD_CWORD_CWORD,
  2726. /* 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
  2727. /* 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
  2728. /* 91 "[" */ CWORD_CCTL_CCTL_CWORD,
  2729. /* 92 "\" */ CBACK_CBACK_CCTL_CBACK,
  2730. /* 93 "]" */ CWORD_CCTL_CCTL_CWORD,
  2731. /* 94 "^" */ CWORD_CWORD_CWORD_CWORD,
  2732. /* 95 "_" */ CWORD_CWORD_CWORD_CWORD,
  2733. /* 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
  2734. /* 97 "a" */ CWORD_CWORD_CWORD_CWORD,
  2735. /* 98 "b" */ CWORD_CWORD_CWORD_CWORD,
  2736. /* 99 "c" */ CWORD_CWORD_CWORD_CWORD,
  2737. /* 100 "d" */ CWORD_CWORD_CWORD_CWORD,
  2738. /* 101 "e" */ CWORD_CWORD_CWORD_CWORD,
  2739. /* 102 "f" */ CWORD_CWORD_CWORD_CWORD,
  2740. /* 103 "g" */ CWORD_CWORD_CWORD_CWORD,
  2741. /* 104 "h" */ CWORD_CWORD_CWORD_CWORD,
  2742. /* 105 "i" */ CWORD_CWORD_CWORD_CWORD,
  2743. /* 106 "j" */ CWORD_CWORD_CWORD_CWORD,
  2744. /* 107 "k" */ CWORD_CWORD_CWORD_CWORD,
  2745. /* 108 "l" */ CWORD_CWORD_CWORD_CWORD,
  2746. /* 109 "m" */ CWORD_CWORD_CWORD_CWORD,
  2747. /* 110 "n" */ CWORD_CWORD_CWORD_CWORD,
  2748. /* 111 "o" */ CWORD_CWORD_CWORD_CWORD,
  2749. /* 112 "p" */ CWORD_CWORD_CWORD_CWORD,
  2750. /* 113 "q" */ CWORD_CWORD_CWORD_CWORD,
  2751. /* 114 "r" */ CWORD_CWORD_CWORD_CWORD,
  2752. /* 115 "s" */ CWORD_CWORD_CWORD_CWORD,
  2753. /* 116 "t" */ CWORD_CWORD_CWORD_CWORD,
  2754. /* 117 "u" */ CWORD_CWORD_CWORD_CWORD,
  2755. /* 118 "v" */ CWORD_CWORD_CWORD_CWORD,
  2756. /* 119 "w" */ CWORD_CWORD_CWORD_CWORD,
  2757. /* 120 "x" */ CWORD_CWORD_CWORD_CWORD,
  2758. /* 121 "y" */ CWORD_CWORD_CWORD_CWORD,
  2759. /* 122 "z" */ CWORD_CWORD_CWORD_CWORD,
  2760. /* 123 "{" */ CWORD_CWORD_CWORD_CWORD,
  2761. /* 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
  2762. /* 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
  2763. /* 126 "~" */ CWORD_CCTL_CCTL_CWORD,
  2764. /* 127 del */ CWORD_CWORD_CWORD_CWORD,
  2765. /* 128 0x80 */ CWORD_CWORD_CWORD_CWORD,
  2766. /* 129 CTLESC */ CCTL_CCTL_CCTL_CCTL,
  2767. /* 130 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
  2768. /* 131 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
  2769. /* 132 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
  2770. /* 133 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
  2771. /* 134 CTLARI */ CCTL_CCTL_CCTL_CCTL,
  2772. /* 135 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
  2773. /* 136 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
  2774. /* 137 */ CWORD_CWORD_CWORD_CWORD,
  2775. /* 138 */ CWORD_CWORD_CWORD_CWORD,
  2776. /* 139 */ CWORD_CWORD_CWORD_CWORD,
  2777. /* 140 */ CWORD_CWORD_CWORD_CWORD,
  2778. /* 141 */ CWORD_CWORD_CWORD_CWORD,
  2779. /* 142 */ CWORD_CWORD_CWORD_CWORD,
  2780. /* 143 */ CWORD_CWORD_CWORD_CWORD,
  2781. /* 144 */ CWORD_CWORD_CWORD_CWORD,
  2782. /* 145 */ CWORD_CWORD_CWORD_CWORD,
  2783. /* 146 */ CWORD_CWORD_CWORD_CWORD,
  2784. /* 147 */ CWORD_CWORD_CWORD_CWORD,
  2785. /* 148 */ CWORD_CWORD_CWORD_CWORD,
  2786. /* 149 */ CWORD_CWORD_CWORD_CWORD,
  2787. /* 150 */ CWORD_CWORD_CWORD_CWORD,
  2788. /* 151 */ CWORD_CWORD_CWORD_CWORD,
  2789. /* 152 */ CWORD_CWORD_CWORD_CWORD,
  2790. /* 153 */ CWORD_CWORD_CWORD_CWORD,
  2791. /* 154 */ CWORD_CWORD_CWORD_CWORD,
  2792. /* 155 */ CWORD_CWORD_CWORD_CWORD,
  2793. /* 156 */ CWORD_CWORD_CWORD_CWORD,
  2794. /* 157 */ CWORD_CWORD_CWORD_CWORD,
  2795. /* 158 */ CWORD_CWORD_CWORD_CWORD,
  2796. /* 159 */ CWORD_CWORD_CWORD_CWORD,
  2797. /* 160 */ CWORD_CWORD_CWORD_CWORD,
  2798. /* 161 */ CWORD_CWORD_CWORD_CWORD,
  2799. /* 162 */ CWORD_CWORD_CWORD_CWORD,
  2800. /* 163 */ CWORD_CWORD_CWORD_CWORD,
  2801. /* 164 */ CWORD_CWORD_CWORD_CWORD,
  2802. /* 165 */ CWORD_CWORD_CWORD_CWORD,
  2803. /* 166 */ CWORD_CWORD_CWORD_CWORD,
  2804. /* 167 */ CWORD_CWORD_CWORD_CWORD,
  2805. /* 168 */ CWORD_CWORD_CWORD_CWORD,
  2806. /* 169 */ CWORD_CWORD_CWORD_CWORD,
  2807. /* 170 */ CWORD_CWORD_CWORD_CWORD,
  2808. /* 171 */ CWORD_CWORD_CWORD_CWORD,
  2809. /* 172 */ CWORD_CWORD_CWORD_CWORD,
  2810. /* 173 */ CWORD_CWORD_CWORD_CWORD,
  2811. /* 174 */ CWORD_CWORD_CWORD_CWORD,
  2812. /* 175 */ CWORD_CWORD_CWORD_CWORD,
  2813. /* 176 */ CWORD_CWORD_CWORD_CWORD,
  2814. /* 177 */ CWORD_CWORD_CWORD_CWORD,
  2815. /* 178 */ CWORD_CWORD_CWORD_CWORD,
  2816. /* 179 */ CWORD_CWORD_CWORD_CWORD,
  2817. /* 180 */ CWORD_CWORD_CWORD_CWORD,
  2818. /* 181 */ CWORD_CWORD_CWORD_CWORD,
  2819. /* 182 */ CWORD_CWORD_CWORD_CWORD,
  2820. /* 183 */ CWORD_CWORD_CWORD_CWORD,
  2821. /* 184 */ CWORD_CWORD_CWORD_CWORD,
  2822. /* 185 */ CWORD_CWORD_CWORD_CWORD,
  2823. /* 186 */ CWORD_CWORD_CWORD_CWORD,
  2824. /* 187 */ CWORD_CWORD_CWORD_CWORD,
  2825. /* 188 */ CWORD_CWORD_CWORD_CWORD,
  2826. /* 189 */ CWORD_CWORD_CWORD_CWORD,
  2827. /* 190 */ CWORD_CWORD_CWORD_CWORD,
  2828. /* 191 */ CWORD_CWORD_CWORD_CWORD,
  2829. /* 192 */ CWORD_CWORD_CWORD_CWORD,
  2830. /* 193 */ CWORD_CWORD_CWORD_CWORD,
  2831. /* 194 */ CWORD_CWORD_CWORD_CWORD,
  2832. /* 195 */ CWORD_CWORD_CWORD_CWORD,
  2833. /* 196 */ CWORD_CWORD_CWORD_CWORD,
  2834. /* 197 */ CWORD_CWORD_CWORD_CWORD,
  2835. /* 198 */ CWORD_CWORD_CWORD_CWORD,
  2836. /* 199 */ CWORD_CWORD_CWORD_CWORD,
  2837. /* 200 */ CWORD_CWORD_CWORD_CWORD,
  2838. /* 201 */ CWORD_CWORD_CWORD_CWORD,
  2839. /* 202 */ CWORD_CWORD_CWORD_CWORD,
  2840. /* 203 */ CWORD_CWORD_CWORD_CWORD,
  2841. /* 204 */ CWORD_CWORD_CWORD_CWORD,
  2842. /* 205 */ CWORD_CWORD_CWORD_CWORD,
  2843. /* 206 */ CWORD_CWORD_CWORD_CWORD,
  2844. /* 207 */ CWORD_CWORD_CWORD_CWORD,
  2845. /* 208 */ CWORD_CWORD_CWORD_CWORD,
  2846. /* 209 */ CWORD_CWORD_CWORD_CWORD,
  2847. /* 210 */ CWORD_CWORD_CWORD_CWORD,
  2848. /* 211 */ CWORD_CWORD_CWORD_CWORD,
  2849. /* 212 */ CWORD_CWORD_CWORD_CWORD,
  2850. /* 213 */ CWORD_CWORD_CWORD_CWORD,
  2851. /* 214 */ CWORD_CWORD_CWORD_CWORD,
  2852. /* 215 */ CWORD_CWORD_CWORD_CWORD,
  2853. /* 216 */ CWORD_CWORD_CWORD_CWORD,
  2854. /* 217 */ CWORD_CWORD_CWORD_CWORD,
  2855. /* 218 */ CWORD_CWORD_CWORD_CWORD,
  2856. /* 219 */ CWORD_CWORD_CWORD_CWORD,
  2857. /* 220 */ CWORD_CWORD_CWORD_CWORD,
  2858. /* 221 */ CWORD_CWORD_CWORD_CWORD,
  2859. /* 222 */ CWORD_CWORD_CWORD_CWORD,
  2860. /* 223 */ CWORD_CWORD_CWORD_CWORD,
  2861. /* 224 */ CWORD_CWORD_CWORD_CWORD,
  2862. /* 225 */ CWORD_CWORD_CWORD_CWORD,
  2863. /* 226 */ CWORD_CWORD_CWORD_CWORD,
  2864. /* 227 */ CWORD_CWORD_CWORD_CWORD,
  2865. /* 228 */ CWORD_CWORD_CWORD_CWORD,
  2866. /* 229 */ CWORD_CWORD_CWORD_CWORD,
  2867. /* 230 */ CWORD_CWORD_CWORD_CWORD,
  2868. /* 231 */ CWORD_CWORD_CWORD_CWORD,
  2869. /* 232 */ CWORD_CWORD_CWORD_CWORD,
  2870. /* 233 */ CWORD_CWORD_CWORD_CWORD,
  2871. /* 234 */ CWORD_CWORD_CWORD_CWORD,
  2872. /* 235 */ CWORD_CWORD_CWORD_CWORD,
  2873. /* 236 */ CWORD_CWORD_CWORD_CWORD,
  2874. /* 237 */ CWORD_CWORD_CWORD_CWORD,
  2875. /* 238 */ CWORD_CWORD_CWORD_CWORD,
  2876. /* 239 */ CWORD_CWORD_CWORD_CWORD,
  2877. /* 230 */ CWORD_CWORD_CWORD_CWORD,
  2878. /* 241 */ CWORD_CWORD_CWORD_CWORD,
  2879. /* 242 */ CWORD_CWORD_CWORD_CWORD,
  2880. /* 243 */ CWORD_CWORD_CWORD_CWORD,
  2881. /* 244 */ CWORD_CWORD_CWORD_CWORD,
  2882. /* 245 */ CWORD_CWORD_CWORD_CWORD,
  2883. /* 246 */ CWORD_CWORD_CWORD_CWORD,
  2884. /* 247 */ CWORD_CWORD_CWORD_CWORD,
  2885. /* 248 */ CWORD_CWORD_CWORD_CWORD,
  2886. /* 249 */ CWORD_CWORD_CWORD_CWORD,
  2887. /* 250 */ CWORD_CWORD_CWORD_CWORD,
  2888. /* 251 */ CWORD_CWORD_CWORD_CWORD,
  2889. /* 252 */ CWORD_CWORD_CWORD_CWORD,
  2890. /* 253 */ CWORD_CWORD_CWORD_CWORD,
  2891. /* 254 */ CWORD_CWORD_CWORD_CWORD,
  2892. /* 255 */ CWORD_CWORD_CWORD_CWORD,
  2893. /* PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
  2894. # if ENABLE_ASH_ALIAS
  2895. /* PEOA */ CSPCL_CIGN_CIGN_CIGN,
  2896. # endif
  2897. };
  2898. #if 1
  2899. # define SIT(c, syntax) ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf)
  2900. #else /* debug version, caught one signed char bug */
  2901. # define SIT(c, syntax) \
  2902. ({ \
  2903. if ((c) < 0 || (c) > (PEOF + ENABLE_ASH_ALIAS)) \
  2904. bb_error_msg_and_die("line:%d c:%d", __LINE__, (c)); \
  2905. if ((syntax) < 0 || (syntax) > (2 + ENABLE_FEATURE_SH_MATH)) \
  2906. bb_error_msg_and_die("line:%d c:%d", __LINE__, (c)); \
  2907. ((S_I_T[syntax_index_table[c]] >> ((syntax)*4)) & 0xf); \
  2908. })
  2909. #endif
  2910. #endif /* !USE_SIT_FUNCTION */
  2911. /* ============ Alias handling */
  2912. #if ENABLE_ASH_ALIAS
  2913. #define ALIASINUSE 1
  2914. #define ALIASDEAD 2
  2915. struct alias {
  2916. struct alias *next;
  2917. char *name;
  2918. char *val;
  2919. int flag;
  2920. };
  2921. static struct alias **atab; // [ATABSIZE];
  2922. #define INIT_G_alias() do { \
  2923. atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
  2924. } while (0)
  2925. static struct alias **
  2926. __lookupalias(const char *name)
  2927. {
  2928. unsigned int hashval;
  2929. struct alias **app;
  2930. const char *p;
  2931. unsigned int ch;
  2932. p = name;
  2933. ch = (unsigned char)*p;
  2934. hashval = ch << 4;
  2935. while (ch) {
  2936. hashval += ch;
  2937. ch = (unsigned char)*++p;
  2938. }
  2939. app = &atab[hashval % ATABSIZE];
  2940. for (; *app; app = &(*app)->next) {
  2941. if (strcmp(name, (*app)->name) == 0) {
  2942. break;
  2943. }
  2944. }
  2945. return app;
  2946. }
  2947. static struct alias *
  2948. lookupalias(const char *name, int check)
  2949. {
  2950. struct alias *ap = *__lookupalias(name);
  2951. if (check && ap && (ap->flag & ALIASINUSE))
  2952. return NULL;
  2953. return ap;
  2954. }
  2955. static struct alias *
  2956. freealias(struct alias *ap)
  2957. {
  2958. struct alias *next;
  2959. if (ap->flag & ALIASINUSE) {
  2960. ap->flag |= ALIASDEAD;
  2961. return ap;
  2962. }
  2963. next = ap->next;
  2964. free(ap->name);
  2965. free(ap->val);
  2966. free(ap);
  2967. return next;
  2968. }
  2969. static void
  2970. setalias(const char *name, const char *val)
  2971. {
  2972. struct alias *ap, **app;
  2973. app = __lookupalias(name);
  2974. ap = *app;
  2975. INT_OFF;
  2976. if (ap) {
  2977. if (!(ap->flag & ALIASINUSE)) {
  2978. free(ap->val);
  2979. }
  2980. ap->val = ckstrdup(val);
  2981. ap->flag &= ~ALIASDEAD;
  2982. } else {
  2983. /* not found */
  2984. ap = ckzalloc(sizeof(struct alias));
  2985. ap->name = ckstrdup(name);
  2986. ap->val = ckstrdup(val);
  2987. /*ap->flag = 0; - ckzalloc did it */
  2988. /*ap->next = NULL;*/
  2989. *app = ap;
  2990. }
  2991. INT_ON;
  2992. }
  2993. static int
  2994. unalias(const char *name)
  2995. {
  2996. struct alias **app;
  2997. app = __lookupalias(name);
  2998. if (*app) {
  2999. INT_OFF;
  3000. *app = freealias(*app);
  3001. INT_ON;
  3002. return 0;
  3003. }
  3004. return 1;
  3005. }
  3006. static void
  3007. rmaliases(void)
  3008. {
  3009. struct alias *ap, **app;
  3010. int i;
  3011. INT_OFF;
  3012. for (i = 0; i < ATABSIZE; i++) {
  3013. app = &atab[i];
  3014. for (ap = *app; ap; ap = *app) {
  3015. *app = freealias(*app);
  3016. if (ap == *app) {
  3017. app = &ap->next;
  3018. }
  3019. }
  3020. }
  3021. INT_ON;
  3022. }
  3023. static void
  3024. printalias(const struct alias *ap)
  3025. {
  3026. out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
  3027. }
  3028. /*
  3029. * TODO - sort output
  3030. */
  3031. static int FAST_FUNC
  3032. aliascmd(int argc UNUSED_PARAM, char **argv)
  3033. {
  3034. char *n, *v;
  3035. int ret = 0;
  3036. struct alias *ap;
  3037. if (!argv[1]) {
  3038. int i;
  3039. for (i = 0; i < ATABSIZE; i++) {
  3040. for (ap = atab[i]; ap; ap = ap->next) {
  3041. printalias(ap);
  3042. }
  3043. }
  3044. return 0;
  3045. }
  3046. while ((n = *++argv) != NULL) {
  3047. v = strchr(n+1, '=');
  3048. if (v == NULL) { /* n+1: funny ksh stuff */
  3049. ap = *__lookupalias(n);
  3050. if (ap == NULL) {
  3051. fprintf(stderr, "%s: %s not found\n", "alias", n);
  3052. ret = 1;
  3053. } else
  3054. printalias(ap);
  3055. } else {
  3056. *v++ = '\0';
  3057. setalias(n, v);
  3058. }
  3059. }
  3060. return ret;
  3061. }
  3062. static int FAST_FUNC
  3063. unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  3064. {
  3065. int i;
  3066. while (nextopt("a") != '\0') {
  3067. rmaliases();
  3068. return 0;
  3069. }
  3070. for (i = 0; *argptr; argptr++) {
  3071. if (unalias(*argptr)) {
  3072. fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
  3073. i = 1;
  3074. }
  3075. }
  3076. return i;
  3077. }
  3078. #endif /* ASH_ALIAS */
  3079. /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
  3080. #define FORK_FG 0
  3081. #define FORK_BG 1
  3082. #define FORK_NOJOB 2
  3083. /* mode flags for showjob(s) */
  3084. #define SHOW_ONLY_PGID 0x01 /* show only pgid (jobs -p) */
  3085. #define SHOW_PIDS 0x02 /* show individual pids, not just one line per job */
  3086. #define SHOW_CHANGED 0x04 /* only jobs whose state has changed */
  3087. #define SHOW_STDERR 0x08 /* print to stderr (else stdout) */
  3088. /*
  3089. * A job structure contains information about a job. A job is either a
  3090. * single process or a set of processes contained in a pipeline. In the
  3091. * latter case, pidlist will be non-NULL, and will point to a -1 terminated
  3092. * array of pids.
  3093. */
  3094. struct procstat {
  3095. pid_t ps_pid; /* process id */
  3096. int ps_status; /* last process status from wait() */
  3097. char *ps_cmd; /* text of command being run */
  3098. };
  3099. struct job {
  3100. struct procstat ps0; /* status of process */
  3101. struct procstat *ps; /* status or processes when more than one */
  3102. #if JOBS
  3103. int stopstatus; /* status of a stopped job */
  3104. #endif
  3105. unsigned nprocs; /* number of processes */
  3106. #define JOBRUNNING 0 /* at least one proc running */
  3107. #define JOBSTOPPED 1 /* all procs are stopped */
  3108. #define JOBDONE 2 /* all procs are completed */
  3109. unsigned
  3110. state: 8,
  3111. #if JOBS
  3112. sigint: 1, /* job was killed by SIGINT */
  3113. jobctl: 1, /* job running under job control */
  3114. #endif
  3115. waited: 1, /* true if this entry has been waited for */
  3116. used: 1, /* true if this entry is in used */
  3117. changed: 1; /* true if status has changed */
  3118. struct job *prev_job; /* previous job */
  3119. };
  3120. static struct job *makejob(/*union node *,*/ int);
  3121. static int forkshell(struct job *, union node *, int);
  3122. static int waitforjob(struct job *);
  3123. #if !JOBS
  3124. enum { doing_jobctl = 0 };
  3125. #define setjobctl(on) do {} while (0)
  3126. #else
  3127. static smallint doing_jobctl; //references:8
  3128. static void setjobctl(int);
  3129. #endif
  3130. /*
  3131. * Ignore a signal.
  3132. */
  3133. static void
  3134. ignoresig(int signo)
  3135. {
  3136. /* Avoid unnecessary system calls. Is it already SIG_IGNed? */
  3137. if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
  3138. /* No, need to do it */
  3139. signal(signo, SIG_IGN);
  3140. }
  3141. sigmode[signo - 1] = S_HARD_IGN;
  3142. }
  3143. /*
  3144. * Only one usage site - in setsignal()
  3145. */
  3146. static void
  3147. signal_handler(int signo)
  3148. {
  3149. if (signo == SIGCHLD) {
  3150. got_sigchld = 1;
  3151. if (!trap[SIGCHLD])
  3152. return;
  3153. }
  3154. gotsig[signo - 1] = 1;
  3155. pending_sig = signo;
  3156. if (signo == SIGINT && !trap[SIGINT]) {
  3157. if (!suppress_int) {
  3158. pending_sig = 0;
  3159. raise_interrupt(); /* does not return */
  3160. }
  3161. pending_int = 1;
  3162. }
  3163. }
  3164. /*
  3165. * Set the signal handler for the specified signal. The routine figures
  3166. * out what it should be set to.
  3167. */
  3168. static void
  3169. setsignal(int signo)
  3170. {
  3171. char *t;
  3172. char cur_act, new_act;
  3173. struct sigaction act;
  3174. t = trap[signo];
  3175. new_act = S_DFL;
  3176. if (t != NULL) { /* trap for this sig is set */
  3177. new_act = S_CATCH;
  3178. if (t[0] == '\0') /* trap is "": ignore this sig */
  3179. new_act = S_IGN;
  3180. }
  3181. if (rootshell && new_act == S_DFL) {
  3182. switch (signo) {
  3183. case SIGINT:
  3184. if (iflag || minusc || sflag == 0)
  3185. new_act = S_CATCH;
  3186. break;
  3187. case SIGQUIT:
  3188. #if DEBUG
  3189. if (debug)
  3190. break;
  3191. #endif
  3192. /* man bash:
  3193. * "In all cases, bash ignores SIGQUIT. Non-builtin
  3194. * commands run by bash have signal handlers
  3195. * set to the values inherited by the shell
  3196. * from its parent". */
  3197. new_act = S_IGN;
  3198. break;
  3199. case SIGTERM:
  3200. if (iflag)
  3201. new_act = S_IGN;
  3202. break;
  3203. #if JOBS
  3204. case SIGTSTP:
  3205. case SIGTTOU:
  3206. if (mflag)
  3207. new_act = S_IGN;
  3208. break;
  3209. #endif
  3210. }
  3211. }
  3212. /* if !rootshell, we reset SIGQUIT to DFL,
  3213. * whereas we have to restore it to what shell got on entry.
  3214. * This is handled by the fact that if signal was IGNored on entry,
  3215. * then cur_act is S_HARD_IGN and we never change its sigaction
  3216. * (see code below).
  3217. */
  3218. if (signo == SIGCHLD)
  3219. new_act = S_CATCH;
  3220. t = &sigmode[signo - 1];
  3221. cur_act = *t;
  3222. if (cur_act == 0) {
  3223. /* current setting is not yet known */
  3224. if (sigaction(signo, NULL, &act)) {
  3225. /* pretend it worked; maybe we should give a warning,
  3226. * but other shells don't. We don't alter sigmode,
  3227. * so we retry every time.
  3228. * btw, in Linux it never fails. --vda */
  3229. return;
  3230. }
  3231. if (act.sa_handler == SIG_IGN) {
  3232. cur_act = S_HARD_IGN;
  3233. if (mflag
  3234. && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
  3235. ) {
  3236. cur_act = S_IGN; /* don't hard ignore these */
  3237. }
  3238. }
  3239. if (act.sa_handler == SIG_DFL && new_act == S_DFL) {
  3240. /* installing SIG_DFL over SIG_DFL is a no-op */
  3241. /* saves one sigaction call in each "sh -c SCRIPT" invocation */
  3242. *t = S_DFL;
  3243. return;
  3244. }
  3245. }
  3246. if (cur_act == S_HARD_IGN || cur_act == new_act)
  3247. return;
  3248. *t = new_act;
  3249. act.sa_handler = SIG_DFL;
  3250. switch (new_act) {
  3251. case S_CATCH:
  3252. act.sa_handler = signal_handler;
  3253. break;
  3254. case S_IGN:
  3255. act.sa_handler = SIG_IGN;
  3256. break;
  3257. }
  3258. /* flags and mask matter only if !DFL and !IGN, but we do it
  3259. * for all cases for more deterministic behavior:
  3260. */
  3261. act.sa_flags = 0; //TODO: why not SA_RESTART?
  3262. sigfillset(&act.sa_mask);
  3263. sigaction_set(signo, &act);
  3264. }
  3265. /* mode flags for set_curjob */
  3266. #define CUR_DELETE 2
  3267. #define CUR_RUNNING 1
  3268. #define CUR_STOPPED 0
  3269. #if JOBS
  3270. /* pgrp of shell on invocation */
  3271. static int initialpgrp; //references:2
  3272. static int ttyfd = -1; //5
  3273. #endif
  3274. /* array of jobs */
  3275. static struct job *jobtab; //5
  3276. /* size of array */
  3277. static unsigned njobs; //4
  3278. /* current job */
  3279. static struct job *curjob; //lots
  3280. /* number of presumed living untracked jobs */
  3281. static int jobless; //4
  3282. #if 0
  3283. /* Bash has a feature: it restores termios after a successful wait for
  3284. * a foreground job which had at least one stopped or sigkilled member.
  3285. * The probable rationale is that SIGSTOP and SIGKILL can preclude task from
  3286. * properly restoring tty state. Should we do this too?
  3287. * A reproducer: ^Z an interactive python:
  3288. *
  3289. * # python
  3290. * Python 2.7.12 (...)
  3291. * >>> ^Z
  3292. * { python leaves tty in -icanon -echo state. We do survive that... }
  3293. * [1]+ Stopped python
  3294. * { ...however, next program (python #2) does not survive it well: }
  3295. * # python
  3296. * Python 2.7.12 (...)
  3297. * >>> Traceback (most recent call last):
  3298. * { above, I typed "qwerty<CR>", but -echo state is still in effect }
  3299. * File "<stdin>", line 1, in <module>
  3300. * NameError: name 'qwerty' is not defined
  3301. *
  3302. * The implementation below is modeled on bash code and seems to work.
  3303. * However, I'm not sure we should do this. For one: what if I'd fg
  3304. * the stopped python instead? It'll be confused by "restored" tty state.
  3305. */
  3306. static struct termios shell_tty_info;
  3307. static void
  3308. get_tty_state(void)
  3309. {
  3310. if (rootshell && ttyfd >= 0)
  3311. tcgetattr(ttyfd, &shell_tty_info);
  3312. }
  3313. static void
  3314. set_tty_state(void)
  3315. {
  3316. /* if (rootshell) - caller ensures this */
  3317. if (ttyfd >= 0)
  3318. tcsetattr(ttyfd, TCSADRAIN, &shell_tty_info);
  3319. }
  3320. static int
  3321. job_signal_status(struct job *jp)
  3322. {
  3323. int status;
  3324. unsigned i;
  3325. struct procstat *ps = jp->ps;
  3326. for (i = 0; i < jp->nprocs; i++) {
  3327. status = ps[i].ps_status;
  3328. if (WIFSIGNALED(status) || WIFSTOPPED(status))
  3329. return status;
  3330. }
  3331. return 0;
  3332. }
  3333. static void
  3334. restore_tty_if_stopped_or_signaled(struct job *jp)
  3335. {
  3336. //TODO: check what happens if we come from waitforjob() in expbackq()
  3337. if (rootshell) {
  3338. int s = job_signal_status(jp);
  3339. if (s) /* WIFSIGNALED(s) || WIFSTOPPED(s) */
  3340. set_tty_state();
  3341. }
  3342. }
  3343. #else
  3344. # define get_tty_state() ((void)0)
  3345. # define restore_tty_if_stopped_or_signaled(jp) ((void)0)
  3346. #endif
  3347. static void
  3348. set_curjob(struct job *jp, unsigned mode)
  3349. {
  3350. struct job *jp1;
  3351. struct job **jpp, **curp;
  3352. /* first remove from list */
  3353. jpp = curp = &curjob;
  3354. while (1) {
  3355. jp1 = *jpp;
  3356. if (jp1 == jp)
  3357. break;
  3358. jpp = &jp1->prev_job;
  3359. }
  3360. *jpp = jp1->prev_job;
  3361. /* Then re-insert in correct position */
  3362. jpp = curp;
  3363. switch (mode) {
  3364. default:
  3365. #if DEBUG
  3366. abort();
  3367. #endif
  3368. case CUR_DELETE:
  3369. /* job being deleted */
  3370. break;
  3371. case CUR_RUNNING:
  3372. /* newly created job or backgrounded job,
  3373. * put after all stopped jobs.
  3374. */
  3375. while (1) {
  3376. jp1 = *jpp;
  3377. #if JOBS
  3378. if (!jp1 || jp1->state != JOBSTOPPED)
  3379. #endif
  3380. break;
  3381. jpp = &jp1->prev_job;
  3382. }
  3383. /* FALLTHROUGH */
  3384. #if JOBS
  3385. case CUR_STOPPED:
  3386. #endif
  3387. /* newly stopped job - becomes curjob */
  3388. jp->prev_job = *jpp;
  3389. *jpp = jp;
  3390. break;
  3391. }
  3392. }
  3393. #if JOBS || DEBUG
  3394. static int
  3395. jobno(const struct job *jp)
  3396. {
  3397. return jp - jobtab + 1;
  3398. }
  3399. #endif
  3400. /*
  3401. * Convert a job name to a job structure.
  3402. */
  3403. #if !JOBS
  3404. #define getjob(name, getctl) getjob(name)
  3405. #endif
  3406. static struct job *
  3407. getjob(const char *name, int getctl)
  3408. {
  3409. struct job *jp;
  3410. struct job *found;
  3411. const char *err_msg = "%s: no such job";
  3412. unsigned num;
  3413. int c;
  3414. const char *p;
  3415. char *(*match)(const char *, const char *);
  3416. jp = curjob;
  3417. p = name;
  3418. if (!p)
  3419. goto currentjob;
  3420. if (*p != '%')
  3421. goto err;
  3422. c = *++p;
  3423. if (!c)
  3424. goto currentjob;
  3425. if (!p[1]) {
  3426. if (c == '+' || c == '%') {
  3427. currentjob:
  3428. err_msg = "No current job";
  3429. goto check;
  3430. }
  3431. if (c == '-') {
  3432. if (jp)
  3433. jp = jp->prev_job;
  3434. err_msg = "No previous job";
  3435. check:
  3436. if (!jp)
  3437. goto err;
  3438. goto gotit;
  3439. }
  3440. }
  3441. if (is_number(p)) {
  3442. num = atoi(p);
  3443. if (num > 0 && num <= njobs) {
  3444. jp = jobtab + num - 1;
  3445. if (jp->used)
  3446. goto gotit;
  3447. goto err;
  3448. }
  3449. }
  3450. match = prefix;
  3451. if (*p == '?') {
  3452. match = strstr;
  3453. p++;
  3454. }
  3455. found = NULL;
  3456. while (jp) {
  3457. if (match(jp->ps[0].ps_cmd, p)) {
  3458. if (found)
  3459. goto err;
  3460. found = jp;
  3461. err_msg = "%s: ambiguous";
  3462. }
  3463. jp = jp->prev_job;
  3464. }
  3465. if (!found)
  3466. goto err;
  3467. jp = found;
  3468. gotit:
  3469. #if JOBS
  3470. err_msg = "job %s not created under job control";
  3471. if (getctl && jp->jobctl == 0)
  3472. goto err;
  3473. #endif
  3474. return jp;
  3475. err:
  3476. ash_msg_and_raise_error(err_msg, name);
  3477. }
  3478. /*
  3479. * Mark a job structure as unused.
  3480. */
  3481. static void
  3482. freejob(struct job *jp)
  3483. {
  3484. struct procstat *ps;
  3485. int i;
  3486. INT_OFF;
  3487. for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
  3488. if (ps->ps_cmd != nullstr)
  3489. free(ps->ps_cmd);
  3490. }
  3491. if (jp->ps != &jp->ps0)
  3492. free(jp->ps);
  3493. jp->used = 0;
  3494. set_curjob(jp, CUR_DELETE);
  3495. INT_ON;
  3496. }
  3497. #if JOBS
  3498. static void
  3499. xtcsetpgrp(int fd, pid_t pgrp)
  3500. {
  3501. if (tcsetpgrp(fd, pgrp))
  3502. ash_msg_and_raise_perror("can't set tty process group");
  3503. }
  3504. /*
  3505. * Turn job control on and off.
  3506. *
  3507. * Note: This code assumes that the third arg to ioctl is a character
  3508. * pointer, which is true on Berkeley systems but not System V. Since
  3509. * System V doesn't have job control yet, this isn't a problem now.
  3510. *
  3511. * Called with interrupts off.
  3512. */
  3513. static void
  3514. setjobctl(int on)
  3515. {
  3516. int fd;
  3517. int pgrp;
  3518. if (on == doing_jobctl || rootshell == 0)
  3519. return;
  3520. if (on) {
  3521. int ofd;
  3522. ofd = fd = open(_PATH_TTY, O_RDWR);
  3523. if (fd < 0) {
  3524. /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
  3525. * That sometimes helps to acquire controlling tty.
  3526. * Obviously, a workaround for bugs when someone
  3527. * failed to provide a controlling tty to bash! :) */
  3528. fd = 2;
  3529. while (!isatty(fd))
  3530. if (--fd < 0)
  3531. goto out;
  3532. }
  3533. /* fd is a tty at this point */
  3534. fd = fcntl(fd, F_DUPFD, 10);
  3535. if (ofd >= 0) /* if it is "/dev/tty", close. If 0/1/2, don't */
  3536. close(ofd);
  3537. if (fd < 0)
  3538. goto out; /* F_DUPFD failed */
  3539. close_on_exec_on(fd);
  3540. while (1) { /* while we are in the background */
  3541. pgrp = tcgetpgrp(fd);
  3542. if (pgrp < 0) {
  3543. out:
  3544. ash_msg("can't access tty; job control turned off");
  3545. mflag = on = 0;
  3546. goto close;
  3547. }
  3548. if (pgrp == getpgrp())
  3549. break;
  3550. killpg(0, SIGTTIN);
  3551. }
  3552. initialpgrp = pgrp;
  3553. setsignal(SIGTSTP);
  3554. setsignal(SIGTTOU);
  3555. setsignal(SIGTTIN);
  3556. pgrp = rootpid;
  3557. setpgid(0, pgrp);
  3558. xtcsetpgrp(fd, pgrp);
  3559. } else {
  3560. /* turning job control off */
  3561. fd = ttyfd;
  3562. pgrp = initialpgrp;
  3563. /* was xtcsetpgrp, but this can make exiting ash
  3564. * loop forever if pty is already deleted */
  3565. tcsetpgrp(fd, pgrp);
  3566. setpgid(0, pgrp);
  3567. setsignal(SIGTSTP);
  3568. setsignal(SIGTTOU);
  3569. setsignal(SIGTTIN);
  3570. close:
  3571. if (fd >= 0)
  3572. close(fd);
  3573. fd = -1;
  3574. }
  3575. ttyfd = fd;
  3576. doing_jobctl = on;
  3577. }
  3578. static int FAST_FUNC
  3579. killcmd(int argc, char **argv)
  3580. {
  3581. if (argv[1] && strcmp(argv[1], "-l") != 0) {
  3582. int i = 1;
  3583. do {
  3584. if (argv[i][0] == '%') {
  3585. /*
  3586. * "kill %N" - job kill
  3587. * Converting to pgrp / pid kill
  3588. */
  3589. struct job *jp;
  3590. char *dst;
  3591. int j, n;
  3592. jp = getjob(argv[i], 0);
  3593. /*
  3594. * In jobs started under job control, we signal
  3595. * entire process group by kill -PGRP_ID.
  3596. * This happens, f.e., in interactive shell.
  3597. *
  3598. * Otherwise, we signal each child via
  3599. * kill PID1 PID2 PID3.
  3600. * Testcases:
  3601. * sh -c 'sleep 1|sleep 1 & kill %1'
  3602. * sh -c 'true|sleep 2 & sleep 1; kill %1'
  3603. * sh -c 'true|sleep 1 & sleep 2; kill %1'
  3604. */
  3605. n = jp->nprocs; /* can't be 0 (I hope) */
  3606. if (jp->jobctl)
  3607. n = 1;
  3608. dst = alloca(n * sizeof(int)*4);
  3609. argv[i] = dst;
  3610. for (j = 0; j < n; j++) {
  3611. struct procstat *ps = &jp->ps[j];
  3612. /* Skip non-running and not-stopped members
  3613. * (i.e. dead members) of the job
  3614. */
  3615. if (ps->ps_status != -1 && !WIFSTOPPED(ps->ps_status))
  3616. continue;
  3617. /*
  3618. * kill_main has matching code to expect
  3619. * leading space. Needed to not confuse
  3620. * negative pids with "kill -SIGNAL_NO" syntax
  3621. */
  3622. dst += sprintf(dst, jp->jobctl ? " -%u" : " %u", (int)ps->ps_pid);
  3623. }
  3624. *dst = '\0';
  3625. }
  3626. } while (argv[++i]);
  3627. }
  3628. return kill_main(argc, argv);
  3629. }
  3630. static void
  3631. showpipe(struct job *jp /*, FILE *out*/)
  3632. {
  3633. struct procstat *ps;
  3634. struct procstat *psend;
  3635. psend = jp->ps + jp->nprocs;
  3636. for (ps = jp->ps + 1; ps < psend; ps++)
  3637. printf(" | %s", ps->ps_cmd);
  3638. newline_and_flush(stdout);
  3639. flush_stdout_stderr();
  3640. }
  3641. static int
  3642. restartjob(struct job *jp, int mode)
  3643. {
  3644. struct procstat *ps;
  3645. int i;
  3646. int status;
  3647. pid_t pgid;
  3648. INT_OFF;
  3649. if (jp->state == JOBDONE)
  3650. goto out;
  3651. jp->state = JOBRUNNING;
  3652. pgid = jp->ps[0].ps_pid;
  3653. if (mode == FORK_FG) {
  3654. get_tty_state();
  3655. xtcsetpgrp(ttyfd, pgid);
  3656. }
  3657. killpg(pgid, SIGCONT);
  3658. ps = jp->ps;
  3659. i = jp->nprocs;
  3660. do {
  3661. if (WIFSTOPPED(ps->ps_status)) {
  3662. ps->ps_status = -1;
  3663. }
  3664. ps++;
  3665. } while (--i);
  3666. out:
  3667. status = (mode == FORK_FG) ? waitforjob(jp) : 0;
  3668. INT_ON;
  3669. return status;
  3670. }
  3671. static int FAST_FUNC
  3672. fg_bgcmd(int argc UNUSED_PARAM, char **argv)
  3673. {
  3674. struct job *jp;
  3675. int mode;
  3676. int retval;
  3677. mode = (**argv == 'f') ? FORK_FG : FORK_BG;
  3678. nextopt(nullstr);
  3679. argv = argptr;
  3680. do {
  3681. jp = getjob(*argv, 1);
  3682. if (mode == FORK_BG) {
  3683. set_curjob(jp, CUR_RUNNING);
  3684. printf("[%d] ", jobno(jp));
  3685. }
  3686. out1str(jp->ps[0].ps_cmd);
  3687. showpipe(jp /*, stdout*/);
  3688. retval = restartjob(jp, mode);
  3689. } while (*argv && *++argv);
  3690. return retval;
  3691. }
  3692. #endif
  3693. static int
  3694. sprint_status48(char *s, int status, int sigonly)
  3695. {
  3696. int col;
  3697. int st;
  3698. col = 0;
  3699. if (!WIFEXITED(status)) {
  3700. #if JOBS
  3701. if (WIFSTOPPED(status))
  3702. st = WSTOPSIG(status);
  3703. else
  3704. #endif
  3705. st = WTERMSIG(status);
  3706. if (sigonly) {
  3707. if (st == SIGINT || st == SIGPIPE)
  3708. goto out;
  3709. #if JOBS
  3710. if (WIFSTOPPED(status))
  3711. goto out;
  3712. #endif
  3713. }
  3714. st &= 0x7f;
  3715. //TODO: use bbox's get_signame? strsignal adds ~600 bytes to text+rodata
  3716. col = fmtstr(s, 32, strsignal(st));
  3717. if (WCOREDUMP(status)) {
  3718. strcpy(s + col, " (core dumped)");
  3719. col += sizeof(" (core dumped)")-1;
  3720. }
  3721. } else if (!sigonly) {
  3722. st = WEXITSTATUS(status);
  3723. col = fmtstr(s, 16, (st ? "Done(%d)" : "Done"), st);
  3724. }
  3725. out:
  3726. return col;
  3727. }
  3728. static int
  3729. wait_block_or_sig(int *status)
  3730. {
  3731. int pid;
  3732. do {
  3733. sigset_t mask;
  3734. /* Poll all children for changes in their state */
  3735. got_sigchld = 0;
  3736. /* if job control is active, accept stopped processes too */
  3737. pid = waitpid(-1, status, doing_jobctl ? (WNOHANG|WUNTRACED) : WNOHANG);
  3738. if (pid != 0)
  3739. break; /* Error (e.g. EINTR, ECHILD) or pid */
  3740. /* Children exist, but none are ready. Sleep until interesting signal */
  3741. #if 1
  3742. sigfillset(&mask);
  3743. sigprocmask(SIG_SETMASK, &mask, &mask);
  3744. while (!got_sigchld && !pending_sig)
  3745. sigsuspend(&mask);
  3746. sigprocmask(SIG_SETMASK, &mask, NULL);
  3747. #else /* unsafe: a signal can set pending_sig after check, but before pause() */
  3748. while (!got_sigchld && !pending_sig)
  3749. pause();
  3750. #endif
  3751. /* If it was SIGCHLD, poll children again */
  3752. } while (got_sigchld);
  3753. return pid;
  3754. }
  3755. #define DOWAIT_NONBLOCK 0
  3756. #define DOWAIT_BLOCK 1
  3757. #define DOWAIT_BLOCK_OR_SIG 2
  3758. static int
  3759. dowait(int block, struct job *job)
  3760. {
  3761. int pid;
  3762. int status;
  3763. struct job *jp;
  3764. struct job *thisjob = NULL;
  3765. TRACE(("dowait(0x%x) called\n", block));
  3766. /* It's wrong to call waitpid() outside of INT_OFF region:
  3767. * signal can arrive just after syscall return and handler can
  3768. * longjmp away, losing stop/exit notification processing.
  3769. * Thus, for "jobs" builtin, and for waiting for a fg job,
  3770. * we call waitpid() (blocking or non-blocking) inside INT_OFF.
  3771. *
  3772. * However, for "wait" builtin it is wrong to simply call waitpid()
  3773. * in INT_OFF region: "wait" needs to wait for any running job
  3774. * to change state, but should exit on any trap too.
  3775. * In INT_OFF region, a signal just before syscall entry can set
  3776. * pending_sig variables, but we can't check them, and we would
  3777. * either enter a sleeping waitpid() (BUG), or need to busy-loop.
  3778. *
  3779. * Because of this, we run inside INT_OFF, but use a special routine
  3780. * which combines waitpid() and sigsuspend().
  3781. * This is the reason why we need to have a handler for SIGCHLD:
  3782. * SIG_DFL handler does not wake sigsuspend().
  3783. */
  3784. INT_OFF;
  3785. if (block == DOWAIT_BLOCK_OR_SIG) {
  3786. pid = wait_block_or_sig(&status);
  3787. } else {
  3788. int wait_flags = 0;
  3789. if (block == DOWAIT_NONBLOCK)
  3790. wait_flags = WNOHANG;
  3791. /* if job control is active, accept stopped processes too */
  3792. if (doing_jobctl)
  3793. wait_flags |= WUNTRACED;
  3794. /* NB: _not_ safe_waitpid, we need to detect EINTR */
  3795. pid = waitpid(-1, &status, wait_flags);
  3796. }
  3797. TRACE(("wait returns pid=%d, status=0x%x, errno=%d(%s)\n",
  3798. pid, status, errno, strerror(errno)));
  3799. if (pid <= 0)
  3800. goto out;
  3801. thisjob = NULL;
  3802. for (jp = curjob; jp; jp = jp->prev_job) {
  3803. int jobstate;
  3804. struct procstat *ps;
  3805. struct procstat *psend;
  3806. if (jp->state == JOBDONE)
  3807. continue;
  3808. jobstate = JOBDONE;
  3809. ps = jp->ps;
  3810. psend = ps + jp->nprocs;
  3811. do {
  3812. if (ps->ps_pid == pid) {
  3813. TRACE(("Job %d: changing status of proc %d "
  3814. "from 0x%x to 0x%x\n",
  3815. jobno(jp), pid, ps->ps_status, status));
  3816. ps->ps_status = status;
  3817. thisjob = jp;
  3818. }
  3819. if (ps->ps_status == -1)
  3820. jobstate = JOBRUNNING;
  3821. #if JOBS
  3822. if (jobstate == JOBRUNNING)
  3823. continue;
  3824. if (WIFSTOPPED(ps->ps_status)) {
  3825. jp->stopstatus = ps->ps_status;
  3826. jobstate = JOBSTOPPED;
  3827. }
  3828. #endif
  3829. } while (++ps < psend);
  3830. if (!thisjob)
  3831. continue;
  3832. /* Found the job where one of its processes changed its state.
  3833. * Is there at least one live and running process in this job? */
  3834. if (jobstate != JOBRUNNING) {
  3835. /* No. All live processes in the job are stopped
  3836. * (JOBSTOPPED) or there are no live processes (JOBDONE)
  3837. */
  3838. thisjob->changed = 1;
  3839. if (thisjob->state != jobstate) {
  3840. TRACE(("Job %d: changing state from %d to %d\n",
  3841. jobno(thisjob), thisjob->state, jobstate));
  3842. thisjob->state = jobstate;
  3843. #if JOBS
  3844. if (jobstate == JOBSTOPPED)
  3845. set_curjob(thisjob, CUR_STOPPED);
  3846. #endif
  3847. }
  3848. }
  3849. goto out;
  3850. }
  3851. /* The process wasn't found in job list */
  3852. #if JOBS
  3853. if (!WIFSTOPPED(status))
  3854. jobless--;
  3855. #endif
  3856. out:
  3857. INT_ON;
  3858. if (thisjob && thisjob == job) {
  3859. char s[48 + 1];
  3860. int len;
  3861. len = sprint_status48(s, status, 1);
  3862. if (len) {
  3863. s[len] = '\n';
  3864. s[len + 1] = '\0';
  3865. out2str(s);
  3866. }
  3867. }
  3868. return pid;
  3869. }
  3870. #if JOBS
  3871. static void
  3872. showjob(struct job *jp, int mode)
  3873. {
  3874. struct procstat *ps;
  3875. struct procstat *psend;
  3876. int col;
  3877. int indent_col;
  3878. char s[16 + 16 + 48];
  3879. FILE *out = (mode & SHOW_STDERR ? stderr : stdout);
  3880. ps = jp->ps;
  3881. if (mode & SHOW_ONLY_PGID) { /* jobs -p */
  3882. /* just output process (group) id of pipeline */
  3883. fprintf(out, "%d\n", ps->ps_pid);
  3884. return;
  3885. }
  3886. col = fmtstr(s, 16, "[%d] ", jobno(jp));
  3887. indent_col = col;
  3888. if (jp == curjob)
  3889. s[col - 3] = '+';
  3890. else if (curjob && jp == curjob->prev_job)
  3891. s[col - 3] = '-';
  3892. if (mode & SHOW_PIDS)
  3893. col += fmtstr(s + col, 16, "%d ", ps->ps_pid);
  3894. psend = ps + jp->nprocs;
  3895. if (jp->state == JOBRUNNING) {
  3896. strcpy(s + col, "Running");
  3897. col += sizeof("Running") - 1;
  3898. } else {
  3899. int status = psend[-1].ps_status;
  3900. if (jp->state == JOBSTOPPED)
  3901. status = jp->stopstatus;
  3902. col += sprint_status48(s + col, status, 0);
  3903. }
  3904. /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
  3905. /* This loop either prints "<cmd1> | <cmd2> | <cmd3>" line
  3906. * or prints several "PID | <cmdN>" lines,
  3907. * depending on SHOW_PIDS bit.
  3908. * We do not print status of individual processes
  3909. * between PID and <cmdN>. bash does it, but not very well:
  3910. * first line shows overall job status, not process status,
  3911. * making it impossible to know 1st process status.
  3912. */
  3913. goto start;
  3914. do {
  3915. /* for each process */
  3916. s[0] = '\0';
  3917. col = 33;
  3918. if (mode & SHOW_PIDS)
  3919. col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->ps_pid) - 1;
  3920. start:
  3921. fprintf(out, "%s%*c%s%s",
  3922. s,
  3923. 33 - col >= 0 ? 33 - col : 0, ' ',
  3924. ps == jp->ps ? "" : "| ",
  3925. ps->ps_cmd
  3926. );
  3927. } while (++ps != psend);
  3928. newline_and_flush(out);
  3929. jp->changed = 0;
  3930. if (jp->state == JOBDONE) {
  3931. TRACE(("showjob: freeing job %d\n", jobno(jp)));
  3932. freejob(jp);
  3933. }
  3934. }
  3935. /*
  3936. * Print a list of jobs. If "change" is nonzero, only print jobs whose
  3937. * statuses have changed since the last call to showjobs.
  3938. */
  3939. static void
  3940. showjobs(int mode)
  3941. {
  3942. struct job *jp;
  3943. TRACE(("showjobs(0x%x) called\n", mode));
  3944. /* Handle all finished jobs */
  3945. while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
  3946. continue;
  3947. for (jp = curjob; jp; jp = jp->prev_job) {
  3948. if (!(mode & SHOW_CHANGED) || jp->changed) {
  3949. showjob(jp, mode);
  3950. }
  3951. }
  3952. }
  3953. static int FAST_FUNC
  3954. jobscmd(int argc UNUSED_PARAM, char **argv)
  3955. {
  3956. int mode, m;
  3957. mode = 0;
  3958. while ((m = nextopt("lp")) != '\0') {
  3959. if (m == 'l')
  3960. mode |= SHOW_PIDS;
  3961. else
  3962. mode |= SHOW_ONLY_PGID;
  3963. }
  3964. argv = argptr;
  3965. if (*argv) {
  3966. do
  3967. showjob(getjob(*argv, 0), mode);
  3968. while (*++argv);
  3969. } else {
  3970. showjobs(mode);
  3971. }
  3972. return 0;
  3973. }
  3974. #endif /* JOBS */
  3975. /* Called only on finished or stopped jobs (no members are running) */
  3976. static int
  3977. getstatus(struct job *job)
  3978. {
  3979. int status;
  3980. int retval;
  3981. struct procstat *ps;
  3982. /* Fetch last member's status */
  3983. ps = job->ps + job->nprocs - 1;
  3984. status = ps->ps_status;
  3985. if (pipefail) {
  3986. /* "set -o pipefail" mode: use last _nonzero_ status */
  3987. while (status == 0 && --ps >= job->ps)
  3988. status = ps->ps_status;
  3989. }
  3990. retval = WEXITSTATUS(status);
  3991. if (!WIFEXITED(status)) {
  3992. #if JOBS
  3993. retval = WSTOPSIG(status);
  3994. if (!WIFSTOPPED(status))
  3995. #endif
  3996. {
  3997. /* XXX: limits number of signals */
  3998. retval = WTERMSIG(status);
  3999. #if JOBS
  4000. if (retval == SIGINT)
  4001. job->sigint = 1;
  4002. #endif
  4003. }
  4004. retval += 128;
  4005. }
  4006. TRACE(("getstatus: job %d, nproc %d, status 0x%x, retval 0x%x\n",
  4007. jobno(job), job->nprocs, status, retval));
  4008. return retval;
  4009. }
  4010. static int FAST_FUNC
  4011. waitcmd(int argc UNUSED_PARAM, char **argv)
  4012. {
  4013. struct job *job;
  4014. int retval;
  4015. struct job *jp;
  4016. nextopt(nullstr);
  4017. retval = 0;
  4018. argv = argptr;
  4019. if (!*argv) {
  4020. /* wait for all jobs */
  4021. for (;;) {
  4022. jp = curjob;
  4023. while (1) {
  4024. if (!jp) /* no running procs */
  4025. goto ret;
  4026. if (jp->state == JOBRUNNING)
  4027. break;
  4028. jp->waited = 1;
  4029. jp = jp->prev_job;
  4030. }
  4031. /* man bash:
  4032. * "When bash is waiting for an asynchronous command via
  4033. * the wait builtin, the reception of a signal for which a trap
  4034. * has been set will cause the wait builtin to return immediately
  4035. * with an exit status greater than 128, immediately after which
  4036. * the trap is executed."
  4037. */
  4038. dowait(DOWAIT_BLOCK_OR_SIG, NULL);
  4039. /* if child sends us a signal *and immediately exits*,
  4040. * dowait() returns pid > 0. Check this case,
  4041. * not "if (dowait() < 0)"!
  4042. */
  4043. if (pending_sig)
  4044. goto sigout;
  4045. }
  4046. }
  4047. retval = 127;
  4048. do {
  4049. if (**argv != '%') {
  4050. pid_t pid = number(*argv);
  4051. job = curjob;
  4052. while (1) {
  4053. if (!job)
  4054. goto repeat;
  4055. if (job->ps[job->nprocs - 1].ps_pid == pid)
  4056. break;
  4057. job = job->prev_job;
  4058. }
  4059. } else {
  4060. job = getjob(*argv, 0);
  4061. }
  4062. /* loop until process terminated or stopped */
  4063. while (job->state == JOBRUNNING) {
  4064. dowait(DOWAIT_BLOCK_OR_SIG, NULL);
  4065. if (pending_sig)
  4066. goto sigout;
  4067. }
  4068. job->waited = 1;
  4069. retval = getstatus(job);
  4070. repeat: ;
  4071. } while (*++argv);
  4072. ret:
  4073. return retval;
  4074. sigout:
  4075. retval = 128 + pending_sig;
  4076. return retval;
  4077. }
  4078. static struct job *
  4079. growjobtab(void)
  4080. {
  4081. size_t len;
  4082. ptrdiff_t offset;
  4083. struct job *jp, *jq;
  4084. len = njobs * sizeof(*jp);
  4085. jq = jobtab;
  4086. jp = ckrealloc(jq, len + 4 * sizeof(*jp));
  4087. offset = (char *)jp - (char *)jq;
  4088. if (offset) {
  4089. /* Relocate pointers */
  4090. size_t l = len;
  4091. jq = (struct job *)((char *)jq + l);
  4092. while (l) {
  4093. l -= sizeof(*jp);
  4094. jq--;
  4095. #define joff(p) ((struct job *)((char *)(p) + l))
  4096. #define jmove(p) (p) = (void *)((char *)(p) + offset)
  4097. if (joff(jp)->ps == &jq->ps0)
  4098. jmove(joff(jp)->ps);
  4099. if (joff(jp)->prev_job)
  4100. jmove(joff(jp)->prev_job);
  4101. }
  4102. if (curjob)
  4103. jmove(curjob);
  4104. #undef joff
  4105. #undef jmove
  4106. }
  4107. njobs += 4;
  4108. jobtab = jp;
  4109. jp = (struct job *)((char *)jp + len);
  4110. jq = jp + 3;
  4111. do {
  4112. jq->used = 0;
  4113. } while (--jq >= jp);
  4114. return jp;
  4115. }
  4116. /*
  4117. * Return a new job structure.
  4118. * Called with interrupts off.
  4119. */
  4120. static struct job *
  4121. makejob(/*union node *node,*/ int nprocs)
  4122. {
  4123. int i;
  4124. struct job *jp;
  4125. for (i = njobs, jp = jobtab; ; jp++) {
  4126. if (--i < 0) {
  4127. jp = growjobtab();
  4128. break;
  4129. }
  4130. if (jp->used == 0)
  4131. break;
  4132. if (jp->state != JOBDONE || !jp->waited)
  4133. continue;
  4134. #if JOBS
  4135. if (doing_jobctl)
  4136. continue;
  4137. #endif
  4138. freejob(jp);
  4139. break;
  4140. }
  4141. memset(jp, 0, sizeof(*jp));
  4142. #if JOBS
  4143. /* jp->jobctl is a bitfield.
  4144. * "jp->jobctl |= doing_jobctl" likely to give awful code */
  4145. if (doing_jobctl)
  4146. jp->jobctl = 1;
  4147. #endif
  4148. jp->prev_job = curjob;
  4149. curjob = jp;
  4150. jp->used = 1;
  4151. jp->ps = &jp->ps0;
  4152. if (nprocs > 1) {
  4153. jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
  4154. }
  4155. TRACE(("makejob(%d) returns %%%d\n", nprocs,
  4156. jobno(jp)));
  4157. return jp;
  4158. }
  4159. #if JOBS
  4160. /*
  4161. * Return a string identifying a command (to be printed by the
  4162. * jobs command).
  4163. */
  4164. static char *cmdnextc;
  4165. static void
  4166. cmdputs(const char *s)
  4167. {
  4168. static const char vstype[VSTYPE + 1][3] = {
  4169. "", "}", "-", "+", "?", "=",
  4170. "%", "%%", "#", "##"
  4171. IF_BASH_SUBSTR(, ":")
  4172. IF_BASH_PATTERN_SUBST(, "/", "//")
  4173. };
  4174. const char *p, *str;
  4175. char cc[2];
  4176. char *nextc;
  4177. unsigned char c;
  4178. unsigned char subtype = 0;
  4179. int quoted = 0;
  4180. cc[1] = '\0';
  4181. nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
  4182. p = s;
  4183. while ((c = *p++) != '\0') {
  4184. str = NULL;
  4185. switch (c) {
  4186. case CTLESC:
  4187. c = *p++;
  4188. break;
  4189. case CTLVAR:
  4190. subtype = *p++;
  4191. if ((subtype & VSTYPE) == VSLENGTH)
  4192. str = "${#";
  4193. else
  4194. str = "${";
  4195. goto dostr;
  4196. case CTLENDVAR:
  4197. str = "\"}" + !(quoted & 1);
  4198. quoted >>= 1;
  4199. subtype = 0;
  4200. goto dostr;
  4201. case CTLBACKQ:
  4202. str = "$(...)";
  4203. goto dostr;
  4204. #if ENABLE_FEATURE_SH_MATH
  4205. case CTLARI:
  4206. str = "$((";
  4207. goto dostr;
  4208. case CTLENDARI:
  4209. str = "))";
  4210. goto dostr;
  4211. #endif
  4212. case CTLQUOTEMARK:
  4213. quoted ^= 1;
  4214. c = '"';
  4215. break;
  4216. case '=':
  4217. if (subtype == 0)
  4218. break;
  4219. if ((subtype & VSTYPE) != VSNORMAL)
  4220. quoted <<= 1;
  4221. str = vstype[subtype & VSTYPE];
  4222. if (subtype & VSNUL)
  4223. c = ':';
  4224. else
  4225. goto checkstr;
  4226. break;
  4227. case '\'':
  4228. case '\\':
  4229. case '"':
  4230. case '$':
  4231. /* These can only happen inside quotes */
  4232. cc[0] = c;
  4233. str = cc;
  4234. //FIXME:
  4235. // $ true $$ &
  4236. // $ <cr>
  4237. // [1]+ Done true ${\$} <<=== BUG: ${\$} is not a valid way to write $$ (${$} would be ok)
  4238. c = '\\';
  4239. break;
  4240. default:
  4241. break;
  4242. }
  4243. USTPUTC(c, nextc);
  4244. checkstr:
  4245. if (!str)
  4246. continue;
  4247. dostr:
  4248. while ((c = *str++) != '\0') {
  4249. USTPUTC(c, nextc);
  4250. }
  4251. } /* while *p++ not NUL */
  4252. if (quoted & 1) {
  4253. USTPUTC('"', nextc);
  4254. }
  4255. *nextc = 0;
  4256. cmdnextc = nextc;
  4257. }
  4258. /* cmdtxt() and cmdlist() call each other */
  4259. static void cmdtxt(union node *n);
  4260. static void
  4261. cmdlist(union node *np, int sep)
  4262. {
  4263. for (; np; np = np->narg.next) {
  4264. if (!sep)
  4265. cmdputs(" ");
  4266. cmdtxt(np);
  4267. if (sep && np->narg.next)
  4268. cmdputs(" ");
  4269. }
  4270. }
  4271. static void
  4272. cmdtxt(union node *n)
  4273. {
  4274. union node *np;
  4275. struct nodelist *lp;
  4276. const char *p;
  4277. if (!n)
  4278. return;
  4279. switch (n->type) {
  4280. default:
  4281. #if DEBUG
  4282. abort();
  4283. #endif
  4284. case NPIPE:
  4285. lp = n->npipe.cmdlist;
  4286. for (;;) {
  4287. cmdtxt(lp->n);
  4288. lp = lp->next;
  4289. if (!lp)
  4290. break;
  4291. cmdputs(" | ");
  4292. }
  4293. break;
  4294. case NSEMI:
  4295. p = "; ";
  4296. goto binop;
  4297. case NAND:
  4298. p = " && ";
  4299. goto binop;
  4300. case NOR:
  4301. p = " || ";
  4302. binop:
  4303. cmdtxt(n->nbinary.ch1);
  4304. cmdputs(p);
  4305. n = n->nbinary.ch2;
  4306. goto donode;
  4307. case NREDIR:
  4308. case NBACKGND:
  4309. n = n->nredir.n;
  4310. goto donode;
  4311. case NNOT:
  4312. cmdputs("!");
  4313. n = n->nnot.com;
  4314. donode:
  4315. cmdtxt(n);
  4316. break;
  4317. case NIF:
  4318. cmdputs("if ");
  4319. cmdtxt(n->nif.test);
  4320. cmdputs("; then ");
  4321. if (n->nif.elsepart) {
  4322. cmdtxt(n->nif.ifpart);
  4323. cmdputs("; else ");
  4324. n = n->nif.elsepart;
  4325. } else {
  4326. n = n->nif.ifpart;
  4327. }
  4328. p = "; fi";
  4329. goto dotail;
  4330. case NSUBSHELL:
  4331. cmdputs("(");
  4332. n = n->nredir.n;
  4333. p = ")";
  4334. goto dotail;
  4335. case NWHILE:
  4336. p = "while ";
  4337. goto until;
  4338. case NUNTIL:
  4339. p = "until ";
  4340. until:
  4341. cmdputs(p);
  4342. cmdtxt(n->nbinary.ch1);
  4343. n = n->nbinary.ch2;
  4344. p = "; done";
  4345. dodo:
  4346. cmdputs("; do ");
  4347. dotail:
  4348. cmdtxt(n);
  4349. goto dotail2;
  4350. case NFOR:
  4351. cmdputs("for ");
  4352. cmdputs(n->nfor.var);
  4353. cmdputs(" in ");
  4354. cmdlist(n->nfor.args, 1);
  4355. n = n->nfor.body;
  4356. p = "; done";
  4357. goto dodo;
  4358. case NDEFUN:
  4359. cmdputs(n->narg.text);
  4360. p = "() { ... }";
  4361. goto dotail2;
  4362. case NCMD:
  4363. cmdlist(n->ncmd.args, 1);
  4364. cmdlist(n->ncmd.redirect, 0);
  4365. break;
  4366. case NARG:
  4367. p = n->narg.text;
  4368. dotail2:
  4369. cmdputs(p);
  4370. break;
  4371. case NHERE:
  4372. case NXHERE:
  4373. p = "<<...";
  4374. goto dotail2;
  4375. case NCASE:
  4376. cmdputs("case ");
  4377. cmdputs(n->ncase.expr->narg.text);
  4378. cmdputs(" in ");
  4379. for (np = n->ncase.cases; np; np = np->nclist.next) {
  4380. cmdtxt(np->nclist.pattern);
  4381. cmdputs(") ");
  4382. cmdtxt(np->nclist.body);
  4383. cmdputs(";; ");
  4384. }
  4385. p = "esac";
  4386. goto dotail2;
  4387. case NTO:
  4388. p = ">";
  4389. goto redir;
  4390. case NCLOBBER:
  4391. p = ">|";
  4392. goto redir;
  4393. case NAPPEND:
  4394. p = ">>";
  4395. goto redir;
  4396. #if BASH_REDIR_OUTPUT
  4397. case NTO2:
  4398. #endif
  4399. case NTOFD:
  4400. p = ">&";
  4401. goto redir;
  4402. case NFROM:
  4403. p = "<";
  4404. goto redir;
  4405. case NFROMFD:
  4406. p = "<&";
  4407. goto redir;
  4408. case NFROMTO:
  4409. p = "<>";
  4410. redir:
  4411. cmdputs(utoa(n->nfile.fd));
  4412. cmdputs(p);
  4413. if (n->type == NTOFD || n->type == NFROMFD) {
  4414. if (n->ndup.dupfd >= 0)
  4415. cmdputs(utoa(n->ndup.dupfd));
  4416. else
  4417. cmdputs("-");
  4418. break;
  4419. }
  4420. n = n->nfile.fname;
  4421. goto donode;
  4422. }
  4423. }
  4424. static char *
  4425. commandtext(union node *n)
  4426. {
  4427. char *name;
  4428. STARTSTACKSTR(cmdnextc);
  4429. cmdtxt(n);
  4430. name = stackblock();
  4431. TRACE(("commandtext: name %p, end %p\n", name, cmdnextc));
  4432. return ckstrdup(name);
  4433. }
  4434. #endif /* JOBS */
  4435. /*
  4436. * Fork off a subshell. If we are doing job control, give the subshell its
  4437. * own process group. Jp is a job structure that the job is to be added to.
  4438. * N is the command that will be evaluated by the child. Both jp and n may
  4439. * be NULL. The mode parameter can be one of the following:
  4440. * FORK_FG - Fork off a foreground process.
  4441. * FORK_BG - Fork off a background process.
  4442. * FORK_NOJOB - Like FORK_FG, but don't give the process its own
  4443. * process group even if job control is on.
  4444. *
  4445. * When job control is turned off, background processes have their standard
  4446. * input redirected to /dev/null (except for the second and later processes
  4447. * in a pipeline).
  4448. *
  4449. * Called with interrupts off.
  4450. */
  4451. /*
  4452. * Clear traps on a fork.
  4453. */
  4454. static void
  4455. clear_traps(void)
  4456. {
  4457. char **tp;
  4458. INT_OFF;
  4459. for (tp = trap; tp < &trap[NSIG]; tp++) {
  4460. if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
  4461. if (trap_ptr == trap)
  4462. free(*tp);
  4463. /* else: it "belongs" to trap_ptr vector, don't free */
  4464. *tp = NULL;
  4465. if ((tp - trap) != 0)
  4466. setsignal(tp - trap);
  4467. }
  4468. }
  4469. may_have_traps = 0;
  4470. INT_ON;
  4471. }
  4472. /* Lives far away from here, needed for forkchild */
  4473. static void closescript(void);
  4474. /* Called after fork(), in child */
  4475. /* jp and n are NULL when called by openhere() for heredoc support */
  4476. static NOINLINE void
  4477. forkchild(struct job *jp, union node *n, int mode)
  4478. {
  4479. int oldlvl;
  4480. TRACE(("Child shell %d\n", getpid()));
  4481. oldlvl = shlvl;
  4482. shlvl++;
  4483. /* man bash: "Non-builtin commands run by bash have signal handlers
  4484. * set to the values inherited by the shell from its parent".
  4485. * Do we do it correctly? */
  4486. closescript();
  4487. if (mode == FORK_NOJOB /* is it `xxx` ? */
  4488. && n && n->type == NCMD /* is it single cmd? */
  4489. /* && n->ncmd.args->type == NARG - always true? */
  4490. && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "trap") == 0
  4491. && n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
  4492. /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
  4493. ) {
  4494. TRACE(("Trap hack\n"));
  4495. /* Awful hack for `trap` or $(trap).
  4496. *
  4497. * http://www.opengroup.org/onlinepubs/009695399/utilities/trap.html
  4498. * contains an example where "trap" is executed in a subshell:
  4499. *
  4500. * save_traps=$(trap)
  4501. * ...
  4502. * eval "$save_traps"
  4503. *
  4504. * Standard does not say that "trap" in subshell shall print
  4505. * parent shell's traps. It only says that its output
  4506. * must have suitable form, but then, in the above example
  4507. * (which is not supposed to be normative), it implies that.
  4508. *
  4509. * bash (and probably other shell) does implement it
  4510. * (traps are reset to defaults, but "trap" still shows them),
  4511. * but as a result, "trap" logic is hopelessly messed up:
  4512. *
  4513. * # trap
  4514. * trap -- 'echo Ho' SIGWINCH <--- we have a handler
  4515. * # (trap) <--- trap is in subshell - no output (correct, traps are reset)
  4516. * # true | trap <--- trap is in subshell - no output (ditto)
  4517. * # echo `true | trap` <--- in subshell - output (but traps are reset!)
  4518. * trap -- 'echo Ho' SIGWINCH
  4519. * # echo `(trap)` <--- in subshell in subshell - output
  4520. * trap -- 'echo Ho' SIGWINCH
  4521. * # echo `true | (trap)` <--- in subshell in subshell in subshell - output!
  4522. * trap -- 'echo Ho' SIGWINCH
  4523. *
  4524. * The rules when to forget and when to not forget traps
  4525. * get really complex and nonsensical.
  4526. *
  4527. * Our solution: ONLY bare $(trap) or `trap` is special.
  4528. */
  4529. /* Save trap handler strings for trap builtin to print */
  4530. trap_ptr = xmemdup(trap, sizeof(trap));
  4531. /* Fall through into clearing traps */
  4532. }
  4533. clear_traps();
  4534. #if JOBS
  4535. /* do job control only in root shell */
  4536. doing_jobctl = 0;
  4537. if (mode != FORK_NOJOB && jp->jobctl && oldlvl == 0) {
  4538. pid_t pgrp;
  4539. if (jp->nprocs == 0)
  4540. pgrp = getpid();
  4541. else
  4542. pgrp = jp->ps[0].ps_pid;
  4543. /* this can fail because we are doing it in the parent also */
  4544. setpgid(0, pgrp);
  4545. if (mode == FORK_FG)
  4546. xtcsetpgrp(ttyfd, pgrp);
  4547. setsignal(SIGTSTP);
  4548. setsignal(SIGTTOU);
  4549. } else
  4550. #endif
  4551. if (mode == FORK_BG) {
  4552. /* man bash: "When job control is not in effect,
  4553. * asynchronous commands ignore SIGINT and SIGQUIT" */
  4554. ignoresig(SIGINT);
  4555. ignoresig(SIGQUIT);
  4556. if (jp->nprocs == 0) {
  4557. close(0);
  4558. if (open(bb_dev_null, O_RDONLY) != 0)
  4559. ash_msg_and_raise_perror("can't open '%s'", bb_dev_null);
  4560. }
  4561. }
  4562. if (oldlvl == 0) {
  4563. if (iflag) { /* why if iflag only? */
  4564. setsignal(SIGINT);
  4565. setsignal(SIGTERM);
  4566. }
  4567. /* man bash:
  4568. * "In all cases, bash ignores SIGQUIT. Non-builtin
  4569. * commands run by bash have signal handlers
  4570. * set to the values inherited by the shell
  4571. * from its parent".
  4572. * Take care of the second rule: */
  4573. setsignal(SIGQUIT);
  4574. }
  4575. #if JOBS
  4576. if (n && n->type == NCMD
  4577. && n->ncmd.args && strcmp(n->ncmd.args->narg.text, "jobs") == 0
  4578. ) {
  4579. TRACE(("Job hack\n"));
  4580. /* "jobs": we do not want to clear job list for it,
  4581. * instead we remove only _its_ own_ job from job list.
  4582. * This makes "jobs .... | cat" more useful.
  4583. */
  4584. freejob(curjob);
  4585. return;
  4586. }
  4587. #endif
  4588. for (jp = curjob; jp; jp = jp->prev_job)
  4589. freejob(jp);
  4590. jobless = 0;
  4591. }
  4592. /* Called after fork(), in parent */
  4593. #if !JOBS
  4594. #define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
  4595. #endif
  4596. static void
  4597. forkparent(struct job *jp, union node *n, int mode, pid_t pid)
  4598. {
  4599. TRACE(("In parent shell: child = %d\n", pid));
  4600. if (!jp) {
  4601. /* jp is NULL when called by openhere() for heredoc support */
  4602. while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
  4603. continue;
  4604. jobless++;
  4605. return;
  4606. }
  4607. #if JOBS
  4608. if (mode != FORK_NOJOB && jp->jobctl) {
  4609. int pgrp;
  4610. if (jp->nprocs == 0)
  4611. pgrp = pid;
  4612. else
  4613. pgrp = jp->ps[0].ps_pid;
  4614. /* This can fail because we are doing it in the child also */
  4615. setpgid(pid, pgrp);
  4616. }
  4617. #endif
  4618. if (mode == FORK_BG) {
  4619. backgndpid = pid; /* set $! */
  4620. set_curjob(jp, CUR_RUNNING);
  4621. }
  4622. if (jp) {
  4623. struct procstat *ps = &jp->ps[jp->nprocs++];
  4624. ps->ps_pid = pid;
  4625. ps->ps_status = -1;
  4626. ps->ps_cmd = nullstr;
  4627. #if JOBS
  4628. if (doing_jobctl && n)
  4629. ps->ps_cmd = commandtext(n);
  4630. #endif
  4631. }
  4632. }
  4633. /* jp and n are NULL when called by openhere() for heredoc support */
  4634. static int
  4635. forkshell(struct job *jp, union node *n, int mode)
  4636. {
  4637. int pid;
  4638. TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
  4639. pid = fork();
  4640. if (pid < 0) {
  4641. TRACE(("Fork failed, errno=%d", errno));
  4642. if (jp)
  4643. freejob(jp);
  4644. ash_msg_and_raise_perror("can't fork");
  4645. }
  4646. if (pid == 0) {
  4647. CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
  4648. forkchild(jp, n, mode);
  4649. } else {
  4650. forkparent(jp, n, mode, pid);
  4651. }
  4652. return pid;
  4653. }
  4654. /*
  4655. * Wait for job to finish.
  4656. *
  4657. * Under job control we have the problem that while a child process
  4658. * is running interrupts generated by the user are sent to the child
  4659. * but not to the shell. This means that an infinite loop started by
  4660. * an interactive user may be hard to kill. With job control turned off,
  4661. * an interactive user may place an interactive program inside a loop.
  4662. * If the interactive program catches interrupts, the user doesn't want
  4663. * these interrupts to also abort the loop. The approach we take here
  4664. * is to have the shell ignore interrupt signals while waiting for a
  4665. * foreground process to terminate, and then send itself an interrupt
  4666. * signal if the child process was terminated by an interrupt signal.
  4667. * Unfortunately, some programs want to do a bit of cleanup and then
  4668. * exit on interrupt; unless these processes terminate themselves by
  4669. * sending a signal to themselves (instead of calling exit) they will
  4670. * confuse this approach.
  4671. *
  4672. * Called with interrupts off.
  4673. */
  4674. static int
  4675. waitforjob(struct job *jp)
  4676. {
  4677. int st;
  4678. TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
  4679. INT_OFF;
  4680. while (jp->state == JOBRUNNING) {
  4681. /* In non-interactive shells, we _can_ get
  4682. * a keyboard signal here and be EINTRed,
  4683. * but we just loop back, waiting for command to complete.
  4684. *
  4685. * man bash:
  4686. * "If bash is waiting for a command to complete and receives
  4687. * a signal for which a trap has been set, the trap
  4688. * will not be executed until the command completes."
  4689. *
  4690. * Reality is that even if trap is not set, bash
  4691. * will not act on the signal until command completes.
  4692. * Try this. sleep5intoff.c:
  4693. * #include <signal.h>
  4694. * #include <unistd.h>
  4695. * int main() {
  4696. * sigset_t set;
  4697. * sigemptyset(&set);
  4698. * sigaddset(&set, SIGINT);
  4699. * sigaddset(&set, SIGQUIT);
  4700. * sigprocmask(SIG_BLOCK, &set, NULL);
  4701. * sleep(5);
  4702. * return 0;
  4703. * }
  4704. * $ bash -c './sleep5intoff; echo hi'
  4705. * ^C^C^C^C <--- pressing ^C once a second
  4706. * $ _
  4707. * $ bash -c './sleep5intoff; echo hi'
  4708. * ^\^\^\^\hi <--- pressing ^\ (SIGQUIT)
  4709. * $ _
  4710. */
  4711. dowait(DOWAIT_BLOCK, jp);
  4712. }
  4713. INT_ON;
  4714. st = getstatus(jp);
  4715. #if JOBS
  4716. if (jp->jobctl) {
  4717. xtcsetpgrp(ttyfd, rootpid);
  4718. restore_tty_if_stopped_or_signaled(jp);
  4719. /*
  4720. * This is truly gross.
  4721. * If we're doing job control, then we did a TIOCSPGRP which
  4722. * caused us (the shell) to no longer be in the controlling
  4723. * session -- so we wouldn't have seen any ^C/SIGINT. So, we
  4724. * intuit from the subprocess exit status whether a SIGINT
  4725. * occurred, and if so interrupt ourselves. Yuck. - mycroft
  4726. */
  4727. if (jp->sigint) /* TODO: do the same with all signals */
  4728. raise(SIGINT); /* ... by raise(jp->sig) instead? */
  4729. }
  4730. if (jp->state == JOBDONE)
  4731. #endif
  4732. freejob(jp);
  4733. return st;
  4734. }
  4735. /*
  4736. * return 1 if there are stopped jobs, otherwise 0
  4737. */
  4738. static int
  4739. stoppedjobs(void)
  4740. {
  4741. struct job *jp;
  4742. int retval;
  4743. retval = 0;
  4744. if (job_warning)
  4745. goto out;
  4746. jp = curjob;
  4747. if (jp && jp->state == JOBSTOPPED) {
  4748. out2str("You have stopped jobs.\n");
  4749. job_warning = 2;
  4750. retval++;
  4751. }
  4752. out:
  4753. return retval;
  4754. }
  4755. /*
  4756. * Code for dealing with input/output redirection.
  4757. */
  4758. #undef EMPTY
  4759. #undef CLOSED
  4760. #define EMPTY -2 /* marks an unused slot in redirtab */
  4761. #define CLOSED -1 /* marks a slot of previously-closed fd */
  4762. /*
  4763. * Handle here documents. Normally we fork off a process to write the
  4764. * data to a pipe. If the document is short, we can stuff the data in
  4765. * the pipe without forking.
  4766. */
  4767. /* openhere needs this forward reference */
  4768. static void expandhere(union node *arg, int fd);
  4769. static int
  4770. openhere(union node *redir)
  4771. {
  4772. int pip[2];
  4773. size_t len = 0;
  4774. if (pipe(pip) < 0)
  4775. ash_msg_and_raise_perror("can't create pipe");
  4776. if (redir->type == NHERE) {
  4777. len = strlen(redir->nhere.doc->narg.text);
  4778. if (len <= PIPE_BUF) {
  4779. full_write(pip[1], redir->nhere.doc->narg.text, len);
  4780. goto out;
  4781. }
  4782. }
  4783. if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
  4784. /* child */
  4785. close(pip[0]);
  4786. ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
  4787. ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
  4788. ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
  4789. ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
  4790. signal(SIGPIPE, SIG_DFL);
  4791. if (redir->type == NHERE)
  4792. full_write(pip[1], redir->nhere.doc->narg.text, len);
  4793. else /* NXHERE */
  4794. expandhere(redir->nhere.doc, pip[1]);
  4795. _exit(EXIT_SUCCESS);
  4796. }
  4797. out:
  4798. close(pip[1]);
  4799. return pip[0];
  4800. }
  4801. static int
  4802. openredirect(union node *redir)
  4803. {
  4804. struct stat sb;
  4805. char *fname;
  4806. int f;
  4807. switch (redir->nfile.type) {
  4808. /* Can't happen, our single caller does this itself */
  4809. // case NTOFD:
  4810. // case NFROMFD:
  4811. // return -1;
  4812. case NHERE:
  4813. case NXHERE:
  4814. return openhere(redir);
  4815. }
  4816. /* For N[X]HERE, reading redir->nfile.expfname would touch beyond
  4817. * allocated space. Do it only when we know it is safe.
  4818. */
  4819. fname = redir->nfile.expfname;
  4820. switch (redir->nfile.type) {
  4821. default:
  4822. #if DEBUG
  4823. abort();
  4824. #endif
  4825. case NFROM:
  4826. f = open(fname, O_RDONLY);
  4827. if (f < 0)
  4828. goto eopen;
  4829. break;
  4830. case NFROMTO:
  4831. f = open(fname, O_RDWR|O_CREAT, 0666);
  4832. if (f < 0)
  4833. goto ecreate;
  4834. break;
  4835. case NTO:
  4836. #if BASH_REDIR_OUTPUT
  4837. case NTO2:
  4838. #endif
  4839. /* Take care of noclobber mode. */
  4840. if (Cflag) {
  4841. if (stat(fname, &sb) < 0) {
  4842. f = open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
  4843. if (f < 0)
  4844. goto ecreate;
  4845. } else if (!S_ISREG(sb.st_mode)) {
  4846. f = open(fname, O_WRONLY, 0666);
  4847. if (f < 0)
  4848. goto ecreate;
  4849. if (fstat(f, &sb) < 0 && S_ISREG(sb.st_mode)) {
  4850. close(f);
  4851. errno = EEXIST;
  4852. goto ecreate;
  4853. }
  4854. } else {
  4855. errno = EEXIST;
  4856. goto ecreate;
  4857. }
  4858. break;
  4859. }
  4860. /* FALLTHROUGH */
  4861. case NCLOBBER:
  4862. f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
  4863. if (f < 0)
  4864. goto ecreate;
  4865. break;
  4866. case NAPPEND:
  4867. f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
  4868. if (f < 0)
  4869. goto ecreate;
  4870. break;
  4871. }
  4872. return f;
  4873. ecreate:
  4874. ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
  4875. eopen:
  4876. ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
  4877. }
  4878. /*
  4879. * Copy a file descriptor to be >= 10. Throws exception on error.
  4880. */
  4881. static int
  4882. savefd(int from)
  4883. {
  4884. int newfd;
  4885. int err;
  4886. newfd = fcntl(from, F_DUPFD, 10);
  4887. err = newfd < 0 ? errno : 0;
  4888. if (err != EBADF) {
  4889. if (err)
  4890. ash_msg_and_raise_perror("%d", from);
  4891. close(from);
  4892. fcntl(newfd, F_SETFD, FD_CLOEXEC);
  4893. }
  4894. return newfd;
  4895. }
  4896. static int
  4897. dup2_or_raise(int from, int to)
  4898. {
  4899. int newfd;
  4900. newfd = (from != to) ? dup2(from, to) : to;
  4901. if (newfd < 0) {
  4902. /* Happens when source fd is not open: try "echo >&99" */
  4903. ash_msg_and_raise_perror("%d", from);
  4904. }
  4905. return newfd;
  4906. }
  4907. static int
  4908. dup_CLOEXEC(int fd, int avoid_fd)
  4909. {
  4910. int newfd;
  4911. repeat:
  4912. newfd = fcntl(fd, F_DUPFD_CLOEXEC, avoid_fd + 1);
  4913. if (newfd >= 0) {
  4914. if (F_DUPFD_CLOEXEC == F_DUPFD) /* if old libc (w/o F_DUPFD_CLOEXEC) */
  4915. fcntl(newfd, F_SETFD, FD_CLOEXEC);
  4916. } else { /* newfd < 0 */
  4917. if (errno == EBUSY)
  4918. goto repeat;
  4919. if (errno == EINTR)
  4920. goto repeat;
  4921. }
  4922. return newfd;
  4923. }
  4924. static int
  4925. xdup_CLOEXEC_and_close(int fd, int avoid_fd)
  4926. {
  4927. int newfd;
  4928. repeat:
  4929. newfd = fcntl(fd, F_DUPFD, avoid_fd + 1);
  4930. if (newfd < 0) {
  4931. if (errno == EBUSY)
  4932. goto repeat;
  4933. if (errno == EINTR)
  4934. goto repeat;
  4935. /* fd was not open? */
  4936. if (errno == EBADF)
  4937. return fd;
  4938. ash_msg_and_raise_perror("%d", newfd);
  4939. }
  4940. fcntl(newfd, F_SETFD, FD_CLOEXEC);
  4941. close(fd);
  4942. return newfd;
  4943. }
  4944. /* Struct def and variable are moved down to the first usage site */
  4945. struct squirrel {
  4946. int orig_fd;
  4947. int moved_to;
  4948. };
  4949. struct redirtab {
  4950. struct redirtab *next;
  4951. int pair_count;
  4952. struct squirrel two_fd[];
  4953. };
  4954. #define redirlist (G_var.redirlist)
  4955. static void
  4956. add_squirrel_closed(struct redirtab *sq, int fd)
  4957. {
  4958. int i;
  4959. if (!sq)
  4960. return;
  4961. for (i = 0; sq->two_fd[i].orig_fd != EMPTY; i++) {
  4962. /* If we collide with an already moved fd... */
  4963. if (fd == sq->two_fd[i].orig_fd) {
  4964. /* Examples:
  4965. * "echo 3>FILE 3>&- 3>FILE"
  4966. * "echo 3>&- 3>FILE"
  4967. * No need for last redirect to insert
  4968. * another "need to close 3" indicator.
  4969. */
  4970. TRACE(("redirect_fd %d: already moved or closed\n", fd));
  4971. return;
  4972. }
  4973. }
  4974. TRACE(("redirect_fd %d: previous fd was closed\n", fd));
  4975. sq->two_fd[i].orig_fd = fd;
  4976. sq->two_fd[i].moved_to = CLOSED;
  4977. }
  4978. static int
  4979. save_fd_on_redirect(int fd, int avoid_fd, struct redirtab *sq)
  4980. {
  4981. int i, new_fd;
  4982. if (avoid_fd < 9) /* the important case here is that it can be -1 */
  4983. avoid_fd = 9;
  4984. #if JOBS
  4985. if (fd == ttyfd) {
  4986. /* Testcase: "ls -l /proc/$$/fd 10>&-" should work */
  4987. ttyfd = xdup_CLOEXEC_and_close(ttyfd, avoid_fd);
  4988. TRACE(("redirect_fd %d: matches ttyfd, moving it to %d\n", fd, ttyfd));
  4989. return 1; /* "we closed fd" */
  4990. }
  4991. #endif
  4992. /* Are we called from redirect(0)? E.g. redirect
  4993. * in a forked child. No need to save fds,
  4994. * we aren't going to use them anymore, ok to trash.
  4995. */
  4996. if (!sq)
  4997. return 0;
  4998. /* If this one of script's fds? */
  4999. if (fd != 0) {
  5000. struct parsefile *pf = g_parsefile;
  5001. while (pf) {
  5002. /* We skip fd == 0 case because of the following:
  5003. * $ ash # running ash interactively
  5004. * $ . ./script.sh
  5005. * and in script.sh: "exec 9>&0".
  5006. * Even though top-level pf_fd _is_ 0,
  5007. * it's still ok to use it: "read" builtin uses it,
  5008. * why should we cripple "exec" builtin?
  5009. */
  5010. if (fd == pf->pf_fd) {
  5011. pf->pf_fd = xdup_CLOEXEC_and_close(fd, avoid_fd);
  5012. return 1; /* "we closed fd" */
  5013. }
  5014. pf = pf->prev;
  5015. }
  5016. }
  5017. /* Check whether it collides with any open fds (e.g. stdio), save fds as needed */
  5018. /* First: do we collide with some already moved fds? */
  5019. for (i = 0; sq->two_fd[i].orig_fd != EMPTY; i++) {
  5020. /* If we collide with an already moved fd... */
  5021. if (fd == sq->two_fd[i].moved_to) {
  5022. new_fd = dup_CLOEXEC(fd, avoid_fd);
  5023. sq->two_fd[i].moved_to = new_fd;
  5024. TRACE(("redirect_fd %d: already busy, moving to %d\n", fd, new_fd));
  5025. if (new_fd < 0) /* what? */
  5026. xfunc_die();
  5027. return 0; /* "we did not close fd" */
  5028. }
  5029. if (fd == sq->two_fd[i].orig_fd) {
  5030. /* Example: echo Hello >/dev/null 1>&2 */
  5031. TRACE(("redirect_fd %d: already moved\n", fd));
  5032. return 0; /* "we did not close fd" */
  5033. }
  5034. }
  5035. /* If this fd is open, we move and remember it; if it's closed, new_fd = CLOSED (-1) */
  5036. new_fd = dup_CLOEXEC(fd, avoid_fd);
  5037. TRACE(("redirect_fd %d: previous fd is moved to %d (-1 if it was closed)\n", fd, new_fd));
  5038. if (new_fd < 0) {
  5039. if (errno != EBADF)
  5040. xfunc_die();
  5041. /* new_fd = CLOSED; - already is -1 */
  5042. }
  5043. sq->two_fd[i].moved_to = new_fd;
  5044. sq->two_fd[i].orig_fd = fd;
  5045. /* if we move stderr, let "set -x" code know */
  5046. if (fd == preverrout_fd)
  5047. preverrout_fd = new_fd;
  5048. return 0; /* "we did not close fd" */
  5049. }
  5050. static int
  5051. internally_opened_fd(int fd, struct redirtab *sq)
  5052. {
  5053. int i;
  5054. #if JOBS
  5055. if (fd == ttyfd)
  5056. return 1;
  5057. #endif
  5058. /* If this one of script's fds? */
  5059. if (fd != 0) {
  5060. struct parsefile *pf = g_parsefile;
  5061. while (pf) {
  5062. if (fd == pf->pf_fd)
  5063. return 1;
  5064. pf = pf->prev;
  5065. }
  5066. }
  5067. if (sq) for (i = 0; i < sq->pair_count && sq->two_fd[i].orig_fd != EMPTY; i++) {
  5068. if (fd == sq->two_fd[i].moved_to)
  5069. return 1;
  5070. }
  5071. return 0;
  5072. }
  5073. /*
  5074. * Process a list of redirection commands. If the REDIR_PUSH flag is set,
  5075. * old file descriptors are stashed away so that the redirection can be
  5076. * undone by calling popredir.
  5077. */
  5078. /* flags passed to redirect */
  5079. #define REDIR_PUSH 01 /* save previous values of file descriptors */
  5080. static void
  5081. redirect(union node *redir, int flags)
  5082. {
  5083. struct redirtab *sv;
  5084. if (!redir)
  5085. return;
  5086. sv = NULL;
  5087. INT_OFF;
  5088. if (flags & REDIR_PUSH)
  5089. sv = redirlist;
  5090. do {
  5091. int fd;
  5092. int newfd;
  5093. int close_fd;
  5094. int closed;
  5095. fd = redir->nfile.fd;
  5096. if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
  5097. //bb_error_msg("doing %d > %d", fd, newfd);
  5098. newfd = redir->ndup.dupfd;
  5099. close_fd = -1;
  5100. } else {
  5101. newfd = openredirect(redir); /* always >= 0 */
  5102. if (fd == newfd) {
  5103. /* open() gave us precisely the fd we wanted.
  5104. * This means that this fd was not busy
  5105. * (not opened to anywhere).
  5106. * Remember to close it on restore:
  5107. */
  5108. add_squirrel_closed(sv, fd);
  5109. continue;
  5110. }
  5111. close_fd = newfd;
  5112. }
  5113. if (fd == newfd)
  5114. continue;
  5115. /* if "N>FILE": move newfd to fd */
  5116. /* if "N>&M": dup newfd to fd */
  5117. /* if "N>&-": close fd (newfd is -1) */
  5118. IF_BASH_REDIR_OUTPUT(redirect_more:)
  5119. closed = save_fd_on_redirect(fd, /*avoid:*/ newfd, sv);
  5120. if (newfd == -1) {
  5121. /* "N>&-" means "close me" */
  5122. if (!closed) {
  5123. /* ^^^ optimization: saving may already
  5124. * have closed it. If not... */
  5125. close(fd);
  5126. }
  5127. } else {
  5128. /* if newfd is a script fd or saved fd, simulate EBADF */
  5129. if (internally_opened_fd(newfd, sv)) {
  5130. errno = EBADF;
  5131. ash_msg_and_raise_perror("%d", newfd);
  5132. }
  5133. dup2_or_raise(newfd, fd);
  5134. if (close_fd >= 0) /* "N>FILE" or ">&FILE" or heredoc? */
  5135. close(close_fd);
  5136. #if BASH_REDIR_OUTPUT
  5137. if (redir->nfile.type == NTO2 && fd == 1) {
  5138. /* ">&FILE". we already redirected to 1, now copy 1 to 2 */
  5139. fd = 2;
  5140. newfd = 1;
  5141. close_fd = -1;
  5142. goto redirect_more;
  5143. }
  5144. #endif
  5145. }
  5146. } while ((redir = redir->nfile.next) != NULL);
  5147. INT_ON;
  5148. //dash:#define REDIR_SAVEFD2 03 /* set preverrout */
  5149. #define REDIR_SAVEFD2 0
  5150. // dash has a bug: since REDIR_SAVEFD2=3 and REDIR_PUSH=1, this test
  5151. // triggers for pure REDIR_PUSH too. Thus, this is done almost always,
  5152. // not only for calls with flags containing REDIR_SAVEFD2.
  5153. // We do this unconditionally (see save_fd_on_redirect()).
  5154. //if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
  5155. // preverrout_fd = copied_fd2;
  5156. }
  5157. static int
  5158. redirectsafe(union node *redir, int flags)
  5159. {
  5160. int err;
  5161. volatile int saveint;
  5162. struct jmploc *volatile savehandler = exception_handler;
  5163. struct jmploc jmploc;
  5164. SAVE_INT(saveint);
  5165. /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
  5166. err = setjmp(jmploc.loc); /* was = setjmp(jmploc.loc) * 2; */
  5167. if (!err) {
  5168. exception_handler = &jmploc;
  5169. redirect(redir, flags);
  5170. }
  5171. exception_handler = savehandler;
  5172. if (err && exception_type != EXERROR)
  5173. longjmp(exception_handler->loc, 1);
  5174. RESTORE_INT(saveint);
  5175. return err;
  5176. }
  5177. static struct redirtab*
  5178. pushredir(union node *redir)
  5179. {
  5180. struct redirtab *sv;
  5181. int i;
  5182. if (!redir)
  5183. return redirlist;
  5184. i = 0;
  5185. do {
  5186. i++;
  5187. #if BASH_REDIR_OUTPUT
  5188. if (redir->nfile.type == NTO2)
  5189. i++;
  5190. #endif
  5191. redir = redir->nfile.next;
  5192. } while (redir);
  5193. sv = ckzalloc(sizeof(*sv) + i * sizeof(sv->two_fd[0]));
  5194. sv->pair_count = i;
  5195. while (--i >= 0)
  5196. sv->two_fd[i].orig_fd = sv->two_fd[i].moved_to = EMPTY;
  5197. sv->next = redirlist;
  5198. redirlist = sv;
  5199. return sv->next;
  5200. }
  5201. /*
  5202. * Undo the effects of the last redirection.
  5203. */
  5204. static void
  5205. popredir(int drop)
  5206. {
  5207. struct redirtab *rp;
  5208. int i;
  5209. if (redirlist == NULL)
  5210. return;
  5211. INT_OFF;
  5212. rp = redirlist;
  5213. for (i = 0; i < rp->pair_count; i++) {
  5214. int fd = rp->two_fd[i].orig_fd;
  5215. int copy = rp->two_fd[i].moved_to;
  5216. if (copy == CLOSED) {
  5217. if (!drop)
  5218. close(fd);
  5219. continue;
  5220. }
  5221. if (copy != EMPTY) {
  5222. if (!drop) {
  5223. /*close(fd);*/
  5224. dup2_or_raise(copy, fd);
  5225. }
  5226. close(copy);
  5227. }
  5228. }
  5229. redirlist = rp->next;
  5230. free(rp);
  5231. INT_ON;
  5232. }
  5233. static void
  5234. unwindredir(struct redirtab *stop)
  5235. {
  5236. while (redirlist != stop)
  5237. popredir(/*drop:*/ 0);
  5238. }
  5239. /* ============ Routines to expand arguments to commands
  5240. *
  5241. * We have to deal with backquotes, shell variables, and file metacharacters.
  5242. */
  5243. #if ENABLE_FEATURE_SH_MATH
  5244. static arith_t
  5245. ash_arith(const char *s)
  5246. {
  5247. arith_state_t math_state;
  5248. arith_t result;
  5249. math_state.lookupvar = lookupvar;
  5250. math_state.setvar = setvar0;
  5251. //math_state.endofname = endofname;
  5252. INT_OFF;
  5253. result = arith(&math_state, s);
  5254. if (math_state.errmsg)
  5255. ash_msg_and_raise_error(math_state.errmsg);
  5256. INT_ON;
  5257. return result;
  5258. }
  5259. #endif
  5260. /*
  5261. * expandarg flags
  5262. */
  5263. #define EXP_FULL 0x1 /* perform word splitting & file globbing */
  5264. #define EXP_TILDE 0x2 /* do normal tilde expansion */
  5265. #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
  5266. #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
  5267. /* ^^^^^^^^^^^^^^ this is meant to support constructs such as "cmd >file*.txt"
  5268. * POSIX says for this case:
  5269. * Pathname expansion shall not be performed on the word by a
  5270. * non-interactive shell; an interactive shell may perform it, but shall
  5271. * do so only when the expansion would result in one word.
  5272. * Currently, our code complies to the above rule by never globbing
  5273. * redirection filenames.
  5274. * Bash performs globbing, unless it is non-interactive and in POSIX mode.
  5275. * (this means that on a typical Linux distro, bash almost always
  5276. * performs globbing, and thus diverges from what we do).
  5277. */
  5278. #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
  5279. #define EXP_QPAT 0x20 /* pattern in quoted parameter expansion */
  5280. #define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
  5281. #define EXP_WORD 0x80 /* expand word in parameter expansion */
  5282. #define EXP_QUOTED 0x100 /* expand word in double quotes */
  5283. /*
  5284. * rmescape() flags
  5285. */
  5286. #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
  5287. #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
  5288. #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
  5289. #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
  5290. #define RMESCAPE_SLASH 0x20 /* Stop globbing after slash */
  5291. /* Add CTLESC when necessary. */
  5292. #define QUOTES_ESC (EXP_FULL | EXP_CASE | EXP_QPAT)
  5293. /* Do not skip NUL characters. */
  5294. #define QUOTES_KEEPNUL EXP_TILDE
  5295. /*
  5296. * Structure specifying which parts of the string should be searched
  5297. * for IFS characters.
  5298. */
  5299. struct ifsregion {
  5300. struct ifsregion *next; /* next region in list */
  5301. int begoff; /* offset of start of region */
  5302. int endoff; /* offset of end of region */
  5303. int nulonly; /* search for nul bytes only */
  5304. };
  5305. struct arglist {
  5306. struct strlist *list;
  5307. struct strlist **lastp;
  5308. };
  5309. /* output of current string */
  5310. static char *expdest;
  5311. /* list of back quote expressions */
  5312. static struct nodelist *argbackq;
  5313. /* first struct in list of ifs regions */
  5314. static struct ifsregion ifsfirst;
  5315. /* last struct in list */
  5316. static struct ifsregion *ifslastp;
  5317. /* holds expanded arg list */
  5318. static struct arglist exparg;
  5319. /*
  5320. * Our own itoa().
  5321. * cvtnum() is used even if math support is off (to prepare $? values and such).
  5322. */
  5323. static int
  5324. cvtnum(arith_t num)
  5325. {
  5326. int len;
  5327. /* 32-bit and wider ints require buffer size of bytes*3 (or less) */
  5328. len = sizeof(arith_t) * 3;
  5329. /* If narrower: worst case, 1-byte ints: need 5 bytes: "-127<NUL>" */
  5330. if (sizeof(arith_t) < 4) len += 2;
  5331. expdest = makestrspace(len, expdest);
  5332. len = fmtstr(expdest, len, ARITH_FMT, num);
  5333. STADJUST(len, expdest);
  5334. return len;
  5335. }
  5336. /*
  5337. * Break the argument string into pieces based upon IFS and add the
  5338. * strings to the argument list. The regions of the string to be
  5339. * searched for IFS characters have been stored by recordregion.
  5340. */
  5341. static void
  5342. ifsbreakup(char *string, struct arglist *arglist)
  5343. {
  5344. struct ifsregion *ifsp;
  5345. struct strlist *sp;
  5346. char *start;
  5347. char *p;
  5348. char *q;
  5349. const char *ifs, *realifs;
  5350. int ifsspc;
  5351. int nulonly;
  5352. start = string;
  5353. if (ifslastp != NULL) {
  5354. ifsspc = 0;
  5355. nulonly = 0;
  5356. realifs = ifsset() ? ifsval() : defifs;
  5357. ifsp = &ifsfirst;
  5358. do {
  5359. p = string + ifsp->begoff;
  5360. nulonly = ifsp->nulonly;
  5361. ifs = nulonly ? nullstr : realifs;
  5362. ifsspc = 0;
  5363. while (p < string + ifsp->endoff) {
  5364. q = p;
  5365. if ((unsigned char)*p == CTLESC)
  5366. p++;
  5367. if (!strchr(ifs, *p)) {
  5368. p++;
  5369. continue;
  5370. }
  5371. if (!nulonly)
  5372. ifsspc = (strchr(defifs, *p) != NULL);
  5373. /* Ignore IFS whitespace at start */
  5374. if (q == start && ifsspc) {
  5375. p++;
  5376. start = p;
  5377. continue;
  5378. }
  5379. *q = '\0';
  5380. sp = stzalloc(sizeof(*sp));
  5381. sp->text = start;
  5382. *arglist->lastp = sp;
  5383. arglist->lastp = &sp->next;
  5384. p++;
  5385. if (!nulonly) {
  5386. for (;;) {
  5387. if (p >= string + ifsp->endoff) {
  5388. break;
  5389. }
  5390. q = p;
  5391. if ((unsigned char)*p == CTLESC)
  5392. p++;
  5393. if (strchr(ifs, *p) == NULL) {
  5394. p = q;
  5395. break;
  5396. }
  5397. if (strchr(defifs, *p) == NULL) {
  5398. if (ifsspc) {
  5399. p++;
  5400. ifsspc = 0;
  5401. } else {
  5402. p = q;
  5403. break;
  5404. }
  5405. } else
  5406. p++;
  5407. }
  5408. }
  5409. start = p;
  5410. } /* while */
  5411. ifsp = ifsp->next;
  5412. } while (ifsp != NULL);
  5413. if (nulonly)
  5414. goto add;
  5415. }
  5416. if (!*start)
  5417. return;
  5418. add:
  5419. sp = stzalloc(sizeof(*sp));
  5420. sp->text = start;
  5421. *arglist->lastp = sp;
  5422. arglist->lastp = &sp->next;
  5423. }
  5424. static void
  5425. ifsfree(void)
  5426. {
  5427. struct ifsregion *p = ifsfirst.next;
  5428. if (!p)
  5429. goto out;
  5430. INT_OFF;
  5431. do {
  5432. struct ifsregion *ifsp;
  5433. ifsp = p->next;
  5434. free(p);
  5435. p = ifsp;
  5436. } while (p);
  5437. ifsfirst.next = NULL;
  5438. INT_ON;
  5439. out:
  5440. ifslastp = NULL;
  5441. }
  5442. static size_t
  5443. esclen(const char *start, const char *p)
  5444. {
  5445. size_t esc = 0;
  5446. while (p > start && (unsigned char)*--p == CTLESC) {
  5447. esc++;
  5448. }
  5449. return esc;
  5450. }
  5451. /*
  5452. * Remove any CTLESC characters from a string.
  5453. */
  5454. static char *
  5455. rmescapes(char *str, int flag)
  5456. {
  5457. static const char qchars[] ALIGN1 = {
  5458. IF_BASH_PATTERN_SUBST('/',) CTLESC, CTLQUOTEMARK, '\0' };
  5459. char *p, *q, *r;
  5460. unsigned inquotes;
  5461. unsigned protect_against_glob;
  5462. unsigned globbing;
  5463. IF_BASH_PATTERN_SUBST(unsigned slash = flag & RMESCAPE_SLASH;)
  5464. p = strpbrk(str, qchars IF_BASH_PATTERN_SUBST(+ !slash));
  5465. if (!p)
  5466. return str;
  5467. q = p;
  5468. r = str;
  5469. if (flag & RMESCAPE_ALLOC) {
  5470. size_t len = p - str;
  5471. size_t fulllen = len + strlen(p) + 1;
  5472. if (flag & RMESCAPE_GROW) {
  5473. int strloc = str - (char *)stackblock();
  5474. r = makestrspace(fulllen, expdest);
  5475. /* p and str may be invalidated by makestrspace */
  5476. str = (char *)stackblock() + strloc;
  5477. p = str + len;
  5478. } else if (flag & RMESCAPE_HEAP) {
  5479. r = ckmalloc(fulllen);
  5480. } else {
  5481. r = stalloc(fulllen);
  5482. }
  5483. q = r;
  5484. if (len > 0) {
  5485. q = (char *)mempcpy(q, str, len);
  5486. }
  5487. }
  5488. inquotes = 0;
  5489. globbing = flag & RMESCAPE_GLOB;
  5490. protect_against_glob = globbing;
  5491. while (*p) {
  5492. if ((unsigned char)*p == CTLQUOTEMARK) {
  5493. // Note: both inquotes and protect_against_glob only affect whether
  5494. // CTLESC,<ch> gets converted to <ch> or to \<ch>
  5495. inquotes = ~inquotes;
  5496. p++;
  5497. protect_against_glob = globbing;
  5498. continue;
  5499. }
  5500. if ((unsigned char)*p == CTLESC) {
  5501. p++;
  5502. #if DEBUG
  5503. if (*p == '\0')
  5504. ash_msg_and_raise_error("CTLESC at EOL (shouldn't happen)");
  5505. #endif
  5506. if (protect_against_glob) {
  5507. /*
  5508. * We used to trust glob() and fnmatch() to eat
  5509. * superfluous escapes (\z where z has no
  5510. * special meaning anyway). But this causes
  5511. * bugs such as string of one greek letter rho
  5512. * (unicode-encoded as two bytes "cf,81")
  5513. * getting encoded as "cf,CTLESC,81"
  5514. * and here, converted to "cf,\,81" -
  5515. * which does not go well with some flavors
  5516. * of fnmatch() in unicode locales
  5517. * (for example, glibc <= 2.22).
  5518. *
  5519. * Lets add "\" only on the chars which need it.
  5520. * Testcases for less obvious chars are shown.
  5521. */
  5522. if (*p == '*'
  5523. || *p == '?'
  5524. || *p == '['
  5525. || *p == '\\' /* case '\' in \\ ) echo ok;; *) echo WRONG;; esac */
  5526. || *p == ']' /* case ']' in [a\]] ) echo ok;; *) echo WRONG;; esac */
  5527. || *p == '-' /* case '-' in [a\-c]) echo ok;; *) echo WRONG;; esac */
  5528. || *p == '!' /* case '!' in [\!] ) echo ok;; *) echo WRONG;; esac */
  5529. /* Some libc support [^negate], that's why "^" also needs love */
  5530. || *p == '^' /* case '^' in [\^] ) echo ok;; *) echo WRONG;; esac */
  5531. ) {
  5532. *q++ = '\\';
  5533. }
  5534. }
  5535. } else if (*p == '\\' && !inquotes) {
  5536. /* naked back slash */
  5537. protect_against_glob = 0;
  5538. goto copy;
  5539. }
  5540. #if BASH_PATTERN_SUBST
  5541. else if (*p == '/' && slash) {
  5542. /* stop handling globbing and mark location of slash */
  5543. globbing = slash = 0;
  5544. *p = CTLESC;
  5545. }
  5546. #endif
  5547. protect_against_glob = globbing;
  5548. copy:
  5549. *q++ = *p++;
  5550. }
  5551. *q = '\0';
  5552. if (flag & RMESCAPE_GROW) {
  5553. expdest = r;
  5554. STADJUST(q - r + 1, expdest);
  5555. }
  5556. return r;
  5557. }
  5558. #define pmatch(a, b) !fnmatch((a), (b), 0)
  5559. /*
  5560. * Prepare a pattern for a expmeta (internal glob(3)) call.
  5561. *
  5562. * Returns an stalloced string.
  5563. */
  5564. static char *
  5565. preglob(const char *pattern, int flag)
  5566. {
  5567. return rmescapes((char *)pattern, flag | RMESCAPE_GLOB);
  5568. }
  5569. /*
  5570. * Put a string on the stack.
  5571. */
  5572. static void
  5573. memtodest(const char *p, size_t len, int syntax, int quotes)
  5574. {
  5575. char *q;
  5576. if (!len)
  5577. return;
  5578. q = makestrspace((quotes & QUOTES_ESC) ? len * 2 : len, expdest);
  5579. do {
  5580. unsigned char c = *p++;
  5581. if (c) {
  5582. if (quotes & QUOTES_ESC) {
  5583. int n = SIT(c, syntax);
  5584. if (n == CCTL
  5585. || (((quotes & EXP_FULL) || syntax != BASESYNTAX)
  5586. && n == CBACK
  5587. )
  5588. ) {
  5589. USTPUTC(CTLESC, q);
  5590. }
  5591. }
  5592. } else if (!(quotes & QUOTES_KEEPNUL))
  5593. continue;
  5594. USTPUTC(c, q);
  5595. } while (--len);
  5596. expdest = q;
  5597. }
  5598. static size_t
  5599. strtodest(const char *p, int syntax, int quotes)
  5600. {
  5601. size_t len = strlen(p);
  5602. memtodest(p, len, syntax, quotes);
  5603. return len;
  5604. }
  5605. /*
  5606. * Record the fact that we have to scan this region of the
  5607. * string for IFS characters.
  5608. */
  5609. static void
  5610. recordregion(int start, int end, int nulonly)
  5611. {
  5612. struct ifsregion *ifsp;
  5613. if (ifslastp == NULL) {
  5614. ifsp = &ifsfirst;
  5615. } else {
  5616. INT_OFF;
  5617. ifsp = ckzalloc(sizeof(*ifsp));
  5618. /*ifsp->next = NULL; - ckzalloc did it */
  5619. ifslastp->next = ifsp;
  5620. INT_ON;
  5621. }
  5622. ifslastp = ifsp;
  5623. ifslastp->begoff = start;
  5624. ifslastp->endoff = end;
  5625. ifslastp->nulonly = nulonly;
  5626. }
  5627. static void
  5628. removerecordregions(int endoff)
  5629. {
  5630. if (ifslastp == NULL)
  5631. return;
  5632. if (ifsfirst.endoff > endoff) {
  5633. while (ifsfirst.next) {
  5634. struct ifsregion *ifsp;
  5635. INT_OFF;
  5636. ifsp = ifsfirst.next->next;
  5637. free(ifsfirst.next);
  5638. ifsfirst.next = ifsp;
  5639. INT_ON;
  5640. }
  5641. if (ifsfirst.begoff > endoff) {
  5642. ifslastp = NULL;
  5643. } else {
  5644. ifslastp = &ifsfirst;
  5645. ifsfirst.endoff = endoff;
  5646. }
  5647. return;
  5648. }
  5649. ifslastp = &ifsfirst;
  5650. while (ifslastp->next && ifslastp->next->begoff < endoff)
  5651. ifslastp = ifslastp->next;
  5652. while (ifslastp->next) {
  5653. struct ifsregion *ifsp;
  5654. INT_OFF;
  5655. ifsp = ifslastp->next->next;
  5656. free(ifslastp->next);
  5657. ifslastp->next = ifsp;
  5658. INT_ON;
  5659. }
  5660. if (ifslastp->endoff > endoff)
  5661. ifslastp->endoff = endoff;
  5662. }
  5663. static char *
  5664. exptilde(char *startp, char *p, int flags)
  5665. {
  5666. unsigned char c;
  5667. char *name;
  5668. struct passwd *pw;
  5669. const char *home;
  5670. int quotes = flags & QUOTES_ESC;
  5671. name = p + 1;
  5672. while ((c = *++p) != '\0') {
  5673. switch (c) {
  5674. case CTLESC:
  5675. return startp;
  5676. case CTLQUOTEMARK:
  5677. return startp;
  5678. case ':':
  5679. if (flags & EXP_VARTILDE)
  5680. goto done;
  5681. break;
  5682. case '/':
  5683. case CTLENDVAR:
  5684. goto done;
  5685. }
  5686. }
  5687. done:
  5688. *p = '\0';
  5689. if (*name == '\0') {
  5690. home = lookupvar("HOME");
  5691. } else {
  5692. pw = getpwnam(name);
  5693. if (pw == NULL)
  5694. goto lose;
  5695. home = pw->pw_dir;
  5696. }
  5697. if (!home || !*home)
  5698. goto lose;
  5699. *p = c;
  5700. strtodest(home, SQSYNTAX, quotes);
  5701. return p;
  5702. lose:
  5703. *p = c;
  5704. return startp;
  5705. }
  5706. /*
  5707. * Execute a command inside back quotes. If it's a builtin command, we
  5708. * want to save its output in a block obtained from malloc. Otherwise
  5709. * we fork off a subprocess and get the output of the command via a pipe.
  5710. * Should be called with interrupts off.
  5711. */
  5712. struct backcmd { /* result of evalbackcmd */
  5713. int fd; /* file descriptor to read from */
  5714. int nleft; /* number of chars in buffer */
  5715. char *buf; /* buffer */
  5716. struct job *jp; /* job structure for command */
  5717. };
  5718. /* These forward decls are needed to use "eval" code for backticks handling: */
  5719. /* flags in argument to evaltree */
  5720. #define EV_EXIT 01 /* exit after evaluating tree */
  5721. #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
  5722. static int evaltree(union node *, int);
  5723. /* An evaltree() which is known to never return.
  5724. * Used to use an alias:
  5725. * static int evaltreenr(union node *, int) __attribute__((alias("evaltree"),__noreturn__));
  5726. * but clang was reported to "transfer" noreturn-ness to evaltree() as well.
  5727. */
  5728. static ALWAYS_INLINE NORETURN void
  5729. evaltreenr(union node *n, int flags)
  5730. {
  5731. evaltree(n, flags);
  5732. bb_unreachable(abort());
  5733. /* NOTREACHED */
  5734. }
  5735. static void FAST_FUNC
  5736. evalbackcmd(union node *n, struct backcmd *result)
  5737. {
  5738. int pip[2];
  5739. struct job *jp;
  5740. result->fd = -1;
  5741. result->buf = NULL;
  5742. result->nleft = 0;
  5743. result->jp = NULL;
  5744. if (n == NULL) {
  5745. goto out;
  5746. }
  5747. if (pipe(pip) < 0)
  5748. ash_msg_and_raise_perror("can't create pipe");
  5749. jp = makejob(/*n,*/ 1);
  5750. if (forkshell(jp, n, FORK_NOJOB) == 0) {
  5751. /* child */
  5752. FORCE_INT_ON;
  5753. close(pip[0]);
  5754. if (pip[1] != 1) {
  5755. /*close(1);*/
  5756. dup2_or_raise(pip[1], 1);
  5757. close(pip[1]);
  5758. }
  5759. /* TODO: eflag clearing makes the following not abort:
  5760. * ash -c 'set -e; z=$(false;echo foo); echo $z'
  5761. * which is what bash does (unless it is in POSIX mode).
  5762. * dash deleted "eflag = 0" line in the commit
  5763. * Date: Mon, 28 Jun 2010 17:11:58 +1000
  5764. * [EVAL] Don't clear eflag in evalbackcmd
  5765. * For now, preserve bash-like behavior, it seems to be somewhat more useful:
  5766. */
  5767. eflag = 0;
  5768. ifsfree();
  5769. evaltreenr(n, EV_EXIT);
  5770. /* NOTREACHED */
  5771. }
  5772. /* parent */
  5773. close(pip[1]);
  5774. result->fd = pip[0];
  5775. result->jp = jp;
  5776. out:
  5777. TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
  5778. result->fd, result->buf, result->nleft, result->jp));
  5779. }
  5780. /*
  5781. * Expand stuff in backwards quotes.
  5782. */
  5783. static void
  5784. expbackq(union node *cmd, int flag)
  5785. {
  5786. struct backcmd in;
  5787. int i;
  5788. char buf[128];
  5789. char *p;
  5790. char *dest;
  5791. int startloc;
  5792. int syntax = flag & EXP_QUOTED ? DQSYNTAX : BASESYNTAX;
  5793. struct stackmark smark;
  5794. INT_OFF;
  5795. startloc = expdest - (char *)stackblock();
  5796. pushstackmark(&smark, startloc);
  5797. evalbackcmd(cmd, &in);
  5798. popstackmark(&smark);
  5799. p = in.buf;
  5800. i = in.nleft;
  5801. if (i == 0)
  5802. goto read;
  5803. for (;;) {
  5804. memtodest(p, i, syntax, flag & QUOTES_ESC);
  5805. read:
  5806. if (in.fd < 0)
  5807. break;
  5808. i = nonblock_immune_read(in.fd, buf, sizeof(buf));
  5809. TRACE(("expbackq: read returns %d\n", i));
  5810. if (i <= 0)
  5811. break;
  5812. p = buf;
  5813. }
  5814. free(in.buf);
  5815. if (in.fd >= 0) {
  5816. close(in.fd);
  5817. back_exitstatus = waitforjob(in.jp);
  5818. }
  5819. INT_ON;
  5820. /* Eat all trailing newlines */
  5821. dest = expdest;
  5822. for (; dest > (char *)stackblock() && dest[-1] == '\n';)
  5823. STUNPUTC(dest);
  5824. expdest = dest;
  5825. if (!(flag & EXP_QUOTED))
  5826. recordregion(startloc, dest - (char *)stackblock(), 0);
  5827. TRACE(("evalbackq: size:%d:'%.*s'\n",
  5828. (int)((dest - (char *)stackblock()) - startloc),
  5829. (int)((dest - (char *)stackblock()) - startloc),
  5830. stackblock() + startloc));
  5831. }
  5832. #if ENABLE_FEATURE_SH_MATH
  5833. /*
  5834. * Expand arithmetic expression. Backup to start of expression,
  5835. * evaluate, place result in (backed up) result, adjust string position.
  5836. */
  5837. static void
  5838. expari(int flag)
  5839. {
  5840. char *p, *start;
  5841. int begoff;
  5842. int len;
  5843. /* ifsfree(); */
  5844. /*
  5845. * This routine is slightly over-complicated for
  5846. * efficiency. Next we scan backwards looking for the
  5847. * start of arithmetic.
  5848. */
  5849. start = stackblock();
  5850. p = expdest - 1;
  5851. *p = '\0';
  5852. p--;
  5853. while (1) {
  5854. int esc;
  5855. while ((unsigned char)*p != CTLARI) {
  5856. p--;
  5857. #if DEBUG
  5858. if (p < start) {
  5859. ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
  5860. }
  5861. #endif
  5862. }
  5863. esc = esclen(start, p);
  5864. if (!(esc % 2)) {
  5865. break;
  5866. }
  5867. p -= esc + 1;
  5868. }
  5869. begoff = p - start;
  5870. removerecordregions(begoff);
  5871. expdest = p;
  5872. if (flag & QUOTES_ESC)
  5873. rmescapes(p + 1, 0);
  5874. len = cvtnum(ash_arith(p + 1));
  5875. if (!(flag & EXP_QUOTED))
  5876. recordregion(begoff, begoff + len, 0);
  5877. }
  5878. #endif
  5879. /* argstr needs it */
  5880. static char *evalvar(char *p, int flags);
  5881. /*
  5882. * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
  5883. * characters to allow for further processing. Otherwise treat
  5884. * $@ like $* since no splitting will be performed.
  5885. */
  5886. static void
  5887. argstr(char *p, int flags)
  5888. {
  5889. static const char spclchars[] ALIGN1 = {
  5890. '=',
  5891. ':',
  5892. CTLQUOTEMARK,
  5893. CTLENDVAR,
  5894. CTLESC,
  5895. CTLVAR,
  5896. CTLBACKQ,
  5897. #if ENABLE_FEATURE_SH_MATH
  5898. CTLENDARI,
  5899. #endif
  5900. '\0'
  5901. };
  5902. const char *reject = spclchars;
  5903. int breakall = (flags & (EXP_WORD | EXP_QUOTED)) == EXP_WORD;
  5904. int inquotes;
  5905. size_t length;
  5906. int startloc;
  5907. if (!(flags & EXP_VARTILDE)) {
  5908. reject += 2;
  5909. } else if (flags & EXP_VARTILDE2) {
  5910. reject++;
  5911. }
  5912. inquotes = 0;
  5913. length = 0;
  5914. if (flags & EXP_TILDE) {
  5915. char *q;
  5916. flags &= ~EXP_TILDE;
  5917. tilde:
  5918. q = p;
  5919. if (*q == '~')
  5920. p = exptilde(p, q, flags);
  5921. }
  5922. start:
  5923. startloc = expdest - (char *)stackblock();
  5924. for (;;) {
  5925. unsigned char c;
  5926. length += strcspn(p + length, reject);
  5927. c = p[length];
  5928. if (c) {
  5929. if (!(c & 0x80)
  5930. IF_FEATURE_SH_MATH(|| c == CTLENDARI)
  5931. ) {
  5932. /* c == '=' || c == ':' || c == CTLENDARI */
  5933. length++;
  5934. }
  5935. }
  5936. if (length > 0) {
  5937. int newloc;
  5938. expdest = stack_nputstr(p, length, expdest);
  5939. newloc = expdest - (char *)stackblock();
  5940. if (breakall && !inquotes && newloc > startloc) {
  5941. recordregion(startloc, newloc, 0);
  5942. }
  5943. startloc = newloc;
  5944. }
  5945. p += length + 1;
  5946. length = 0;
  5947. switch (c) {
  5948. case '\0':
  5949. goto breakloop;
  5950. case '=':
  5951. if (flags & EXP_VARTILDE2) {
  5952. p--;
  5953. continue;
  5954. }
  5955. flags |= EXP_VARTILDE2;
  5956. reject++;
  5957. /* fall through */
  5958. case ':':
  5959. /*
  5960. * sort of a hack - expand tildes in variable
  5961. * assignments (after the first '=' and after ':'s).
  5962. */
  5963. if (*--p == '~') {
  5964. goto tilde;
  5965. }
  5966. continue;
  5967. }
  5968. switch (c) {
  5969. case CTLENDVAR: /* ??? */
  5970. goto breakloop;
  5971. case CTLQUOTEMARK:
  5972. inquotes ^= EXP_QUOTED;
  5973. /* "$@" syntax adherence hack */
  5974. if (inquotes && !memcmp(p, dolatstr + 1, DOLATSTRLEN - 1)) {
  5975. p = evalvar(p + 1, flags | inquotes) + 1;
  5976. goto start;
  5977. }
  5978. addquote:
  5979. if (flags & QUOTES_ESC) {
  5980. p--;
  5981. length++;
  5982. startloc++;
  5983. }
  5984. break;
  5985. case CTLESC:
  5986. startloc++;
  5987. length++;
  5988. /*
  5989. * Quoted parameter expansion pattern: remove quote
  5990. * unless inside inner quotes or we have a literal
  5991. * backslash.
  5992. */
  5993. if (((flags | inquotes) & (EXP_QPAT | EXP_QUOTED)) ==
  5994. EXP_QPAT && *p != '\\')
  5995. break;
  5996. goto addquote;
  5997. case CTLVAR:
  5998. TRACE(("argstr: evalvar('%s')\n", p));
  5999. p = evalvar(p, flags | inquotes);
  6000. TRACE(("argstr: evalvar:'%s'\n", (char *)stackblock()));
  6001. goto start;
  6002. case CTLBACKQ:
  6003. expbackq(argbackq->n, flags | inquotes);
  6004. argbackq = argbackq->next;
  6005. goto start;
  6006. #if ENABLE_FEATURE_SH_MATH
  6007. case CTLENDARI:
  6008. p--;
  6009. expari(flags | inquotes);
  6010. goto start;
  6011. #endif
  6012. }
  6013. }
  6014. breakloop: ;
  6015. }
  6016. static char *
  6017. scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM,
  6018. char *pattern, int quotes, int zero)
  6019. {
  6020. char *loc, *loc2;
  6021. char c;
  6022. loc = startp;
  6023. loc2 = rmesc;
  6024. do {
  6025. int match;
  6026. const char *s = loc2;
  6027. c = *loc2;
  6028. if (zero) {
  6029. *loc2 = '\0';
  6030. s = rmesc;
  6031. }
  6032. match = pmatch(pattern, s);
  6033. *loc2 = c;
  6034. if (match)
  6035. return loc;
  6036. if (quotes && (unsigned char)*loc == CTLESC)
  6037. loc++;
  6038. loc++;
  6039. loc2++;
  6040. } while (c);
  6041. return NULL;
  6042. }
  6043. static char *
  6044. scanright(char *startp, char *rmesc, char *rmescend,
  6045. char *pattern, int quotes, int match_at_start)
  6046. {
  6047. #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
  6048. int try2optimize = match_at_start;
  6049. #endif
  6050. int esc = 0;
  6051. char *loc;
  6052. char *loc2;
  6053. /* If we called by "${v/pattern/repl}" or "${v//pattern/repl}":
  6054. * startp="escaped_value_of_v" rmesc="raw_value_of_v"
  6055. * rmescend=""(ptr to NUL in rmesc) pattern="pattern" quotes=match_at_start=1
  6056. * Logic:
  6057. * loc starts at NUL at the end of startp, loc2 starts at the end of rmesc,
  6058. * and on each iteration they go back two/one char until they reach the beginning.
  6059. * We try to find a match in "raw_value_of_v", "raw_value_of_", "raw_value_of" etc.
  6060. */
  6061. /* TODO: document in what other circumstances we are called. */
  6062. for (loc = pattern - 1, loc2 = rmescend; loc >= startp; loc2--) {
  6063. int match;
  6064. char c = *loc2;
  6065. const char *s = loc2;
  6066. if (match_at_start) {
  6067. *loc2 = '\0';
  6068. s = rmesc;
  6069. }
  6070. match = pmatch(pattern, s);
  6071. //bb_error_msg("pmatch(pattern:'%s',s:'%s'):%d", pattern, s, match);
  6072. *loc2 = c;
  6073. if (match)
  6074. return loc;
  6075. #if !ENABLE_ASH_OPTIMIZE_FOR_SIZE
  6076. if (try2optimize) {
  6077. /* Maybe we can optimize this:
  6078. * if pattern ends with unescaped *, we can avoid checking
  6079. * shorter strings: if "foo*" doesn't match "raw_value_of_v",
  6080. * it won't match truncated "raw_value_of_" strings too.
  6081. */
  6082. unsigned plen = strlen(pattern);
  6083. /* Does it end with "*"? */
  6084. if (plen != 0 && pattern[--plen] == '*') {
  6085. /* "xxxx*" is not escaped */
  6086. /* "xxx\*" is escaped */
  6087. /* "xx\\*" is not escaped */
  6088. /* "x\\\*" is escaped */
  6089. int slashes = 0;
  6090. while (plen != 0 && pattern[--plen] == '\\')
  6091. slashes++;
  6092. if (!(slashes & 1))
  6093. break; /* ends with unescaped "*" */
  6094. }
  6095. try2optimize = 0;
  6096. }
  6097. #endif
  6098. loc--;
  6099. if (quotes) {
  6100. if (--esc < 0) {
  6101. esc = esclen(startp, loc);
  6102. }
  6103. if (esc % 2) {
  6104. esc--;
  6105. loc--;
  6106. }
  6107. }
  6108. }
  6109. return NULL;
  6110. }
  6111. static void varunset(const char *, const char *, const char *, int) NORETURN;
  6112. static void
  6113. varunset(const char *end, const char *var, const char *umsg, int varflags)
  6114. {
  6115. const char *msg;
  6116. const char *tail;
  6117. tail = nullstr;
  6118. msg = "parameter not set";
  6119. if (umsg) {
  6120. if ((unsigned char)*end == CTLENDVAR) {
  6121. if (varflags & VSNUL)
  6122. tail = " or null";
  6123. } else {
  6124. msg = umsg;
  6125. }
  6126. }
  6127. ash_msg_and_raise_error("%.*s: %s%s", (int)(end - var - 1), var, msg, tail);
  6128. }
  6129. static const char *
  6130. subevalvar(char *p, char *varname, int strloc, int subtype,
  6131. int startloc, int varflags, int flag)
  6132. {
  6133. struct nodelist *saveargbackq = argbackq;
  6134. int quotes = flag & QUOTES_ESC;
  6135. char *startp;
  6136. char *loc;
  6137. char *rmesc, *rmescend;
  6138. char *str;
  6139. int amount, resetloc;
  6140. IF_BASH_PATTERN_SUBST(int workloc;)
  6141. IF_BASH_PATTERN_SUBST(char *repl = NULL;)
  6142. int zero;
  6143. char *(*scan)(char*, char*, char*, char*, int, int);
  6144. //bb_error_msg("subevalvar(p:'%s',varname:'%s',strloc:%d,subtype:%d,startloc:%d,varflags:%x,quotes:%d)",
  6145. // p, varname, strloc, subtype, startloc, varflags, quotes);
  6146. argstr(p, EXP_TILDE | (subtype != VSASSIGN && subtype != VSQUESTION ?
  6147. (flag & (EXP_QUOTED | EXP_QPAT) ? EXP_QPAT : EXP_CASE) : 0)
  6148. );
  6149. STPUTC('\0', expdest);
  6150. argbackq = saveargbackq;
  6151. startp = (char *)stackblock() + startloc;
  6152. switch (subtype) {
  6153. case VSASSIGN:
  6154. setvar0(varname, startp);
  6155. amount = startp - expdest;
  6156. STADJUST(amount, expdest);
  6157. return startp;
  6158. case VSQUESTION:
  6159. varunset(p, varname, startp, varflags);
  6160. /* NOTREACHED */
  6161. #if BASH_SUBSTR
  6162. case VSSUBSTR: {
  6163. int pos, len, orig_len;
  6164. char *colon;
  6165. loc = str = stackblock() + strloc;
  6166. # if !ENABLE_FEATURE_SH_MATH
  6167. # define ash_arith number
  6168. # endif
  6169. /* Read POS in ${var:POS:LEN} */
  6170. colon = strchr(loc, ':');
  6171. if (colon) *colon = '\0';
  6172. pos = ash_arith(loc);
  6173. if (colon) *colon = ':';
  6174. /* Read LEN in ${var:POS:LEN} */
  6175. len = str - startp - 1;
  6176. /* *loc != '\0', guaranteed by parser */
  6177. if (quotes) {
  6178. char *ptr;
  6179. /* Adjust the length by the number of escapes */
  6180. for (ptr = startp; ptr < (str - 1); ptr++) {
  6181. if ((unsigned char)*ptr == CTLESC) {
  6182. len--;
  6183. ptr++;
  6184. }
  6185. }
  6186. }
  6187. orig_len = len;
  6188. if (*loc++ == ':') {
  6189. /* ${var::LEN} */
  6190. len = ash_arith(loc);
  6191. } else {
  6192. /* Skip POS in ${var:POS:LEN} */
  6193. len = orig_len;
  6194. while (*loc && *loc != ':') {
  6195. loc++;
  6196. }
  6197. if (*loc++ == ':') {
  6198. len = ash_arith(loc);
  6199. }
  6200. }
  6201. # undef ash_arith
  6202. if (pos < 0) {
  6203. /* ${VAR:$((-n)):l} starts n chars from the end */
  6204. pos = orig_len + pos;
  6205. }
  6206. if ((unsigned)pos >= orig_len) {
  6207. /* apart from obvious ${VAR:999999:l},
  6208. * covers ${VAR:$((-9999999)):l} - result is ""
  6209. * (bash compat)
  6210. */
  6211. pos = 0;
  6212. len = 0;
  6213. }
  6214. if (len < 0) {
  6215. /* ${VAR:N:-M} sets LEN to strlen()-M */
  6216. len = (orig_len - pos) + len;
  6217. }
  6218. if ((unsigned)len > (orig_len - pos))
  6219. len = orig_len - pos;
  6220. for (str = startp; pos; str++, pos--) {
  6221. if (quotes && (unsigned char)*str == CTLESC)
  6222. str++;
  6223. }
  6224. for (loc = startp; len; len--) {
  6225. if (quotes && (unsigned char)*str == CTLESC)
  6226. *loc++ = *str++;
  6227. *loc++ = *str++;
  6228. }
  6229. *loc = '\0';
  6230. amount = loc - expdest;
  6231. STADJUST(amount, expdest);
  6232. return loc;
  6233. }
  6234. #endif /* BASH_SUBSTR */
  6235. }
  6236. resetloc = expdest - (char *)stackblock();
  6237. #if BASH_PATTERN_SUBST
  6238. /* We'll comeback here if we grow the stack while handling
  6239. * a VSREPLACE or VSREPLACEALL, since our pointers into the
  6240. * stack will need rebasing, and we'll need to remove our work
  6241. * areas each time
  6242. */
  6243. restart:
  6244. #endif
  6245. amount = expdest - ((char *)stackblock() + resetloc);
  6246. STADJUST(-amount, expdest);
  6247. startp = (char *)stackblock() + startloc;
  6248. rmesc = startp;
  6249. rmescend = (char *)stackblock() + strloc;
  6250. if (quotes) {
  6251. rmesc = rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
  6252. if (rmesc != startp) {
  6253. rmescend = expdest;
  6254. startp = (char *)stackblock() + startloc;
  6255. }
  6256. }
  6257. rmescend--;
  6258. str = (char *)stackblock() + strloc;
  6259. /*
  6260. * Example: v='a\bc'; echo ${v/\\b/_\\_\z_}
  6261. * The result is a_\_z_c (not a\_\_z_c)!
  6262. *
  6263. * The search pattern and replace string treat backslashes differently!
  6264. * RMESCAPE_SLASH causes preglob to work differently on the pattern
  6265. * and string. It's only used on the first call.
  6266. */
  6267. preglob(str, IF_BASH_PATTERN_SUBST(
  6268. (subtype == VSREPLACE || subtype == VSREPLACEALL) && !repl ?
  6269. RMESCAPE_SLASH : ) 0);
  6270. #if BASH_PATTERN_SUBST
  6271. workloc = expdest - (char *)stackblock();
  6272. if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
  6273. int len;
  6274. char *idx, *end;
  6275. if (!repl) {
  6276. repl = strchr(str, CTLESC);
  6277. if (repl)
  6278. *repl++ = '\0';
  6279. else
  6280. repl = nullstr;
  6281. }
  6282. //bb_error_msg("str:'%s' repl:'%s'", str, repl);
  6283. /* If there's no pattern to match, return the expansion unmolested */
  6284. if (str[0] == '\0')
  6285. return NULL;
  6286. len = 0;
  6287. idx = startp;
  6288. end = str - 1;
  6289. while (idx < end) {
  6290. try_to_match:
  6291. loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
  6292. //bb_error_msg("scanright('%s'):'%s'", str, loc);
  6293. if (!loc) {
  6294. /* No match, advance */
  6295. char *restart_detect = stackblock();
  6296. skip_matching:
  6297. STPUTC(*idx, expdest);
  6298. if (quotes && (unsigned char)*idx == CTLESC) {
  6299. idx++;
  6300. len++;
  6301. STPUTC(*idx, expdest);
  6302. }
  6303. if (stackblock() != restart_detect)
  6304. goto restart;
  6305. idx++;
  6306. len++;
  6307. rmesc++;
  6308. /* continue; - prone to quadratic behavior, smarter code: */
  6309. if (idx >= end)
  6310. break;
  6311. if (str[0] == '*') {
  6312. /* Pattern is "*foo". If "*foo" does not match "long_string",
  6313. * it would never match "ong_string" etc, no point in trying.
  6314. */
  6315. goto skip_matching;
  6316. }
  6317. goto try_to_match;
  6318. }
  6319. if (subtype == VSREPLACEALL) {
  6320. while (idx < loc) {
  6321. if (quotes && (unsigned char)*idx == CTLESC)
  6322. idx++;
  6323. idx++;
  6324. rmesc++;
  6325. }
  6326. } else {
  6327. idx = loc;
  6328. }
  6329. //bb_error_msg("repl:'%s'", repl);
  6330. for (loc = (char*)repl; *loc; loc++) {
  6331. char *restart_detect = stackblock();
  6332. if (quotes && *loc == '\\') {
  6333. STPUTC(CTLESC, expdest);
  6334. len++;
  6335. }
  6336. STPUTC(*loc, expdest);
  6337. if (stackblock() != restart_detect)
  6338. goto restart;
  6339. len++;
  6340. }
  6341. if (subtype == VSREPLACE) {
  6342. //bb_error_msg("tail:'%s', quotes:%x", idx, quotes);
  6343. while (*idx) {
  6344. char *restart_detect = stackblock();
  6345. STPUTC(*idx, expdest);
  6346. if (stackblock() != restart_detect)
  6347. goto restart;
  6348. len++;
  6349. idx++;
  6350. }
  6351. break;
  6352. }
  6353. }
  6354. /* We've put the replaced text into a buffer at workloc, now
  6355. * move it to the right place and adjust the stack.
  6356. */
  6357. STPUTC('\0', expdest);
  6358. startp = (char *)stackblock() + startloc;
  6359. memmove(startp, (char *)stackblock() + workloc, len + 1);
  6360. //bb_error_msg("startp:'%s'", startp);
  6361. amount = expdest - (startp + len);
  6362. STADJUST(-amount, expdest);
  6363. return startp;
  6364. }
  6365. #endif /* BASH_PATTERN_SUBST */
  6366. subtype -= VSTRIMRIGHT;
  6367. #if DEBUG
  6368. if (subtype < 0 || subtype > 7)
  6369. abort();
  6370. #endif
  6371. /* zero = (subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX) */
  6372. zero = subtype >> 1;
  6373. /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
  6374. scan = (subtype & 1) ^ zero ? scanleft : scanright;
  6375. loc = scan(startp, rmesc, rmescend, str, quotes, zero);
  6376. if (loc) {
  6377. if (zero) {
  6378. memmove(startp, loc, str - loc);
  6379. loc = startp + (str - loc) - 1;
  6380. }
  6381. *loc = '\0';
  6382. amount = loc - expdest;
  6383. STADJUST(amount, expdest);
  6384. }
  6385. return loc;
  6386. }
  6387. /*
  6388. * Add the value of a specialized variable to the stack string.
  6389. * name parameter (examples):
  6390. * ash -c 'echo $1' name:'1='
  6391. * ash -c 'echo $qwe' name:'qwe='
  6392. * ash -c 'echo $$' name:'$='
  6393. * ash -c 'echo ${$}' name:'$='
  6394. * ash -c 'echo ${$##q}' name:'$=q'
  6395. * ash -c 'echo ${#$}' name:'$='
  6396. * note: examples with bad shell syntax:
  6397. * ash -c 'echo ${#$1}' name:'$=1'
  6398. * ash -c 'echo ${#1#}' name:'1=#'
  6399. */
  6400. static NOINLINE ssize_t
  6401. varvalue(char *name, int varflags, int flags, int *quotedp)
  6402. {
  6403. const char *p;
  6404. int num;
  6405. int i;
  6406. ssize_t len = 0;
  6407. int sep;
  6408. int quoted = *quotedp;
  6409. int subtype = varflags & VSTYPE;
  6410. int discard = subtype == VSPLUS || subtype == VSLENGTH;
  6411. int quotes = (discard ? 0 : (flags & QUOTES_ESC)) | QUOTES_KEEPNUL;
  6412. int syntax;
  6413. sep = (flags & EXP_FULL) << CHAR_BIT;
  6414. syntax = quoted ? DQSYNTAX : BASESYNTAX;
  6415. switch (*name) {
  6416. case '$':
  6417. num = rootpid;
  6418. goto numvar;
  6419. case '?':
  6420. num = exitstatus;
  6421. goto numvar;
  6422. case '#':
  6423. num = shellparam.nparam;
  6424. goto numvar;
  6425. case '!':
  6426. num = backgndpid;
  6427. if (num == 0)
  6428. return -1;
  6429. numvar:
  6430. len = cvtnum(num);
  6431. goto check_1char_name;
  6432. case '-':
  6433. expdest = makestrspace(NOPTS, expdest);
  6434. for (i = NOPTS - 1; i >= 0; i--) {
  6435. if (optlist[i]) {
  6436. USTPUTC(optletters(i), expdest);
  6437. len++;
  6438. }
  6439. }
  6440. check_1char_name:
  6441. #if 0
  6442. /* handles cases similar to ${#$1} */
  6443. if (name[2] != '\0')
  6444. raise_error_syntax("bad substitution");
  6445. #endif
  6446. break;
  6447. case '@':
  6448. if (quoted && sep)
  6449. goto param;
  6450. /* fall through */
  6451. case '*': {
  6452. char **ap;
  6453. char sepc;
  6454. if (quoted)
  6455. sep = 0;
  6456. sep |= ifsset() ? ifsval()[0] : ' ';
  6457. param:
  6458. sepc = sep;
  6459. *quotedp = !sepc;
  6460. ap = shellparam.p;
  6461. if (!ap)
  6462. return -1;
  6463. while ((p = *ap++) != NULL) {
  6464. len += strtodest(p, syntax, quotes);
  6465. if (*ap && sep) {
  6466. len++;
  6467. memtodest(&sepc, 1, syntax, quotes);
  6468. }
  6469. }
  6470. break;
  6471. } /* case '*' */
  6472. case '0':
  6473. case '1':
  6474. case '2':
  6475. case '3':
  6476. case '4':
  6477. case '5':
  6478. case '6':
  6479. case '7':
  6480. case '8':
  6481. case '9':
  6482. num = atoi(name); /* number(name) fails on ${N#str} etc */
  6483. if (num < 0 || num > shellparam.nparam)
  6484. return -1;
  6485. p = num ? shellparam.p[num - 1] : arg0;
  6486. goto value;
  6487. default:
  6488. /* NB: name has form "VAR=..." */
  6489. p = lookupvar(name);
  6490. value:
  6491. if (!p)
  6492. return -1;
  6493. len = strtodest(p, syntax, quotes);
  6494. #if ENABLE_UNICODE_SUPPORT
  6495. if (subtype == VSLENGTH && len > 0) {
  6496. reinit_unicode_for_ash();
  6497. if (unicode_status == UNICODE_ON) {
  6498. STADJUST(-len, expdest);
  6499. discard = 0;
  6500. len = unicode_strlen(p);
  6501. }
  6502. }
  6503. #endif
  6504. break;
  6505. }
  6506. if (discard)
  6507. STADJUST(-len, expdest);
  6508. return len;
  6509. }
  6510. /*
  6511. * Expand a variable, and return a pointer to the next character in the
  6512. * input string.
  6513. */
  6514. static char *
  6515. evalvar(char *p, int flag)
  6516. {
  6517. char varflags;
  6518. char subtype;
  6519. int quoted;
  6520. char easy;
  6521. char *var;
  6522. int patloc;
  6523. int startloc;
  6524. ssize_t varlen;
  6525. varflags = (unsigned char) *p++;
  6526. subtype = varflags & VSTYPE;
  6527. if (!subtype)
  6528. raise_error_syntax("bad substitution");
  6529. quoted = flag & EXP_QUOTED;
  6530. var = p;
  6531. easy = (!quoted || (*var == '@' && shellparam.nparam));
  6532. startloc = expdest - (char *)stackblock();
  6533. p = strchr(p, '=') + 1; //TODO: use var_end(p)?
  6534. again:
  6535. varlen = varvalue(var, varflags, flag, &quoted);
  6536. if (varflags & VSNUL)
  6537. varlen--;
  6538. if (subtype == VSPLUS) {
  6539. varlen = -1 - varlen;
  6540. goto vsplus;
  6541. }
  6542. if (subtype == VSMINUS) {
  6543. vsplus:
  6544. if (varlen < 0) {
  6545. argstr(
  6546. p,
  6547. flag | EXP_TILDE | EXP_WORD
  6548. );
  6549. goto end;
  6550. }
  6551. goto record;
  6552. }
  6553. if (subtype == VSASSIGN || subtype == VSQUESTION) {
  6554. if (varlen >= 0)
  6555. goto record;
  6556. subevalvar(p, var, 0, subtype, startloc, varflags,
  6557. flag & ~QUOTES_ESC);
  6558. varflags &= ~VSNUL;
  6559. /*
  6560. * Remove any recorded regions beyond
  6561. * start of variable
  6562. */
  6563. removerecordregions(startloc);
  6564. goto again;
  6565. }
  6566. if (varlen < 0 && uflag)
  6567. varunset(p, var, 0, 0);
  6568. if (subtype == VSLENGTH) {
  6569. cvtnum(varlen > 0 ? varlen : 0);
  6570. goto record;
  6571. }
  6572. if (subtype == VSNORMAL) {
  6573. record:
  6574. if (!easy)
  6575. goto end;
  6576. recordregion(startloc, expdest - (char *)stackblock(), quoted);
  6577. goto end;
  6578. }
  6579. #if DEBUG
  6580. switch (subtype) {
  6581. case VSTRIMLEFT:
  6582. case VSTRIMLEFTMAX:
  6583. case VSTRIMRIGHT:
  6584. case VSTRIMRIGHTMAX:
  6585. #if BASH_SUBSTR
  6586. case VSSUBSTR:
  6587. #endif
  6588. #if BASH_PATTERN_SUBST
  6589. case VSREPLACE:
  6590. case VSREPLACEALL:
  6591. #endif
  6592. break;
  6593. default:
  6594. abort();
  6595. }
  6596. #endif
  6597. if (varlen >= 0) {
  6598. /*
  6599. * Terminate the string and start recording the pattern
  6600. * right after it
  6601. */
  6602. STPUTC('\0', expdest);
  6603. patloc = expdest - (char *)stackblock();
  6604. if (NULL == subevalvar(p, /* varname: */ NULL, patloc, subtype,
  6605. startloc, varflags, flag)) {
  6606. int amount = expdest - (
  6607. (char *)stackblock() + patloc - 1
  6608. );
  6609. STADJUST(-amount, expdest);
  6610. }
  6611. /* Remove any recorded regions beyond start of variable */
  6612. removerecordregions(startloc);
  6613. goto record;
  6614. }
  6615. end:
  6616. if (subtype != VSNORMAL) { /* skip to end of alternative */
  6617. int nesting = 1;
  6618. for (;;) {
  6619. unsigned char c = *p++;
  6620. if (c == CTLESC)
  6621. p++;
  6622. else if (c == CTLBACKQ) {
  6623. if (varlen >= 0)
  6624. argbackq = argbackq->next;
  6625. } else if (c == CTLVAR) {
  6626. if ((*p++ & VSTYPE) != VSNORMAL)
  6627. nesting++;
  6628. } else if (c == CTLENDVAR) {
  6629. if (--nesting == 0)
  6630. break;
  6631. }
  6632. }
  6633. }
  6634. return p;
  6635. }
  6636. /*
  6637. * Add a file name to the list.
  6638. */
  6639. static void
  6640. addfname(const char *name)
  6641. {
  6642. struct strlist *sp;
  6643. sp = stzalloc(sizeof(*sp));
  6644. sp->text = sstrdup(name);
  6645. *exparg.lastp = sp;
  6646. exparg.lastp = &sp->next;
  6647. }
  6648. /* Avoid glob() (and thus, stat() et al) for words like "echo" */
  6649. static int
  6650. hasmeta(const char *p)
  6651. {
  6652. static const char chars[] ALIGN1 = {
  6653. '*', '?', '[', '\\', CTLQUOTEMARK, CTLESC, 0
  6654. };
  6655. for (;;) {
  6656. p = strpbrk(p, chars);
  6657. if (!p)
  6658. break;
  6659. switch ((unsigned char)*p) {
  6660. case CTLQUOTEMARK:
  6661. for (;;) {
  6662. p++;
  6663. if ((unsigned char)*p == CTLQUOTEMARK)
  6664. break;
  6665. if ((unsigned char)*p == CTLESC)
  6666. p++;
  6667. if (*p == '\0') /* huh? */
  6668. return 0;
  6669. }
  6670. break;
  6671. case '\\':
  6672. case CTLESC:
  6673. p++;
  6674. if (*p == '\0')
  6675. return 0;
  6676. break;
  6677. case '[':
  6678. if (!strchr(p + 1, ']')) {
  6679. /* It's not a properly closed [] pattern,
  6680. * but other metas may follow. Continue checking.
  6681. * my[file* _is_ globbed by bash
  6682. * and matches filenames like "my[file1".
  6683. */
  6684. break;
  6685. }
  6686. /* fallthrough */
  6687. default:
  6688. /* case '*': */
  6689. /* case '?': */
  6690. return 1;
  6691. }
  6692. p++;
  6693. }
  6694. return 0;
  6695. }
  6696. /* If we want to use glob() from libc... */
  6697. #if !ENABLE_ASH_INTERNAL_GLOB
  6698. /* Add the result of glob() to the list */
  6699. static void
  6700. addglob(const glob_t *pglob)
  6701. {
  6702. char **p = pglob->gl_pathv;
  6703. do {
  6704. addfname(*p);
  6705. } while (*++p);
  6706. }
  6707. static void
  6708. expandmeta(struct strlist *str /*, int flag*/)
  6709. {
  6710. /* TODO - EXP_REDIR */
  6711. while (str) {
  6712. char *p;
  6713. glob_t pglob;
  6714. int i;
  6715. if (fflag)
  6716. goto nometa;
  6717. if (!hasmeta(str->text))
  6718. goto nometa;
  6719. INT_OFF;
  6720. p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
  6721. // GLOB_NOMAGIC (GNU): if no *?[ chars in pattern, return it even if no match
  6722. // GLOB_NOCHECK: if no match, return unchanged pattern (sans \* escapes?)
  6723. //
  6724. // glibc 2.24.90 glob(GLOB_NOMAGIC) does not remove backslashes used for escaping:
  6725. // if you pass it "file\?", it returns "file\?", not "file?", if no match.
  6726. // Which means you need to unescape the string, right? Not so fast:
  6727. // if there _is_ a file named "file\?" (with backslash), it is returned
  6728. // as "file\?" too (whichever pattern you used to find it, say, "file*").
  6729. // You DON'T KNOW by looking at the result whether you need to unescape it.
  6730. //
  6731. // Worse, globbing of "file\?" in a directory with two files, "file?" and "file\?",
  6732. // returns "file\?" - which is WRONG: "file\?" pattern matches "file?" file.
  6733. // Without GLOB_NOMAGIC, this works correctly ("file?" is returned as a match).
  6734. // With GLOB_NOMAGIC | GLOB_NOCHECK, this also works correctly.
  6735. // i = glob(p, GLOB_NOMAGIC | GLOB_NOCHECK, NULL, &pglob);
  6736. // i = glob(p, GLOB_NOMAGIC, NULL, &pglob);
  6737. i = glob(p, 0, NULL, &pglob);
  6738. //bb_error_msg("glob('%s'):%d '%s'...", p, i, pglob.gl_pathv ? pglob.gl_pathv[0] : "-");
  6739. if (p != str->text)
  6740. free(p);
  6741. switch (i) {
  6742. case 0:
  6743. #if 0 // glibc 2.24.90 bug? Patterns like "*/file", when match, don't set GLOB_MAGCHAR
  6744. /* GLOB_MAGCHAR is set if *?[ chars were seen (GNU) */
  6745. if (!(pglob.gl_flags & GLOB_MAGCHAR))
  6746. goto nometa2;
  6747. #endif
  6748. addglob(&pglob);
  6749. globfree(&pglob);
  6750. INT_ON;
  6751. break;
  6752. case GLOB_NOMATCH:
  6753. //nometa2:
  6754. globfree(&pglob);
  6755. INT_ON;
  6756. nometa:
  6757. *exparg.lastp = str;
  6758. rmescapes(str->text, 0);
  6759. exparg.lastp = &str->next;
  6760. break;
  6761. default: /* GLOB_NOSPACE */
  6762. globfree(&pglob);
  6763. INT_ON;
  6764. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  6765. }
  6766. str = str->next;
  6767. }
  6768. }
  6769. #else
  6770. /* ENABLE_ASH_INTERNAL_GLOB: Homegrown globbing code. (dash also has both, uses homegrown one.) */
  6771. /*
  6772. * Do metacharacter (i.e. *, ?, [...]) expansion.
  6773. */
  6774. static void
  6775. expmeta(char *expdir, char *enddir, char *name)
  6776. {
  6777. char *p;
  6778. const char *cp;
  6779. char *start;
  6780. char *endname;
  6781. int metaflag;
  6782. struct stat statb;
  6783. DIR *dirp;
  6784. struct dirent *dp;
  6785. int atend;
  6786. int matchdot;
  6787. int esc;
  6788. metaflag = 0;
  6789. start = name;
  6790. for (p = name; esc = 0, *p; p += esc + 1) {
  6791. if (*p == '*' || *p == '?')
  6792. metaflag = 1;
  6793. else if (*p == '[') {
  6794. char *q = p + 1;
  6795. if (*q == '!')
  6796. q++;
  6797. for (;;) {
  6798. if (*q == '\\')
  6799. q++;
  6800. if (*q == '/' || *q == '\0')
  6801. break;
  6802. if (*++q == ']') {
  6803. metaflag = 1;
  6804. break;
  6805. }
  6806. }
  6807. } else {
  6808. if (*p == '\\')
  6809. esc++;
  6810. if (p[esc] == '/') {
  6811. if (metaflag)
  6812. break;
  6813. start = p + esc + 1;
  6814. }
  6815. }
  6816. }
  6817. if (metaflag == 0) { /* we've reached the end of the file name */
  6818. if (enddir != expdir)
  6819. metaflag++;
  6820. p = name;
  6821. do {
  6822. if (*p == '\\')
  6823. p++;
  6824. *enddir++ = *p;
  6825. } while (*p++);
  6826. if (metaflag == 0 || lstat(expdir, &statb) >= 0)
  6827. addfname(expdir);
  6828. return;
  6829. }
  6830. endname = p;
  6831. if (name < start) {
  6832. p = name;
  6833. do {
  6834. if (*p == '\\')
  6835. p++;
  6836. *enddir++ = *p++;
  6837. } while (p < start);
  6838. }
  6839. if (enddir == expdir) {
  6840. cp = ".";
  6841. } else if (enddir == expdir + 1 && *expdir == '/') {
  6842. cp = "/";
  6843. } else {
  6844. cp = expdir;
  6845. enddir[-1] = '\0';
  6846. }
  6847. dirp = opendir(cp);
  6848. if (dirp == NULL)
  6849. return;
  6850. if (enddir != expdir)
  6851. enddir[-1] = '/';
  6852. if (*endname == 0) {
  6853. atend = 1;
  6854. } else {
  6855. atend = 0;
  6856. *endname = '\0';
  6857. endname += esc + 1;
  6858. }
  6859. matchdot = 0;
  6860. p = start;
  6861. if (*p == '\\')
  6862. p++;
  6863. if (*p == '.')
  6864. matchdot++;
  6865. while (!pending_int && (dp = readdir(dirp)) != NULL) {
  6866. if (dp->d_name[0] == '.' && !matchdot)
  6867. continue;
  6868. if (pmatch(start, dp->d_name)) {
  6869. if (atend) {
  6870. strcpy(enddir, dp->d_name);
  6871. addfname(expdir);
  6872. } else {
  6873. for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
  6874. continue;
  6875. p[-1] = '/';
  6876. expmeta(expdir, p, endname);
  6877. }
  6878. }
  6879. }
  6880. closedir(dirp);
  6881. if (!atend)
  6882. endname[-esc - 1] = esc ? '\\' : '/';
  6883. }
  6884. static struct strlist *
  6885. msort(struct strlist *list, int len)
  6886. {
  6887. struct strlist *p, *q = NULL;
  6888. struct strlist **lpp;
  6889. int half;
  6890. int n;
  6891. if (len <= 1)
  6892. return list;
  6893. half = len >> 1;
  6894. p = list;
  6895. for (n = half; --n >= 0;) {
  6896. q = p;
  6897. p = p->next;
  6898. }
  6899. q->next = NULL; /* terminate first half of list */
  6900. q = msort(list, half); /* sort first half of list */
  6901. p = msort(p, len - half); /* sort second half */
  6902. lpp = &list;
  6903. for (;;) {
  6904. #if ENABLE_LOCALE_SUPPORT
  6905. if (strcoll(p->text, q->text) < 0)
  6906. #else
  6907. if (strcmp(p->text, q->text) < 0)
  6908. #endif
  6909. {
  6910. *lpp = p;
  6911. lpp = &p->next;
  6912. p = *lpp;
  6913. if (p == NULL) {
  6914. *lpp = q;
  6915. break;
  6916. }
  6917. } else {
  6918. *lpp = q;
  6919. lpp = &q->next;
  6920. q = *lpp;
  6921. if (q == NULL) {
  6922. *lpp = p;
  6923. break;
  6924. }
  6925. }
  6926. }
  6927. return list;
  6928. }
  6929. /*
  6930. * Sort the results of file name expansion. It calculates the number of
  6931. * strings to sort and then calls msort (short for merge sort) to do the
  6932. * work.
  6933. */
  6934. static struct strlist *
  6935. expsort(struct strlist *str)
  6936. {
  6937. int len;
  6938. struct strlist *sp;
  6939. len = 0;
  6940. for (sp = str; sp; sp = sp->next)
  6941. len++;
  6942. return msort(str, len);
  6943. }
  6944. static void
  6945. expandmeta(struct strlist *str /*, int flag*/)
  6946. {
  6947. /* TODO - EXP_REDIR */
  6948. while (str) {
  6949. char *expdir;
  6950. struct strlist **savelastp;
  6951. struct strlist *sp;
  6952. char *p;
  6953. if (fflag)
  6954. goto nometa;
  6955. if (!hasmeta(str->text))
  6956. goto nometa;
  6957. savelastp = exparg.lastp;
  6958. INT_OFF;
  6959. p = preglob(str->text, RMESCAPE_ALLOC | RMESCAPE_HEAP);
  6960. {
  6961. int i = strlen(str->text);
  6962. //BUGGY estimation of how long expanded name can be
  6963. expdir = ckmalloc(i < 2048 ? 2048 : i+1);
  6964. }
  6965. expmeta(expdir, expdir, p);
  6966. free(expdir);
  6967. if (p != str->text)
  6968. free(p);
  6969. INT_ON;
  6970. if (exparg.lastp == savelastp) {
  6971. /*
  6972. * no matches
  6973. */
  6974. nometa:
  6975. *exparg.lastp = str;
  6976. rmescapes(str->text, 0);
  6977. exparg.lastp = &str->next;
  6978. } else {
  6979. *exparg.lastp = NULL;
  6980. *savelastp = sp = expsort(*savelastp);
  6981. while (sp->next != NULL)
  6982. sp = sp->next;
  6983. exparg.lastp = &sp->next;
  6984. }
  6985. str = str->next;
  6986. }
  6987. }
  6988. #endif /* ENABLE_ASH_INTERNAL_GLOB */
  6989. /*
  6990. * Perform variable substitution and command substitution on an argument,
  6991. * placing the resulting list of arguments in arglist. If EXP_FULL is true,
  6992. * perform splitting and file name expansion. When arglist is NULL, perform
  6993. * here document expansion.
  6994. */
  6995. static void
  6996. expandarg(union node *arg, struct arglist *arglist, int flag)
  6997. {
  6998. struct strlist *sp;
  6999. char *p;
  7000. argbackq = arg->narg.backquote;
  7001. STARTSTACKSTR(expdest);
  7002. TRACE(("expandarg: argstr('%s',flags:%x)\n", arg->narg.text, flag));
  7003. argstr(arg->narg.text, flag);
  7004. p = _STPUTC('\0', expdest);
  7005. expdest = p - 1;
  7006. if (arglist == NULL) {
  7007. /* here document expanded */
  7008. goto out;
  7009. }
  7010. p = grabstackstr(p);
  7011. TRACE(("expandarg: p:'%s'\n", p));
  7012. exparg.lastp = &exparg.list;
  7013. /*
  7014. * TODO - EXP_REDIR
  7015. */
  7016. if (flag & EXP_FULL) {
  7017. ifsbreakup(p, &exparg);
  7018. *exparg.lastp = NULL;
  7019. exparg.lastp = &exparg.list;
  7020. expandmeta(exparg.list /*, flag*/);
  7021. } else {
  7022. sp = stzalloc(sizeof(*sp));
  7023. sp->text = p;
  7024. *exparg.lastp = sp;
  7025. exparg.lastp = &sp->next;
  7026. }
  7027. *exparg.lastp = NULL;
  7028. if (exparg.list) {
  7029. *arglist->lastp = exparg.list;
  7030. arglist->lastp = exparg.lastp;
  7031. }
  7032. out:
  7033. ifsfree();
  7034. }
  7035. /*
  7036. * Expand shell variables and backquotes inside a here document.
  7037. */
  7038. static void
  7039. expandhere(union node *arg, int fd)
  7040. {
  7041. expandarg(arg, (struct arglist *)NULL, EXP_QUOTED);
  7042. full_write(fd, stackblock(), expdest - (char *)stackblock());
  7043. }
  7044. /*
  7045. * Returns true if the pattern matches the string.
  7046. */
  7047. static int
  7048. patmatch(char *pattern, const char *string)
  7049. {
  7050. char *p = preglob(pattern, 0);
  7051. int r = pmatch(p, string);
  7052. //bb_error_msg("!fnmatch(pattern:'%s',str:'%s',0):%d", p, string, r);
  7053. return r;
  7054. }
  7055. /*
  7056. * See if a pattern matches in a case statement.
  7057. */
  7058. static int
  7059. casematch(union node *pattern, char *val)
  7060. {
  7061. struct stackmark smark;
  7062. int result;
  7063. setstackmark(&smark);
  7064. argbackq = pattern->narg.backquote;
  7065. STARTSTACKSTR(expdest);
  7066. argstr(pattern->narg.text, EXP_TILDE | EXP_CASE);
  7067. STACKSTRNUL(expdest);
  7068. ifsfree();
  7069. result = patmatch(stackblock(), val);
  7070. popstackmark(&smark);
  7071. return result;
  7072. }
  7073. /* ============ find_command */
  7074. struct builtincmd {
  7075. const char *name;
  7076. int (*builtin)(int, char **) FAST_FUNC;
  7077. /* unsigned flags; */
  7078. };
  7079. #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
  7080. /* "regular" builtins always take precedence over commands,
  7081. * regardless of PATH=....%builtin... position */
  7082. #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
  7083. #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
  7084. struct cmdentry {
  7085. smallint cmdtype; /* CMDxxx */
  7086. union param {
  7087. int index;
  7088. /* index >= 0 for commands without path (slashes) */
  7089. /* (TODO: what exactly does the value mean? PATH position?) */
  7090. /* index == -1 for commands with slashes */
  7091. /* index == (-2 - applet_no) for NOFORK applets */
  7092. const struct builtincmd *cmd;
  7093. struct funcnode *func;
  7094. } u;
  7095. };
  7096. /* values of cmdtype */
  7097. #define CMDUNKNOWN -1 /* no entry in table for command */
  7098. #define CMDNORMAL 0 /* command is an executable program */
  7099. #define CMDFUNCTION 1 /* command is a shell function */
  7100. #define CMDBUILTIN 2 /* command is a shell builtin */
  7101. /* action to find_command() */
  7102. #define DO_ERR 0x01 /* prints errors */
  7103. #define DO_ABS 0x02 /* checks absolute paths */
  7104. #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
  7105. #define DO_ALTPATH 0x08 /* using alternate path */
  7106. #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
  7107. static void find_command(char *, struct cmdentry *, int, const char *);
  7108. /* ============ Hashing commands */
  7109. /*
  7110. * When commands are first encountered, they are entered in a hash table.
  7111. * This ensures that a full path search will not have to be done for them
  7112. * on each invocation.
  7113. *
  7114. * We should investigate converting to a linear search, even though that
  7115. * would make the command name "hash" a misnomer.
  7116. */
  7117. struct tblentry {
  7118. struct tblentry *next; /* next entry in hash chain */
  7119. union param param; /* definition of builtin function */
  7120. smallint cmdtype; /* CMDxxx */
  7121. char rehash; /* if set, cd done since entry created */
  7122. char cmdname[1]; /* name of command */
  7123. };
  7124. static struct tblentry **cmdtable;
  7125. #define INIT_G_cmdtable() do { \
  7126. cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
  7127. } while (0)
  7128. static int builtinloc = -1; /* index in path of %builtin, or -1 */
  7129. static void
  7130. tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) const char *cmd, char **argv, char **envp)
  7131. {
  7132. #if ENABLE_FEATURE_SH_STANDALONE
  7133. if (applet_no >= 0) {
  7134. if (APPLET_IS_NOEXEC(applet_no)) {
  7135. clearenv();
  7136. while (*envp)
  7137. putenv(*envp++);
  7138. popredir(/*drop:*/ 1);
  7139. run_noexec_applet_and_exit(applet_no, cmd, argv);
  7140. }
  7141. /* re-exec ourselves with the new arguments */
  7142. execve(bb_busybox_exec_path, argv, envp);
  7143. /* If they called chroot or otherwise made the binary no longer
  7144. * executable, fall through */
  7145. }
  7146. #endif
  7147. repeat:
  7148. #ifdef SYSV
  7149. do {
  7150. execve(cmd, argv, envp);
  7151. } while (errno == EINTR);
  7152. #else
  7153. execve(cmd, argv, envp);
  7154. #endif
  7155. if (cmd != bb_busybox_exec_path && errno == ENOEXEC) {
  7156. /* Run "cmd" as a shell script:
  7157. * http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
  7158. * "If the execve() function fails with ENOEXEC, the shell
  7159. * shall execute a command equivalent to having a shell invoked
  7160. * with the command name as its first operand,
  7161. * with any remaining arguments passed to the new shell"
  7162. *
  7163. * That is, do not use $SHELL, user's shell, or /bin/sh;
  7164. * just call ourselves.
  7165. *
  7166. * Note that bash reads ~80 chars of the file, and if it sees
  7167. * a zero byte before it sees newline, it doesn't try to
  7168. * interpret it, but fails with "cannot execute binary file"
  7169. * message and exit code 126. For one, this prevents attempts
  7170. * to interpret foreign ELF binaries as shell scripts.
  7171. */
  7172. argv[0] = (char*) cmd;
  7173. cmd = bb_busybox_exec_path;
  7174. /* NB: this is only possible because all callers of shellexec()
  7175. * ensure that the argv[-1] slot exists!
  7176. */
  7177. argv--;
  7178. argv[0] = (char*) "ash";
  7179. goto repeat;
  7180. }
  7181. }
  7182. /*
  7183. * Exec a program. Never returns. If you change this routine, you may
  7184. * have to change the find_command routine as well.
  7185. * argv[-1] must exist and be writable! See tryexec() for why.
  7186. */
  7187. static void shellexec(char *prog, char **argv, const char *path, int idx) NORETURN;
  7188. static void shellexec(char *prog, char **argv, const char *path, int idx)
  7189. {
  7190. char *cmdname;
  7191. int e;
  7192. char **envp;
  7193. int exerrno;
  7194. int applet_no = -1; /* used only by FEATURE_SH_STANDALONE */
  7195. envp = listvars(VEXPORT, VUNSET, /*strlist:*/ NULL, /*end:*/ NULL);
  7196. if (strchr(prog, '/') != NULL
  7197. #if ENABLE_FEATURE_SH_STANDALONE
  7198. || (applet_no = find_applet_by_name(prog)) >= 0
  7199. #endif
  7200. ) {
  7201. tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) prog, argv, envp);
  7202. if (applet_no >= 0) {
  7203. /* We tried execing ourself, but it didn't work.
  7204. * Maybe /proc/self/exe doesn't exist?
  7205. * Try $PATH search.
  7206. */
  7207. goto try_PATH;
  7208. }
  7209. e = errno;
  7210. } else {
  7211. try_PATH:
  7212. e = ENOENT;
  7213. while ((cmdname = path_advance(&path, prog)) != NULL) {
  7214. if (--idx < 0 && pathopt == NULL) {
  7215. tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
  7216. if (errno != ENOENT && errno != ENOTDIR)
  7217. e = errno;
  7218. }
  7219. stunalloc(cmdname);
  7220. }
  7221. }
  7222. /* Map to POSIX errors */
  7223. switch (e) {
  7224. case EACCES:
  7225. exerrno = 126;
  7226. break;
  7227. case ENOENT:
  7228. exerrno = 127;
  7229. break;
  7230. default:
  7231. exerrno = 2;
  7232. break;
  7233. }
  7234. exitstatus = exerrno;
  7235. TRACE(("shellexec failed for %s, errno %d, suppress_int %d\n",
  7236. prog, e, suppress_int));
  7237. ash_msg_and_raise(EXEXIT, "%s: %s", prog, errmsg(e, "not found"));
  7238. /* NOTREACHED */
  7239. }
  7240. static void
  7241. printentry(struct tblentry *cmdp)
  7242. {
  7243. int idx;
  7244. const char *path;
  7245. char *name;
  7246. idx = cmdp->param.index;
  7247. path = pathval();
  7248. do {
  7249. name = path_advance(&path, cmdp->cmdname);
  7250. stunalloc(name);
  7251. } while (--idx >= 0);
  7252. out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
  7253. }
  7254. /*
  7255. * Clear out command entries. The argument specifies the first entry in
  7256. * PATH which has changed.
  7257. */
  7258. static void
  7259. clearcmdentry(int firstchange)
  7260. {
  7261. struct tblentry **tblp;
  7262. struct tblentry **pp;
  7263. struct tblentry *cmdp;
  7264. INT_OFF;
  7265. for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
  7266. pp = tblp;
  7267. while ((cmdp = *pp) != NULL) {
  7268. if ((cmdp->cmdtype == CMDNORMAL &&
  7269. cmdp->param.index >= firstchange)
  7270. || (cmdp->cmdtype == CMDBUILTIN &&
  7271. builtinloc >= firstchange)
  7272. ) {
  7273. *pp = cmdp->next;
  7274. free(cmdp);
  7275. } else {
  7276. pp = &cmdp->next;
  7277. }
  7278. }
  7279. }
  7280. INT_ON;
  7281. }
  7282. /*
  7283. * Locate a command in the command hash table. If "add" is nonzero,
  7284. * add the command to the table if it is not already present. The
  7285. * variable "lastcmdentry" is set to point to the address of the link
  7286. * pointing to the entry, so that delete_cmd_entry can delete the
  7287. * entry.
  7288. *
  7289. * Interrupts must be off if called with add != 0.
  7290. */
  7291. static struct tblentry **lastcmdentry;
  7292. static struct tblentry *
  7293. cmdlookup(const char *name, int add)
  7294. {
  7295. unsigned int hashval;
  7296. const char *p;
  7297. struct tblentry *cmdp;
  7298. struct tblentry **pp;
  7299. p = name;
  7300. hashval = (unsigned char)*p << 4;
  7301. while (*p)
  7302. hashval += (unsigned char)*p++;
  7303. hashval &= 0x7FFF;
  7304. pp = &cmdtable[hashval % CMDTABLESIZE];
  7305. for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
  7306. if (strcmp(cmdp->cmdname, name) == 0)
  7307. break;
  7308. pp = &cmdp->next;
  7309. }
  7310. if (add && cmdp == NULL) {
  7311. cmdp = *pp = ckzalloc(sizeof(struct tblentry)
  7312. + strlen(name)
  7313. /* + 1 - already done because
  7314. * tblentry::cmdname is char[1] */);
  7315. /*cmdp->next = NULL; - ckzalloc did it */
  7316. cmdp->cmdtype = CMDUNKNOWN;
  7317. strcpy(cmdp->cmdname, name);
  7318. }
  7319. lastcmdentry = pp;
  7320. return cmdp;
  7321. }
  7322. /*
  7323. * Delete the command entry returned on the last lookup.
  7324. */
  7325. static void
  7326. delete_cmd_entry(void)
  7327. {
  7328. struct tblentry *cmdp;
  7329. INT_OFF;
  7330. cmdp = *lastcmdentry;
  7331. *lastcmdentry = cmdp->next;
  7332. if (cmdp->cmdtype == CMDFUNCTION)
  7333. freefunc(cmdp->param.func);
  7334. free(cmdp);
  7335. INT_ON;
  7336. }
  7337. /*
  7338. * Add a new command entry, replacing any existing command entry for
  7339. * the same name - except special builtins.
  7340. */
  7341. static void
  7342. addcmdentry(char *name, struct cmdentry *entry)
  7343. {
  7344. struct tblentry *cmdp;
  7345. cmdp = cmdlookup(name, 1);
  7346. if (cmdp->cmdtype == CMDFUNCTION) {
  7347. freefunc(cmdp->param.func);
  7348. }
  7349. cmdp->cmdtype = entry->cmdtype;
  7350. cmdp->param = entry->u;
  7351. cmdp->rehash = 0;
  7352. }
  7353. static int FAST_FUNC
  7354. hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  7355. {
  7356. struct tblentry **pp;
  7357. struct tblentry *cmdp;
  7358. int c;
  7359. struct cmdentry entry;
  7360. char *name;
  7361. if (nextopt("r") != '\0') {
  7362. clearcmdentry(0);
  7363. return 0;
  7364. }
  7365. if (*argptr == NULL) {
  7366. for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
  7367. for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
  7368. if (cmdp->cmdtype == CMDNORMAL)
  7369. printentry(cmdp);
  7370. }
  7371. }
  7372. return 0;
  7373. }
  7374. c = 0;
  7375. while ((name = *argptr) != NULL) {
  7376. cmdp = cmdlookup(name, 0);
  7377. if (cmdp != NULL
  7378. && (cmdp->cmdtype == CMDNORMAL
  7379. || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
  7380. ) {
  7381. delete_cmd_entry();
  7382. }
  7383. find_command(name, &entry, DO_ERR, pathval());
  7384. if (entry.cmdtype == CMDUNKNOWN)
  7385. c = 1;
  7386. argptr++;
  7387. }
  7388. return c;
  7389. }
  7390. /*
  7391. * Called when a cd is done. Marks all commands so the next time they
  7392. * are executed they will be rehashed.
  7393. */
  7394. static void
  7395. hashcd(void)
  7396. {
  7397. struct tblentry **pp;
  7398. struct tblentry *cmdp;
  7399. for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
  7400. for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
  7401. if (cmdp->cmdtype == CMDNORMAL
  7402. || (cmdp->cmdtype == CMDBUILTIN
  7403. && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
  7404. && builtinloc > 0)
  7405. ) {
  7406. cmdp->rehash = 1;
  7407. }
  7408. }
  7409. }
  7410. }
  7411. /*
  7412. * Fix command hash table when PATH changed.
  7413. * Called before PATH is changed. The argument is the new value of PATH;
  7414. * pathval() still returns the old value at this point.
  7415. * Called with interrupts off.
  7416. */
  7417. static void FAST_FUNC
  7418. changepath(const char *new)
  7419. {
  7420. const char *old;
  7421. int firstchange;
  7422. int idx;
  7423. int idx_bltin;
  7424. old = pathval();
  7425. firstchange = 9999; /* assume no change */
  7426. idx = 0;
  7427. idx_bltin = -1;
  7428. for (;;) {
  7429. if (*old != *new) {
  7430. firstchange = idx;
  7431. if ((*old == '\0' && *new == ':')
  7432. || (*old == ':' && *new == '\0')
  7433. ) {
  7434. firstchange++;
  7435. }
  7436. old = new; /* ignore subsequent differences */
  7437. }
  7438. if (*new == '\0')
  7439. break;
  7440. if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
  7441. idx_bltin = idx;
  7442. if (*new == ':')
  7443. idx++;
  7444. new++;
  7445. old++;
  7446. }
  7447. if (builtinloc < 0 && idx_bltin >= 0)
  7448. builtinloc = idx_bltin; /* zap builtins */
  7449. if (builtinloc >= 0 && idx_bltin < 0)
  7450. firstchange = 0;
  7451. clearcmdentry(firstchange);
  7452. builtinloc = idx_bltin;
  7453. }
  7454. enum {
  7455. TEOF,
  7456. TNL,
  7457. TREDIR,
  7458. TWORD,
  7459. TSEMI,
  7460. TBACKGND,
  7461. TAND,
  7462. TOR,
  7463. TPIPE,
  7464. TLP,
  7465. TRP,
  7466. TENDCASE,
  7467. TENDBQUOTE,
  7468. TNOT,
  7469. TCASE,
  7470. TDO,
  7471. TDONE,
  7472. TELIF,
  7473. TELSE,
  7474. TESAC,
  7475. TFI,
  7476. TFOR,
  7477. #if BASH_FUNCTION
  7478. TFUNCTION,
  7479. #endif
  7480. TIF,
  7481. TIN,
  7482. TTHEN,
  7483. TUNTIL,
  7484. TWHILE,
  7485. TBEGIN,
  7486. TEND
  7487. };
  7488. typedef smallint token_id_t;
  7489. /* Nth bit indicates if token marks the end of a list */
  7490. enum {
  7491. tokendlist = 0
  7492. /* 0 */ | (1u << TEOF)
  7493. /* 1 */ | (0u << TNL)
  7494. /* 2 */ | (0u << TREDIR)
  7495. /* 3 */ | (0u << TWORD)
  7496. /* 4 */ | (0u << TSEMI)
  7497. /* 5 */ | (0u << TBACKGND)
  7498. /* 6 */ | (0u << TAND)
  7499. /* 7 */ | (0u << TOR)
  7500. /* 8 */ | (0u << TPIPE)
  7501. /* 9 */ | (0u << TLP)
  7502. /* 10 */ | (1u << TRP)
  7503. /* 11 */ | (1u << TENDCASE)
  7504. /* 12 */ | (1u << TENDBQUOTE)
  7505. /* 13 */ | (0u << TNOT)
  7506. /* 14 */ | (0u << TCASE)
  7507. /* 15 */ | (1u << TDO)
  7508. /* 16 */ | (1u << TDONE)
  7509. /* 17 */ | (1u << TELIF)
  7510. /* 18 */ | (1u << TELSE)
  7511. /* 19 */ | (1u << TESAC)
  7512. /* 20 */ | (1u << TFI)
  7513. /* 21 */ | (0u << TFOR)
  7514. #if BASH_FUNCTION
  7515. /* 22 */ | (0u << TFUNCTION)
  7516. #endif
  7517. /* 23 */ | (0u << TIF)
  7518. /* 24 */ | (0u << TIN)
  7519. /* 25 */ | (1u << TTHEN)
  7520. /* 26 */ | (0u << TUNTIL)
  7521. /* 27 */ | (0u << TWHILE)
  7522. /* 28 */ | (0u << TBEGIN)
  7523. /* 29 */ | (1u << TEND)
  7524. , /* thus far 29 bits used */
  7525. };
  7526. static const char *const tokname_array[] = {
  7527. "end of file",
  7528. "newline",
  7529. "redirection",
  7530. "word",
  7531. ";",
  7532. "&",
  7533. "&&",
  7534. "||",
  7535. "|",
  7536. "(",
  7537. ")",
  7538. ";;",
  7539. "`",
  7540. #define KWDOFFSET 13
  7541. /* the following are keywords */
  7542. "!",
  7543. "case",
  7544. "do",
  7545. "done",
  7546. "elif",
  7547. "else",
  7548. "esac",
  7549. "fi",
  7550. "for",
  7551. #if BASH_FUNCTION
  7552. "function",
  7553. #endif
  7554. "if",
  7555. "in",
  7556. "then",
  7557. "until",
  7558. "while",
  7559. "{",
  7560. "}",
  7561. };
  7562. /* Wrapper around strcmp for qsort/bsearch/... */
  7563. static int
  7564. pstrcmp(const void *a, const void *b)
  7565. {
  7566. return strcmp((char*)a, *(char**)b);
  7567. }
  7568. static const char *const *
  7569. findkwd(const char *s)
  7570. {
  7571. return bsearch(s, tokname_array + KWDOFFSET,
  7572. ARRAY_SIZE(tokname_array) - KWDOFFSET,
  7573. sizeof(tokname_array[0]), pstrcmp);
  7574. }
  7575. /*
  7576. * Locate and print what a word is...
  7577. */
  7578. static int
  7579. describe_command(char *command, const char *path, int describe_command_verbose)
  7580. {
  7581. struct cmdentry entry;
  7582. #if ENABLE_ASH_ALIAS
  7583. const struct alias *ap;
  7584. #endif
  7585. path = path ? path : pathval();
  7586. if (describe_command_verbose) {
  7587. out1str(command);
  7588. }
  7589. /* First look at the keywords */
  7590. if (findkwd(command)) {
  7591. out1str(describe_command_verbose ? " is a shell keyword" : command);
  7592. goto out;
  7593. }
  7594. #if ENABLE_ASH_ALIAS
  7595. /* Then look at the aliases */
  7596. ap = lookupalias(command, 0);
  7597. if (ap != NULL) {
  7598. if (!describe_command_verbose) {
  7599. out1str("alias ");
  7600. printalias(ap);
  7601. return 0;
  7602. }
  7603. out1fmt(" is an alias for %s", ap->val);
  7604. goto out;
  7605. }
  7606. #endif
  7607. /* Brute force */
  7608. find_command(command, &entry, DO_ABS, path);
  7609. switch (entry.cmdtype) {
  7610. case CMDNORMAL: {
  7611. int j = entry.u.index;
  7612. char *p;
  7613. if (j < 0) {
  7614. p = command;
  7615. } else {
  7616. do {
  7617. p = path_advance(&path, command);
  7618. stunalloc(p);
  7619. } while (--j >= 0);
  7620. }
  7621. if (describe_command_verbose) {
  7622. out1fmt(" is %s", p);
  7623. } else {
  7624. out1str(p);
  7625. }
  7626. break;
  7627. }
  7628. case CMDFUNCTION:
  7629. if (describe_command_verbose) {
  7630. out1str(" is a shell function");
  7631. } else {
  7632. out1str(command);
  7633. }
  7634. break;
  7635. case CMDBUILTIN:
  7636. if (describe_command_verbose) {
  7637. out1fmt(" is a %sshell builtin",
  7638. IS_BUILTIN_SPECIAL(entry.u.cmd) ?
  7639. "special " : nullstr
  7640. );
  7641. } else {
  7642. out1str(command);
  7643. }
  7644. break;
  7645. default:
  7646. if (describe_command_verbose) {
  7647. out1str(": not found\n");
  7648. }
  7649. return 127;
  7650. }
  7651. out:
  7652. out1str("\n");
  7653. return 0;
  7654. }
  7655. static int FAST_FUNC
  7656. typecmd(int argc UNUSED_PARAM, char **argv)
  7657. {
  7658. int i = 1;
  7659. int err = 0;
  7660. int verbose = 1;
  7661. /* type -p ... ? (we don't bother checking for 'p') */
  7662. if (argv[1] && argv[1][0] == '-') {
  7663. i++;
  7664. verbose = 0;
  7665. }
  7666. while (argv[i]) {
  7667. err |= describe_command(argv[i++], NULL, verbose);
  7668. }
  7669. return err;
  7670. }
  7671. #if ENABLE_ASH_CMDCMD
  7672. /* Is it "command [-p] PROG ARGS" bltin, no other opts? Return ptr to "PROG" if yes */
  7673. static char **
  7674. parse_command_args(char **argv, const char **path)
  7675. {
  7676. char *cp, c;
  7677. for (;;) {
  7678. cp = *++argv;
  7679. if (!cp)
  7680. return NULL;
  7681. if (*cp++ != '-')
  7682. break;
  7683. c = *cp++;
  7684. if (!c)
  7685. break;
  7686. if (c == '-' && !*cp) {
  7687. if (!*++argv)
  7688. return NULL;
  7689. break;
  7690. }
  7691. do {
  7692. switch (c) {
  7693. case 'p':
  7694. *path = bb_default_path;
  7695. break;
  7696. default:
  7697. /* run 'typecmd' for other options */
  7698. return NULL;
  7699. }
  7700. c = *cp++;
  7701. } while (c);
  7702. }
  7703. return argv;
  7704. }
  7705. static int FAST_FUNC
  7706. commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  7707. {
  7708. char *cmd;
  7709. int c;
  7710. enum {
  7711. VERIFY_BRIEF = 1,
  7712. VERIFY_VERBOSE = 2,
  7713. } verify = 0;
  7714. const char *path = NULL;
  7715. /* "command [-p] PROG ARGS" (that is, without -V or -v)
  7716. * never reaches this function.
  7717. */
  7718. while ((c = nextopt("pvV")) != '\0')
  7719. if (c == 'V')
  7720. verify |= VERIFY_VERBOSE;
  7721. else if (c == 'v')
  7722. /*verify |= VERIFY_BRIEF*/;
  7723. #if DEBUG
  7724. else if (c != 'p')
  7725. abort();
  7726. #endif
  7727. else
  7728. path = bb_default_path;
  7729. /* Mimic bash: just "command -v" doesn't complain, it's a nop */
  7730. cmd = *argptr;
  7731. if (/*verify && */ cmd)
  7732. return describe_command(cmd, path, verify /* - VERIFY_BRIEF*/);
  7733. return 0;
  7734. }
  7735. #endif
  7736. /*static int funcblocksize; // size of structures in function */
  7737. /*static int funcstringsize; // size of strings in node */
  7738. static void *funcblock; /* block to allocate function from */
  7739. static char *funcstring_end; /* end of block to allocate strings from */
  7740. static const uint8_t nodesize[N_NUMBER] ALIGN1 = {
  7741. [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
  7742. [NPIPE ] = SHELL_ALIGN(sizeof(struct npipe)),
  7743. [NREDIR ] = SHELL_ALIGN(sizeof(struct nredir)),
  7744. [NBACKGND ] = SHELL_ALIGN(sizeof(struct nredir)),
  7745. [NSUBSHELL] = SHELL_ALIGN(sizeof(struct nredir)),
  7746. [NAND ] = SHELL_ALIGN(sizeof(struct nbinary)),
  7747. [NOR ] = SHELL_ALIGN(sizeof(struct nbinary)),
  7748. [NSEMI ] = SHELL_ALIGN(sizeof(struct nbinary)),
  7749. [NIF ] = SHELL_ALIGN(sizeof(struct nif)),
  7750. [NWHILE ] = SHELL_ALIGN(sizeof(struct nbinary)),
  7751. [NUNTIL ] = SHELL_ALIGN(sizeof(struct nbinary)),
  7752. [NFOR ] = SHELL_ALIGN(sizeof(struct nfor)),
  7753. [NCASE ] = SHELL_ALIGN(sizeof(struct ncase)),
  7754. [NCLIST ] = SHELL_ALIGN(sizeof(struct nclist)),
  7755. [NDEFUN ] = SHELL_ALIGN(sizeof(struct narg)),
  7756. [NARG ] = SHELL_ALIGN(sizeof(struct narg)),
  7757. [NTO ] = SHELL_ALIGN(sizeof(struct nfile)),
  7758. #if BASH_REDIR_OUTPUT
  7759. [NTO2 ] = SHELL_ALIGN(sizeof(struct nfile)),
  7760. #endif
  7761. [NCLOBBER ] = SHELL_ALIGN(sizeof(struct nfile)),
  7762. [NFROM ] = SHELL_ALIGN(sizeof(struct nfile)),
  7763. [NFROMTO ] = SHELL_ALIGN(sizeof(struct nfile)),
  7764. [NAPPEND ] = SHELL_ALIGN(sizeof(struct nfile)),
  7765. [NTOFD ] = SHELL_ALIGN(sizeof(struct ndup)),
  7766. [NFROMFD ] = SHELL_ALIGN(sizeof(struct ndup)),
  7767. [NHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
  7768. [NXHERE ] = SHELL_ALIGN(sizeof(struct nhere)),
  7769. [NNOT ] = SHELL_ALIGN(sizeof(struct nnot)),
  7770. };
  7771. static int calcsize(int funcblocksize, union node *n);
  7772. static int
  7773. sizenodelist(int funcblocksize, struct nodelist *lp)
  7774. {
  7775. while (lp) {
  7776. funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
  7777. funcblocksize = calcsize(funcblocksize, lp->n);
  7778. lp = lp->next;
  7779. }
  7780. return funcblocksize;
  7781. }
  7782. static int
  7783. calcsize(int funcblocksize, union node *n)
  7784. {
  7785. if (n == NULL)
  7786. return funcblocksize;
  7787. funcblocksize += nodesize[n->type];
  7788. switch (n->type) {
  7789. case NCMD:
  7790. funcblocksize = calcsize(funcblocksize, n->ncmd.redirect);
  7791. funcblocksize = calcsize(funcblocksize, n->ncmd.args);
  7792. funcblocksize = calcsize(funcblocksize, n->ncmd.assign);
  7793. break;
  7794. case NPIPE:
  7795. funcblocksize = sizenodelist(funcblocksize, n->npipe.cmdlist);
  7796. break;
  7797. case NREDIR:
  7798. case NBACKGND:
  7799. case NSUBSHELL:
  7800. funcblocksize = calcsize(funcblocksize, n->nredir.redirect);
  7801. funcblocksize = calcsize(funcblocksize, n->nredir.n);
  7802. break;
  7803. case NAND:
  7804. case NOR:
  7805. case NSEMI:
  7806. case NWHILE:
  7807. case NUNTIL:
  7808. funcblocksize = calcsize(funcblocksize, n->nbinary.ch2);
  7809. funcblocksize = calcsize(funcblocksize, n->nbinary.ch1);
  7810. break;
  7811. case NIF:
  7812. funcblocksize = calcsize(funcblocksize, n->nif.elsepart);
  7813. funcblocksize = calcsize(funcblocksize, n->nif.ifpart);
  7814. funcblocksize = calcsize(funcblocksize, n->nif.test);
  7815. break;
  7816. case NFOR:
  7817. funcblocksize += SHELL_ALIGN(strlen(n->nfor.var) + 1); /* was funcstringsize += ... */
  7818. funcblocksize = calcsize(funcblocksize, n->nfor.body);
  7819. funcblocksize = calcsize(funcblocksize, n->nfor.args);
  7820. break;
  7821. case NCASE:
  7822. funcblocksize = calcsize(funcblocksize, n->ncase.cases);
  7823. funcblocksize = calcsize(funcblocksize, n->ncase.expr);
  7824. break;
  7825. case NCLIST:
  7826. funcblocksize = calcsize(funcblocksize, n->nclist.body);
  7827. funcblocksize = calcsize(funcblocksize, n->nclist.pattern);
  7828. funcblocksize = calcsize(funcblocksize, n->nclist.next);
  7829. break;
  7830. case NDEFUN:
  7831. case NARG:
  7832. funcblocksize = sizenodelist(funcblocksize, n->narg.backquote);
  7833. funcblocksize += SHELL_ALIGN(strlen(n->narg.text) + 1); /* was funcstringsize += ... */
  7834. funcblocksize = calcsize(funcblocksize, n->narg.next);
  7835. break;
  7836. case NTO:
  7837. #if BASH_REDIR_OUTPUT
  7838. case NTO2:
  7839. #endif
  7840. case NCLOBBER:
  7841. case NFROM:
  7842. case NFROMTO:
  7843. case NAPPEND:
  7844. funcblocksize = calcsize(funcblocksize, n->nfile.fname);
  7845. funcblocksize = calcsize(funcblocksize, n->nfile.next);
  7846. break;
  7847. case NTOFD:
  7848. case NFROMFD:
  7849. funcblocksize = calcsize(funcblocksize, n->ndup.vname);
  7850. funcblocksize = calcsize(funcblocksize, n->ndup.next);
  7851. break;
  7852. case NHERE:
  7853. case NXHERE:
  7854. funcblocksize = calcsize(funcblocksize, n->nhere.doc);
  7855. funcblocksize = calcsize(funcblocksize, n->nhere.next);
  7856. break;
  7857. case NNOT:
  7858. funcblocksize = calcsize(funcblocksize, n->nnot.com);
  7859. break;
  7860. };
  7861. return funcblocksize;
  7862. }
  7863. static char *
  7864. nodeckstrdup(char *s)
  7865. {
  7866. funcstring_end -= SHELL_ALIGN(strlen(s) + 1);
  7867. return strcpy(funcstring_end, s);
  7868. }
  7869. static union node *copynode(union node *);
  7870. static struct nodelist *
  7871. copynodelist(struct nodelist *lp)
  7872. {
  7873. struct nodelist *start;
  7874. struct nodelist **lpp;
  7875. lpp = &start;
  7876. while (lp) {
  7877. *lpp = funcblock;
  7878. funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
  7879. (*lpp)->n = copynode(lp->n);
  7880. lp = lp->next;
  7881. lpp = &(*lpp)->next;
  7882. }
  7883. *lpp = NULL;
  7884. return start;
  7885. }
  7886. static union node *
  7887. copynode(union node *n)
  7888. {
  7889. union node *new;
  7890. if (n == NULL)
  7891. return NULL;
  7892. new = funcblock;
  7893. funcblock = (char *) funcblock + nodesize[n->type];
  7894. switch (n->type) {
  7895. case NCMD:
  7896. new->ncmd.redirect = copynode(n->ncmd.redirect);
  7897. new->ncmd.args = copynode(n->ncmd.args);
  7898. new->ncmd.assign = copynode(n->ncmd.assign);
  7899. break;
  7900. case NPIPE:
  7901. new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
  7902. new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
  7903. break;
  7904. case NREDIR:
  7905. case NBACKGND:
  7906. case NSUBSHELL:
  7907. new->nredir.redirect = copynode(n->nredir.redirect);
  7908. new->nredir.n = copynode(n->nredir.n);
  7909. break;
  7910. case NAND:
  7911. case NOR:
  7912. case NSEMI:
  7913. case NWHILE:
  7914. case NUNTIL:
  7915. new->nbinary.ch2 = copynode(n->nbinary.ch2);
  7916. new->nbinary.ch1 = copynode(n->nbinary.ch1);
  7917. break;
  7918. case NIF:
  7919. new->nif.elsepart = copynode(n->nif.elsepart);
  7920. new->nif.ifpart = copynode(n->nif.ifpart);
  7921. new->nif.test = copynode(n->nif.test);
  7922. break;
  7923. case NFOR:
  7924. new->nfor.var = nodeckstrdup(n->nfor.var);
  7925. new->nfor.body = copynode(n->nfor.body);
  7926. new->nfor.args = copynode(n->nfor.args);
  7927. break;
  7928. case NCASE:
  7929. new->ncase.cases = copynode(n->ncase.cases);
  7930. new->ncase.expr = copynode(n->ncase.expr);
  7931. break;
  7932. case NCLIST:
  7933. new->nclist.body = copynode(n->nclist.body);
  7934. new->nclist.pattern = copynode(n->nclist.pattern);
  7935. new->nclist.next = copynode(n->nclist.next);
  7936. break;
  7937. case NDEFUN:
  7938. case NARG:
  7939. new->narg.backquote = copynodelist(n->narg.backquote);
  7940. new->narg.text = nodeckstrdup(n->narg.text);
  7941. new->narg.next = copynode(n->narg.next);
  7942. break;
  7943. case NTO:
  7944. #if BASH_REDIR_OUTPUT
  7945. case NTO2:
  7946. #endif
  7947. case NCLOBBER:
  7948. case NFROM:
  7949. case NFROMTO:
  7950. case NAPPEND:
  7951. new->nfile.fname = copynode(n->nfile.fname);
  7952. new->nfile.fd = n->nfile.fd;
  7953. new->nfile.next = copynode(n->nfile.next);
  7954. break;
  7955. case NTOFD:
  7956. case NFROMFD:
  7957. new->ndup.vname = copynode(n->ndup.vname);
  7958. new->ndup.dupfd = n->ndup.dupfd;
  7959. new->ndup.fd = n->ndup.fd;
  7960. new->ndup.next = copynode(n->ndup.next);
  7961. break;
  7962. case NHERE:
  7963. case NXHERE:
  7964. new->nhere.doc = copynode(n->nhere.doc);
  7965. new->nhere.fd = n->nhere.fd;
  7966. new->nhere.next = copynode(n->nhere.next);
  7967. break;
  7968. case NNOT:
  7969. new->nnot.com = copynode(n->nnot.com);
  7970. break;
  7971. };
  7972. new->type = n->type;
  7973. return new;
  7974. }
  7975. /*
  7976. * Make a copy of a parse tree.
  7977. */
  7978. static struct funcnode *
  7979. copyfunc(union node *n)
  7980. {
  7981. struct funcnode *f;
  7982. size_t blocksize;
  7983. /*funcstringsize = 0;*/
  7984. blocksize = offsetof(struct funcnode, n) + calcsize(0, n);
  7985. f = ckzalloc(blocksize /* + funcstringsize */);
  7986. funcblock = (char *) f + offsetof(struct funcnode, n);
  7987. funcstring_end = (char *) f + blocksize;
  7988. copynode(n);
  7989. /* f->count = 0; - ckzalloc did it */
  7990. return f;
  7991. }
  7992. /*
  7993. * Define a shell function.
  7994. */
  7995. static void
  7996. defun(union node *func)
  7997. {
  7998. struct cmdentry entry;
  7999. INT_OFF;
  8000. entry.cmdtype = CMDFUNCTION;
  8001. entry.u.func = copyfunc(func);
  8002. addcmdentry(func->narg.text, &entry);
  8003. INT_ON;
  8004. }
  8005. /* Reasons for skipping commands (see comment on breakcmd routine) */
  8006. #define SKIPBREAK (1 << 0)
  8007. #define SKIPCONT (1 << 1)
  8008. #define SKIPFUNC (1 << 2)
  8009. static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
  8010. static int skipcount; /* number of levels to skip */
  8011. static int funcnest; /* depth of function calls */
  8012. static int loopnest; /* current loop nesting level */
  8013. /* Forward decl way out to parsing code - dotrap needs it */
  8014. static int evalstring(char *s, int flags);
  8015. /* Called to execute a trap.
  8016. * Single callsite - at the end of evaltree().
  8017. * If we return non-zero, evaltree raises EXEXIT exception.
  8018. *
  8019. * Perhaps we should avoid entering new trap handlers
  8020. * while we are executing a trap handler. [is it a TODO?]
  8021. */
  8022. static void
  8023. dotrap(void)
  8024. {
  8025. uint8_t *g;
  8026. int sig;
  8027. uint8_t last_status;
  8028. if (!pending_sig)
  8029. return;
  8030. last_status = exitstatus;
  8031. pending_sig = 0;
  8032. barrier();
  8033. TRACE(("dotrap entered\n"));
  8034. for (sig = 1, g = gotsig; sig < NSIG; sig++, g++) {
  8035. char *p;
  8036. if (!*g)
  8037. continue;
  8038. if (evalskip) {
  8039. pending_sig = sig;
  8040. break;
  8041. }
  8042. p = trap[sig];
  8043. /* non-trapped SIGINT is handled separately by raise_interrupt,
  8044. * don't upset it by resetting gotsig[SIGINT-1] */
  8045. if (sig == SIGINT && !p)
  8046. continue;
  8047. TRACE(("sig %d is active, will run handler '%s'\n", sig, p));
  8048. *g = 0;
  8049. if (!p)
  8050. continue;
  8051. evalstring(p, 0);
  8052. }
  8053. exitstatus = last_status;
  8054. TRACE(("dotrap returns\n"));
  8055. }
  8056. /* forward declarations - evaluation is fairly recursive business... */
  8057. static int evalloop(union node *, int);
  8058. static int evalfor(union node *, int);
  8059. static int evalcase(union node *, int);
  8060. static int evalsubshell(union node *, int);
  8061. static void expredir(union node *);
  8062. static int evalpipe(union node *, int);
  8063. static int evalcommand(union node *, int);
  8064. static int evalbltin(const struct builtincmd *, int, char **, int);
  8065. static void prehash(union node *);
  8066. /*
  8067. * Evaluate a parse tree. The value is left in the global variable
  8068. * exitstatus.
  8069. */
  8070. static int
  8071. evaltree(union node *n, int flags)
  8072. {
  8073. int checkexit = 0;
  8074. int (*evalfn)(union node *, int);
  8075. int status = 0;
  8076. if (n == NULL) {
  8077. TRACE(("evaltree(NULL) called\n"));
  8078. goto out;
  8079. }
  8080. TRACE(("evaltree(%p: %d, %d) called\n", n, n->type, flags));
  8081. dotrap();
  8082. switch (n->type) {
  8083. default:
  8084. #if DEBUG
  8085. out1fmt("Node type = %d\n", n->type);
  8086. fflush_all();
  8087. break;
  8088. #endif
  8089. case NNOT:
  8090. status = !evaltree(n->nnot.com, EV_TESTED);
  8091. goto setstatus;
  8092. case NREDIR:
  8093. expredir(n->nredir.redirect);
  8094. pushredir(n->nredir.redirect);
  8095. status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
  8096. if (!status) {
  8097. status = evaltree(n->nredir.n, flags & EV_TESTED);
  8098. }
  8099. if (n->nredir.redirect)
  8100. popredir(/*drop:*/ 0);
  8101. goto setstatus;
  8102. case NCMD:
  8103. evalfn = evalcommand;
  8104. checkexit:
  8105. if (eflag && !(flags & EV_TESTED))
  8106. checkexit = ~0;
  8107. goto calleval;
  8108. case NFOR:
  8109. evalfn = evalfor;
  8110. goto calleval;
  8111. case NWHILE:
  8112. case NUNTIL:
  8113. evalfn = evalloop;
  8114. goto calleval;
  8115. case NSUBSHELL:
  8116. case NBACKGND:
  8117. evalfn = evalsubshell;
  8118. goto checkexit;
  8119. case NPIPE:
  8120. evalfn = evalpipe;
  8121. goto checkexit;
  8122. case NCASE:
  8123. evalfn = evalcase;
  8124. goto calleval;
  8125. case NAND:
  8126. case NOR:
  8127. case NSEMI: {
  8128. #if NAND + 1 != NOR
  8129. #error NAND + 1 != NOR
  8130. #endif
  8131. #if NOR + 1 != NSEMI
  8132. #error NOR + 1 != NSEMI
  8133. #endif
  8134. unsigned is_or = n->type - NAND;
  8135. status = evaltree(
  8136. n->nbinary.ch1,
  8137. (flags | ((is_or >> 1) - 1)) & EV_TESTED
  8138. );
  8139. if ((!status) == is_or || evalskip)
  8140. break;
  8141. n = n->nbinary.ch2;
  8142. evaln:
  8143. evalfn = evaltree;
  8144. calleval:
  8145. status = evalfn(n, flags);
  8146. goto setstatus;
  8147. }
  8148. case NIF:
  8149. status = evaltree(n->nif.test, EV_TESTED);
  8150. if (evalskip)
  8151. break;
  8152. if (!status) {
  8153. n = n->nif.ifpart;
  8154. goto evaln;
  8155. }
  8156. if (n->nif.elsepart) {
  8157. n = n->nif.elsepart;
  8158. goto evaln;
  8159. }
  8160. status = 0;
  8161. goto setstatus;
  8162. case NDEFUN:
  8163. defun(n);
  8164. /* Not necessary. To test it:
  8165. * "false; f() { qwerty; }; echo $?" should print 0.
  8166. */
  8167. /* status = 0; */
  8168. setstatus:
  8169. exitstatus = status;
  8170. break;
  8171. }
  8172. out:
  8173. /* Order of checks below is important:
  8174. * signal handlers trigger before exit caused by "set -e".
  8175. */
  8176. dotrap();
  8177. if (checkexit & status)
  8178. raise_exception(EXEXIT);
  8179. if (flags & EV_EXIT)
  8180. raise_exception(EXEXIT);
  8181. TRACE(("leaving evaltree (no interrupts)\n"));
  8182. return exitstatus;
  8183. }
  8184. static int
  8185. skiploop(void)
  8186. {
  8187. int skip = evalskip;
  8188. switch (skip) {
  8189. case 0:
  8190. break;
  8191. case SKIPBREAK:
  8192. case SKIPCONT:
  8193. if (--skipcount <= 0) {
  8194. evalskip = 0;
  8195. break;
  8196. }
  8197. skip = SKIPBREAK;
  8198. break;
  8199. }
  8200. return skip;
  8201. }
  8202. static int
  8203. evalloop(union node *n, int flags)
  8204. {
  8205. int skip;
  8206. int status;
  8207. loopnest++;
  8208. status = 0;
  8209. flags &= EV_TESTED;
  8210. do {
  8211. int i;
  8212. i = evaltree(n->nbinary.ch1, EV_TESTED);
  8213. skip = skiploop();
  8214. if (skip == SKIPFUNC)
  8215. status = i;
  8216. if (skip)
  8217. continue;
  8218. if (n->type != NWHILE)
  8219. i = !i;
  8220. if (i != 0)
  8221. break;
  8222. status = evaltree(n->nbinary.ch2, flags);
  8223. skip = skiploop();
  8224. } while (!(skip & ~SKIPCONT));
  8225. loopnest--;
  8226. return status;
  8227. }
  8228. static int
  8229. evalfor(union node *n, int flags)
  8230. {
  8231. struct arglist arglist;
  8232. union node *argp;
  8233. struct strlist *sp;
  8234. struct stackmark smark;
  8235. int status = 0;
  8236. setstackmark(&smark);
  8237. arglist.list = NULL;
  8238. arglist.lastp = &arglist.list;
  8239. for (argp = n->nfor.args; argp; argp = argp->narg.next) {
  8240. expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
  8241. }
  8242. *arglist.lastp = NULL;
  8243. loopnest++;
  8244. flags &= EV_TESTED;
  8245. for (sp = arglist.list; sp; sp = sp->next) {
  8246. setvar0(n->nfor.var, sp->text);
  8247. status = evaltree(n->nfor.body, flags);
  8248. if (skiploop() & ~SKIPCONT)
  8249. break;
  8250. }
  8251. loopnest--;
  8252. popstackmark(&smark);
  8253. return status;
  8254. }
  8255. static int
  8256. evalcase(union node *n, int flags)
  8257. {
  8258. union node *cp;
  8259. union node *patp;
  8260. struct arglist arglist;
  8261. struct stackmark smark;
  8262. int status = 0;
  8263. setstackmark(&smark);
  8264. arglist.list = NULL;
  8265. arglist.lastp = &arglist.list;
  8266. expandarg(n->ncase.expr, &arglist, EXP_TILDE);
  8267. for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
  8268. for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
  8269. if (casematch(patp, arglist.list->text)) {
  8270. /* Ensure body is non-empty as otherwise
  8271. * EV_EXIT may prevent us from setting the
  8272. * exit status.
  8273. */
  8274. if (evalskip == 0 && cp->nclist.body) {
  8275. status = evaltree(cp->nclist.body, flags);
  8276. }
  8277. goto out;
  8278. }
  8279. }
  8280. }
  8281. out:
  8282. popstackmark(&smark);
  8283. return status;
  8284. }
  8285. /*
  8286. * Kick off a subshell to evaluate a tree.
  8287. */
  8288. static int
  8289. evalsubshell(union node *n, int flags)
  8290. {
  8291. struct job *jp;
  8292. int backgnd = (n->type == NBACKGND); /* FORK_BG(1) if yes, else FORK_FG(0) */
  8293. int status;
  8294. expredir(n->nredir.redirect);
  8295. if (!backgnd && (flags & EV_EXIT) && !may_have_traps)
  8296. goto nofork;
  8297. INT_OFF;
  8298. if (backgnd == FORK_FG)
  8299. get_tty_state();
  8300. jp = makejob(/*n,*/ 1);
  8301. if (forkshell(jp, n, backgnd) == 0) {
  8302. /* child */
  8303. INT_ON;
  8304. flags |= EV_EXIT;
  8305. if (backgnd)
  8306. flags &= ~EV_TESTED;
  8307. nofork:
  8308. redirect(n->nredir.redirect, 0);
  8309. evaltreenr(n->nredir.n, flags);
  8310. /* never returns */
  8311. }
  8312. /* parent */
  8313. status = 0;
  8314. if (backgnd == FORK_FG)
  8315. status = waitforjob(jp);
  8316. INT_ON;
  8317. return status;
  8318. }
  8319. /*
  8320. * Compute the names of the files in a redirection list.
  8321. */
  8322. static void fixredir(union node *, const char *, int);
  8323. static void
  8324. expredir(union node *n)
  8325. {
  8326. union node *redir;
  8327. for (redir = n; redir; redir = redir->nfile.next) {
  8328. struct arglist fn;
  8329. fn.list = NULL;
  8330. fn.lastp = &fn.list;
  8331. switch (redir->type) {
  8332. case NFROMTO:
  8333. case NFROM:
  8334. case NTO:
  8335. #if BASH_REDIR_OUTPUT
  8336. case NTO2:
  8337. #endif
  8338. case NCLOBBER:
  8339. case NAPPEND:
  8340. expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
  8341. TRACE(("expredir expanded to '%s'\n", fn.list->text));
  8342. #if BASH_REDIR_OUTPUT
  8343. store_expfname:
  8344. #endif
  8345. #if 0
  8346. // By the design of stack allocator, the loop of this kind:
  8347. // while true; do while true; do break; done </dev/null; done
  8348. // will look like a memory leak: ash plans to free expfname's
  8349. // of "/dev/null" as soon as it finishes running the loop
  8350. // (in this case, never).
  8351. // This "fix" is wrong:
  8352. if (redir->nfile.expfname)
  8353. stunalloc(redir->nfile.expfname);
  8354. // It results in corrupted state of stacked allocations.
  8355. #endif
  8356. redir->nfile.expfname = fn.list->text;
  8357. break;
  8358. case NFROMFD:
  8359. case NTOFD: /* >& */
  8360. if (redir->ndup.vname) {
  8361. expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
  8362. if (fn.list == NULL)
  8363. ash_msg_and_raise_error("redir error");
  8364. #if BASH_REDIR_OUTPUT
  8365. //FIXME: we used expandarg with different args!
  8366. if (!isdigit_str9(fn.list->text)) {
  8367. /* >&file, not >&fd */
  8368. if (redir->nfile.fd != 1) /* 123>&file - BAD */
  8369. ash_msg_and_raise_error("redir error");
  8370. redir->type = NTO2;
  8371. goto store_expfname;
  8372. }
  8373. #endif
  8374. fixredir(redir, fn.list->text, 1);
  8375. }
  8376. break;
  8377. }
  8378. }
  8379. }
  8380. /*
  8381. * Evaluate a pipeline. All the processes in the pipeline are children
  8382. * of the process creating the pipeline. (This differs from some versions
  8383. * of the shell, which make the last process in a pipeline the parent
  8384. * of all the rest.)
  8385. */
  8386. static int
  8387. evalpipe(union node *n, int flags)
  8388. {
  8389. struct job *jp;
  8390. struct nodelist *lp;
  8391. int pipelen;
  8392. int prevfd;
  8393. int pip[2];
  8394. int status = 0;
  8395. TRACE(("evalpipe(0x%lx) called\n", (long)n));
  8396. pipelen = 0;
  8397. for (lp = n->npipe.cmdlist; lp; lp = lp->next)
  8398. pipelen++;
  8399. flags |= EV_EXIT;
  8400. INT_OFF;
  8401. if (n->npipe.pipe_backgnd == 0)
  8402. get_tty_state();
  8403. jp = makejob(/*n,*/ pipelen);
  8404. prevfd = -1;
  8405. for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
  8406. prehash(lp->n);
  8407. pip[1] = -1;
  8408. if (lp->next) {
  8409. if (pipe(pip) < 0) {
  8410. close(prevfd);
  8411. ash_msg_and_raise_perror("can't create pipe");
  8412. }
  8413. }
  8414. if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
  8415. /* child */
  8416. INT_ON;
  8417. if (pip[1] >= 0) {
  8418. close(pip[0]);
  8419. }
  8420. if (prevfd > 0) {
  8421. dup2(prevfd, 0);
  8422. close(prevfd);
  8423. }
  8424. if (pip[1] > 1) {
  8425. dup2(pip[1], 1);
  8426. close(pip[1]);
  8427. }
  8428. evaltreenr(lp->n, flags);
  8429. /* never returns */
  8430. }
  8431. /* parent */
  8432. if (prevfd >= 0)
  8433. close(prevfd);
  8434. prevfd = pip[0];
  8435. /* Don't want to trigger debugging */
  8436. if (pip[1] != -1)
  8437. close(pip[1]);
  8438. }
  8439. if (n->npipe.pipe_backgnd == 0) {
  8440. status = waitforjob(jp);
  8441. TRACE(("evalpipe: job done exit status %d\n", status));
  8442. }
  8443. INT_ON;
  8444. return status;
  8445. }
  8446. /*
  8447. * Controls whether the shell is interactive or not.
  8448. */
  8449. static void
  8450. setinteractive(int on)
  8451. {
  8452. static smallint is_interactive;
  8453. if (++on == is_interactive)
  8454. return;
  8455. is_interactive = on;
  8456. setsignal(SIGINT);
  8457. setsignal(SIGQUIT);
  8458. setsignal(SIGTERM);
  8459. #if !ENABLE_FEATURE_SH_EXTRA_QUIET
  8460. if (is_interactive > 1) {
  8461. /* Looks like they want an interactive shell */
  8462. static smallint did_banner;
  8463. if (!did_banner) {
  8464. /* note: ash and hush share this string */
  8465. out1fmt("\n\n%s %s\n"
  8466. IF_ASH_HELP("Enter 'help' for a list of built-in commands.\n")
  8467. "\n",
  8468. bb_banner,
  8469. "built-in shell (ash)"
  8470. );
  8471. did_banner = 1;
  8472. }
  8473. }
  8474. #endif
  8475. }
  8476. static void
  8477. optschanged(void)
  8478. {
  8479. #if DEBUG
  8480. opentrace();
  8481. #endif
  8482. setinteractive(iflag);
  8483. setjobctl(mflag);
  8484. #if ENABLE_FEATURE_EDITING_VI
  8485. if (viflag)
  8486. line_input_state->flags |= VI_MODE;
  8487. else
  8488. line_input_state->flags &= ~VI_MODE;
  8489. #else
  8490. viflag = 0; /* forcibly keep the option off */
  8491. #endif
  8492. }
  8493. struct localvar_list {
  8494. struct localvar_list *next;
  8495. struct localvar *lv;
  8496. };
  8497. static struct localvar_list *localvar_stack;
  8498. /*
  8499. * Called after a function returns.
  8500. * Interrupts must be off.
  8501. */
  8502. static void
  8503. poplocalvars(int keep)
  8504. {
  8505. struct localvar_list *ll;
  8506. struct localvar *lvp, *next;
  8507. struct var *vp;
  8508. INT_OFF;
  8509. ll = localvar_stack;
  8510. localvar_stack = ll->next;
  8511. next = ll->lv;
  8512. free(ll);
  8513. while ((lvp = next) != NULL) {
  8514. next = lvp->next;
  8515. vp = lvp->vp;
  8516. TRACE(("poplocalvar %s\n", vp ? vp->var_text : "-"));
  8517. if (keep) {
  8518. int bits = VSTRFIXED;
  8519. if (lvp->flags != VUNSET) {
  8520. if (vp->var_text == lvp->text)
  8521. bits |= VTEXTFIXED;
  8522. else if (!(lvp->flags & (VTEXTFIXED|VSTACK)))
  8523. free((char*)lvp->text);
  8524. }
  8525. vp->flags &= ~bits;
  8526. vp->flags |= (lvp->flags & bits);
  8527. if ((vp->flags &
  8528. (VEXPORT|VREADONLY|VSTRFIXED|VUNSET)) == VUNSET)
  8529. unsetvar(vp->var_text);
  8530. } else if (vp == NULL) { /* $- saved */
  8531. memcpy(optlist, lvp->text, sizeof(optlist));
  8532. free((char*)lvp->text);
  8533. optschanged();
  8534. } else if (lvp->flags == VUNSET) {
  8535. vp->flags &= ~(VSTRFIXED|VREADONLY);
  8536. unsetvar(vp->var_text);
  8537. } else {
  8538. if (vp->var_func)
  8539. vp->var_func(var_end(lvp->text));
  8540. if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
  8541. free((char*)vp->var_text);
  8542. vp->flags = lvp->flags;
  8543. vp->var_text = lvp->text;
  8544. }
  8545. free(lvp);
  8546. }
  8547. INT_ON;
  8548. }
  8549. /*
  8550. * Create a new localvar environment.
  8551. */
  8552. static struct localvar_list *
  8553. pushlocalvars(void)
  8554. {
  8555. struct localvar_list *ll;
  8556. INT_OFF;
  8557. ll = ckzalloc(sizeof(*ll));
  8558. /*ll->lv = NULL; - zalloc did it */
  8559. ll->next = localvar_stack;
  8560. localvar_stack = ll;
  8561. INT_ON;
  8562. return ll->next;
  8563. }
  8564. static void
  8565. unwindlocalvars(struct localvar_list *stop)
  8566. {
  8567. while (localvar_stack != stop)
  8568. poplocalvars(0);
  8569. }
  8570. static int
  8571. evalfun(struct funcnode *func, int argc, char **argv, int flags)
  8572. {
  8573. volatile struct shparam saveparam;
  8574. struct jmploc *volatile savehandler;
  8575. struct jmploc jmploc;
  8576. int e;
  8577. saveparam = shellparam;
  8578. savehandler = exception_handler;
  8579. e = setjmp(jmploc.loc);
  8580. if (e) {
  8581. goto funcdone;
  8582. }
  8583. INT_OFF;
  8584. exception_handler = &jmploc;
  8585. shellparam.malloced = 0;
  8586. func->count++;
  8587. funcnest++;
  8588. INT_ON;
  8589. shellparam.nparam = argc - 1;
  8590. shellparam.p = argv + 1;
  8591. #if ENABLE_ASH_GETOPTS
  8592. shellparam.optind = 1;
  8593. shellparam.optoff = -1;
  8594. #endif
  8595. pushlocalvars();
  8596. evaltree(func->n.narg.next, flags & EV_TESTED);
  8597. poplocalvars(0);
  8598. funcdone:
  8599. INT_OFF;
  8600. funcnest--;
  8601. freefunc(func);
  8602. freeparam(&shellparam);
  8603. shellparam = saveparam;
  8604. exception_handler = savehandler;
  8605. INT_ON;
  8606. evalskip &= ~SKIPFUNC;
  8607. return e;
  8608. }
  8609. /*
  8610. * Make a variable a local variable. When a variable is made local, it's
  8611. * value and flags are saved in a localvar structure. The saved values
  8612. * will be restored when the shell function returns. We handle the name
  8613. * "-" as a special case: it makes changes to "set +-options" local
  8614. * (options will be restored on return from the function).
  8615. */
  8616. static void
  8617. mklocal(char *name)
  8618. {
  8619. struct localvar *lvp;
  8620. struct var **vpp;
  8621. struct var *vp;
  8622. char *eq = strchr(name, '=');
  8623. INT_OFF;
  8624. /* Cater for duplicate "local". Examples:
  8625. * x=0; f() { local x=1; echo $x; local x; echo $x; }; f; echo $x
  8626. * x=0; f() { local x=1; echo $x; local x=2; echo $x; }; f; echo $x
  8627. */
  8628. lvp = localvar_stack->lv;
  8629. while (lvp) {
  8630. if (lvp->vp && varcmp(lvp->vp->var_text, name) == 0) {
  8631. if (eq)
  8632. setvareq(name, 0);
  8633. /* else:
  8634. * it's a duplicate "local VAR" declaration, do nothing
  8635. */
  8636. goto ret;
  8637. }
  8638. lvp = lvp->next;
  8639. }
  8640. lvp = ckzalloc(sizeof(*lvp));
  8641. if (LONE_DASH(name)) {
  8642. char *p;
  8643. p = ckmalloc(sizeof(optlist));
  8644. lvp->text = memcpy(p, optlist, sizeof(optlist));
  8645. vp = NULL;
  8646. } else {
  8647. vpp = hashvar(name);
  8648. vp = *findvar(vpp, name);
  8649. if (vp == NULL) {
  8650. /* variable did not exist yet */
  8651. if (eq)
  8652. vp = setvareq(name, VSTRFIXED);
  8653. else
  8654. vp = setvar(name, NULL, VSTRFIXED);
  8655. lvp->flags = VUNSET;
  8656. } else {
  8657. lvp->text = vp->var_text;
  8658. lvp->flags = vp->flags;
  8659. /* make sure neither "struct var" nor string gets freed
  8660. * during (un)setting:
  8661. */
  8662. vp->flags |= VSTRFIXED|VTEXTFIXED;
  8663. if (eq)
  8664. setvareq(name, 0);
  8665. else
  8666. /* "local VAR" unsets VAR: */
  8667. setvar0(name, NULL);
  8668. }
  8669. }
  8670. lvp->vp = vp;
  8671. lvp->next = localvar_stack->lv;
  8672. localvar_stack->lv = lvp;
  8673. ret:
  8674. INT_ON;
  8675. }
  8676. /*
  8677. * The "local" command.
  8678. */
  8679. static int FAST_FUNC
  8680. localcmd(int argc UNUSED_PARAM, char **argv)
  8681. {
  8682. char *name;
  8683. if (!localvar_stack)
  8684. ash_msg_and_raise_error("not in a function");
  8685. argv = argptr;
  8686. while ((name = *argv++) != NULL) {
  8687. mklocal(name);
  8688. }
  8689. return 0;
  8690. }
  8691. static int FAST_FUNC
  8692. falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  8693. {
  8694. return 1;
  8695. }
  8696. static int FAST_FUNC
  8697. truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  8698. {
  8699. return 0;
  8700. }
  8701. static int FAST_FUNC
  8702. execcmd(int argc UNUSED_PARAM, char **argv)
  8703. {
  8704. optionarg = NULL;
  8705. while (nextopt("a:") != '\0')
  8706. /* nextopt() sets optionarg to "-a ARGV0" */;
  8707. argv = argptr;
  8708. if (argv[0]) {
  8709. char *prog;
  8710. iflag = 0; /* exit on error */
  8711. mflag = 0;
  8712. optschanged();
  8713. /* We should set up signals for "exec CMD"
  8714. * the same way as for "CMD" without "exec".
  8715. * But optschanged->setinteractive->setsignal
  8716. * still thought we are a root shell. Therefore, for example,
  8717. * SIGQUIT is still set to IGN. Fix it:
  8718. */
  8719. shlvl++;
  8720. setsignal(SIGQUIT);
  8721. /*setsignal(SIGTERM); - unnecessary because of iflag=0 */
  8722. /*setsignal(SIGTSTP); - unnecessary because of mflag=0 */
  8723. /*setsignal(SIGTTOU); - unnecessary because of mflag=0 */
  8724. prog = argv[0];
  8725. if (optionarg)
  8726. argv[0] = optionarg;
  8727. shellexec(prog, argv, pathval(), 0);
  8728. /* NOTREACHED */
  8729. }
  8730. return 0;
  8731. }
  8732. /*
  8733. * The return command.
  8734. */
  8735. static int FAST_FUNC
  8736. returncmd(int argc UNUSED_PARAM, char **argv)
  8737. {
  8738. /*
  8739. * If called outside a function, do what ksh does;
  8740. * skip the rest of the file.
  8741. */
  8742. evalskip = SKIPFUNC;
  8743. return argv[1] ? number(argv[1]) : exitstatus;
  8744. }
  8745. /* Forward declarations for builtintab[] */
  8746. static int breakcmd(int, char **) FAST_FUNC;
  8747. static int dotcmd(int, char **) FAST_FUNC;
  8748. static int evalcmd(int, char **, int) FAST_FUNC;
  8749. static int exitcmd(int, char **) FAST_FUNC;
  8750. static int exportcmd(int, char **) FAST_FUNC;
  8751. #if ENABLE_ASH_GETOPTS
  8752. static int getoptscmd(int, char **) FAST_FUNC;
  8753. #endif
  8754. #if ENABLE_ASH_HELP
  8755. static int helpcmd(int, char **) FAST_FUNC;
  8756. #endif
  8757. #if MAX_HISTORY
  8758. static int historycmd(int, char **) FAST_FUNC;
  8759. #endif
  8760. #if ENABLE_FEATURE_SH_MATH
  8761. static int letcmd(int, char **) FAST_FUNC;
  8762. #endif
  8763. static int readcmd(int, char **) FAST_FUNC;
  8764. static int setcmd(int, char **) FAST_FUNC;
  8765. static int shiftcmd(int, char **) FAST_FUNC;
  8766. static int timescmd(int, char **) FAST_FUNC;
  8767. static int trapcmd(int, char **) FAST_FUNC;
  8768. static int umaskcmd(int, char **) FAST_FUNC;
  8769. static int unsetcmd(int, char **) FAST_FUNC;
  8770. static int ulimitcmd(int, char **) FAST_FUNC;
  8771. #define BUILTIN_NOSPEC "0"
  8772. #define BUILTIN_SPECIAL "1"
  8773. #define BUILTIN_REGULAR "2"
  8774. #define BUILTIN_SPEC_REG "3"
  8775. #define BUILTIN_ASSIGN "4"
  8776. #define BUILTIN_SPEC_ASSG "5"
  8777. #define BUILTIN_REG_ASSG "6"
  8778. #define BUILTIN_SPEC_REG_ASSG "7"
  8779. /* Stubs for calling non-FAST_FUNC's */
  8780. #if ENABLE_ASH_ECHO
  8781. static int FAST_FUNC echocmd(int argc, char **argv) { return echo_main(argc, argv); }
  8782. #endif
  8783. #if ENABLE_ASH_PRINTF
  8784. static int FAST_FUNC printfcmd(int argc, char **argv) { return printf_main(argc, argv); }
  8785. #endif
  8786. #if ENABLE_ASH_TEST || BASH_TEST2
  8787. static int FAST_FUNC testcmd(int argc, char **argv) { return test_main(argc, argv); }
  8788. #endif
  8789. /* Keep these in proper order since it is searched via bsearch() */
  8790. static const struct builtincmd builtintab[] = {
  8791. { BUILTIN_SPEC_REG "." , dotcmd },
  8792. { BUILTIN_SPEC_REG ":" , truecmd },
  8793. #if ENABLE_ASH_TEST
  8794. { BUILTIN_REGULAR "[" , testcmd },
  8795. #endif
  8796. #if BASH_TEST2
  8797. { BUILTIN_REGULAR "[[" , testcmd },
  8798. #endif
  8799. #if ENABLE_ASH_ALIAS
  8800. { BUILTIN_REG_ASSG "alias" , aliascmd },
  8801. #endif
  8802. #if JOBS
  8803. { BUILTIN_REGULAR "bg" , fg_bgcmd },
  8804. #endif
  8805. { BUILTIN_SPEC_REG "break" , breakcmd },
  8806. { BUILTIN_REGULAR "cd" , cdcmd },
  8807. { BUILTIN_NOSPEC "chdir" , cdcmd },
  8808. #if ENABLE_ASH_CMDCMD
  8809. { BUILTIN_REGULAR "command" , commandcmd },
  8810. #endif
  8811. { BUILTIN_SPEC_REG "continue", breakcmd },
  8812. #if ENABLE_ASH_ECHO
  8813. { BUILTIN_REGULAR "echo" , echocmd },
  8814. #endif
  8815. { BUILTIN_SPEC_REG "eval" , NULL }, /*evalcmd() has a differing prototype*/
  8816. { BUILTIN_SPEC_REG "exec" , execcmd },
  8817. { BUILTIN_SPEC_REG "exit" , exitcmd },
  8818. { BUILTIN_SPEC_REG_ASSG "export" , exportcmd },
  8819. { BUILTIN_REGULAR "false" , falsecmd },
  8820. #if JOBS
  8821. { BUILTIN_REGULAR "fg" , fg_bgcmd },
  8822. #endif
  8823. #if ENABLE_ASH_GETOPTS
  8824. { BUILTIN_REGULAR "getopts" , getoptscmd },
  8825. #endif
  8826. { BUILTIN_NOSPEC "hash" , hashcmd },
  8827. #if ENABLE_ASH_HELP
  8828. { BUILTIN_NOSPEC "help" , helpcmd },
  8829. #endif
  8830. #if MAX_HISTORY
  8831. { BUILTIN_NOSPEC "history" , historycmd },
  8832. #endif
  8833. #if JOBS
  8834. { BUILTIN_REGULAR "jobs" , jobscmd },
  8835. { BUILTIN_REGULAR "kill" , killcmd },
  8836. #endif
  8837. #if ENABLE_FEATURE_SH_MATH
  8838. { BUILTIN_NOSPEC "let" , letcmd },
  8839. #endif
  8840. { BUILTIN_SPEC_REG_ASSG "local" , localcmd },
  8841. #if ENABLE_ASH_PRINTF
  8842. { BUILTIN_REGULAR "printf" , printfcmd },
  8843. #endif
  8844. { BUILTIN_NOSPEC "pwd" , pwdcmd },
  8845. { BUILTIN_REGULAR "read" , readcmd },
  8846. { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
  8847. { BUILTIN_SPEC_REG "return" , returncmd },
  8848. { BUILTIN_SPEC_REG "set" , setcmd },
  8849. { BUILTIN_SPEC_REG "shift" , shiftcmd },
  8850. #if BASH_SOURCE
  8851. { BUILTIN_SPEC_REG "source" , dotcmd },
  8852. #endif
  8853. #if ENABLE_ASH_TEST
  8854. { BUILTIN_REGULAR "test" , testcmd },
  8855. #endif
  8856. { BUILTIN_SPEC_REG "times" , timescmd },
  8857. { BUILTIN_SPEC_REG "trap" , trapcmd },
  8858. { BUILTIN_REGULAR "true" , truecmd },
  8859. { BUILTIN_NOSPEC "type" , typecmd },
  8860. { BUILTIN_NOSPEC "ulimit" , ulimitcmd },
  8861. { BUILTIN_REGULAR "umask" , umaskcmd },
  8862. #if ENABLE_ASH_ALIAS
  8863. { BUILTIN_REGULAR "unalias" , unaliascmd },
  8864. #endif
  8865. { BUILTIN_SPEC_REG "unset" , unsetcmd },
  8866. { BUILTIN_REGULAR "wait" , waitcmd },
  8867. };
  8868. /* Should match the above table! */
  8869. #define COMMANDCMD (builtintab + \
  8870. /* . : */ 2 + \
  8871. /* [ */ 1 * ENABLE_ASH_TEST + \
  8872. /* [[ */ 1 * BASH_TEST2 + \
  8873. /* alias */ 1 * ENABLE_ASH_ALIAS + \
  8874. /* bg */ 1 * ENABLE_ASH_JOB_CONTROL + \
  8875. /* break cd cddir */ 3)
  8876. #define EVALCMD (COMMANDCMD + \
  8877. /* command */ 1 * ENABLE_ASH_CMDCMD + \
  8878. /* continue */ 1 + \
  8879. /* echo */ 1 * ENABLE_ASH_ECHO + \
  8880. 0)
  8881. #define EXECCMD (EVALCMD + \
  8882. /* eval */ 1)
  8883. /*
  8884. * Search the table of builtin commands.
  8885. */
  8886. static int
  8887. pstrcmp1(const void *a, const void *b)
  8888. {
  8889. return strcmp((char*)a, *(char**)b + 1);
  8890. }
  8891. static struct builtincmd *
  8892. find_builtin(const char *name)
  8893. {
  8894. struct builtincmd *bp;
  8895. bp = bsearch(
  8896. name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
  8897. pstrcmp1
  8898. );
  8899. return bp;
  8900. }
  8901. /*
  8902. * Execute a simple command.
  8903. */
  8904. static int
  8905. isassignment(const char *p)
  8906. {
  8907. const char *q = endofname(p);
  8908. if (p == q)
  8909. return 0;
  8910. return *q == '=';
  8911. }
  8912. static int FAST_FUNC
  8913. bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  8914. {
  8915. /* Preserve exitstatus of a previous possible redirection
  8916. * as POSIX mandates */
  8917. return back_exitstatus;
  8918. }
  8919. static int
  8920. evalcommand(union node *cmd, int flags)
  8921. {
  8922. static const struct builtincmd null_bltin = {
  8923. "\0\0", bltincmd /* why three NULs? */
  8924. };
  8925. struct localvar_list *localvar_stop;
  8926. struct redirtab *redir_stop;
  8927. struct stackmark smark;
  8928. union node *argp;
  8929. struct arglist arglist;
  8930. struct arglist varlist;
  8931. char **argv;
  8932. int argc;
  8933. const struct strlist *sp;
  8934. struct cmdentry cmdentry;
  8935. struct job *jp;
  8936. char *lastarg;
  8937. const char *path;
  8938. int spclbltin;
  8939. int status;
  8940. char **nargv;
  8941. smallint cmd_is_exec;
  8942. /* First expand the arguments. */
  8943. TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
  8944. setstackmark(&smark);
  8945. localvar_stop = pushlocalvars();
  8946. back_exitstatus = 0;
  8947. cmdentry.cmdtype = CMDBUILTIN;
  8948. cmdentry.u.cmd = &null_bltin;
  8949. varlist.lastp = &varlist.list;
  8950. *varlist.lastp = NULL;
  8951. arglist.lastp = &arglist.list;
  8952. *arglist.lastp = NULL;
  8953. argc = 0;
  8954. if (cmd->ncmd.args) {
  8955. struct builtincmd *bcmd;
  8956. smallint pseudovarflag;
  8957. bcmd = find_builtin(cmd->ncmd.args->narg.text);
  8958. pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
  8959. for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
  8960. struct strlist **spp;
  8961. spp = arglist.lastp;
  8962. if (pseudovarflag && isassignment(argp->narg.text))
  8963. expandarg(argp, &arglist, EXP_VARTILDE);
  8964. else
  8965. expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
  8966. for (sp = *spp; sp; sp = sp->next)
  8967. argc++;
  8968. }
  8969. }
  8970. /* Reserve one extra spot at the front for shellexec. */
  8971. nargv = stalloc(sizeof(char *) * (argc + 2));
  8972. argv = ++nargv;
  8973. for (sp = arglist.list; sp; sp = sp->next) {
  8974. TRACE(("evalcommand arg: %s\n", sp->text));
  8975. *nargv++ = sp->text;
  8976. }
  8977. *nargv = NULL;
  8978. lastarg = NULL;
  8979. if (iflag && funcnest == 0 && argc > 0)
  8980. lastarg = nargv[-1];
  8981. expredir(cmd->ncmd.redirect);
  8982. redir_stop = pushredir(cmd->ncmd.redirect);
  8983. preverrout_fd = 2;
  8984. if (BASH_XTRACEFD && xflag) {
  8985. /* NB: bash closes fd == $BASH_XTRACEFD when it is changed.
  8986. * we do not emulate this. We only use its value.
  8987. */
  8988. const char *xtracefd = lookupvar("BASH_XTRACEFD");
  8989. if (xtracefd && is_number(xtracefd))
  8990. preverrout_fd = atoi(xtracefd);
  8991. }
  8992. status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
  8993. path = vpath.var_text;
  8994. for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
  8995. struct strlist **spp;
  8996. char *p;
  8997. spp = varlist.lastp;
  8998. expandarg(argp, &varlist, EXP_VARTILDE);
  8999. mklocal((*spp)->text);
  9000. /*
  9001. * Modify the command lookup path, if a PATH= assignment
  9002. * is present
  9003. */
  9004. p = (*spp)->text;
  9005. if (varcmp(p, path) == 0)
  9006. path = p;
  9007. }
  9008. /* Print the command if xflag is set. */
  9009. if (xflag) {
  9010. const char *pfx = "";
  9011. fdprintf(preverrout_fd, "%s", expandstr(ps4val(), DQSYNTAX));
  9012. sp = varlist.list;
  9013. while (sp) {
  9014. char *varval = sp->text;
  9015. char *eq = strchrnul(varval, '=');
  9016. if (*eq)
  9017. eq++;
  9018. fdprintf(preverrout_fd, "%s%.*s%s",
  9019. pfx,
  9020. (int)(eq - varval), varval,
  9021. maybe_single_quote(eq)
  9022. );
  9023. sp = sp->next;
  9024. pfx = " ";
  9025. }
  9026. sp = arglist.list;
  9027. while (sp) {
  9028. fdprintf(preverrout_fd, "%s%s",
  9029. pfx,
  9030. /* always quote if matches reserved word: */
  9031. findkwd(sp->text)
  9032. ? single_quote(sp->text)
  9033. : maybe_single_quote(sp->text)
  9034. );
  9035. sp = sp->next;
  9036. pfx = " ";
  9037. }
  9038. safe_write(preverrout_fd, "\n", 1);
  9039. }
  9040. cmd_is_exec = 0;
  9041. spclbltin = -1;
  9042. /* Now locate the command. */
  9043. if (argc) {
  9044. int cmd_flag = DO_ERR;
  9045. #if ENABLE_ASH_CMDCMD
  9046. const char *oldpath = path + 5;
  9047. #endif
  9048. path += 5;
  9049. for (;;) {
  9050. find_command(argv[0], &cmdentry, cmd_flag, path);
  9051. if (cmdentry.cmdtype == CMDUNKNOWN) {
  9052. flush_stdout_stderr();
  9053. status = 127;
  9054. goto bail;
  9055. }
  9056. /* implement bltin and command here */
  9057. if (cmdentry.cmdtype != CMDBUILTIN)
  9058. break;
  9059. if (spclbltin < 0)
  9060. spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
  9061. if (cmdentry.u.cmd == EXECCMD)
  9062. cmd_is_exec = 1;
  9063. #if ENABLE_ASH_CMDCMD
  9064. if (cmdentry.u.cmd == COMMANDCMD) {
  9065. path = oldpath;
  9066. nargv = parse_command_args(argv, &path);
  9067. if (!nargv)
  9068. break;
  9069. /* It's "command [-p] PROG ARGS" (that is, no -Vv).
  9070. * nargv => "PROG". path is updated if -p.
  9071. */
  9072. argc -= nargv - argv;
  9073. argv = nargv;
  9074. cmd_flag |= DO_NOFUNC;
  9075. } else
  9076. #endif
  9077. break;
  9078. }
  9079. }
  9080. if (status) {
  9081. bail:
  9082. exitstatus = status;
  9083. /* We have a redirection error. */
  9084. if (spclbltin > 0)
  9085. raise_exception(EXERROR);
  9086. goto out;
  9087. }
  9088. /* Execute the command. */
  9089. switch (cmdentry.cmdtype) {
  9090. default: {
  9091. #if ENABLE_FEATURE_SH_NOFORK && NUM_APPLETS > 1
  9092. /* (1) BUG: if variables are set, we need to fork, or save/restore them
  9093. * around run_nofork_applet() call.
  9094. * (2) Should this check also be done in forkshell()?
  9095. * (perhaps it should, so that "VAR=VAL nofork" at least avoids exec...)
  9096. */
  9097. /* find_command() encodes applet_no as (-2 - applet_no) */
  9098. int applet_no = (- cmdentry.u.index - 2);
  9099. if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
  9100. char **sv_environ;
  9101. INT_OFF;
  9102. sv_environ = environ;
  9103. environ = listvars(VEXPORT, VUNSET, varlist.list, /*end:*/ NULL);
  9104. /*
  9105. * Run <applet>_main().
  9106. * Signals (^C) can't interrupt here.
  9107. * Otherwise we can mangle stdio or malloc internal state.
  9108. * This makes applets which can run for a long time
  9109. * and/or wait for user input ineligible for NOFORK:
  9110. * for example, "yes" or "rm" (rm -i waits for input).
  9111. */
  9112. status = run_nofork_applet(applet_no, argv);
  9113. environ = sv_environ;
  9114. /*
  9115. * Try enabling NOFORK for "yes" applet.
  9116. * ^C _will_ stop it (write returns EINTR),
  9117. * but this causes stdout FILE to be stuck
  9118. * and needing clearerr(). What if other applets
  9119. * also can get EINTRs? Do we need to switch
  9120. * our signals to SA_RESTART?
  9121. */
  9122. /*clearerr(stdout);*/
  9123. INT_ON;
  9124. break;
  9125. }
  9126. #endif
  9127. /* Can we avoid forking? For example, very last command
  9128. * in a script or a subshell does not need forking,
  9129. * we can just exec it.
  9130. */
  9131. if (!(flags & EV_EXIT) || may_have_traps) {
  9132. /* No, forking off a child is necessary */
  9133. INT_OFF;
  9134. get_tty_state();
  9135. jp = makejob(/*cmd,*/ 1);
  9136. if (forkshell(jp, cmd, FORK_FG) != 0) {
  9137. /* parent */
  9138. status = waitforjob(jp);
  9139. INT_ON;
  9140. TRACE(("forked child exited with %d\n", status));
  9141. break;
  9142. }
  9143. /* child */
  9144. FORCE_INT_ON;
  9145. /* fall through to exec'ing external program */
  9146. }
  9147. listsetvar(varlist.list, VEXPORT|VSTACK);
  9148. shellexec(argv[0], argv, path, cmdentry.u.index);
  9149. /* NOTREACHED */
  9150. } /* default */
  9151. case CMDBUILTIN:
  9152. if (spclbltin > 0 || argc == 0) {
  9153. poplocalvars(1);
  9154. if (cmd_is_exec && argc > 1)
  9155. listsetvar(varlist.list, VEXPORT);
  9156. }
  9157. /* Tight loop with builtins only:
  9158. * "while kill -0 $child; do true; done"
  9159. * will never exit even if $child died, unless we do this
  9160. * to reap the zombie and make kill detect that it's gone: */
  9161. dowait(DOWAIT_NONBLOCK, NULL);
  9162. if (evalbltin(cmdentry.u.cmd, argc, argv, flags)) {
  9163. if (exception_type == EXERROR && spclbltin <= 0) {
  9164. FORCE_INT_ON;
  9165. goto readstatus;
  9166. }
  9167. raise:
  9168. longjmp(exception_handler->loc, 1);
  9169. }
  9170. goto readstatus;
  9171. case CMDFUNCTION:
  9172. poplocalvars(1);
  9173. /* See above for the rationale */
  9174. dowait(DOWAIT_NONBLOCK, NULL);
  9175. if (evalfun(cmdentry.u.func, argc, argv, flags))
  9176. goto raise;
  9177. readstatus:
  9178. status = exitstatus;
  9179. break;
  9180. } /* switch */
  9181. out:
  9182. if (cmd->ncmd.redirect)
  9183. popredir(/*drop:*/ cmd_is_exec);
  9184. unwindredir(redir_stop);
  9185. unwindlocalvars(localvar_stop);
  9186. if (lastarg) {
  9187. /* dsl: I think this is intended to be used to support
  9188. * '_' in 'vi' command mode during line editing...
  9189. * However I implemented that within libedit itself.
  9190. */
  9191. setvar0("_", lastarg);
  9192. }
  9193. popstackmark(&smark);
  9194. return status;
  9195. }
  9196. static int
  9197. evalbltin(const struct builtincmd *cmd, int argc, char **argv, int flags)
  9198. {
  9199. char *volatile savecmdname;
  9200. struct jmploc *volatile savehandler;
  9201. struct jmploc jmploc;
  9202. int status;
  9203. int i;
  9204. savecmdname = commandname;
  9205. savehandler = exception_handler;
  9206. i = setjmp(jmploc.loc);
  9207. if (i)
  9208. goto cmddone;
  9209. exception_handler = &jmploc;
  9210. commandname = argv[0];
  9211. argptr = argv + 1;
  9212. optptr = NULL; /* initialize nextopt */
  9213. if (cmd == EVALCMD)
  9214. status = evalcmd(argc, argv, flags);
  9215. else
  9216. status = (*cmd->builtin)(argc, argv);
  9217. flush_stdout_stderr();
  9218. status |= ferror(stdout);
  9219. exitstatus = status;
  9220. cmddone:
  9221. clearerr(stdout);
  9222. commandname = savecmdname;
  9223. exception_handler = savehandler;
  9224. return i;
  9225. }
  9226. static int
  9227. goodname(const char *p)
  9228. {
  9229. return endofname(p)[0] == '\0';
  9230. }
  9231. /*
  9232. * Search for a command. This is called before we fork so that the
  9233. * location of the command will be available in the parent as well as
  9234. * the child. The check for "goodname" is an overly conservative
  9235. * check that the name will not be subject to expansion.
  9236. */
  9237. static void
  9238. prehash(union node *n)
  9239. {
  9240. struct cmdentry entry;
  9241. if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
  9242. find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
  9243. }
  9244. /* ============ Builtin commands
  9245. *
  9246. * Builtin commands whose functions are closely tied to evaluation
  9247. * are implemented here.
  9248. */
  9249. /*
  9250. * Handle break and continue commands. Break, continue, and return are
  9251. * all handled by setting the evalskip flag. The evaluation routines
  9252. * above all check this flag, and if it is set they start skipping
  9253. * commands rather than executing them. The variable skipcount is
  9254. * the number of loops to break/continue, or the number of function
  9255. * levels to return. (The latter is always 1.) It should probably
  9256. * be an error to break out of more loops than exist, but it isn't
  9257. * in the standard shell so we don't make it one here.
  9258. */
  9259. static int FAST_FUNC
  9260. breakcmd(int argc UNUSED_PARAM, char **argv)
  9261. {
  9262. int n = argv[1] ? number(argv[1]) : 1;
  9263. if (n <= 0)
  9264. ash_msg_and_raise_error(msg_illnum, argv[1]);
  9265. if (n > loopnest)
  9266. n = loopnest;
  9267. if (n > 0) {
  9268. evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
  9269. skipcount = n;
  9270. }
  9271. return 0;
  9272. }
  9273. /*
  9274. * This implements the input routines used by the parser.
  9275. */
  9276. enum {
  9277. INPUT_PUSH_FILE = 1,
  9278. INPUT_NOFILE_OK = 2,
  9279. };
  9280. static smallint checkkwd;
  9281. /* values of checkkwd variable */
  9282. #define CHKALIAS 0x1
  9283. #define CHKKWD 0x2
  9284. #define CHKNL 0x4
  9285. #define CHKEOFMARK 0x8
  9286. /*
  9287. * Push a string back onto the input at this current parsefile level.
  9288. * We handle aliases this way.
  9289. */
  9290. #if !ENABLE_ASH_ALIAS
  9291. #define pushstring(s, ap) pushstring(s)
  9292. #endif
  9293. static void
  9294. pushstring(char *s, struct alias *ap)
  9295. {
  9296. struct strpush *sp;
  9297. int len;
  9298. len = strlen(s);
  9299. INT_OFF;
  9300. if (g_parsefile->strpush) {
  9301. sp = ckzalloc(sizeof(*sp));
  9302. sp->prev = g_parsefile->strpush;
  9303. } else {
  9304. sp = &(g_parsefile->basestrpush);
  9305. }
  9306. g_parsefile->strpush = sp;
  9307. sp->prev_string = g_parsefile->next_to_pgetc;
  9308. sp->prev_left_in_line = g_parsefile->left_in_line;
  9309. sp->unget = g_parsefile->unget;
  9310. memcpy(sp->lastc, g_parsefile->lastc, sizeof(sp->lastc));
  9311. #if ENABLE_ASH_ALIAS
  9312. sp->ap = ap;
  9313. if (ap) {
  9314. ap->flag |= ALIASINUSE;
  9315. sp->string = s;
  9316. }
  9317. #endif
  9318. g_parsefile->next_to_pgetc = s;
  9319. g_parsefile->left_in_line = len;
  9320. g_parsefile->unget = 0;
  9321. INT_ON;
  9322. }
  9323. static void
  9324. popstring(void)
  9325. {
  9326. struct strpush *sp = g_parsefile->strpush;
  9327. INT_OFF;
  9328. #if ENABLE_ASH_ALIAS
  9329. if (sp->ap) {
  9330. if (g_parsefile->next_to_pgetc[-1] == ' '
  9331. || g_parsefile->next_to_pgetc[-1] == '\t'
  9332. ) {
  9333. checkkwd |= CHKALIAS;
  9334. }
  9335. if (sp->string != sp->ap->val) {
  9336. free(sp->string);
  9337. }
  9338. sp->ap->flag &= ~ALIASINUSE;
  9339. if (sp->ap->flag & ALIASDEAD) {
  9340. unalias(sp->ap->name);
  9341. }
  9342. }
  9343. #endif
  9344. g_parsefile->next_to_pgetc = sp->prev_string;
  9345. g_parsefile->left_in_line = sp->prev_left_in_line;
  9346. g_parsefile->unget = sp->unget;
  9347. memcpy(g_parsefile->lastc, sp->lastc, sizeof(sp->lastc));
  9348. g_parsefile->strpush = sp->prev;
  9349. if (sp != &(g_parsefile->basestrpush))
  9350. free(sp);
  9351. INT_ON;
  9352. }
  9353. static int
  9354. preadfd(void)
  9355. {
  9356. int nr;
  9357. char *buf = g_parsefile->buf;
  9358. g_parsefile->next_to_pgetc = buf;
  9359. #if ENABLE_FEATURE_EDITING
  9360. retry:
  9361. if (!iflag || g_parsefile->pf_fd != STDIN_FILENO)
  9362. nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
  9363. else {
  9364. # if ENABLE_ASH_IDLE_TIMEOUT
  9365. int timeout = -1;
  9366. if (iflag) {
  9367. const char *tmout_var = lookupvar("TMOUT");
  9368. if (tmout_var) {
  9369. timeout = atoi(tmout_var) * 1000;
  9370. if (timeout <= 0)
  9371. timeout = -1;
  9372. }
  9373. }
  9374. line_input_state->timeout = timeout;
  9375. # endif
  9376. # if ENABLE_FEATURE_TAB_COMPLETION
  9377. line_input_state->path_lookup = pathval();
  9378. # endif
  9379. reinit_unicode_for_ash();
  9380. nr = read_line_input(line_input_state, cmdedit_prompt, buf, IBUFSIZ);
  9381. if (nr == 0) {
  9382. /* ^C pressed, "convert" to SIGINT */
  9383. write(STDOUT_FILENO, "^C", 2);
  9384. if (trap[SIGINT]) {
  9385. buf[0] = '\n';
  9386. buf[1] = '\0';
  9387. raise(SIGINT);
  9388. return 1;
  9389. }
  9390. exitstatus = 128 + SIGINT;
  9391. bb_putchar('\n');
  9392. goto retry;
  9393. }
  9394. if (nr < 0) {
  9395. if (errno == 0) {
  9396. /* Ctrl+D pressed */
  9397. nr = 0;
  9398. }
  9399. # if ENABLE_ASH_IDLE_TIMEOUT
  9400. else if (errno == EAGAIN && timeout > 0) {
  9401. puts("\007timed out waiting for input: auto-logout");
  9402. exitshell();
  9403. }
  9404. # endif
  9405. }
  9406. }
  9407. #else
  9408. nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
  9409. #endif
  9410. #if 0 /* disabled: nonblock_immune_read() handles this problem */
  9411. if (nr < 0) {
  9412. if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
  9413. int flags = fcntl(0, F_GETFL);
  9414. if (flags >= 0 && (flags & O_NONBLOCK)) {
  9415. flags &= ~O_NONBLOCK;
  9416. if (fcntl(0, F_SETFL, flags) >= 0) {
  9417. out2str("sh: turning off NDELAY mode\n");
  9418. goto retry;
  9419. }
  9420. }
  9421. }
  9422. }
  9423. #endif
  9424. return nr;
  9425. }
  9426. /*
  9427. * Refill the input buffer and return the next input character:
  9428. *
  9429. * 1) If a string was pushed back on the input, pop it;
  9430. * 2) If an EOF was pushed back (g_parsefile->left_in_line < -BIGNUM)
  9431. * or we are reading from a string so we can't refill the buffer,
  9432. * return EOF.
  9433. * 3) If there is more stuff in this buffer, use it else call read to fill it.
  9434. * 4) Process input up to the next newline, deleting nul characters.
  9435. */
  9436. //#define pgetc_debug(...) bb_error_msg(__VA_ARGS__)
  9437. #define pgetc_debug(...) ((void)0)
  9438. static int pgetc(void);
  9439. static int
  9440. preadbuffer(void)
  9441. {
  9442. char *q;
  9443. int more;
  9444. if (g_parsefile->strpush) {
  9445. #if ENABLE_ASH_ALIAS
  9446. if (g_parsefile->left_in_line == -1
  9447. && g_parsefile->strpush->ap
  9448. && g_parsefile->next_to_pgetc[-1] != ' '
  9449. && g_parsefile->next_to_pgetc[-1] != '\t'
  9450. ) {
  9451. pgetc_debug("preadbuffer PEOA");
  9452. return PEOA;
  9453. }
  9454. #endif
  9455. popstring();
  9456. return pgetc();
  9457. }
  9458. /* on both branches above g_parsefile->left_in_line < 0.
  9459. * "pgetc" needs refilling.
  9460. */
  9461. /* -90 is our -BIGNUM. Below we use -99 to mark "EOF on read",
  9462. * pungetc() may increment it a few times.
  9463. * Assuming it won't increment it to less than -90.
  9464. */
  9465. if (g_parsefile->left_in_line < -90 || g_parsefile->buf == NULL) {
  9466. pgetc_debug("preadbuffer PEOF1");
  9467. /* even in failure keep left_in_line and next_to_pgetc
  9468. * in lock step, for correct multi-layer pungetc.
  9469. * left_in_line was decremented before preadbuffer(),
  9470. * must inc next_to_pgetc: */
  9471. g_parsefile->next_to_pgetc++;
  9472. return PEOF;
  9473. }
  9474. more = g_parsefile->left_in_buffer;
  9475. if (more <= 0) {
  9476. flush_stdout_stderr();
  9477. again:
  9478. more = preadfd();
  9479. if (more <= 0) {
  9480. /* don't try reading again */
  9481. g_parsefile->left_in_line = -99;
  9482. pgetc_debug("preadbuffer PEOF2");
  9483. g_parsefile->next_to_pgetc++;
  9484. return PEOF;
  9485. }
  9486. }
  9487. /* Find out where's the end of line.
  9488. * Set g_parsefile->left_in_line
  9489. * and g_parsefile->left_in_buffer acordingly.
  9490. * NUL chars are deleted.
  9491. */
  9492. q = g_parsefile->next_to_pgetc;
  9493. for (;;) {
  9494. char c;
  9495. more--;
  9496. c = *q;
  9497. if (c == '\0') {
  9498. memmove(q, q + 1, more);
  9499. } else {
  9500. q++;
  9501. if (c == '\n') {
  9502. g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
  9503. break;
  9504. }
  9505. }
  9506. if (more <= 0) {
  9507. g_parsefile->left_in_line = q - g_parsefile->next_to_pgetc - 1;
  9508. if (g_parsefile->left_in_line < 0)
  9509. goto again;
  9510. break;
  9511. }
  9512. }
  9513. g_parsefile->left_in_buffer = more;
  9514. if (vflag) {
  9515. char save = *q;
  9516. *q = '\0';
  9517. out2str(g_parsefile->next_to_pgetc);
  9518. *q = save;
  9519. }
  9520. pgetc_debug("preadbuffer at %d:%p'%s'",
  9521. g_parsefile->left_in_line,
  9522. g_parsefile->next_to_pgetc,
  9523. g_parsefile->next_to_pgetc);
  9524. return (unsigned char)*g_parsefile->next_to_pgetc++;
  9525. }
  9526. static void
  9527. nlprompt(void)
  9528. {
  9529. g_parsefile->linno++;
  9530. setprompt_if(doprompt, 2);
  9531. }
  9532. static void
  9533. nlnoprompt(void)
  9534. {
  9535. g_parsefile->linno++;
  9536. needprompt = doprompt;
  9537. }
  9538. static int
  9539. pgetc(void)
  9540. {
  9541. int c;
  9542. pgetc_debug("pgetc at %d:%p'%s'",
  9543. g_parsefile->left_in_line,
  9544. g_parsefile->next_to_pgetc,
  9545. g_parsefile->next_to_pgetc);
  9546. if (g_parsefile->unget)
  9547. return g_parsefile->lastc[--g_parsefile->unget];
  9548. if (--g_parsefile->left_in_line >= 0)
  9549. c = (unsigned char)*g_parsefile->next_to_pgetc++;
  9550. else
  9551. c = preadbuffer();
  9552. g_parsefile->lastc[1] = g_parsefile->lastc[0];
  9553. g_parsefile->lastc[0] = c;
  9554. return c;
  9555. }
  9556. #if ENABLE_ASH_ALIAS
  9557. static int
  9558. pgetc_without_PEOA(void)
  9559. {
  9560. int c;
  9561. do {
  9562. pgetc_debug("pgetc at %d:%p'%s'",
  9563. g_parsefile->left_in_line,
  9564. g_parsefile->next_to_pgetc,
  9565. g_parsefile->next_to_pgetc);
  9566. c = pgetc();
  9567. } while (c == PEOA);
  9568. return c;
  9569. }
  9570. #else
  9571. # define pgetc_without_PEOA() pgetc()
  9572. #endif
  9573. /*
  9574. * Undo a call to pgetc. Only two characters may be pushed back.
  9575. * PEOF may be pushed back.
  9576. */
  9577. static void
  9578. pungetc(void)
  9579. {
  9580. g_parsefile->unget++;
  9581. }
  9582. /* This one eats backslash+newline */
  9583. static int
  9584. pgetc_eatbnl(void)
  9585. {
  9586. int c;
  9587. while ((c = pgetc()) == '\\') {
  9588. if (pgetc() != '\n') {
  9589. pungetc();
  9590. break;
  9591. }
  9592. nlprompt();
  9593. }
  9594. return c;
  9595. }
  9596. /*
  9597. * To handle the "." command, a stack of input files is used. Pushfile
  9598. * adds a new entry to the stack and popfile restores the previous level.
  9599. */
  9600. static void
  9601. pushfile(void)
  9602. {
  9603. struct parsefile *pf;
  9604. pf = ckzalloc(sizeof(*pf));
  9605. pf->prev = g_parsefile;
  9606. pf->pf_fd = -1;
  9607. /*pf->strpush = NULL; - ckzalloc did it */
  9608. /*pf->basestrpush.prev = NULL;*/
  9609. /*pf->unget = 0;*/
  9610. g_parsefile = pf;
  9611. }
  9612. static void
  9613. popfile(void)
  9614. {
  9615. struct parsefile *pf = g_parsefile;
  9616. if (pf == &basepf)
  9617. return;
  9618. INT_OFF;
  9619. if (pf->pf_fd >= 0)
  9620. close(pf->pf_fd);
  9621. free(pf->buf);
  9622. while (pf->strpush)
  9623. popstring();
  9624. g_parsefile = pf->prev;
  9625. free(pf);
  9626. INT_ON;
  9627. }
  9628. /*
  9629. * Return to top level.
  9630. */
  9631. static void
  9632. popallfiles(void)
  9633. {
  9634. while (g_parsefile != &basepf)
  9635. popfile();
  9636. }
  9637. /*
  9638. * Close the file(s) that the shell is reading commands from. Called
  9639. * after a fork is done.
  9640. */
  9641. static void
  9642. closescript(void)
  9643. {
  9644. popallfiles();
  9645. if (g_parsefile->pf_fd > 0) {
  9646. close(g_parsefile->pf_fd);
  9647. g_parsefile->pf_fd = 0;
  9648. }
  9649. }
  9650. /*
  9651. * Like setinputfile, but takes an open file descriptor. Call this with
  9652. * interrupts off.
  9653. */
  9654. static void
  9655. setinputfd(int fd, int push)
  9656. {
  9657. if (push) {
  9658. pushfile();
  9659. g_parsefile->buf = NULL;
  9660. }
  9661. g_parsefile->pf_fd = fd;
  9662. if (g_parsefile->buf == NULL)
  9663. g_parsefile->buf = ckmalloc(IBUFSIZ);
  9664. g_parsefile->left_in_buffer = 0;
  9665. g_parsefile->left_in_line = 0;
  9666. g_parsefile->linno = 1;
  9667. }
  9668. /*
  9669. * Set the input to take input from a file. If push is set, push the
  9670. * old input onto the stack first.
  9671. */
  9672. static int
  9673. setinputfile(const char *fname, int flags)
  9674. {
  9675. int fd;
  9676. INT_OFF;
  9677. fd = open(fname, O_RDONLY);
  9678. if (fd < 0) {
  9679. if (flags & INPUT_NOFILE_OK)
  9680. goto out;
  9681. exitstatus = 127;
  9682. ash_msg_and_raise_perror("can't open '%s'", fname);
  9683. }
  9684. if (fd < 10)
  9685. fd = savefd(fd);
  9686. else
  9687. close_on_exec_on(fd);
  9688. setinputfd(fd, flags & INPUT_PUSH_FILE);
  9689. out:
  9690. INT_ON;
  9691. return fd;
  9692. }
  9693. /*
  9694. * Like setinputfile, but takes input from a string.
  9695. */
  9696. static void
  9697. setinputstring(char *string)
  9698. {
  9699. INT_OFF;
  9700. pushfile();
  9701. g_parsefile->next_to_pgetc = string;
  9702. g_parsefile->left_in_line = strlen(string);
  9703. g_parsefile->buf = NULL;
  9704. g_parsefile->linno = 1;
  9705. INT_ON;
  9706. }
  9707. /*
  9708. * Routines to check for mail.
  9709. */
  9710. #if ENABLE_ASH_MAIL
  9711. /* Hash of mtimes of mailboxes */
  9712. static unsigned mailtime_hash;
  9713. /* Set if MAIL or MAILPATH is changed. */
  9714. static smallint mail_var_path_changed;
  9715. /*
  9716. * Print appropriate message(s) if mail has arrived.
  9717. * If mail_var_path_changed is set,
  9718. * then the value of MAIL has mail_var_path_changed,
  9719. * so we just update the values.
  9720. */
  9721. static void
  9722. chkmail(void)
  9723. {
  9724. const char *mpath;
  9725. char *p;
  9726. char *q;
  9727. unsigned new_hash;
  9728. struct stackmark smark;
  9729. struct stat statb;
  9730. setstackmark(&smark);
  9731. mpath = mpathset() ? mpathval() : mailval();
  9732. new_hash = 0;
  9733. for (;;) {
  9734. p = path_advance(&mpath, nullstr);
  9735. if (p == NULL)
  9736. break;
  9737. if (*p == '\0')
  9738. continue;
  9739. for (q = p; *q; q++)
  9740. continue;
  9741. #if DEBUG
  9742. if (q[-1] != '/')
  9743. abort();
  9744. #endif
  9745. q[-1] = '\0'; /* delete trailing '/' */
  9746. if (stat(p, &statb) < 0) {
  9747. continue;
  9748. }
  9749. /* Very simplistic "hash": just a sum of all mtimes */
  9750. new_hash += (unsigned)statb.st_mtime;
  9751. }
  9752. if (!mail_var_path_changed && mailtime_hash != new_hash) {
  9753. if (mailtime_hash != 0)
  9754. out2str("you have mail\n");
  9755. mailtime_hash = new_hash;
  9756. }
  9757. mail_var_path_changed = 0;
  9758. popstackmark(&smark);
  9759. }
  9760. static void FAST_FUNC
  9761. changemail(const char *val UNUSED_PARAM)
  9762. {
  9763. mail_var_path_changed = 1;
  9764. }
  9765. #endif /* ASH_MAIL */
  9766. /* ============ ??? */
  9767. /*
  9768. * Set the shell parameters.
  9769. */
  9770. static void
  9771. setparam(char **argv)
  9772. {
  9773. char **newparam;
  9774. char **ap;
  9775. int nparam;
  9776. for (nparam = 0; argv[nparam]; nparam++)
  9777. continue;
  9778. ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
  9779. while (*argv) {
  9780. *ap++ = ckstrdup(*argv++);
  9781. }
  9782. *ap = NULL;
  9783. freeparam(&shellparam);
  9784. shellparam.malloced = 1;
  9785. shellparam.nparam = nparam;
  9786. shellparam.p = newparam;
  9787. #if ENABLE_ASH_GETOPTS
  9788. shellparam.optind = 1;
  9789. shellparam.optoff = -1;
  9790. #endif
  9791. }
  9792. /*
  9793. * Process shell options. The global variable argptr contains a pointer
  9794. * to the argument list; we advance it past the options.
  9795. *
  9796. * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
  9797. * For a non-interactive shell, an error condition encountered
  9798. * by a special built-in ... shall cause the shell to write a diagnostic message
  9799. * to standard error and exit as shown in the following table:
  9800. * Error Special Built-In
  9801. * ...
  9802. * Utility syntax error (option or operand error) Shall exit
  9803. * ...
  9804. * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
  9805. * we see that bash does not do that (set "finishes" with error code 1 instead,
  9806. * and shell continues), and people rely on this behavior!
  9807. * Testcase:
  9808. * set -o barfoo 2>/dev/null
  9809. * echo $?
  9810. *
  9811. * Oh well. Let's mimic that.
  9812. */
  9813. static int
  9814. plus_minus_o(char *name, int val)
  9815. {
  9816. int i;
  9817. if (name) {
  9818. for (i = 0; i < NOPTS; i++) {
  9819. if (strcmp(name, optnames(i)) == 0) {
  9820. optlist[i] = val;
  9821. return 0;
  9822. }
  9823. }
  9824. ash_msg("illegal option %co %s", val ? '-' : '+', name);
  9825. return 1;
  9826. }
  9827. for (i = 0; i < NOPTS; i++) {
  9828. if (val) {
  9829. out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
  9830. } else {
  9831. out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
  9832. }
  9833. }
  9834. return 0;
  9835. }
  9836. static void
  9837. setoption(int flag, int val)
  9838. {
  9839. int i;
  9840. for (i = 0; i < NOPTS; i++) {
  9841. if (optletters(i) == flag) {
  9842. optlist[i] = val;
  9843. return;
  9844. }
  9845. }
  9846. ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
  9847. /* NOTREACHED */
  9848. }
  9849. static int
  9850. options(int cmdline, int *login_sh)
  9851. {
  9852. char *p;
  9853. int val;
  9854. int c;
  9855. if (cmdline)
  9856. minusc = NULL;
  9857. while ((p = *argptr) != NULL) {
  9858. c = *p++;
  9859. if (c != '-' && c != '+')
  9860. break;
  9861. argptr++;
  9862. val = 0; /* val = 0 if c == '+' */
  9863. if (c == '-') {
  9864. val = 1;
  9865. if (p[0] == '\0' || LONE_DASH(p)) {
  9866. if (!cmdline) {
  9867. /* "-" means turn off -x and -v */
  9868. if (p[0] == '\0')
  9869. xflag = vflag = 0;
  9870. /* "--" means reset params */
  9871. else if (*argptr == NULL)
  9872. setparam(argptr);
  9873. }
  9874. break; /* "-" or "--" terminates options */
  9875. }
  9876. }
  9877. /* first char was + or - */
  9878. while ((c = *p++) != '\0') {
  9879. /* bash 3.2 indeed handles -c CMD and +c CMD the same */
  9880. if (c == 'c' && cmdline) {
  9881. minusc = p; /* command is after shell args */
  9882. } else if (c == 'o') {
  9883. if (plus_minus_o(*argptr, val)) {
  9884. /* it already printed err message */
  9885. return 1; /* error */
  9886. }
  9887. if (*argptr)
  9888. argptr++;
  9889. } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
  9890. if (login_sh)
  9891. *login_sh = 1;
  9892. /* bash does not accept +-login, we also won't */
  9893. } else if (cmdline && val && (c == '-')) { /* long options */
  9894. if (strcmp(p, "login") == 0) {
  9895. if (login_sh)
  9896. *login_sh = 1;
  9897. }
  9898. break;
  9899. } else {
  9900. setoption(c, val);
  9901. }
  9902. }
  9903. }
  9904. return 0;
  9905. }
  9906. /*
  9907. * The shift builtin command.
  9908. */
  9909. static int FAST_FUNC
  9910. shiftcmd(int argc UNUSED_PARAM, char **argv)
  9911. {
  9912. int n;
  9913. char **ap1, **ap2;
  9914. n = 1;
  9915. if (argv[1])
  9916. n = number(argv[1]);
  9917. if (n > shellparam.nparam)
  9918. return 1;
  9919. INT_OFF;
  9920. shellparam.nparam -= n;
  9921. for (ap1 = shellparam.p; --n >= 0; ap1++) {
  9922. if (shellparam.malloced)
  9923. free(*ap1);
  9924. }
  9925. ap2 = shellparam.p;
  9926. while ((*ap2++ = *ap1++) != NULL)
  9927. continue;
  9928. #if ENABLE_ASH_GETOPTS
  9929. shellparam.optind = 1;
  9930. shellparam.optoff = -1;
  9931. #endif
  9932. INT_ON;
  9933. return 0;
  9934. }
  9935. /*
  9936. * POSIX requires that 'set' (but not export or readonly) output the
  9937. * variables in lexicographic order - by the locale's collating order (sigh).
  9938. * Maybe we could keep them in an ordered balanced binary tree
  9939. * instead of hashed lists.
  9940. * For now just roll 'em through qsort for printing...
  9941. */
  9942. static int
  9943. showvars(const char *sep_prefix, int on, int off)
  9944. {
  9945. const char *sep;
  9946. char **ep, **epend;
  9947. ep = listvars(on, off, /*strlist:*/ NULL, &epend);
  9948. qsort(ep, epend - ep, sizeof(char *), vpcmp);
  9949. sep = *sep_prefix ? " " : sep_prefix;
  9950. for (; ep < epend; ep++) {
  9951. const char *p;
  9952. const char *q;
  9953. p = endofname(*ep);
  9954. /* Used to have simple "p = strchrnul(*ep, '=')" here instead, but this
  9955. * makes "export -p" to have output not suitable for "eval":
  9956. * import os
  9957. * os.environ["test-test"]="test"
  9958. * if os.fork() == 0:
  9959. * os.execv("ash", [ 'ash', '-c', 'eval $(export -p); echo OK' ]) # fixes this
  9960. * os.execv("ash", [ 'ash', '-c', 'env | grep test-test' ])
  9961. */
  9962. q = nullstr;
  9963. if (*p == '=')
  9964. q = single_quote(++p);
  9965. out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
  9966. }
  9967. return 0;
  9968. }
  9969. /*
  9970. * The set command builtin.
  9971. */
  9972. static int FAST_FUNC
  9973. setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  9974. {
  9975. int retval;
  9976. if (!argv[1])
  9977. return showvars(nullstr, 0, VUNSET);
  9978. INT_OFF;
  9979. retval = options(/*cmdline:*/ 0, NULL);
  9980. if (retval == 0) { /* if no parse error... */
  9981. optschanged();
  9982. if (*argptr != NULL) {
  9983. setparam(argptr);
  9984. }
  9985. }
  9986. INT_ON;
  9987. return retval;
  9988. }
  9989. #if ENABLE_ASH_RANDOM_SUPPORT
  9990. static void FAST_FUNC
  9991. change_random(const char *value)
  9992. {
  9993. uint32_t t;
  9994. if (value == NULL) {
  9995. /* "get", generate */
  9996. t = next_random(&random_gen);
  9997. /* set without recursion */
  9998. setvar(vrandom.var_text, utoa(t), VNOFUNC);
  9999. vrandom.flags &= ~VNOFUNC;
  10000. } else {
  10001. /* set/reset */
  10002. t = strtoul(value, NULL, 10);
  10003. INIT_RANDOM_T(&random_gen, (t ? t : 1), t);
  10004. }
  10005. }
  10006. #endif
  10007. #if ENABLE_ASH_GETOPTS
  10008. static int
  10009. getopts(char *optstr, char *optvar, char **optfirst)
  10010. {
  10011. char *p, *q;
  10012. char c = '?';
  10013. int done = 0;
  10014. char sbuf[2];
  10015. char **optnext;
  10016. int ind = shellparam.optind;
  10017. int off = shellparam.optoff;
  10018. sbuf[1] = '\0';
  10019. shellparam.optind = -1;
  10020. optnext = optfirst + ind - 1;
  10021. if (ind <= 1 || off < 0 || (int)strlen(optnext[-1]) < off)
  10022. p = NULL;
  10023. else
  10024. p = optnext[-1] + off;
  10025. if (p == NULL || *p == '\0') {
  10026. /* Current word is done, advance */
  10027. p = *optnext;
  10028. if (p == NULL || *p != '-' || *++p == '\0') {
  10029. atend:
  10030. unsetvar("OPTARG");
  10031. p = NULL;
  10032. done = 1;
  10033. goto out;
  10034. }
  10035. optnext++;
  10036. if (LONE_DASH(p)) /* check for "--" */
  10037. goto atend;
  10038. }
  10039. c = *p++;
  10040. for (q = optstr; *q != c;) {
  10041. if (*q == '\0') {
  10042. /* OPTERR is a bashism */
  10043. const char *cp = lookupvar("OPTERR");
  10044. if ((cp && LONE_CHAR(cp, '0'))
  10045. || (optstr[0] == ':')
  10046. ) {
  10047. sbuf[0] = c;
  10048. /*sbuf[1] = '\0'; - already is */
  10049. setvar0("OPTARG", sbuf);
  10050. } else {
  10051. fprintf(stderr, "Illegal option -%c\n", c);
  10052. unsetvar("OPTARG");
  10053. }
  10054. c = '?';
  10055. goto out;
  10056. }
  10057. if (*++q == ':')
  10058. q++;
  10059. }
  10060. if (*++q == ':') {
  10061. if (*p == '\0' && (p = *optnext) == NULL) {
  10062. /* OPTERR is a bashism */
  10063. const char *cp = lookupvar("OPTERR");
  10064. if ((cp && LONE_CHAR(cp, '0'))
  10065. || (optstr[0] == ':')
  10066. ) {
  10067. sbuf[0] = c;
  10068. /*sbuf[1] = '\0'; - already is */
  10069. setvar0("OPTARG", sbuf);
  10070. c = ':';
  10071. } else {
  10072. fprintf(stderr, "No arg for -%c option\n", c);
  10073. unsetvar("OPTARG");
  10074. c = '?';
  10075. }
  10076. goto out;
  10077. }
  10078. if (p == *optnext)
  10079. optnext++;
  10080. setvar0("OPTARG", p);
  10081. p = NULL;
  10082. } else
  10083. setvar0("OPTARG", nullstr);
  10084. out:
  10085. ind = optnext - optfirst + 1;
  10086. setvar("OPTIND", itoa(ind), VNOFUNC);
  10087. sbuf[0] = c;
  10088. /*sbuf[1] = '\0'; - already is */
  10089. setvar0(optvar, sbuf);
  10090. shellparam.optoff = p ? p - *(optnext - 1) : -1;
  10091. shellparam.optind = ind;
  10092. return done;
  10093. }
  10094. /*
  10095. * The getopts builtin. Shellparam.optnext points to the next argument
  10096. * to be processed. Shellparam.optptr points to the next character to
  10097. * be processed in the current argument. If shellparam.optnext is NULL,
  10098. * then it's the first time getopts has been called.
  10099. */
  10100. static int FAST_FUNC
  10101. getoptscmd(int argc, char **argv)
  10102. {
  10103. char **optbase;
  10104. if (argc < 3)
  10105. ash_msg_and_raise_error("usage: getopts optstring var [arg]");
  10106. if (argc == 3) {
  10107. optbase = shellparam.p;
  10108. if ((unsigned)shellparam.optind > shellparam.nparam + 1) {
  10109. shellparam.optind = 1;
  10110. shellparam.optoff = -1;
  10111. }
  10112. } else {
  10113. optbase = &argv[3];
  10114. if ((unsigned)shellparam.optind > argc - 2) {
  10115. shellparam.optind = 1;
  10116. shellparam.optoff = -1;
  10117. }
  10118. }
  10119. return getopts(argv[1], argv[2], optbase);
  10120. }
  10121. #endif /* ASH_GETOPTS */
  10122. /* ============ Shell parser */
  10123. struct heredoc {
  10124. struct heredoc *next; /* next here document in list */
  10125. union node *here; /* redirection node */
  10126. char *eofmark; /* string indicating end of input */
  10127. smallint striptabs; /* if set, strip leading tabs */
  10128. };
  10129. static smallint tokpushback; /* last token pushed back */
  10130. static smallint quoteflag; /* set if (part of) last token was quoted */
  10131. static token_id_t lasttoken; /* last token read (integer id Txxx) */
  10132. static struct heredoc *heredoclist; /* list of here documents to read */
  10133. static char *wordtext; /* text of last word returned by readtoken */
  10134. static struct nodelist *backquotelist;
  10135. static union node *redirnode;
  10136. static struct heredoc *heredoc;
  10137. static const char *
  10138. tokname(char *buf, int tok)
  10139. {
  10140. if (tok < TSEMI)
  10141. return tokname_array[tok];
  10142. sprintf(buf, "\"%s\"", tokname_array[tok]);
  10143. return buf;
  10144. }
  10145. /* raise_error_unexpected_syntax:
  10146. * Called when an unexpected token is read during the parse. The argument
  10147. * is the token that is expected, or -1 if more than one type of token can
  10148. * occur at this point.
  10149. */
  10150. static void raise_error_unexpected_syntax(int) NORETURN;
  10151. static void
  10152. raise_error_unexpected_syntax(int token)
  10153. {
  10154. char msg[64];
  10155. char buf[16];
  10156. int l;
  10157. l = sprintf(msg, "unexpected %s", tokname(buf, lasttoken));
  10158. if (token >= 0)
  10159. sprintf(msg + l, " (expecting %s)", tokname(buf, token));
  10160. raise_error_syntax(msg);
  10161. /* NOTREACHED */
  10162. }
  10163. /* parsing is heavily cross-recursive, need these forward decls */
  10164. static union node *andor(void);
  10165. static union node *pipeline(void);
  10166. static union node *parse_command(void);
  10167. static void parseheredoc(void);
  10168. static int peektoken(void);
  10169. static int readtoken(void);
  10170. static union node *
  10171. list(int nlflag)
  10172. {
  10173. union node *n1, *n2, *n3;
  10174. int tok;
  10175. n1 = NULL;
  10176. for (;;) {
  10177. switch (peektoken()) {
  10178. case TNL:
  10179. if (!(nlflag & 1))
  10180. break;
  10181. parseheredoc();
  10182. return n1;
  10183. case TEOF:
  10184. if (!n1 && (nlflag & 1))
  10185. n1 = NODE_EOF;
  10186. parseheredoc();
  10187. return n1;
  10188. }
  10189. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  10190. if (nlflag == 2 && ((1 << peektoken()) & tokendlist))
  10191. return n1;
  10192. nlflag |= 2;
  10193. n2 = andor();
  10194. tok = readtoken();
  10195. if (tok == TBACKGND) {
  10196. if (n2->type == NPIPE) {
  10197. n2->npipe.pipe_backgnd = 1;
  10198. } else {
  10199. if (n2->type != NREDIR) {
  10200. n3 = stzalloc(sizeof(struct nredir));
  10201. n3->nredir.n = n2;
  10202. /*n3->nredir.redirect = NULL; - stzalloc did it */
  10203. n2 = n3;
  10204. }
  10205. n2->type = NBACKGND;
  10206. }
  10207. }
  10208. if (n1 == NULL) {
  10209. n1 = n2;
  10210. } else {
  10211. n3 = stzalloc(sizeof(struct nbinary));
  10212. n3->type = NSEMI;
  10213. n3->nbinary.ch1 = n1;
  10214. n3->nbinary.ch2 = n2;
  10215. n1 = n3;
  10216. }
  10217. switch (tok) {
  10218. case TNL:
  10219. case TEOF:
  10220. tokpushback = 1;
  10221. /* fall through */
  10222. case TBACKGND:
  10223. case TSEMI:
  10224. break;
  10225. default:
  10226. if ((nlflag & 1))
  10227. raise_error_unexpected_syntax(-1);
  10228. tokpushback = 1;
  10229. return n1;
  10230. }
  10231. }
  10232. }
  10233. static union node *
  10234. andor(void)
  10235. {
  10236. union node *n1, *n2, *n3;
  10237. int t;
  10238. n1 = pipeline();
  10239. for (;;) {
  10240. t = readtoken();
  10241. if (t == TAND) {
  10242. t = NAND;
  10243. } else if (t == TOR) {
  10244. t = NOR;
  10245. } else {
  10246. tokpushback = 1;
  10247. return n1;
  10248. }
  10249. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  10250. n2 = pipeline();
  10251. n3 = stzalloc(sizeof(struct nbinary));
  10252. n3->type = t;
  10253. n3->nbinary.ch1 = n1;
  10254. n3->nbinary.ch2 = n2;
  10255. n1 = n3;
  10256. }
  10257. }
  10258. static union node *
  10259. pipeline(void)
  10260. {
  10261. union node *n1, *n2, *pipenode;
  10262. struct nodelist *lp, *prev;
  10263. int negate;
  10264. negate = 0;
  10265. TRACE(("pipeline: entered\n"));
  10266. if (readtoken() == TNOT) {
  10267. negate = !negate;
  10268. checkkwd = CHKKWD | CHKALIAS;
  10269. } else
  10270. tokpushback = 1;
  10271. n1 = parse_command();
  10272. if (readtoken() == TPIPE) {
  10273. pipenode = stzalloc(sizeof(struct npipe));
  10274. pipenode->type = NPIPE;
  10275. /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
  10276. lp = stzalloc(sizeof(struct nodelist));
  10277. pipenode->npipe.cmdlist = lp;
  10278. lp->n = n1;
  10279. do {
  10280. prev = lp;
  10281. lp = stzalloc(sizeof(struct nodelist));
  10282. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  10283. lp->n = parse_command();
  10284. prev->next = lp;
  10285. } while (readtoken() == TPIPE);
  10286. lp->next = NULL;
  10287. n1 = pipenode;
  10288. }
  10289. tokpushback = 1;
  10290. if (negate) {
  10291. n2 = stzalloc(sizeof(struct nnot));
  10292. n2->type = NNOT;
  10293. n2->nnot.com = n1;
  10294. return n2;
  10295. }
  10296. return n1;
  10297. }
  10298. static union node *
  10299. makename(void)
  10300. {
  10301. union node *n;
  10302. n = stzalloc(sizeof(struct narg));
  10303. n->type = NARG;
  10304. /*n->narg.next = NULL; - stzalloc did it */
  10305. n->narg.text = wordtext;
  10306. n->narg.backquote = backquotelist;
  10307. return n;
  10308. }
  10309. static void
  10310. fixredir(union node *n, const char *text, int err)
  10311. {
  10312. int fd;
  10313. TRACE(("Fix redir %s %d\n", text, err));
  10314. if (!err)
  10315. n->ndup.vname = NULL;
  10316. fd = bb_strtou(text, NULL, 10);
  10317. if (!errno && fd >= 0)
  10318. n->ndup.dupfd = fd;
  10319. else if (LONE_DASH(text))
  10320. n->ndup.dupfd = -1;
  10321. else {
  10322. if (err)
  10323. raise_error_syntax("bad fd number");
  10324. n->ndup.vname = makename();
  10325. }
  10326. }
  10327. static void
  10328. parsefname(void)
  10329. {
  10330. union node *n = redirnode;
  10331. if (n->type == NHERE)
  10332. checkkwd = CHKEOFMARK;
  10333. if (readtoken() != TWORD)
  10334. raise_error_unexpected_syntax(-1);
  10335. if (n->type == NHERE) {
  10336. struct heredoc *here = heredoc;
  10337. struct heredoc *p;
  10338. if (quoteflag == 0)
  10339. n->type = NXHERE;
  10340. TRACE(("Here document %d\n", n->type));
  10341. rmescapes(wordtext, 0);
  10342. here->eofmark = wordtext;
  10343. here->next = NULL;
  10344. if (heredoclist == NULL)
  10345. heredoclist = here;
  10346. else {
  10347. for (p = heredoclist; p->next; p = p->next)
  10348. continue;
  10349. p->next = here;
  10350. }
  10351. } else if (n->type == NTOFD || n->type == NFROMFD) {
  10352. fixredir(n, wordtext, 0);
  10353. } else {
  10354. n->nfile.fname = makename();
  10355. }
  10356. }
  10357. static union node *
  10358. simplecmd(void)
  10359. {
  10360. union node *args, **app;
  10361. union node *n = NULL;
  10362. union node *vars, **vpp;
  10363. union node **rpp, *redir;
  10364. int savecheckkwd;
  10365. #if BASH_TEST2
  10366. smallint double_brackets_flag = 0;
  10367. #endif
  10368. IF_BASH_FUNCTION(smallint function_flag = 0;)
  10369. args = NULL;
  10370. app = &args;
  10371. vars = NULL;
  10372. vpp = &vars;
  10373. redir = NULL;
  10374. rpp = &redir;
  10375. savecheckkwd = CHKALIAS;
  10376. for (;;) {
  10377. int t;
  10378. checkkwd = savecheckkwd;
  10379. t = readtoken();
  10380. switch (t) {
  10381. #if BASH_FUNCTION
  10382. case TFUNCTION:
  10383. if (peektoken() != TWORD)
  10384. raise_error_unexpected_syntax(TWORD);
  10385. function_flag = 1;
  10386. break;
  10387. #endif
  10388. #if BASH_TEST2
  10389. case TAND: /* "&&" */
  10390. case TOR: /* "||" */
  10391. if (!double_brackets_flag) {
  10392. tokpushback = 1;
  10393. goto out;
  10394. }
  10395. wordtext = (char *) (t == TAND ? "-a" : "-o");
  10396. #endif
  10397. case TWORD:
  10398. n = stzalloc(sizeof(struct narg));
  10399. n->type = NARG;
  10400. /*n->narg.next = NULL; - stzalloc did it */
  10401. n->narg.text = wordtext;
  10402. #if BASH_TEST2
  10403. if (strcmp("[[", wordtext) == 0)
  10404. double_brackets_flag = 1;
  10405. else if (strcmp("]]", wordtext) == 0)
  10406. double_brackets_flag = 0;
  10407. #endif
  10408. n->narg.backquote = backquotelist;
  10409. if (savecheckkwd && isassignment(wordtext)) {
  10410. *vpp = n;
  10411. vpp = &n->narg.next;
  10412. } else {
  10413. *app = n;
  10414. app = &n->narg.next;
  10415. savecheckkwd = 0;
  10416. }
  10417. #if BASH_FUNCTION
  10418. if (function_flag) {
  10419. checkkwd = CHKNL | CHKKWD;
  10420. switch (peektoken()) {
  10421. case TBEGIN:
  10422. case TIF:
  10423. case TCASE:
  10424. case TUNTIL:
  10425. case TWHILE:
  10426. case TFOR:
  10427. goto do_func;
  10428. case TLP:
  10429. function_flag = 0;
  10430. break;
  10431. case TWORD:
  10432. if (strcmp("[[", wordtext) == 0)
  10433. goto do_func;
  10434. /* fall through */
  10435. default:
  10436. raise_error_unexpected_syntax(-1);
  10437. }
  10438. }
  10439. #endif
  10440. break;
  10441. case TREDIR:
  10442. *rpp = n = redirnode;
  10443. rpp = &n->nfile.next;
  10444. parsefname(); /* read name of redirection file */
  10445. break;
  10446. case TLP:
  10447. IF_BASH_FUNCTION(do_func:)
  10448. if (args && app == &args->narg.next
  10449. && !vars && !redir
  10450. ) {
  10451. struct builtincmd *bcmd;
  10452. const char *name;
  10453. /* We have a function */
  10454. if (IF_BASH_FUNCTION(!function_flag &&) readtoken() != TRP)
  10455. raise_error_unexpected_syntax(TRP);
  10456. name = n->narg.text;
  10457. if (!goodname(name)
  10458. || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
  10459. ) {
  10460. raise_error_syntax("bad function name");
  10461. }
  10462. n->type = NDEFUN;
  10463. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  10464. n->narg.next = parse_command();
  10465. return n;
  10466. }
  10467. IF_BASH_FUNCTION(function_flag = 0;)
  10468. /* fall through */
  10469. default:
  10470. tokpushback = 1;
  10471. goto out;
  10472. }
  10473. }
  10474. out:
  10475. *app = NULL;
  10476. *vpp = NULL;
  10477. *rpp = NULL;
  10478. n = stzalloc(sizeof(struct ncmd));
  10479. n->type = NCMD;
  10480. n->ncmd.args = args;
  10481. n->ncmd.assign = vars;
  10482. n->ncmd.redirect = redir;
  10483. return n;
  10484. }
  10485. static union node *
  10486. parse_command(void)
  10487. {
  10488. union node *n1, *n2;
  10489. union node *ap, **app;
  10490. union node *cp, **cpp;
  10491. union node *redir, **rpp;
  10492. union node **rpp2;
  10493. int t;
  10494. redir = NULL;
  10495. rpp2 = &redir;
  10496. switch (readtoken()) {
  10497. default:
  10498. raise_error_unexpected_syntax(-1);
  10499. /* NOTREACHED */
  10500. case TIF:
  10501. n1 = stzalloc(sizeof(struct nif));
  10502. n1->type = NIF;
  10503. n1->nif.test = list(0);
  10504. if (readtoken() != TTHEN)
  10505. raise_error_unexpected_syntax(TTHEN);
  10506. n1->nif.ifpart = list(0);
  10507. n2 = n1;
  10508. while (readtoken() == TELIF) {
  10509. n2->nif.elsepart = stzalloc(sizeof(struct nif));
  10510. n2 = n2->nif.elsepart;
  10511. n2->type = NIF;
  10512. n2->nif.test = list(0);
  10513. if (readtoken() != TTHEN)
  10514. raise_error_unexpected_syntax(TTHEN);
  10515. n2->nif.ifpart = list(0);
  10516. }
  10517. if (lasttoken == TELSE)
  10518. n2->nif.elsepart = list(0);
  10519. else {
  10520. n2->nif.elsepart = NULL;
  10521. tokpushback = 1;
  10522. }
  10523. t = TFI;
  10524. break;
  10525. case TWHILE:
  10526. case TUNTIL: {
  10527. int got;
  10528. n1 = stzalloc(sizeof(struct nbinary));
  10529. n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
  10530. n1->nbinary.ch1 = list(0);
  10531. got = readtoken();
  10532. if (got != TDO) {
  10533. TRACE(("expecting DO got '%s' %s\n", tokname_array[got],
  10534. got == TWORD ? wordtext : ""));
  10535. raise_error_unexpected_syntax(TDO);
  10536. }
  10537. n1->nbinary.ch2 = list(0);
  10538. t = TDONE;
  10539. break;
  10540. }
  10541. case TFOR:
  10542. if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
  10543. raise_error_syntax("bad for loop variable");
  10544. n1 = stzalloc(sizeof(struct nfor));
  10545. n1->type = NFOR;
  10546. n1->nfor.var = wordtext;
  10547. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  10548. if (readtoken() == TIN) {
  10549. app = &ap;
  10550. while (readtoken() == TWORD) {
  10551. n2 = stzalloc(sizeof(struct narg));
  10552. n2->type = NARG;
  10553. /*n2->narg.next = NULL; - stzalloc did it */
  10554. n2->narg.text = wordtext;
  10555. n2->narg.backquote = backquotelist;
  10556. *app = n2;
  10557. app = &n2->narg.next;
  10558. }
  10559. *app = NULL;
  10560. n1->nfor.args = ap;
  10561. if (lasttoken != TNL && lasttoken != TSEMI)
  10562. raise_error_unexpected_syntax(-1);
  10563. } else {
  10564. n2 = stzalloc(sizeof(struct narg));
  10565. n2->type = NARG;
  10566. /*n2->narg.next = NULL; - stzalloc did it */
  10567. n2->narg.text = (char *)dolatstr;
  10568. /*n2->narg.backquote = NULL;*/
  10569. n1->nfor.args = n2;
  10570. /*
  10571. * Newline or semicolon here is optional (but note
  10572. * that the original Bourne shell only allowed NL).
  10573. */
  10574. if (lasttoken != TSEMI)
  10575. tokpushback = 1;
  10576. }
  10577. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  10578. if (readtoken() != TDO)
  10579. raise_error_unexpected_syntax(TDO);
  10580. n1->nfor.body = list(0);
  10581. t = TDONE;
  10582. break;
  10583. case TCASE:
  10584. n1 = stzalloc(sizeof(struct ncase));
  10585. n1->type = NCASE;
  10586. if (readtoken() != TWORD)
  10587. raise_error_unexpected_syntax(TWORD);
  10588. n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
  10589. n2->type = NARG;
  10590. /*n2->narg.next = NULL; - stzalloc did it */
  10591. n2->narg.text = wordtext;
  10592. n2->narg.backquote = backquotelist;
  10593. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  10594. if (readtoken() != TIN)
  10595. raise_error_unexpected_syntax(TIN);
  10596. cpp = &n1->ncase.cases;
  10597. next_case:
  10598. checkkwd = CHKNL | CHKKWD;
  10599. t = readtoken();
  10600. while (t != TESAC) {
  10601. if (lasttoken == TLP)
  10602. readtoken();
  10603. *cpp = cp = stzalloc(sizeof(struct nclist));
  10604. cp->type = NCLIST;
  10605. app = &cp->nclist.pattern;
  10606. for (;;) {
  10607. *app = ap = stzalloc(sizeof(struct narg));
  10608. ap->type = NARG;
  10609. /*ap->narg.next = NULL; - stzalloc did it */
  10610. ap->narg.text = wordtext;
  10611. ap->narg.backquote = backquotelist;
  10612. if (readtoken() != TPIPE)
  10613. break;
  10614. app = &ap->narg.next;
  10615. readtoken();
  10616. }
  10617. //ap->narg.next = NULL;
  10618. if (lasttoken != TRP)
  10619. raise_error_unexpected_syntax(TRP);
  10620. cp->nclist.body = list(2);
  10621. cpp = &cp->nclist.next;
  10622. checkkwd = CHKNL | CHKKWD;
  10623. t = readtoken();
  10624. if (t != TESAC) {
  10625. if (t != TENDCASE)
  10626. raise_error_unexpected_syntax(TENDCASE);
  10627. goto next_case;
  10628. }
  10629. }
  10630. *cpp = NULL;
  10631. goto redir;
  10632. case TLP:
  10633. n1 = stzalloc(sizeof(struct nredir));
  10634. n1->type = NSUBSHELL;
  10635. n1->nredir.n = list(0);
  10636. /*n1->nredir.redirect = NULL; - stzalloc did it */
  10637. t = TRP;
  10638. break;
  10639. case TBEGIN:
  10640. n1 = list(0);
  10641. t = TEND;
  10642. break;
  10643. IF_BASH_FUNCTION(case TFUNCTION:)
  10644. case TWORD:
  10645. case TREDIR:
  10646. tokpushback = 1;
  10647. return simplecmd();
  10648. }
  10649. if (readtoken() != t)
  10650. raise_error_unexpected_syntax(t);
  10651. redir:
  10652. /* Now check for redirection which may follow command */
  10653. checkkwd = CHKKWD | CHKALIAS;
  10654. rpp = rpp2;
  10655. while (readtoken() == TREDIR) {
  10656. *rpp = n2 = redirnode;
  10657. rpp = &n2->nfile.next;
  10658. parsefname();
  10659. }
  10660. tokpushback = 1;
  10661. *rpp = NULL;
  10662. if (redir) {
  10663. if (n1->type != NSUBSHELL) {
  10664. n2 = stzalloc(sizeof(struct nredir));
  10665. n2->type = NREDIR;
  10666. n2->nredir.n = n1;
  10667. n1 = n2;
  10668. }
  10669. n1->nredir.redirect = redir;
  10670. }
  10671. return n1;
  10672. }
  10673. #if BASH_DOLLAR_SQUOTE
  10674. static int
  10675. decode_dollar_squote(void)
  10676. {
  10677. static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
  10678. int c, cnt;
  10679. char *p;
  10680. char buf[4];
  10681. c = pgetc();
  10682. p = strchr(C_escapes, c);
  10683. if (p) {
  10684. buf[0] = c;
  10685. p = buf;
  10686. cnt = 3;
  10687. if ((unsigned char)(c - '0') <= 7) { /* \ooo */
  10688. do {
  10689. c = pgetc();
  10690. *++p = c;
  10691. } while ((unsigned char)(c - '0') <= 7 && --cnt);
  10692. pungetc();
  10693. } else if (c == 'x') { /* \xHH */
  10694. do {
  10695. c = pgetc();
  10696. *++p = c;
  10697. } while (isxdigit(c) && --cnt);
  10698. pungetc();
  10699. if (cnt == 3) { /* \x but next char is "bad" */
  10700. c = 'x';
  10701. goto unrecognized;
  10702. }
  10703. } else { /* simple seq like \\ or \t */
  10704. p++;
  10705. }
  10706. *p = '\0';
  10707. p = buf;
  10708. c = bb_process_escape_sequence((void*)&p);
  10709. } else { /* unrecognized "\z": print both chars unless ' or " */
  10710. if (c != '\'' && c != '"') {
  10711. unrecognized:
  10712. c |= 0x100; /* "please encode \, then me" */
  10713. }
  10714. }
  10715. return c;
  10716. }
  10717. #endif
  10718. /* Used by expandstr to get here-doc like behaviour. */
  10719. #define FAKEEOFMARK ((char*)(uintptr_t)1)
  10720. static ALWAYS_INLINE int
  10721. realeofmark(const char *eofmark)
  10722. {
  10723. return eofmark && eofmark != FAKEEOFMARK;
  10724. }
  10725. /*
  10726. * If eofmark is NULL, read a word or a redirection symbol. If eofmark
  10727. * is not NULL, read a here document. In the latter case, eofmark is the
  10728. * word which marks the end of the document and striptabs is true if
  10729. * leading tabs should be stripped from the document. The argument c
  10730. * is the first character of the input token or document.
  10731. *
  10732. * Because C does not have internal subroutines, I have simulated them
  10733. * using goto's to implement the subroutine linkage. The following macros
  10734. * will run code that appears at the end of readtoken1.
  10735. */
  10736. #define CHECKEND() {goto checkend; checkend_return:;}
  10737. #define PARSEREDIR() {goto parseredir; parseredir_return:;}
  10738. #define PARSESUB() {goto parsesub; parsesub_return:;}
  10739. #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
  10740. #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
  10741. #define PARSEARITH() {goto parsearith; parsearith_return:;}
  10742. static int
  10743. readtoken1(int c, int syntax, char *eofmark, int striptabs)
  10744. {
  10745. /* NB: syntax parameter fits into smallint */
  10746. /* c parameter is an unsigned char or PEOF or PEOA */
  10747. char *out;
  10748. size_t len;
  10749. struct nodelist *bqlist;
  10750. smallint quotef;
  10751. smallint dblquote;
  10752. smallint oldstyle;
  10753. IF_FEATURE_SH_MATH(smallint prevsyntax;) /* syntax before arithmetic */
  10754. smallint pssyntax; /* we are expanding a prompt string */
  10755. int varnest; /* levels of variables expansion */
  10756. IF_FEATURE_SH_MATH(int arinest;) /* levels of arithmetic expansion */
  10757. IF_FEATURE_SH_MATH(int parenlevel;) /* levels of parens in arithmetic */
  10758. int dqvarnest; /* levels of variables expansion within double quotes */
  10759. IF_BASH_DOLLAR_SQUOTE(smallint bash_dollar_squote = 0;)
  10760. startlinno = g_parsefile->linno;
  10761. bqlist = NULL;
  10762. quotef = 0;
  10763. IF_FEATURE_SH_MATH(prevsyntax = 0;)
  10764. #if ENABLE_ASH_EXPAND_PRMT
  10765. pssyntax = (syntax == PSSYNTAX);
  10766. if (pssyntax)
  10767. syntax = DQSYNTAX;
  10768. #else
  10769. pssyntax = 0; /* constant */
  10770. #endif
  10771. dblquote = (syntax == DQSYNTAX);
  10772. varnest = 0;
  10773. IF_FEATURE_SH_MATH(arinest = 0;)
  10774. IF_FEATURE_SH_MATH(parenlevel = 0;)
  10775. dqvarnest = 0;
  10776. STARTSTACKSTR(out);
  10777. loop:
  10778. /* For each line, until end of word */
  10779. CHECKEND(); /* set c to PEOF if at end of here document */
  10780. for (;;) { /* until end of line or end of word */
  10781. CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
  10782. switch (SIT(c, syntax)) {
  10783. case CNL: /* '\n' */
  10784. if (syntax == BASESYNTAX)
  10785. goto endword; /* exit outer loop */
  10786. USTPUTC(c, out);
  10787. nlprompt();
  10788. c = pgetc();
  10789. goto loop; /* continue outer loop */
  10790. case CWORD:
  10791. USTPUTC(c, out);
  10792. break;
  10793. case CCTL:
  10794. #if BASH_DOLLAR_SQUOTE
  10795. if (c == '\\' && bash_dollar_squote) {
  10796. c = decode_dollar_squote();
  10797. if (c == '\0') {
  10798. /* skip $'\000', $'\x00' (like bash) */
  10799. break;
  10800. }
  10801. if (c & 0x100) {
  10802. /* Unknown escape. Encode as '\z' */
  10803. c = (unsigned char)c;
  10804. if (eofmark == NULL || dblquote)
  10805. USTPUTC(CTLESC, out);
  10806. USTPUTC('\\', out);
  10807. }
  10808. }
  10809. #endif
  10810. if (eofmark == NULL || dblquote)
  10811. USTPUTC(CTLESC, out);
  10812. USTPUTC(c, out);
  10813. break;
  10814. case CBACK: /* backslash */
  10815. c = pgetc_without_PEOA();
  10816. if (c == PEOF) {
  10817. USTPUTC(CTLESC, out);
  10818. USTPUTC('\\', out);
  10819. pungetc();
  10820. } else if (c == '\n') {
  10821. nlprompt();
  10822. } else {
  10823. if (pssyntax && c == '$') {
  10824. USTPUTC(CTLESC, out);
  10825. USTPUTC('\\', out);
  10826. }
  10827. /* Backslash is retained if we are in "str" and next char isn't special */
  10828. if (dblquote
  10829. && c != '\\'
  10830. && c != '`'
  10831. && c != '$'
  10832. && (c != '"' || eofmark != NULL)
  10833. ) {
  10834. USTPUTC('\\', out);
  10835. }
  10836. USTPUTC(CTLESC, out);
  10837. USTPUTC(c, out);
  10838. quotef = 1;
  10839. }
  10840. break;
  10841. case CSQUOTE:
  10842. syntax = SQSYNTAX;
  10843. quotemark:
  10844. if (eofmark == NULL) {
  10845. USTPUTC(CTLQUOTEMARK, out);
  10846. }
  10847. break;
  10848. case CDQUOTE:
  10849. syntax = DQSYNTAX;
  10850. dblquote = 1;
  10851. goto quotemark;
  10852. case CENDQUOTE:
  10853. IF_BASH_DOLLAR_SQUOTE(bash_dollar_squote = 0;)
  10854. if (eofmark != NULL && varnest == 0) {
  10855. USTPUTC(c, out);
  10856. } else {
  10857. if (dqvarnest == 0) {
  10858. syntax = BASESYNTAX;
  10859. dblquote = 0;
  10860. }
  10861. quotef = 1;
  10862. goto quotemark;
  10863. }
  10864. break;
  10865. case CVAR: /* '$' */
  10866. PARSESUB(); /* parse substitution */
  10867. break;
  10868. case CENDVAR: /* '}' */
  10869. if (varnest > 0) {
  10870. varnest--;
  10871. if (dqvarnest > 0) {
  10872. dqvarnest--;
  10873. }
  10874. c = CTLENDVAR;
  10875. }
  10876. USTPUTC(c, out);
  10877. break;
  10878. #if ENABLE_FEATURE_SH_MATH
  10879. case CLP: /* '(' in arithmetic */
  10880. parenlevel++;
  10881. USTPUTC(c, out);
  10882. break;
  10883. case CRP: /* ')' in arithmetic */
  10884. if (parenlevel > 0) {
  10885. parenlevel--;
  10886. } else {
  10887. if (pgetc_eatbnl() == ')') {
  10888. c = CTLENDARI;
  10889. if (--arinest == 0) {
  10890. syntax = prevsyntax;
  10891. }
  10892. } else {
  10893. /*
  10894. * unbalanced parens
  10895. * (don't 2nd guess - no error)
  10896. */
  10897. pungetc();
  10898. }
  10899. }
  10900. USTPUTC(c, out);
  10901. break;
  10902. #endif
  10903. case CBQUOTE: /* '`' */
  10904. PARSEBACKQOLD();
  10905. break;
  10906. case CENDFILE:
  10907. goto endword; /* exit outer loop */
  10908. case CIGN:
  10909. break;
  10910. default:
  10911. if (varnest == 0) {
  10912. #if BASH_REDIR_OUTPUT
  10913. if (c == '&') {
  10914. //Can't call pgetc_eatbnl() here, this requires three-deep pungetc()
  10915. if (pgetc() == '>')
  10916. c = 0x100 + '>'; /* flag &> */
  10917. pungetc();
  10918. }
  10919. #endif
  10920. goto endword; /* exit outer loop */
  10921. }
  10922. IF_ASH_ALIAS(if (c != PEOA))
  10923. USTPUTC(c, out);
  10924. }
  10925. c = pgetc();
  10926. } /* for (;;) */
  10927. endword:
  10928. #if ENABLE_FEATURE_SH_MATH
  10929. if (syntax == ARISYNTAX)
  10930. raise_error_syntax("missing '))'");
  10931. #endif
  10932. if (syntax != BASESYNTAX && eofmark == NULL)
  10933. raise_error_syntax("unterminated quoted string");
  10934. if (varnest != 0) {
  10935. startlinno = g_parsefile->linno;
  10936. /* { */
  10937. raise_error_syntax("missing '}'");
  10938. }
  10939. USTPUTC('\0', out);
  10940. len = out - (char *)stackblock();
  10941. out = stackblock();
  10942. if (eofmark == NULL) {
  10943. if ((c == '>' || c == '<' IF_BASH_REDIR_OUTPUT( || c == 0x100 + '>'))
  10944. && quotef == 0
  10945. ) {
  10946. if (isdigit_str9(out)) {
  10947. PARSEREDIR(); /* passed as params: out, c */
  10948. lasttoken = TREDIR;
  10949. return lasttoken;
  10950. }
  10951. /* else: non-number X seen, interpret it
  10952. * as "NNNX>file" = "NNNX >file" */
  10953. }
  10954. pungetc();
  10955. }
  10956. quoteflag = quotef;
  10957. backquotelist = bqlist;
  10958. grabstackblock(len);
  10959. wordtext = out;
  10960. lasttoken = TWORD;
  10961. return lasttoken;
  10962. /* end of readtoken routine */
  10963. /*
  10964. * Check to see whether we are at the end of the here document. When this
  10965. * is called, c is set to the first character of the next input line. If
  10966. * we are at the end of the here document, this routine sets the c to PEOF.
  10967. */
  10968. checkend: {
  10969. if (realeofmark(eofmark)) {
  10970. int markloc;
  10971. char *p;
  10972. #if ENABLE_ASH_ALIAS
  10973. if (c == PEOA)
  10974. c = pgetc_without_PEOA();
  10975. #endif
  10976. if (striptabs) {
  10977. while (c == '\t') {
  10978. c = pgetc_without_PEOA();
  10979. }
  10980. }
  10981. markloc = out - (char *)stackblock();
  10982. for (p = eofmark; STPUTC(c, out), *p; p++) {
  10983. if (c != *p)
  10984. goto more_heredoc;
  10985. c = pgetc_without_PEOA();
  10986. }
  10987. if (c == '\n' || c == PEOF) {
  10988. c = PEOF;
  10989. g_parsefile->linno++;
  10990. needprompt = doprompt;
  10991. } else {
  10992. int len_here;
  10993. more_heredoc:
  10994. p = (char *)stackblock() + markloc + 1;
  10995. len_here = out - p;
  10996. if (len_here) {
  10997. len_here -= (c >= PEOF);
  10998. c = p[-1];
  10999. if (len_here) {
  11000. char *str;
  11001. str = alloca(len_here + 1);
  11002. *(char *)mempcpy(str, p, len_here) = '\0';
  11003. pushstring(str, NULL);
  11004. }
  11005. }
  11006. }
  11007. STADJUST((char *)stackblock() + markloc - out, out);
  11008. }
  11009. goto checkend_return;
  11010. }
  11011. /*
  11012. * Parse a redirection operator. The variable "out" points to a string
  11013. * specifying the fd to be redirected. The variable "c" contains the
  11014. * first character of the redirection operator.
  11015. */
  11016. parseredir: {
  11017. /* out is already checked to be a valid number or "" */
  11018. int fd = (*out == '\0' ? -1 : atoi(out));
  11019. union node *np;
  11020. np = stzalloc(sizeof(struct nfile));
  11021. if (c == '>') {
  11022. np->nfile.fd = 1;
  11023. c = pgetc();
  11024. if (c == '>')
  11025. np->type = NAPPEND;
  11026. else if (c == '|')
  11027. np->type = NCLOBBER;
  11028. else if (c == '&')
  11029. np->type = NTOFD;
  11030. /* it also can be NTO2 (>&file), but we can't figure it out yet */
  11031. else {
  11032. np->type = NTO;
  11033. pungetc();
  11034. }
  11035. }
  11036. #if BASH_REDIR_OUTPUT
  11037. else if (c == 0x100 + '>') { /* this flags &> redirection */
  11038. np->nfile.fd = 1;
  11039. pgetc(); /* this is '>', no need to check */
  11040. np->type = NTO2;
  11041. }
  11042. #endif
  11043. else { /* c == '<' */
  11044. /*np->nfile.fd = 0; - stzalloc did it */
  11045. c = pgetc();
  11046. switch (c) {
  11047. case '<':
  11048. if (sizeof(struct nfile) != sizeof(struct nhere)) {
  11049. np = stzalloc(sizeof(struct nhere));
  11050. /*np->nfile.fd = 0; - stzalloc did it */
  11051. }
  11052. np->type = NHERE;
  11053. heredoc = stzalloc(sizeof(struct heredoc));
  11054. heredoc->here = np;
  11055. c = pgetc();
  11056. if (c == '-') {
  11057. heredoc->striptabs = 1;
  11058. } else {
  11059. /*heredoc->striptabs = 0; - stzalloc did it */
  11060. pungetc();
  11061. }
  11062. break;
  11063. case '&':
  11064. np->type = NFROMFD;
  11065. break;
  11066. case '>':
  11067. np->type = NFROMTO;
  11068. break;
  11069. default:
  11070. np->type = NFROM;
  11071. pungetc();
  11072. break;
  11073. }
  11074. }
  11075. if (fd >= 0)
  11076. np->nfile.fd = fd;
  11077. redirnode = np;
  11078. goto parseredir_return;
  11079. }
  11080. /*
  11081. * Parse a substitution. At this point, we have read the dollar sign
  11082. * and nothing else.
  11083. */
  11084. /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
  11085. * (assuming ascii char codes, as the original implementation did) */
  11086. #define is_special(c) \
  11087. (((unsigned)(c) - 33 < 32) \
  11088. && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
  11089. parsesub: {
  11090. unsigned char subtype;
  11091. int typeloc;
  11092. c = pgetc_eatbnl();
  11093. if ((checkkwd & CHKEOFMARK)
  11094. || c > 255 /* PEOA or PEOF */
  11095. || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
  11096. ) {
  11097. #if BASH_DOLLAR_SQUOTE
  11098. if (syntax != DQSYNTAX && c == '\'')
  11099. bash_dollar_squote = 1;
  11100. else
  11101. #endif
  11102. USTPUTC('$', out);
  11103. pungetc();
  11104. } else if (c == '(') {
  11105. /* $(command) or $((arith)) */
  11106. if (pgetc_eatbnl() == '(') {
  11107. #if ENABLE_FEATURE_SH_MATH
  11108. PARSEARITH();
  11109. #else
  11110. raise_error_syntax("support for $((arith)) is disabled");
  11111. #endif
  11112. } else {
  11113. pungetc();
  11114. PARSEBACKQNEW();
  11115. }
  11116. } else {
  11117. /* $VAR, $<specialchar>, ${...}, or PEOA/PEOF */
  11118. USTPUTC(CTLVAR, out);
  11119. typeloc = out - (char *)stackblock();
  11120. STADJUST(1, out);
  11121. subtype = VSNORMAL;
  11122. if (c == '{') {
  11123. c = pgetc_eatbnl();
  11124. subtype = 0;
  11125. }
  11126. varname:
  11127. if (is_name(c)) {
  11128. /* $[{[#]]NAME[}] */
  11129. do {
  11130. STPUTC(c, out);
  11131. c = pgetc_eatbnl();
  11132. } while (is_in_name(c));
  11133. } else if (isdigit(c)) {
  11134. /* $[{[#]]NUM[}] */
  11135. do {
  11136. STPUTC(c, out);
  11137. c = pgetc_eatbnl();
  11138. } while (isdigit(c));
  11139. } else {
  11140. /* $[{[#]]<specialchar>[}] */
  11141. int cc = c;
  11142. c = pgetc_eatbnl();
  11143. if (!subtype && cc == '#') {
  11144. subtype = VSLENGTH;
  11145. if (c == '_' || isalnum(c))
  11146. goto varname;
  11147. cc = c;
  11148. c = pgetc_eatbnl();
  11149. if (cc == '}' || c != '}') {
  11150. pungetc();
  11151. subtype = 0;
  11152. c = cc;
  11153. cc = '#';
  11154. }
  11155. }
  11156. if (!is_special(cc)) {
  11157. if (subtype == VSLENGTH)
  11158. subtype = 0;
  11159. goto badsub;
  11160. }
  11161. USTPUTC(cc, out);
  11162. }
  11163. if (c != '}' && subtype == VSLENGTH) {
  11164. /* ${#VAR didn't end with } */
  11165. goto badsub;
  11166. }
  11167. if (subtype == 0) {
  11168. static const char types[] ALIGN1 = "}-+?=";
  11169. /* ${VAR...} but not $VAR or ${#VAR} */
  11170. /* c == first char after VAR */
  11171. switch (c) {
  11172. case ':':
  11173. c = pgetc_eatbnl();
  11174. #if BASH_SUBSTR
  11175. /* This check is only needed to not misinterpret
  11176. * ${VAR:-WORD}, ${VAR:+WORD}, ${VAR:=WORD}, ${VAR:?WORD}
  11177. * constructs.
  11178. */
  11179. if (!strchr(types, c)) {
  11180. subtype = VSSUBSTR;
  11181. pungetc();
  11182. break; /* "goto badsub" is bigger (!) */
  11183. }
  11184. #endif
  11185. subtype = VSNUL;
  11186. /*FALLTHROUGH*/
  11187. default: {
  11188. const char *p = strchr(types, c);
  11189. if (p == NULL)
  11190. break;
  11191. subtype |= p - types + VSNORMAL;
  11192. break;
  11193. }
  11194. case '%':
  11195. case '#': {
  11196. int cc = c;
  11197. subtype = (c == '#' ? VSTRIMLEFT : VSTRIMRIGHT);
  11198. c = pgetc_eatbnl();
  11199. if (c != cc)
  11200. goto badsub;
  11201. subtype++;
  11202. break;
  11203. }
  11204. #if BASH_PATTERN_SUBST
  11205. case '/':
  11206. /* ${v/[/]pattern/repl} */
  11207. //TODO: encode pattern and repl separately.
  11208. // Currently ${v/$var_with_slash/repl} is horribly broken
  11209. subtype = VSREPLACE;
  11210. c = pgetc_eatbnl();
  11211. if (c != '/')
  11212. goto badsub;
  11213. subtype++; /* VSREPLACEALL */
  11214. break;
  11215. #endif
  11216. }
  11217. } else {
  11218. badsub:
  11219. pungetc();
  11220. }
  11221. ((unsigned char *)stackblock())[typeloc] = subtype;
  11222. if (subtype != VSNORMAL) {
  11223. varnest++;
  11224. if (dblquote)
  11225. dqvarnest++;
  11226. }
  11227. STPUTC('=', out);
  11228. }
  11229. goto parsesub_return;
  11230. }
  11231. /*
  11232. * Called to parse command substitutions. Newstyle is set if the command
  11233. * is enclosed inside $(...); nlpp is a pointer to the head of the linked
  11234. * list of commands (passed by reference), and savelen is the number of
  11235. * characters on the top of the stack which must be preserved.
  11236. */
  11237. parsebackq: {
  11238. struct nodelist **nlpp;
  11239. union node *n;
  11240. char *str;
  11241. size_t savelen;
  11242. smallint saveprompt = 0;
  11243. str = NULL;
  11244. savelen = out - (char *)stackblock();
  11245. if (savelen > 0) {
  11246. /*
  11247. * FIXME: this can allocate very large block on stack and SEGV.
  11248. * Example:
  11249. * echo "..<100kbytes>..`true` $(true) `true` ..."
  11250. * allocates 100kb for every command subst. With about
  11251. * a hundred command substitutions stack overflows.
  11252. * With larger prepended string, SEGV happens sooner.
  11253. */
  11254. str = alloca(savelen);
  11255. memcpy(str, stackblock(), savelen);
  11256. }
  11257. if (oldstyle) {
  11258. /* We must read until the closing backquote, giving special
  11259. * treatment to some slashes, and then push the string and
  11260. * reread it as input, interpreting it normally.
  11261. */
  11262. char *pout;
  11263. size_t psavelen;
  11264. char *pstr;
  11265. STARTSTACKSTR(pout);
  11266. for (;;) {
  11267. int pc;
  11268. setprompt_if(needprompt, 2);
  11269. pc = pgetc();
  11270. switch (pc) {
  11271. case '`':
  11272. goto done;
  11273. case '\\':
  11274. pc = pgetc();
  11275. if (pc == '\n') {
  11276. nlprompt();
  11277. /*
  11278. * If eating a newline, avoid putting
  11279. * the newline into the new character
  11280. * stream (via the STPUTC after the
  11281. * switch).
  11282. */
  11283. continue;
  11284. }
  11285. if (pc != '\\' && pc != '`' && pc != '$'
  11286. && (!dblquote || pc != '"')
  11287. ) {
  11288. STPUTC('\\', pout);
  11289. }
  11290. if (pc <= 255 /* not PEOA or PEOF */) {
  11291. break;
  11292. }
  11293. /* fall through */
  11294. case PEOF:
  11295. IF_ASH_ALIAS(case PEOA:)
  11296. startlinno = g_parsefile->linno;
  11297. raise_error_syntax("EOF in backquote substitution");
  11298. case '\n':
  11299. nlnoprompt();
  11300. break;
  11301. default:
  11302. break;
  11303. }
  11304. STPUTC(pc, pout);
  11305. }
  11306. done:
  11307. STPUTC('\0', pout);
  11308. psavelen = pout - (char *)stackblock();
  11309. if (psavelen > 0) {
  11310. pstr = grabstackstr(pout);
  11311. setinputstring(pstr);
  11312. }
  11313. }
  11314. nlpp = &bqlist;
  11315. while (*nlpp)
  11316. nlpp = &(*nlpp)->next;
  11317. *nlpp = stzalloc(sizeof(**nlpp));
  11318. /* (*nlpp)->next = NULL; - stzalloc did it */
  11319. if (oldstyle) {
  11320. saveprompt = doprompt;
  11321. doprompt = 0;
  11322. }
  11323. n = list(2);
  11324. if (oldstyle)
  11325. doprompt = saveprompt;
  11326. else if (readtoken() != TRP)
  11327. raise_error_unexpected_syntax(TRP);
  11328. (*nlpp)->n = n;
  11329. if (oldstyle) {
  11330. /*
  11331. * Start reading from old file again, ignoring any pushed back
  11332. * tokens left from the backquote parsing
  11333. */
  11334. popfile();
  11335. tokpushback = 0;
  11336. }
  11337. while (stackblocksize() <= savelen)
  11338. growstackblock();
  11339. STARTSTACKSTR(out);
  11340. if (str) {
  11341. memcpy(out, str, savelen);
  11342. STADJUST(savelen, out);
  11343. }
  11344. USTPUTC(CTLBACKQ, out);
  11345. if (oldstyle)
  11346. goto parsebackq_oldreturn;
  11347. goto parsebackq_newreturn;
  11348. }
  11349. #if ENABLE_FEATURE_SH_MATH
  11350. /*
  11351. * Parse an arithmetic expansion (indicate start of one and set state)
  11352. */
  11353. parsearith: {
  11354. if (++arinest == 1) {
  11355. prevsyntax = syntax;
  11356. syntax = ARISYNTAX;
  11357. }
  11358. USTPUTC(CTLARI, out);
  11359. goto parsearith_return;
  11360. }
  11361. #endif
  11362. } /* end of readtoken */
  11363. /*
  11364. * Read the next input token.
  11365. * If the token is a word, we set backquotelist to the list of cmds in
  11366. * backquotes. We set quoteflag to true if any part of the word was
  11367. * quoted.
  11368. * If the token is TREDIR, then we set redirnode to a structure containing
  11369. * the redirection.
  11370. * In all cases, the variable startlinno is set to the number of the line
  11371. * on which the token starts.
  11372. *
  11373. * [Change comment: here documents and internal procedures]
  11374. * [Readtoken shouldn't have any arguments. Perhaps we should make the
  11375. * word parsing code into a separate routine. In this case, readtoken
  11376. * doesn't need to have any internal procedures, but parseword does.
  11377. * We could also make parseoperator in essence the main routine, and
  11378. * have parseword (readtoken1?) handle both words and redirection.]
  11379. */
  11380. #define NEW_xxreadtoken
  11381. #ifdef NEW_xxreadtoken
  11382. /* singles must be first! */
  11383. static const char xxreadtoken_chars[7] ALIGN1 = {
  11384. '\n', '(', ')', /* singles */
  11385. '&', '|', ';', /* doubles */
  11386. 0
  11387. };
  11388. #define xxreadtoken_singles 3
  11389. #define xxreadtoken_doubles 3
  11390. static const char xxreadtoken_tokens[] ALIGN1 = {
  11391. TNL, TLP, TRP, /* only single occurrence allowed */
  11392. TBACKGND, TPIPE, TSEMI, /* if single occurrence */
  11393. TEOF, /* corresponds to trailing nul */
  11394. TAND, TOR, TENDCASE /* if double occurrence */
  11395. };
  11396. static int
  11397. xxreadtoken(void)
  11398. {
  11399. int c;
  11400. if (tokpushback) {
  11401. tokpushback = 0;
  11402. return lasttoken;
  11403. }
  11404. setprompt_if(needprompt, 2);
  11405. startlinno = g_parsefile->linno;
  11406. for (;;) { /* until token or start of word found */
  11407. c = pgetc();
  11408. if (c == ' ' || c == '\t' IF_ASH_ALIAS( || c == PEOA))
  11409. continue;
  11410. if (c == '#') {
  11411. while ((c = pgetc()) != '\n' && c != PEOF)
  11412. continue;
  11413. pungetc();
  11414. } else if (c == '\\') {
  11415. if (pgetc() != '\n') {
  11416. pungetc();
  11417. break; /* return readtoken1(...) */
  11418. }
  11419. nlprompt();
  11420. } else {
  11421. const char *p;
  11422. p = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
  11423. if (c != PEOF) {
  11424. if (c == '\n') {
  11425. nlnoprompt();
  11426. }
  11427. p = strchr(xxreadtoken_chars, c);
  11428. if (p == NULL)
  11429. break; /* return readtoken1(...) */
  11430. if ((int)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
  11431. int cc = pgetc();
  11432. if (cc == c) { /* double occurrence? */
  11433. p += xxreadtoken_doubles + 1;
  11434. } else {
  11435. pungetc();
  11436. #if BASH_REDIR_OUTPUT
  11437. if (c == '&' && cc == '>') /* &> */
  11438. break; /* return readtoken1(...) */
  11439. #endif
  11440. }
  11441. }
  11442. }
  11443. lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
  11444. return lasttoken;
  11445. }
  11446. } /* for (;;) */
  11447. return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
  11448. }
  11449. #else /* old xxreadtoken */
  11450. #define RETURN(token) return lasttoken = token
  11451. static int
  11452. xxreadtoken(void)
  11453. {
  11454. int c;
  11455. if (tokpushback) {
  11456. tokpushback = 0;
  11457. return lasttoken;
  11458. }
  11459. setprompt_if(needprompt, 2);
  11460. startlinno = g_parsefile->linno;
  11461. for (;;) { /* until token or start of word found */
  11462. c = pgetc();
  11463. switch (c) {
  11464. case ' ': case '\t':
  11465. IF_ASH_ALIAS(case PEOA:)
  11466. continue;
  11467. case '#':
  11468. while ((c = pgetc()) != '\n' && c != PEOF)
  11469. continue;
  11470. pungetc();
  11471. continue;
  11472. case '\\':
  11473. if (pgetc() == '\n') {
  11474. nlprompt();
  11475. continue;
  11476. }
  11477. pungetc();
  11478. goto breakloop;
  11479. case '\n':
  11480. nlnoprompt();
  11481. RETURN(TNL);
  11482. case PEOF:
  11483. RETURN(TEOF);
  11484. case '&':
  11485. if (pgetc() == '&')
  11486. RETURN(TAND);
  11487. pungetc();
  11488. RETURN(TBACKGND);
  11489. case '|':
  11490. if (pgetc() == '|')
  11491. RETURN(TOR);
  11492. pungetc();
  11493. RETURN(TPIPE);
  11494. case ';':
  11495. if (pgetc() == ';')
  11496. RETURN(TENDCASE);
  11497. pungetc();
  11498. RETURN(TSEMI);
  11499. case '(':
  11500. RETURN(TLP);
  11501. case ')':
  11502. RETURN(TRP);
  11503. default:
  11504. goto breakloop;
  11505. }
  11506. }
  11507. breakloop:
  11508. return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
  11509. #undef RETURN
  11510. }
  11511. #endif /* old xxreadtoken */
  11512. static int
  11513. readtoken(void)
  11514. {
  11515. int t;
  11516. int kwd = checkkwd;
  11517. #if DEBUG
  11518. smallint alreadyseen = tokpushback;
  11519. #endif
  11520. #if ENABLE_ASH_ALIAS
  11521. top:
  11522. #endif
  11523. t = xxreadtoken();
  11524. /*
  11525. * eat newlines
  11526. */
  11527. if (kwd & CHKNL) {
  11528. while (t == TNL) {
  11529. parseheredoc();
  11530. t = xxreadtoken();
  11531. }
  11532. }
  11533. if (t != TWORD || quoteflag) {
  11534. goto out;
  11535. }
  11536. /*
  11537. * check for keywords
  11538. */
  11539. if (kwd & CHKKWD) {
  11540. const char *const *pp;
  11541. pp = findkwd(wordtext);
  11542. if (pp) {
  11543. lasttoken = t = pp - tokname_array;
  11544. TRACE(("keyword '%s' recognized\n", tokname_array[t]));
  11545. goto out;
  11546. }
  11547. }
  11548. if (checkkwd & CHKALIAS) {
  11549. #if ENABLE_ASH_ALIAS
  11550. struct alias *ap;
  11551. ap = lookupalias(wordtext, 1);
  11552. if (ap != NULL) {
  11553. if (*ap->val) {
  11554. pushstring(ap->val, ap);
  11555. }
  11556. goto top;
  11557. }
  11558. #endif
  11559. }
  11560. out:
  11561. checkkwd = 0;
  11562. #if DEBUG
  11563. if (!alreadyseen)
  11564. TRACE(("token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
  11565. else
  11566. TRACE(("reread token '%s' %s\n", tokname_array[t], t == TWORD ? wordtext : ""));
  11567. #endif
  11568. return t;
  11569. }
  11570. static int
  11571. peektoken(void)
  11572. {
  11573. int t;
  11574. t = readtoken();
  11575. tokpushback = 1;
  11576. return t;
  11577. }
  11578. /*
  11579. * Read and parse a command. Returns NODE_EOF on end of file.
  11580. * (NULL is a valid parse tree indicating a blank line.)
  11581. */
  11582. static union node *
  11583. parsecmd(int interact)
  11584. {
  11585. tokpushback = 0;
  11586. checkkwd = 0;
  11587. heredoclist = 0;
  11588. doprompt = interact;
  11589. setprompt_if(doprompt, doprompt);
  11590. needprompt = 0;
  11591. return list(1);
  11592. }
  11593. /*
  11594. * Input any here documents.
  11595. */
  11596. static void
  11597. parseheredoc(void)
  11598. {
  11599. struct heredoc *here;
  11600. union node *n;
  11601. here = heredoclist;
  11602. heredoclist = NULL;
  11603. while (here) {
  11604. setprompt_if(needprompt, 2);
  11605. readtoken1(pgetc(), here->here->type == NHERE ? SQSYNTAX : DQSYNTAX,
  11606. here->eofmark, here->striptabs);
  11607. n = stzalloc(sizeof(struct narg));
  11608. n->narg.type = NARG;
  11609. /*n->narg.next = NULL; - stzalloc did it */
  11610. n->narg.text = wordtext;
  11611. n->narg.backquote = backquotelist;
  11612. here->here->nhere.doc = n;
  11613. here = here->next;
  11614. }
  11615. }
  11616. static const char *
  11617. expandstr(const char *ps, int syntax_type)
  11618. {
  11619. union node n;
  11620. int saveprompt;
  11621. /* XXX Fix (char *) cast. */
  11622. setinputstring((char *)ps);
  11623. saveprompt = doprompt;
  11624. doprompt = 0;
  11625. /* readtoken1() might die horribly.
  11626. * Try a prompt with syntactically wrong command:
  11627. * PS1='$(date "+%H:%M:%S) > '
  11628. */
  11629. {
  11630. volatile int saveint;
  11631. struct jmploc *volatile savehandler = exception_handler;
  11632. struct jmploc jmploc;
  11633. SAVE_INT(saveint);
  11634. if (setjmp(jmploc.loc) == 0) {
  11635. exception_handler = &jmploc;
  11636. readtoken1(pgetc(), syntax_type, FAKEEOFMARK, 0);
  11637. }
  11638. exception_handler = savehandler;
  11639. RESTORE_INT(saveint);
  11640. }
  11641. doprompt = saveprompt;
  11642. popfile();
  11643. n.narg.type = NARG;
  11644. n.narg.next = NULL;
  11645. n.narg.text = wordtext;
  11646. n.narg.backquote = backquotelist;
  11647. expandarg(&n, NULL, EXP_QUOTED);
  11648. return stackblock();
  11649. }
  11650. static inline int
  11651. parser_eof(void)
  11652. {
  11653. return tokpushback && lasttoken == TEOF;
  11654. }
  11655. /*
  11656. * Execute a command or commands contained in a string.
  11657. */
  11658. static int
  11659. evalstring(char *s, int flags)
  11660. {
  11661. struct jmploc *volatile savehandler;
  11662. struct jmploc jmploc;
  11663. int ex;
  11664. union node *n;
  11665. struct stackmark smark;
  11666. int status;
  11667. s = sstrdup(s);
  11668. setinputstring(s);
  11669. setstackmark(&smark);
  11670. status = 0;
  11671. /* On exception inside execution loop, we must popfile().
  11672. * Try interactively:
  11673. * readonly a=a
  11674. * command eval "a=b" # throws "is read only" error
  11675. * "command BLTIN" is not supposed to abort (even in non-interactive use).
  11676. * But if we skip popfile(), we hit EOF in eval's string, and exit.
  11677. */
  11678. savehandler = exception_handler;
  11679. ex = setjmp(jmploc.loc);
  11680. if (ex)
  11681. goto out;
  11682. exception_handler = &jmploc;
  11683. while ((n = parsecmd(0)) != NODE_EOF) {
  11684. int i;
  11685. i = evaltree(n, flags & ~(parser_eof() ? 0 : EV_EXIT));
  11686. if (n)
  11687. status = i;
  11688. popstackmark(&smark);
  11689. if (evalskip)
  11690. break;
  11691. }
  11692. out:
  11693. popstackmark(&smark);
  11694. popfile();
  11695. stunalloc(s);
  11696. exception_handler = savehandler;
  11697. if (ex)
  11698. longjmp(exception_handler->loc, ex);
  11699. return status;
  11700. }
  11701. /*
  11702. * The eval command.
  11703. */
  11704. static int FAST_FUNC
  11705. evalcmd(int argc UNUSED_PARAM, char **argv, int flags)
  11706. {
  11707. char *p;
  11708. char *concat;
  11709. if (argv[1]) {
  11710. p = argv[1];
  11711. argv += 2;
  11712. if (argv[0]) {
  11713. STARTSTACKSTR(concat);
  11714. for (;;) {
  11715. concat = stack_putstr(p, concat);
  11716. p = *argv++;
  11717. if (p == NULL)
  11718. break;
  11719. STPUTC(' ', concat);
  11720. }
  11721. STPUTC('\0', concat);
  11722. p = grabstackstr(concat);
  11723. }
  11724. return evalstring(p, flags & EV_TESTED);
  11725. }
  11726. return 0;
  11727. }
  11728. /*
  11729. * Read and execute commands.
  11730. * "Top" is nonzero for the top level command loop;
  11731. * it turns on prompting if the shell is interactive.
  11732. */
  11733. static int
  11734. cmdloop(int top)
  11735. {
  11736. union node *n;
  11737. struct stackmark smark;
  11738. int inter;
  11739. int status = 0;
  11740. int numeof = 0;
  11741. TRACE(("cmdloop(%d) called\n", top));
  11742. for (;;) {
  11743. int skip;
  11744. setstackmark(&smark);
  11745. #if JOBS
  11746. if (doing_jobctl)
  11747. showjobs(SHOW_CHANGED|SHOW_STDERR);
  11748. #endif
  11749. inter = 0;
  11750. if (iflag && top) {
  11751. inter++;
  11752. chkmail();
  11753. }
  11754. n = parsecmd(inter);
  11755. #if DEBUG
  11756. if (DEBUG > 2 && debug && (n != NODE_EOF))
  11757. showtree(n);
  11758. #endif
  11759. if (n == NODE_EOF) {
  11760. if (!top || numeof >= 50)
  11761. break;
  11762. if (!stoppedjobs()) {
  11763. if (!Iflag)
  11764. break;
  11765. out2str("\nUse \"exit\" to leave shell.\n");
  11766. }
  11767. numeof++;
  11768. } else if (nflag == 0) {
  11769. int i;
  11770. /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
  11771. job_warning >>= 1;
  11772. numeof = 0;
  11773. i = evaltree(n, 0);
  11774. if (n)
  11775. status = i;
  11776. }
  11777. popstackmark(&smark);
  11778. skip = evalskip;
  11779. if (skip) {
  11780. evalskip &= ~SKIPFUNC;
  11781. break;
  11782. }
  11783. }
  11784. return status;
  11785. }
  11786. /*
  11787. * Take commands from a file. To be compatible we should do a path
  11788. * search for the file, which is necessary to find sub-commands.
  11789. */
  11790. static char *
  11791. find_dot_file(char *name)
  11792. {
  11793. char *fullname;
  11794. const char *path = pathval();
  11795. struct stat statb;
  11796. /* don't try this for absolute or relative paths */
  11797. if (strchr(name, '/'))
  11798. return name;
  11799. while ((fullname = path_advance(&path, name)) != NULL) {
  11800. if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
  11801. /*
  11802. * Don't bother freeing here, since it will
  11803. * be freed by the caller.
  11804. */
  11805. return fullname;
  11806. }
  11807. if (fullname != name)
  11808. stunalloc(fullname);
  11809. }
  11810. /* not found in the PATH */
  11811. ash_msg_and_raise_error("%s: not found", name);
  11812. /* NOTREACHED */
  11813. }
  11814. static int FAST_FUNC
  11815. dotcmd(int argc_ UNUSED_PARAM, char **argv_ UNUSED_PARAM)
  11816. {
  11817. /* "false; . empty_file; echo $?" should print 0, not 1: */
  11818. int status = 0;
  11819. char *fullname;
  11820. char **argv;
  11821. char *args_need_save;
  11822. volatile struct shparam saveparam;
  11823. //???
  11824. // struct strlist *sp;
  11825. // for (sp = cmdenviron; sp; sp = sp->next)
  11826. // setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
  11827. nextopt(nullstr); /* handle possible "--" */
  11828. argv = argptr;
  11829. if (!argv[0]) {
  11830. /* bash says: "bash: .: filename argument required" */
  11831. return 2; /* bash compat */
  11832. }
  11833. /* This aborts if file isn't found, which is POSIXly correct.
  11834. * bash returns exitcode 1 instead.
  11835. */
  11836. fullname = find_dot_file(argv[0]);
  11837. argv++;
  11838. args_need_save = argv[0];
  11839. if (args_need_save) { /* ". FILE ARGS", and ARGS are not empty */
  11840. int argc;
  11841. saveparam = shellparam;
  11842. shellparam.malloced = 0;
  11843. argc = 1;
  11844. while (argv[argc])
  11845. argc++;
  11846. shellparam.nparam = argc;
  11847. shellparam.p = argv;
  11848. };
  11849. /* This aborts if file can't be opened, which is POSIXly correct.
  11850. * bash returns exitcode 1 instead.
  11851. */
  11852. setinputfile(fullname, INPUT_PUSH_FILE);
  11853. commandname = fullname;
  11854. status = cmdloop(0);
  11855. popfile();
  11856. if (args_need_save) {
  11857. freeparam(&shellparam);
  11858. shellparam = saveparam;
  11859. };
  11860. return status;
  11861. }
  11862. static int FAST_FUNC
  11863. exitcmd(int argc UNUSED_PARAM, char **argv)
  11864. {
  11865. if (stoppedjobs())
  11866. return 0;
  11867. if (argv[1])
  11868. exitstatus = number(argv[1]);
  11869. raise_exception(EXEXIT);
  11870. /* NOTREACHED */
  11871. }
  11872. /*
  11873. * Read a file containing shell functions.
  11874. */
  11875. static void
  11876. readcmdfile(char *name)
  11877. {
  11878. setinputfile(name, INPUT_PUSH_FILE);
  11879. cmdloop(0);
  11880. popfile();
  11881. }
  11882. /* ============ find_command inplementation */
  11883. /*
  11884. * Resolve a command name. If you change this routine, you may have to
  11885. * change the shellexec routine as well.
  11886. */
  11887. static void
  11888. find_command(char *name, struct cmdentry *entry, int act, const char *path)
  11889. {
  11890. struct tblentry *cmdp;
  11891. int idx;
  11892. int prev;
  11893. char *fullname;
  11894. struct stat statb;
  11895. int e;
  11896. int updatetbl;
  11897. struct builtincmd *bcmd;
  11898. /* If name contains a slash, don't use PATH or hash table */
  11899. if (strchr(name, '/') != NULL) {
  11900. entry->u.index = -1;
  11901. if (act & DO_ABS) {
  11902. while (stat(name, &statb) < 0) {
  11903. #ifdef SYSV
  11904. if (errno == EINTR)
  11905. continue;
  11906. #endif
  11907. entry->cmdtype = CMDUNKNOWN;
  11908. return;
  11909. }
  11910. }
  11911. entry->cmdtype = CMDNORMAL;
  11912. return;
  11913. }
  11914. /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
  11915. updatetbl = (path == pathval());
  11916. if (!updatetbl) {
  11917. act |= DO_ALTPATH;
  11918. if (strstr(path, "%builtin") != NULL)
  11919. act |= DO_ALTBLTIN;
  11920. }
  11921. /* If name is in the table, check answer will be ok */
  11922. cmdp = cmdlookup(name, 0);
  11923. if (cmdp != NULL) {
  11924. int bit;
  11925. switch (cmdp->cmdtype) {
  11926. default:
  11927. #if DEBUG
  11928. abort();
  11929. #endif
  11930. case CMDNORMAL:
  11931. bit = DO_ALTPATH;
  11932. break;
  11933. case CMDFUNCTION:
  11934. bit = DO_NOFUNC;
  11935. break;
  11936. case CMDBUILTIN:
  11937. bit = DO_ALTBLTIN;
  11938. break;
  11939. }
  11940. if (act & bit) {
  11941. updatetbl = 0;
  11942. cmdp = NULL;
  11943. } else if (cmdp->rehash == 0)
  11944. /* if not invalidated by cd, we're done */
  11945. goto success;
  11946. }
  11947. /* If %builtin not in path, check for builtin next */
  11948. bcmd = find_builtin(name);
  11949. if (bcmd) {
  11950. if (IS_BUILTIN_REGULAR(bcmd))
  11951. goto builtin_success;
  11952. if (act & DO_ALTPATH) {
  11953. if (!(act & DO_ALTBLTIN))
  11954. goto builtin_success;
  11955. } else if (builtinloc <= 0) {
  11956. goto builtin_success;
  11957. }
  11958. }
  11959. #if ENABLE_FEATURE_SH_STANDALONE
  11960. {
  11961. int applet_no = find_applet_by_name(name);
  11962. if (applet_no >= 0) {
  11963. entry->cmdtype = CMDNORMAL;
  11964. entry->u.index = -2 - applet_no;
  11965. return;
  11966. }
  11967. }
  11968. #endif
  11969. /* We have to search path. */
  11970. prev = -1; /* where to start */
  11971. if (cmdp && cmdp->rehash) { /* doing a rehash */
  11972. if (cmdp->cmdtype == CMDBUILTIN)
  11973. prev = builtinloc;
  11974. else
  11975. prev = cmdp->param.index;
  11976. }
  11977. e = ENOENT;
  11978. idx = -1;
  11979. loop:
  11980. while ((fullname = path_advance(&path, name)) != NULL) {
  11981. stunalloc(fullname);
  11982. /* NB: code below will still use fullname
  11983. * despite it being "unallocated" */
  11984. idx++;
  11985. if (pathopt) {
  11986. if (prefix(pathopt, "builtin")) {
  11987. if (bcmd)
  11988. goto builtin_success;
  11989. continue;
  11990. }
  11991. if ((act & DO_NOFUNC)
  11992. || !prefix(pathopt, "func")
  11993. ) { /* ignore unimplemented options */
  11994. continue;
  11995. }
  11996. }
  11997. /* if rehash, don't redo absolute path names */
  11998. if (fullname[0] == '/' && idx <= prev) {
  11999. if (idx < prev)
  12000. continue;
  12001. TRACE(("searchexec \"%s\": no change\n", name));
  12002. goto success;
  12003. }
  12004. while (stat(fullname, &statb) < 0) {
  12005. #ifdef SYSV
  12006. if (errno == EINTR)
  12007. continue;
  12008. #endif
  12009. if (errno != ENOENT && errno != ENOTDIR)
  12010. e = errno;
  12011. goto loop;
  12012. }
  12013. e = EACCES; /* if we fail, this will be the error */
  12014. if (!S_ISREG(statb.st_mode))
  12015. continue;
  12016. if (pathopt) { /* this is a %func directory */
  12017. stalloc(strlen(fullname) + 1);
  12018. /* NB: stalloc will return space pointed by fullname
  12019. * (because we don't have any intervening allocations
  12020. * between stunalloc above and this stalloc) */
  12021. readcmdfile(fullname);
  12022. cmdp = cmdlookup(name, 0);
  12023. if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
  12024. ash_msg_and_raise_error("%s not defined in %s", name, fullname);
  12025. stunalloc(fullname);
  12026. goto success;
  12027. }
  12028. TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
  12029. if (!updatetbl) {
  12030. entry->cmdtype = CMDNORMAL;
  12031. entry->u.index = idx;
  12032. return;
  12033. }
  12034. INT_OFF;
  12035. cmdp = cmdlookup(name, 1);
  12036. cmdp->cmdtype = CMDNORMAL;
  12037. cmdp->param.index = idx;
  12038. INT_ON;
  12039. goto success;
  12040. }
  12041. /* We failed. If there was an entry for this command, delete it */
  12042. if (cmdp && updatetbl)
  12043. delete_cmd_entry();
  12044. if (act & DO_ERR)
  12045. ash_msg("%s: %s", name, errmsg(e, "not found"));
  12046. entry->cmdtype = CMDUNKNOWN;
  12047. return;
  12048. builtin_success:
  12049. if (!updatetbl) {
  12050. entry->cmdtype = CMDBUILTIN;
  12051. entry->u.cmd = bcmd;
  12052. return;
  12053. }
  12054. INT_OFF;
  12055. cmdp = cmdlookup(name, 1);
  12056. cmdp->cmdtype = CMDBUILTIN;
  12057. cmdp->param.cmd = bcmd;
  12058. INT_ON;
  12059. success:
  12060. cmdp->rehash = 0;
  12061. entry->cmdtype = cmdp->cmdtype;
  12062. entry->u = cmdp->param;
  12063. }
  12064. /*
  12065. * The trap builtin.
  12066. */
  12067. static int FAST_FUNC
  12068. trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  12069. {
  12070. char *action;
  12071. char **ap;
  12072. int signo, exitcode;
  12073. nextopt(nullstr);
  12074. ap = argptr;
  12075. if (!*ap) {
  12076. for (signo = 0; signo < NSIG; signo++) {
  12077. char *tr = trap_ptr[signo];
  12078. if (tr) {
  12079. /* note: bash adds "SIG", but only if invoked
  12080. * as "bash". If called as "sh", or if set -o posix,
  12081. * then it prints short signal names.
  12082. * We are printing short names: */
  12083. out1fmt("trap -- %s %s\n",
  12084. single_quote(tr),
  12085. get_signame(signo));
  12086. /* trap_ptr != trap only if we are in special-cased `trap` code.
  12087. * In this case, we will exit very soon, no need to free(). */
  12088. /* if (trap_ptr != trap && tp[0]) */
  12089. /* free(tr); */
  12090. }
  12091. }
  12092. /*
  12093. if (trap_ptr != trap) {
  12094. free(trap_ptr);
  12095. trap_ptr = trap;
  12096. }
  12097. */
  12098. return 0;
  12099. }
  12100. /* Why the second check?
  12101. * "trap NUM [sig2]..." is the same as "trap - NUM [sig2]..."
  12102. * In this case, NUM is signal no, not an action.
  12103. */
  12104. action = NULL;
  12105. if (ap[1] && !is_number(ap[0]))
  12106. action = *ap++;
  12107. exitcode = 0;
  12108. while (*ap) {
  12109. signo = get_signum(*ap);
  12110. if (signo < 0) {
  12111. /* Mimic bash message exactly */
  12112. ash_msg("%s: invalid signal specification", *ap);
  12113. exitcode = 1;
  12114. goto next;
  12115. }
  12116. INT_OFF;
  12117. if (action) {
  12118. if (LONE_DASH(action))
  12119. action = NULL;
  12120. else {
  12121. if (action[0]) /* not NULL and not "" and not "-" */
  12122. may_have_traps = 1;
  12123. action = ckstrdup(action);
  12124. }
  12125. }
  12126. free(trap[signo]);
  12127. trap[signo] = action;
  12128. if (signo != 0)
  12129. setsignal(signo);
  12130. INT_ON;
  12131. next:
  12132. ap++;
  12133. }
  12134. return exitcode;
  12135. }
  12136. /* ============ Builtins */
  12137. #if ENABLE_ASH_HELP
  12138. static int FAST_FUNC
  12139. helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  12140. {
  12141. unsigned col;
  12142. unsigned i;
  12143. out1fmt(
  12144. "Built-in commands:\n"
  12145. "------------------\n");
  12146. for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
  12147. col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
  12148. builtintab[i].name + 1);
  12149. if (col > 60) {
  12150. out1fmt("\n");
  12151. col = 0;
  12152. }
  12153. }
  12154. # if ENABLE_FEATURE_SH_STANDALONE
  12155. {
  12156. const char *a = applet_names;
  12157. while (*a) {
  12158. col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
  12159. if (col > 60) {
  12160. out1fmt("\n");
  12161. col = 0;
  12162. }
  12163. while (*a++ != '\0')
  12164. continue;
  12165. }
  12166. }
  12167. # endif
  12168. newline_and_flush(stdout);
  12169. return EXIT_SUCCESS;
  12170. }
  12171. #endif
  12172. #if MAX_HISTORY
  12173. static int FAST_FUNC
  12174. historycmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  12175. {
  12176. show_history(line_input_state);
  12177. return EXIT_SUCCESS;
  12178. }
  12179. #endif
  12180. /*
  12181. * The export and readonly commands.
  12182. */
  12183. static int FAST_FUNC
  12184. exportcmd(int argc UNUSED_PARAM, char **argv)
  12185. {
  12186. struct var *vp;
  12187. char *name;
  12188. const char *p;
  12189. char **aptr;
  12190. char opt;
  12191. int flag;
  12192. int flag_off;
  12193. /* "readonly" in bash accepts, but ignores -n.
  12194. * We do the same: it saves a conditional in nextopt's param.
  12195. */
  12196. flag_off = 0;
  12197. while ((opt = nextopt("np")) != '\0') {
  12198. if (opt == 'n')
  12199. flag_off = VEXPORT;
  12200. }
  12201. flag = VEXPORT;
  12202. if (argv[0][0] == 'r') {
  12203. flag = VREADONLY;
  12204. flag_off = 0; /* readonly ignores -n */
  12205. }
  12206. flag_off = ~flag_off;
  12207. /*if (opt_p_not_specified) - bash doesn't check this. Try "export -p NAME" */
  12208. {
  12209. aptr = argptr;
  12210. name = *aptr;
  12211. if (name) {
  12212. do {
  12213. p = strchr(name, '=');
  12214. if (p != NULL) {
  12215. p++;
  12216. } else {
  12217. vp = *findvar(hashvar(name), name);
  12218. if (vp) {
  12219. vp->flags = ((vp->flags | flag) & flag_off);
  12220. continue;
  12221. }
  12222. }
  12223. setvar(name, p, (flag & flag_off));
  12224. } while ((name = *++aptr) != NULL);
  12225. return 0;
  12226. }
  12227. }
  12228. /* No arguments. Show the list of exported or readonly vars.
  12229. * -n is ignored.
  12230. */
  12231. showvars(argv[0], flag, 0);
  12232. return 0;
  12233. }
  12234. /*
  12235. * Delete a function if it exists.
  12236. */
  12237. static void
  12238. unsetfunc(const char *name)
  12239. {
  12240. struct tblentry *cmdp;
  12241. cmdp = cmdlookup(name, 0);
  12242. if (cmdp != NULL && cmdp->cmdtype == CMDFUNCTION)
  12243. delete_cmd_entry();
  12244. }
  12245. /*
  12246. * The unset builtin command. We unset the function before we unset the
  12247. * variable to allow a function to be unset when there is a readonly variable
  12248. * with the same name.
  12249. */
  12250. static int FAST_FUNC
  12251. unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  12252. {
  12253. char **ap;
  12254. int i;
  12255. int flag = 0;
  12256. while ((i = nextopt("vf")) != 0) {
  12257. flag = i;
  12258. }
  12259. for (ap = argptr; *ap; ap++) {
  12260. if (flag != 'f') {
  12261. unsetvar(*ap);
  12262. continue;
  12263. }
  12264. if (flag != 'v')
  12265. unsetfunc(*ap);
  12266. }
  12267. return 0;
  12268. }
  12269. static const unsigned char timescmd_str[] ALIGN1 = {
  12270. ' ', offsetof(struct tms, tms_utime),
  12271. '\n', offsetof(struct tms, tms_stime),
  12272. ' ', offsetof(struct tms, tms_cutime),
  12273. '\n', offsetof(struct tms, tms_cstime),
  12274. 0
  12275. };
  12276. static int FAST_FUNC
  12277. timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  12278. {
  12279. unsigned clk_tck;
  12280. const unsigned char *p;
  12281. struct tms buf;
  12282. clk_tck = bb_clk_tck();
  12283. times(&buf);
  12284. p = timescmd_str;
  12285. do {
  12286. unsigned sec, frac;
  12287. unsigned long t;
  12288. t = *(clock_t *)(((char *) &buf) + p[1]);
  12289. sec = t / clk_tck;
  12290. frac = t % clk_tck;
  12291. out1fmt("%um%u.%03us%c",
  12292. sec / 60, sec % 60,
  12293. (frac * 1000) / clk_tck,
  12294. p[0]);
  12295. p += 2;
  12296. } while (*p);
  12297. return 0;
  12298. }
  12299. #if ENABLE_FEATURE_SH_MATH
  12300. /*
  12301. * The let builtin. Partially stolen from GNU Bash, the Bourne Again SHell.
  12302. * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
  12303. *
  12304. * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
  12305. */
  12306. static int FAST_FUNC
  12307. letcmd(int argc UNUSED_PARAM, char **argv)
  12308. {
  12309. arith_t i;
  12310. argv++;
  12311. if (!*argv)
  12312. ash_msg_and_raise_error("expression expected");
  12313. do {
  12314. i = ash_arith(*argv);
  12315. } while (*++argv);
  12316. return !i;
  12317. }
  12318. #endif
  12319. /*
  12320. * The read builtin. Options:
  12321. * -r Do not interpret '\' specially
  12322. * -s Turn off echo (tty only)
  12323. * -n NCHARS Read NCHARS max
  12324. * -p PROMPT Display PROMPT on stderr (if input is from tty)
  12325. * -t SECONDS Timeout after SECONDS (tty or pipe only)
  12326. * -u FD Read from given FD instead of fd 0
  12327. * -d DELIM End on DELIM char, not newline
  12328. * This uses unbuffered input, which may be avoidable in some cases.
  12329. * TODO: bash also has:
  12330. * -a ARRAY Read into array[0],[1],etc
  12331. * -e Use line editing (tty only)
  12332. */
  12333. static int FAST_FUNC
  12334. readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  12335. {
  12336. char *opt_n = NULL;
  12337. char *opt_p = NULL;
  12338. char *opt_t = NULL;
  12339. char *opt_u = NULL;
  12340. char *opt_d = NULL; /* optimized out if !BASH */
  12341. int read_flags = 0;
  12342. const char *r;
  12343. int i;
  12344. while ((i = nextopt("p:u:rt:n:sd:")) != '\0') {
  12345. switch (i) {
  12346. case 'p':
  12347. opt_p = optionarg;
  12348. break;
  12349. case 'n':
  12350. opt_n = optionarg;
  12351. break;
  12352. case 's':
  12353. read_flags |= BUILTIN_READ_SILENT;
  12354. break;
  12355. case 't':
  12356. opt_t = optionarg;
  12357. break;
  12358. case 'r':
  12359. read_flags |= BUILTIN_READ_RAW;
  12360. break;
  12361. case 'u':
  12362. opt_u = optionarg;
  12363. break;
  12364. #if BASH_READ_D
  12365. case 'd':
  12366. opt_d = optionarg;
  12367. break;
  12368. #endif
  12369. default:
  12370. break;
  12371. }
  12372. }
  12373. /* "read -s" needs to save/restore termios, can't allow ^C
  12374. * to jump out of it.
  12375. */
  12376. again:
  12377. INT_OFF;
  12378. r = shell_builtin_read(setvar0,
  12379. argptr,
  12380. bltinlookup("IFS"), /* can be NULL */
  12381. read_flags,
  12382. opt_n,
  12383. opt_p,
  12384. opt_t,
  12385. opt_u,
  12386. opt_d
  12387. );
  12388. INT_ON;
  12389. if ((uintptr_t)r == 1 && errno == EINTR) {
  12390. /* To get SIGCHLD: sleep 1 & read x; echo $x
  12391. * Correct behavior is to not exit "read"
  12392. */
  12393. if (pending_sig == 0)
  12394. goto again;
  12395. }
  12396. if ((uintptr_t)r > 1)
  12397. ash_msg_and_raise_error(r);
  12398. return (uintptr_t)r;
  12399. }
  12400. static int FAST_FUNC
  12401. umaskcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  12402. {
  12403. static const char permuser[3] ALIGN1 = "ogu";
  12404. mode_t mask;
  12405. int symbolic_mode = 0;
  12406. while (nextopt("S") != '\0') {
  12407. symbolic_mode = 1;
  12408. }
  12409. INT_OFF;
  12410. mask = umask(0);
  12411. umask(mask);
  12412. INT_ON;
  12413. if (*argptr == NULL) {
  12414. if (symbolic_mode) {
  12415. char buf[sizeof(",u=rwx,g=rwx,o=rwx")];
  12416. char *p = buf;
  12417. int i;
  12418. i = 2;
  12419. for (;;) {
  12420. *p++ = ',';
  12421. *p++ = permuser[i];
  12422. *p++ = '=';
  12423. /* mask is 0..0uuugggooo. i=2 selects uuu bits */
  12424. if (!(mask & 0400)) *p++ = 'r';
  12425. if (!(mask & 0200)) *p++ = 'w';
  12426. if (!(mask & 0100)) *p++ = 'x';
  12427. mask <<= 3;
  12428. if (--i < 0)
  12429. break;
  12430. }
  12431. *p = '\0';
  12432. puts(buf + 1);
  12433. } else {
  12434. out1fmt("%04o\n", mask);
  12435. }
  12436. } else {
  12437. char *modestr = *argptr;
  12438. /* numeric umasks are taken as-is */
  12439. /* symbolic umasks are inverted: "umask a=rx" calls umask(222) */
  12440. if (!isdigit(modestr[0]))
  12441. mask ^= 0777;
  12442. mask = bb_parse_mode(modestr, mask);
  12443. if ((unsigned)mask > 0777) {
  12444. ash_msg_and_raise_error("illegal mode: %s", modestr);
  12445. }
  12446. if (!isdigit(modestr[0]))
  12447. mask ^= 0777;
  12448. umask(mask);
  12449. }
  12450. return 0;
  12451. }
  12452. static int FAST_FUNC
  12453. ulimitcmd(int argc UNUSED_PARAM, char **argv)
  12454. {
  12455. return shell_builtin_ulimit(argv);
  12456. }
  12457. /* ============ main() and helpers */
  12458. /*
  12459. * Called to exit the shell.
  12460. */
  12461. static void
  12462. exitshell(void)
  12463. {
  12464. struct jmploc loc;
  12465. char *p;
  12466. int status;
  12467. #if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
  12468. save_history(line_input_state);
  12469. #endif
  12470. status = exitstatus;
  12471. TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
  12472. if (setjmp(loc.loc)) {
  12473. if (exception_type == EXEXIT)
  12474. status = exitstatus;
  12475. goto out;
  12476. }
  12477. exception_handler = &loc;
  12478. p = trap[0];
  12479. if (p) {
  12480. trap[0] = NULL;
  12481. evalskip = 0;
  12482. evalstring(p, 0);
  12483. /*free(p); - we'll exit soon */
  12484. }
  12485. out:
  12486. /* dash wraps setjobctl(0) in "if (setjmp(loc.loc) == 0) {...}".
  12487. * our setjobctl(0) does not panic if tcsetpgrp fails inside it.
  12488. */
  12489. setjobctl(0);
  12490. flush_stdout_stderr();
  12491. _exit(status);
  12492. /* NOTREACHED */
  12493. }
  12494. /* Don't inline: conserve stack of caller from having our locals too */
  12495. static NOINLINE void
  12496. init(void)
  12497. {
  12498. /* we will never free this */
  12499. basepf.next_to_pgetc = basepf.buf = ckmalloc(IBUFSIZ);
  12500. basepf.linno = 1;
  12501. sigmode[SIGCHLD - 1] = S_DFL; /* ensure we install handler even if it is SIG_IGNed */
  12502. setsignal(SIGCHLD);
  12503. /* bash re-enables SIGHUP which is SIG_IGNed on entry.
  12504. * Try: "trap '' HUP; bash; echo RET" and type "kill -HUP $$"
  12505. */
  12506. signal(SIGHUP, SIG_DFL);
  12507. {
  12508. char **envp;
  12509. const char *p;
  12510. initvar();
  12511. for (envp = environ; envp && *envp; envp++) {
  12512. /* Used to have
  12513. * p = endofname(*envp);
  12514. * if (p != *envp && *p == '=') {
  12515. * here to weed out badly-named variables, but this breaks
  12516. * scenarios where people do want them passed to children:
  12517. * import os
  12518. * os.environ["test-test"]="test"
  12519. * if os.fork() == 0:
  12520. * os.execv("ash", [ 'ash', '-c', 'eval $(export -p); echo OK' ]) # fixes this
  12521. * os.execv("ash", [ 'ash', '-c', 'env | grep test-test' ]) # breaks this
  12522. */
  12523. if (strchr(*envp, '=')) {
  12524. setvareq(*envp, VEXPORT|VTEXTFIXED);
  12525. }
  12526. }
  12527. setvareq((char*)defoptindvar, VTEXTFIXED);
  12528. setvar0("PPID", utoa(getppid()));
  12529. #if BASH_SHLVL_VAR
  12530. p = lookupvar("SHLVL");
  12531. setvar("SHLVL", utoa((p ? atoi(p) : 0) + 1), VEXPORT);
  12532. #endif
  12533. #if BASH_HOSTNAME_VAR
  12534. if (!lookupvar("HOSTNAME")) {
  12535. struct utsname uts;
  12536. uname(&uts);
  12537. setvar0("HOSTNAME", uts.nodename);
  12538. }
  12539. #endif
  12540. p = lookupvar("PWD");
  12541. if (p) {
  12542. struct stat st1, st2;
  12543. if (p[0] != '/' || stat(p, &st1) || stat(".", &st2)
  12544. || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino
  12545. ) {
  12546. p = NULL;
  12547. }
  12548. }
  12549. setpwd(p, 0);
  12550. }
  12551. }
  12552. //usage:#define ash_trivial_usage
  12553. //usage: "[-/+OPTIONS] [-/+o OPT]... [-c 'SCRIPT' [ARG0 [ARGS]] / FILE [ARGS]]"
  12554. //usage:#define ash_full_usage "\n\n"
  12555. //usage: "Unix shell interpreter"
  12556. /*
  12557. * Process the shell command line arguments.
  12558. */
  12559. static int
  12560. procargs(char **argv)
  12561. {
  12562. int i;
  12563. const char *xminusc;
  12564. char **xargv;
  12565. int login_sh;
  12566. xargv = argv;
  12567. login_sh = xargv[0] && xargv[0][0] == '-';
  12568. arg0 = xargv[0];
  12569. /* if (xargv[0]) - mmm, this is always true! */
  12570. xargv++;
  12571. for (i = 0; i < NOPTS; i++)
  12572. optlist[i] = 2;
  12573. argptr = xargv;
  12574. if (options(/*cmdline:*/ 1, &login_sh)) {
  12575. /* it already printed err message */
  12576. raise_exception(EXERROR);
  12577. }
  12578. xargv = argptr;
  12579. xminusc = minusc;
  12580. if (*xargv == NULL) {
  12581. if (xminusc)
  12582. ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
  12583. sflag = 1;
  12584. }
  12585. if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
  12586. iflag = 1;
  12587. if (mflag == 2)
  12588. mflag = iflag;
  12589. for (i = 0; i < NOPTS; i++)
  12590. if (optlist[i] == 2)
  12591. optlist[i] = 0;
  12592. #if DEBUG == 2
  12593. debug = 1;
  12594. #endif
  12595. /* POSIX 1003.2: first arg after "-c CMD" is $0, remainder $1... */
  12596. if (xminusc) {
  12597. minusc = *xargv++;
  12598. if (*xargv)
  12599. goto setarg0;
  12600. } else if (!sflag) {
  12601. setinputfile(*xargv, 0);
  12602. setarg0:
  12603. arg0 = *xargv++;
  12604. commandname = arg0;
  12605. }
  12606. shellparam.p = xargv;
  12607. #if ENABLE_ASH_GETOPTS
  12608. shellparam.optind = 1;
  12609. shellparam.optoff = -1;
  12610. #endif
  12611. /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
  12612. while (*xargv) {
  12613. shellparam.nparam++;
  12614. xargv++;
  12615. }
  12616. optschanged();
  12617. return login_sh;
  12618. }
  12619. /*
  12620. * Read /etc/profile, ~/.profile, $ENV.
  12621. */
  12622. static void
  12623. read_profile(const char *name)
  12624. {
  12625. name = expandstr(name, DQSYNTAX);
  12626. if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
  12627. return;
  12628. cmdloop(0);
  12629. popfile();
  12630. }
  12631. /*
  12632. * This routine is called when an error or an interrupt occurs in an
  12633. * interactive shell and control is returned to the main command loop.
  12634. * (In dash, this function is auto-generated by build machinery).
  12635. */
  12636. static void
  12637. reset(void)
  12638. {
  12639. /* from eval.c: */
  12640. evalskip = 0;
  12641. loopnest = 0;
  12642. /* from expand.c: */
  12643. ifsfree();
  12644. /* from input.c: */
  12645. g_parsefile->left_in_buffer = 0;
  12646. g_parsefile->left_in_line = 0; /* clear input buffer */
  12647. popallfiles();
  12648. /* from redir.c: */
  12649. unwindredir(NULL);
  12650. /* from var.c: */
  12651. unwindlocalvars(NULL);
  12652. }
  12653. #if PROFILE
  12654. static short profile_buf[16384];
  12655. extern int etext();
  12656. #endif
  12657. /*
  12658. * Main routine. We initialize things, parse the arguments, execute
  12659. * profiles if we're a login shell, and then call cmdloop to execute
  12660. * commands. The setjmp call sets up the location to jump to when an
  12661. * exception occurs. When an exception occurs the variable "state"
  12662. * is used to figure out how far we had gotten.
  12663. */
  12664. int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  12665. int ash_main(int argc UNUSED_PARAM, char **argv)
  12666. {
  12667. volatile smallint state;
  12668. struct jmploc jmploc;
  12669. struct stackmark smark;
  12670. int login_sh;
  12671. /* Initialize global data */
  12672. INIT_G_misc();
  12673. INIT_G_memstack();
  12674. INIT_G_var();
  12675. #if ENABLE_ASH_ALIAS
  12676. INIT_G_alias();
  12677. #endif
  12678. INIT_G_cmdtable();
  12679. #if PROFILE
  12680. monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
  12681. #endif
  12682. #if ENABLE_FEATURE_EDITING
  12683. line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
  12684. #endif
  12685. state = 0;
  12686. if (setjmp(jmploc.loc)) {
  12687. smallint e;
  12688. smallint s;
  12689. reset();
  12690. e = exception_type;
  12691. s = state;
  12692. if (e == EXEXIT || s == 0 || iflag == 0 || shlvl) {
  12693. exitshell();
  12694. }
  12695. if (e == EXINT) {
  12696. newline_and_flush(stderr);
  12697. }
  12698. popstackmark(&smark);
  12699. FORCE_INT_ON; /* enable interrupts */
  12700. if (s == 1)
  12701. goto state1;
  12702. if (s == 2)
  12703. goto state2;
  12704. if (s == 3)
  12705. goto state3;
  12706. goto state4;
  12707. }
  12708. exception_handler = &jmploc;
  12709. rootpid = getpid();
  12710. init();
  12711. setstackmark(&smark);
  12712. login_sh = procargs(argv);
  12713. #if DEBUG
  12714. TRACE(("Shell args: "));
  12715. trace_puts_args(argv);
  12716. #endif
  12717. if (login_sh) {
  12718. const char *hp;
  12719. state = 1;
  12720. read_profile("/etc/profile");
  12721. state1:
  12722. state = 2;
  12723. hp = lookupvar("HOME");
  12724. if (hp)
  12725. read_profile("$HOME/.profile");
  12726. }
  12727. state2:
  12728. state = 3;
  12729. if (
  12730. #ifndef linux
  12731. getuid() == geteuid() && getgid() == getegid() &&
  12732. #endif
  12733. iflag
  12734. ) {
  12735. const char *shinit = lookupvar("ENV");
  12736. if (shinit != NULL && *shinit != '\0')
  12737. read_profile(shinit);
  12738. }
  12739. popstackmark(&smark);
  12740. state3:
  12741. state = 4;
  12742. if (minusc) {
  12743. /* evalstring pushes parsefile stack.
  12744. * Ensure we don't falsely claim that 0 (stdin)
  12745. * is one of stacked source fds.
  12746. * Testcase: ash -c 'exec 1>&0' must not complain. */
  12747. // if (!sflag) g_parsefile->pf_fd = -1;
  12748. // ^^ not necessary since now we special-case fd 0
  12749. // in save_fd_on_redirect()
  12750. evalstring(minusc, sflag ? 0 : EV_EXIT);
  12751. }
  12752. if (sflag || minusc == NULL) {
  12753. #if MAX_HISTORY > 0 && ENABLE_FEATURE_EDITING_SAVEHISTORY
  12754. if (iflag) {
  12755. const char *hp = lookupvar("HISTFILE");
  12756. if (!hp) {
  12757. hp = lookupvar("HOME");
  12758. if (hp) {
  12759. INT_OFF;
  12760. hp = concat_path_file(hp, ".ash_history");
  12761. setvar0("HISTFILE", hp);
  12762. free((char*)hp);
  12763. INT_ON;
  12764. hp = lookupvar("HISTFILE");
  12765. }
  12766. }
  12767. if (hp)
  12768. line_input_state->hist_file = hp;
  12769. # if ENABLE_FEATURE_SH_HISTFILESIZE
  12770. hp = lookupvar("HISTFILESIZE");
  12771. line_input_state->max_history = size_from_HISTFILESIZE(hp);
  12772. # endif
  12773. }
  12774. #endif
  12775. state4: /* XXX ??? - why isn't this before the "if" statement */
  12776. cmdloop(1);
  12777. }
  12778. #if PROFILE
  12779. monitor(0);
  12780. #endif
  12781. #ifdef GPROF
  12782. {
  12783. extern void _mcleanup(void);
  12784. _mcleanup();
  12785. }
  12786. #endif
  12787. TRACE(("End of main reached\n"));
  12788. exitshell();
  12789. /* NOTREACHED */
  12790. }
  12791. /*-
  12792. * Copyright (c) 1989, 1991, 1993, 1994
  12793. * The Regents of the University of California. All rights reserved.
  12794. *
  12795. * This code is derived from software contributed to Berkeley by
  12796. * Kenneth Almquist.
  12797. *
  12798. * Redistribution and use in source and binary forms, with or without
  12799. * modification, are permitted provided that the following conditions
  12800. * are met:
  12801. * 1. Redistributions of source code must retain the above copyright
  12802. * notice, this list of conditions and the following disclaimer.
  12803. * 2. Redistributions in binary form must reproduce the above copyright
  12804. * notice, this list of conditions and the following disclaimer in the
  12805. * documentation and/or other materials provided with the distribution.
  12806. * 3. Neither the name of the University nor the names of its contributors
  12807. * may be used to endorse or promote products derived from this software
  12808. * without specific prior written permission.
  12809. *
  12810. * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ''AS IS'' AND
  12811. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  12812. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  12813. * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
  12814. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  12815. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  12816. * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  12817. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  12818. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  12819. * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  12820. * SUCH DAMAGE.
  12821. */