ash.c 296 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * ash shell port for busybox
  4. *
  5. * Copyright (c) 1989, 1991, 1993, 1994
  6. * The Regents of the University of California. All rights reserved.
  7. *
  8. * Copyright (c) 1997-2005 Herbert Xu <herbert@gondor.apana.org.au>
  9. * was re-ported from NetBSD and debianized.
  10. *
  11. *
  12. * This code is derived from software contributed to Berkeley by
  13. * Kenneth Almquist.
  14. *
  15. * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
  16. *
  17. * Original BSD copyright notice is retained at the end of this file.
  18. */
  19. /*
  20. * rewrite arith.y to micro stack based cryptic algorithm by
  21. * Copyright (c) 2001 Aaron Lehmann <aaronl@vitelus.com>
  22. *
  23. * Modified by Paul Mundt <lethal@linux-sh.org> (c) 2004 to support
  24. * dynamic variables.
  25. *
  26. * Modified by Vladimir Oleynik <dzo@simtreas.ru> (c) 2001-2005 to be
  27. * used in busybox and size optimizations,
  28. * rewrote arith (see notes to this), added locale support,
  29. * rewrote dynamic variables.
  30. *
  31. */
  32. /*
  33. * The follow should be set to reflect the type of system you have:
  34. * JOBS -> 1 if you have Berkeley job control, 0 otherwise.
  35. * define SYSV if you are running under System V.
  36. * define DEBUG=1 to compile in debugging ('set -o debug' to turn on)
  37. * define DEBUG=2 to compile in and turn on debugging.
  38. *
  39. * When debugging is on, debugging info will be written to ./trace and
  40. * a quit signal will generate a core dump.
  41. */
  42. #define DEBUG 0
  43. #define PROFILE 0
  44. #define IFS_BROKEN
  45. #define JOBS ENABLE_ASH_JOB_CONTROL
  46. #if DEBUG
  47. #ifndef _GNU_SOURCE
  48. #define _GNU_SOURCE
  49. #endif
  50. #endif
  51. #include "busybox.h" /* for applet_names */
  52. #include <paths.h>
  53. #include <setjmp.h>
  54. #include <fnmatch.h>
  55. #if JOBS || ENABLE_ASH_READ_NCHARS
  56. #include <termios.h>
  57. #endif
  58. #ifndef PIPE_BUF
  59. #define PIPE_BUF 4096 /* amount of buffering in a pipe */
  60. #endif
  61. #if defined(__uClinux__)
  62. #error "Do not even bother, ash will not run on uClinux"
  63. #endif
  64. /* ============ Hash table sizes. Configurable. */
  65. #define VTABSIZE 39
  66. #define ATABSIZE 39
  67. #define CMDTABLESIZE 31 /* should be prime */
  68. /* ============ Misc helpers */
  69. #define xbarrier() do { __asm__ __volatile__ ("": : :"memory"); } while (0)
  70. /* C99 say: "char" declaration may be signed or unsigned default */
  71. #define signed_char2int(sc) ((int)((signed char)sc))
  72. /* ============ Shell options */
  73. static const char *const optletters_optnames[] = {
  74. "e" "errexit",
  75. "f" "noglob",
  76. "I" "ignoreeof",
  77. "i" "interactive",
  78. "m" "monitor",
  79. "n" "noexec",
  80. "s" "stdin",
  81. "x" "xtrace",
  82. "v" "verbose",
  83. "C" "noclobber",
  84. "a" "allexport",
  85. "b" "notify",
  86. "u" "nounset",
  87. "\0" "vi"
  88. #if DEBUG
  89. ,"\0" "nolog"
  90. ,"\0" "debug"
  91. #endif
  92. };
  93. #define optletters(n) optletters_optnames[(n)][0]
  94. #define optnames(n) (&optletters_optnames[(n)][1])
  95. enum { NOPTS = ARRAY_SIZE(optletters_optnames) };
  96. /* ============ Misc data */
  97. static const char homestr[] ALIGN1 = "HOME";
  98. static const char snlfmt[] ALIGN1 = "%s\n";
  99. static const char illnum[] ALIGN1 = "Illegal number: %s";
  100. /*
  101. * We enclose jmp_buf in a structure so that we can declare pointers to
  102. * jump locations. The global variable handler contains the location to
  103. * jump to when an exception occurs, and the global variable exception
  104. * contains a code identifying the exception. To implement nested
  105. * exception handlers, the user should save the value of handler on entry
  106. * to an inner scope, set handler to point to a jmploc structure for the
  107. * inner scope, and restore handler on exit from the scope.
  108. */
  109. struct jmploc {
  110. jmp_buf loc;
  111. };
  112. struct globals_misc {
  113. /* pid of main shell */
  114. int rootpid;
  115. /* shell level: 0 for the main shell, 1 for its children, and so on */
  116. int shlvl;
  117. #define rootshell (!shlvl)
  118. char *minusc; /* argument to -c option */
  119. char *curdir; // = nullstr; /* current working directory */
  120. char *physdir; // = nullstr; /* physical working directory */
  121. char *arg0; /* value of $0 */
  122. struct jmploc *exception_handler;
  123. // disabled by vda: cannot understand how it was supposed to work -
  124. // cannot fix bugs. That's why you have to explain your non-trivial designs!
  125. // /* do we generate EXSIG events */
  126. // int exsig; /* counter */
  127. volatile int suppressint; /* counter */
  128. volatile /*sig_atomic_t*/ smallint intpending; /* 1 = got SIGINT */
  129. /* last pending signal */
  130. volatile /*sig_atomic_t*/ smallint pendingsig;
  131. smallint exception; /* kind of exception (0..5) */
  132. /* exceptions */
  133. #define EXINT 0 /* SIGINT received */
  134. #define EXERROR 1 /* a generic error */
  135. #define EXSHELLPROC 2 /* execute a shell procedure */
  136. #define EXEXEC 3 /* command execution failed */
  137. #define EXEXIT 4 /* exit the shell */
  138. #define EXSIG 5 /* trapped signal in wait(1) */
  139. smallint isloginsh;
  140. char nullstr[1]; /* zero length string */
  141. char optlist[NOPTS];
  142. #define eflag optlist[0]
  143. #define fflag optlist[1]
  144. #define Iflag optlist[2]
  145. #define iflag optlist[3]
  146. #define mflag optlist[4]
  147. #define nflag optlist[5]
  148. #define sflag optlist[6]
  149. #define xflag optlist[7]
  150. #define vflag optlist[8]
  151. #define Cflag optlist[9]
  152. #define aflag optlist[10]
  153. #define bflag optlist[11]
  154. #define uflag optlist[12]
  155. #define viflag optlist[13]
  156. #if DEBUG
  157. #define nolog optlist[14]
  158. #define debug optlist[15]
  159. #endif
  160. /* trap handler commands */
  161. /*
  162. * Sigmode records the current value of the signal handlers for the various
  163. * modes. A value of zero means that the current handler is not known.
  164. * S_HARD_IGN indicates that the signal was ignored on entry to the shell,
  165. */
  166. char sigmode[NSIG - 1];
  167. #define S_DFL 1 /* default signal handling (SIG_DFL) */
  168. #define S_CATCH 2 /* signal is caught */
  169. #define S_IGN 3 /* signal is ignored (SIG_IGN) */
  170. #define S_HARD_IGN 4 /* signal is ignored permenantly */
  171. #define S_RESET 5 /* temporary - to reset a hard ignored sig */
  172. /* indicates specified signal received */
  173. char gotsig[NSIG - 1]; /* offset by 1: "signal" 0 is meaningless */
  174. char *trap[NSIG];
  175. /* Rarely referenced stuff */
  176. #if ENABLE_ASH_RANDOM_SUPPORT
  177. /* Random number generators */
  178. int32_t random_galois_LFSR; /* Galois LFSR (fast but weak). signed! */
  179. uint32_t random_LCG; /* LCG (fast but weak) */
  180. #endif
  181. pid_t backgndpid; /* pid of last background process */
  182. smallint job_warning; /* user was warned about stopped jobs (can be 2, 1 or 0). */
  183. };
  184. extern struct globals_misc *const ash_ptr_to_globals_misc;
  185. #define G_misc (*ash_ptr_to_globals_misc)
  186. #define rootpid (G_misc.rootpid )
  187. #define shlvl (G_misc.shlvl )
  188. #define minusc (G_misc.minusc )
  189. #define curdir (G_misc.curdir )
  190. #define physdir (G_misc.physdir )
  191. #define arg0 (G_misc.arg0 )
  192. #define exception_handler (G_misc.exception_handler)
  193. #define exception (G_misc.exception )
  194. #define suppressint (G_misc.suppressint )
  195. #define intpending (G_misc.intpending )
  196. //#define exsig (G_misc.exsig )
  197. #define pendingsig (G_misc.pendingsig )
  198. #define isloginsh (G_misc.isloginsh )
  199. #define nullstr (G_misc.nullstr )
  200. #define optlist (G_misc.optlist )
  201. #define sigmode (G_misc.sigmode )
  202. #define gotsig (G_misc.gotsig )
  203. #define trap (G_misc.trap )
  204. #define random_galois_LFSR (G_misc.random_galois_LFSR)
  205. #define random_LCG (G_misc.random_LCG )
  206. #define backgndpid (G_misc.backgndpid )
  207. #define job_warning (G_misc.job_warning)
  208. #define INIT_G_misc() do { \
  209. (*(struct globals_misc**)&ash_ptr_to_globals_misc) = xzalloc(sizeof(G_misc)); \
  210. barrier(); \
  211. curdir = nullstr; \
  212. physdir = nullstr; \
  213. } while (0)
  214. /* ============ Interrupts / exceptions */
  215. /*
  216. * These macros allow the user to suspend the handling of interrupt signals
  217. * over a period of time. This is similar to SIGHOLD or to sigblock, but
  218. * much more efficient and portable. (But hacking the kernel is so much
  219. * more fun than worrying about efficiency and portability. :-))
  220. */
  221. #define INT_OFF do { \
  222. suppressint++; \
  223. xbarrier(); \
  224. } while (0)
  225. /*
  226. * Called to raise an exception. Since C doesn't include exceptions, we
  227. * just do a longjmp to the exception handler. The type of exception is
  228. * stored in the global variable "exception".
  229. */
  230. static void raise_exception(int) NORETURN;
  231. static void
  232. raise_exception(int e)
  233. {
  234. #if DEBUG
  235. if (exception_handler == NULL)
  236. abort();
  237. #endif
  238. INT_OFF;
  239. exception = e;
  240. longjmp(exception_handler->loc, 1);
  241. }
  242. /*
  243. * Called from trap.c when a SIGINT is received. (If the user specifies
  244. * that SIGINT is to be trapped or ignored using the trap builtin, then
  245. * this routine is not called.) Suppressint is nonzero when interrupts
  246. * are held using the INT_OFF macro. (The test for iflag is just
  247. * defensive programming.)
  248. */
  249. static void raise_interrupt(void) NORETURN;
  250. static void
  251. raise_interrupt(void)
  252. {
  253. int i;
  254. intpending = 0;
  255. /* Signal is not automatically unmasked after it is raised,
  256. * do it ourself - unmask all signals */
  257. sigprocmask_allsigs(SIG_UNBLOCK);
  258. /* pendingsig = 0; - now done in onsig() */
  259. i = EXSIG;
  260. if (gotsig[SIGINT - 1] && !trap[SIGINT]) {
  261. if (!(rootshell && iflag)) {
  262. /* Kill ourself with SIGINT */
  263. signal(SIGINT, SIG_DFL);
  264. raise(SIGINT);
  265. }
  266. i = EXINT;
  267. }
  268. raise_exception(i);
  269. /* NOTREACHED */
  270. }
  271. #if ENABLE_ASH_OPTIMIZE_FOR_SIZE
  272. static void
  273. int_on(void)
  274. {
  275. if (--suppressint == 0 && intpending) {
  276. raise_interrupt();
  277. }
  278. }
  279. #define INT_ON int_on()
  280. static void
  281. force_int_on(void)
  282. {
  283. suppressint = 0;
  284. if (intpending)
  285. raise_interrupt();
  286. }
  287. #define FORCE_INT_ON force_int_on()
  288. #else
  289. #define INT_ON do { \
  290. xbarrier(); \
  291. if (--suppressint == 0 && intpending) \
  292. raise_interrupt(); \
  293. } while (0)
  294. #define FORCE_INT_ON do { \
  295. xbarrier(); \
  296. suppressint = 0; \
  297. if (intpending) \
  298. raise_interrupt(); \
  299. } while (0)
  300. #endif /* ASH_OPTIMIZE_FOR_SIZE */
  301. #define SAVE_INT(v) ((v) = suppressint)
  302. #define RESTORE_INT(v) do { \
  303. xbarrier(); \
  304. suppressint = (v); \
  305. if (suppressint == 0 && intpending) \
  306. raise_interrupt(); \
  307. } while (0)
  308. /*
  309. * Ignore a signal. Only one usage site - in forkchild()
  310. */
  311. static void
  312. ignoresig(int signo)
  313. {
  314. if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
  315. signal(signo, SIG_IGN);
  316. }
  317. sigmode[signo - 1] = S_HARD_IGN;
  318. }
  319. /*
  320. * Signal handler. Only one usage site - in setsignal()
  321. */
  322. static void
  323. onsig(int signo)
  324. {
  325. gotsig[signo - 1] = 1;
  326. pendingsig = signo;
  327. if (/* exsig || */ (signo == SIGINT && !trap[SIGINT])) {
  328. if (!suppressint) {
  329. pendingsig = 0;
  330. raise_interrupt(); /* does not return */
  331. }
  332. intpending = 1;
  333. }
  334. }
  335. /* ============ Stdout/stderr output */
  336. static void
  337. outstr(const char *p, FILE *file)
  338. {
  339. INT_OFF;
  340. fputs(p, file);
  341. INT_ON;
  342. }
  343. static void
  344. flush_stdout_stderr(void)
  345. {
  346. INT_OFF;
  347. fflush(stdout);
  348. fflush(stderr);
  349. INT_ON;
  350. }
  351. static void
  352. flush_stderr(void)
  353. {
  354. INT_OFF;
  355. fflush(stderr);
  356. INT_ON;
  357. }
  358. static void
  359. outcslow(int c, FILE *dest)
  360. {
  361. INT_OFF;
  362. putc(c, dest);
  363. fflush(dest);
  364. INT_ON;
  365. }
  366. static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
  367. static int
  368. out1fmt(const char *fmt, ...)
  369. {
  370. va_list ap;
  371. int r;
  372. INT_OFF;
  373. va_start(ap, fmt);
  374. r = vprintf(fmt, ap);
  375. va_end(ap);
  376. INT_ON;
  377. return r;
  378. }
  379. static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
  380. static int
  381. fmtstr(char *outbuf, size_t length, const char *fmt, ...)
  382. {
  383. va_list ap;
  384. int ret;
  385. va_start(ap, fmt);
  386. INT_OFF;
  387. ret = vsnprintf(outbuf, length, fmt, ap);
  388. va_end(ap);
  389. INT_ON;
  390. return ret;
  391. }
  392. static void
  393. out1str(const char *p)
  394. {
  395. outstr(p, stdout);
  396. }
  397. static void
  398. out2str(const char *p)
  399. {
  400. outstr(p, stderr);
  401. flush_stderr();
  402. }
  403. /* ============ Parser structures */
  404. /* control characters in argument strings */
  405. #define CTLESC '\201' /* escape next character */
  406. #define CTLVAR '\202' /* variable defn */
  407. #define CTLENDVAR '\203'
  408. #define CTLBACKQ '\204'
  409. #define CTLQUOTE 01 /* ored with CTLBACKQ code if in quotes */
  410. /* CTLBACKQ | CTLQUOTE == '\205' */
  411. #define CTLARI '\206' /* arithmetic expression */
  412. #define CTLENDARI '\207'
  413. #define CTLQUOTEMARK '\210'
  414. /* variable substitution byte (follows CTLVAR) */
  415. #define VSTYPE 0x0f /* type of variable substitution */
  416. #define VSNUL 0x10 /* colon--treat the empty string as unset */
  417. #define VSQUOTE 0x80 /* inside double quotes--suppress splitting */
  418. /* values of VSTYPE field */
  419. #define VSNORMAL 0x1 /* normal variable: $var or ${var} */
  420. #define VSMINUS 0x2 /* ${var-text} */
  421. #define VSPLUS 0x3 /* ${var+text} */
  422. #define VSQUESTION 0x4 /* ${var?message} */
  423. #define VSASSIGN 0x5 /* ${var=text} */
  424. #define VSTRIMRIGHT 0x6 /* ${var%pattern} */
  425. #define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
  426. #define VSTRIMLEFT 0x8 /* ${var#pattern} */
  427. #define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
  428. #define VSLENGTH 0xa /* ${#var} */
  429. #if ENABLE_ASH_BASH_COMPAT
  430. #define VSSUBSTR 0xc /* ${var:position:length} */
  431. #define VSREPLACE 0xd /* ${var/pattern/replacement} */
  432. #define VSREPLACEALL 0xe /* ${var//pattern/replacement} */
  433. #endif
  434. static const char dolatstr[] ALIGN1 = {
  435. CTLVAR, VSNORMAL|VSQUOTE, '@', '=', '\0'
  436. };
  437. #define NCMD 0
  438. #define NPIPE 1
  439. #define NREDIR 2
  440. #define NBACKGND 3
  441. #define NSUBSHELL 4
  442. #define NAND 5
  443. #define NOR 6
  444. #define NSEMI 7
  445. #define NIF 8
  446. #define NWHILE 9
  447. #define NUNTIL 10
  448. #define NFOR 11
  449. #define NCASE 12
  450. #define NCLIST 13
  451. #define NDEFUN 14
  452. #define NARG 15
  453. #define NTO 16
  454. #define NCLOBBER 17
  455. #define NFROM 18
  456. #define NFROMTO 19
  457. #define NAPPEND 20
  458. #define NTOFD 21
  459. #define NFROMFD 22
  460. #define NHERE 23
  461. #define NXHERE 24
  462. #define NNOT 25
  463. union node;
  464. struct ncmd {
  465. smallint type; /* Nxxxx */
  466. union node *assign;
  467. union node *args;
  468. union node *redirect;
  469. };
  470. struct npipe {
  471. smallint type;
  472. smallint pipe_backgnd;
  473. struct nodelist *cmdlist;
  474. };
  475. struct nredir {
  476. smallint type;
  477. union node *n;
  478. union node *redirect;
  479. };
  480. struct nbinary {
  481. smallint type;
  482. union node *ch1;
  483. union node *ch2;
  484. };
  485. struct nif {
  486. smallint type;
  487. union node *test;
  488. union node *ifpart;
  489. union node *elsepart;
  490. };
  491. struct nfor {
  492. smallint type;
  493. union node *args;
  494. union node *body;
  495. char *var;
  496. };
  497. struct ncase {
  498. smallint type;
  499. union node *expr;
  500. union node *cases;
  501. };
  502. struct nclist {
  503. smallint type;
  504. union node *next;
  505. union node *pattern;
  506. union node *body;
  507. };
  508. struct narg {
  509. smallint type;
  510. union node *next;
  511. char *text;
  512. struct nodelist *backquote;
  513. };
  514. struct nfile {
  515. smallint type;
  516. union node *next;
  517. int fd;
  518. union node *fname;
  519. char *expfname;
  520. };
  521. struct ndup {
  522. smallint type;
  523. union node *next; /* must match nfile's layout */
  524. int fd; /* must match nfile's layout */
  525. int dupfd;
  526. union node *vname;
  527. };
  528. struct nhere {
  529. smallint type;
  530. union node *next;
  531. int fd;
  532. union node *doc;
  533. };
  534. struct nnot {
  535. smallint type;
  536. union node *com;
  537. };
  538. union node {
  539. smallint type;
  540. struct ncmd ncmd;
  541. struct npipe npipe;
  542. struct nredir nredir;
  543. struct nbinary nbinary;
  544. struct nif nif;
  545. struct nfor nfor;
  546. struct ncase ncase;
  547. struct nclist nclist;
  548. struct narg narg;
  549. struct nfile nfile;
  550. struct ndup ndup;
  551. struct nhere nhere;
  552. struct nnot nnot;
  553. };
  554. struct nodelist {
  555. struct nodelist *next;
  556. union node *n;
  557. };
  558. struct funcnode {
  559. int count;
  560. union node n;
  561. };
  562. /*
  563. * Free a parse tree.
  564. */
  565. static void
  566. freefunc(struct funcnode *f)
  567. {
  568. if (f && --f->count < 0)
  569. free(f);
  570. }
  571. /* ============ Debugging output */
  572. #if DEBUG
  573. static FILE *tracefile;
  574. static void
  575. trace_printf(const char *fmt, ...)
  576. {
  577. va_list va;
  578. if (debug != 1)
  579. return;
  580. va_start(va, fmt);
  581. vfprintf(tracefile, fmt, va);
  582. va_end(va);
  583. }
  584. static void
  585. trace_vprintf(const char *fmt, va_list va)
  586. {
  587. if (debug != 1)
  588. return;
  589. vfprintf(tracefile, fmt, va);
  590. }
  591. static void
  592. trace_puts(const char *s)
  593. {
  594. if (debug != 1)
  595. return;
  596. fputs(s, tracefile);
  597. }
  598. static void
  599. trace_puts_quoted(char *s)
  600. {
  601. char *p;
  602. char c;
  603. if (debug != 1)
  604. return;
  605. putc('"', tracefile);
  606. for (p = s; *p; p++) {
  607. switch (*p) {
  608. case '\n': c = 'n'; goto backslash;
  609. case '\t': c = 't'; goto backslash;
  610. case '\r': c = 'r'; goto backslash;
  611. case '"': c = '"'; goto backslash;
  612. case '\\': c = '\\'; goto backslash;
  613. case CTLESC: c = 'e'; goto backslash;
  614. case CTLVAR: c = 'v'; goto backslash;
  615. case CTLVAR+CTLQUOTE: c = 'V'; goto backslash;
  616. case CTLBACKQ: c = 'q'; goto backslash;
  617. case CTLBACKQ+CTLQUOTE: c = 'Q'; goto backslash;
  618. backslash:
  619. putc('\\', tracefile);
  620. putc(c, tracefile);
  621. break;
  622. default:
  623. if (*p >= ' ' && *p <= '~')
  624. putc(*p, tracefile);
  625. else {
  626. putc('\\', tracefile);
  627. putc(*p >> 6 & 03, tracefile);
  628. putc(*p >> 3 & 07, tracefile);
  629. putc(*p & 07, tracefile);
  630. }
  631. break;
  632. }
  633. }
  634. putc('"', tracefile);
  635. }
  636. static void
  637. trace_puts_args(char **ap)
  638. {
  639. if (debug != 1)
  640. return;
  641. if (!*ap)
  642. return;
  643. while (1) {
  644. trace_puts_quoted(*ap);
  645. if (!*++ap) {
  646. putc('\n', tracefile);
  647. break;
  648. }
  649. putc(' ', tracefile);
  650. }
  651. }
  652. static void
  653. opentrace(void)
  654. {
  655. char s[100];
  656. #ifdef O_APPEND
  657. int flags;
  658. #endif
  659. if (debug != 1) {
  660. if (tracefile)
  661. fflush(tracefile);
  662. /* leave open because libedit might be using it */
  663. return;
  664. }
  665. strcpy(s, "./trace");
  666. if (tracefile) {
  667. if (!freopen(s, "a", tracefile)) {
  668. fprintf(stderr, "Can't re-open %s\n", s);
  669. debug = 0;
  670. return;
  671. }
  672. } else {
  673. tracefile = fopen(s, "a");
  674. if (tracefile == NULL) {
  675. fprintf(stderr, "Can't open %s\n", s);
  676. debug = 0;
  677. return;
  678. }
  679. }
  680. #ifdef O_APPEND
  681. flags = fcntl(fileno(tracefile), F_GETFL);
  682. if (flags >= 0)
  683. fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
  684. #endif
  685. setlinebuf(tracefile);
  686. fputs("\nTracing started.\n", tracefile);
  687. }
  688. static void
  689. indent(int amount, char *pfx, FILE *fp)
  690. {
  691. int i;
  692. for (i = 0; i < amount; i++) {
  693. if (pfx && i == amount - 1)
  694. fputs(pfx, fp);
  695. putc('\t', fp);
  696. }
  697. }
  698. /* little circular references here... */
  699. static void shtree(union node *n, int ind, char *pfx, FILE *fp);
  700. static void
  701. sharg(union node *arg, FILE *fp)
  702. {
  703. char *p;
  704. struct nodelist *bqlist;
  705. int subtype;
  706. if (arg->type != NARG) {
  707. out1fmt("<node type %d>\n", arg->type);
  708. abort();
  709. }
  710. bqlist = arg->narg.backquote;
  711. for (p = arg->narg.text; *p; p++) {
  712. switch (*p) {
  713. case CTLESC:
  714. putc(*++p, fp);
  715. break;
  716. case CTLVAR:
  717. putc('$', fp);
  718. putc('{', fp);
  719. subtype = *++p;
  720. if (subtype == VSLENGTH)
  721. putc('#', fp);
  722. while (*p != '=')
  723. putc(*p++, fp);
  724. if (subtype & VSNUL)
  725. putc(':', fp);
  726. switch (subtype & VSTYPE) {
  727. case VSNORMAL:
  728. putc('}', fp);
  729. break;
  730. case VSMINUS:
  731. putc('-', fp);
  732. break;
  733. case VSPLUS:
  734. putc('+', fp);
  735. break;
  736. case VSQUESTION:
  737. putc('?', fp);
  738. break;
  739. case VSASSIGN:
  740. putc('=', fp);
  741. break;
  742. case VSTRIMLEFT:
  743. putc('#', fp);
  744. break;
  745. case VSTRIMLEFTMAX:
  746. putc('#', fp);
  747. putc('#', fp);
  748. break;
  749. case VSTRIMRIGHT:
  750. putc('%', fp);
  751. break;
  752. case VSTRIMRIGHTMAX:
  753. putc('%', fp);
  754. putc('%', fp);
  755. break;
  756. case VSLENGTH:
  757. break;
  758. default:
  759. out1fmt("<subtype %d>", subtype);
  760. }
  761. break;
  762. case CTLENDVAR:
  763. putc('}', fp);
  764. break;
  765. case CTLBACKQ:
  766. case CTLBACKQ|CTLQUOTE:
  767. putc('$', fp);
  768. putc('(', fp);
  769. shtree(bqlist->n, -1, NULL, fp);
  770. putc(')', fp);
  771. break;
  772. default:
  773. putc(*p, fp);
  774. break;
  775. }
  776. }
  777. }
  778. static void
  779. shcmd(union node *cmd, FILE *fp)
  780. {
  781. union node *np;
  782. int first;
  783. const char *s;
  784. int dftfd;
  785. first = 1;
  786. for (np = cmd->ncmd.args; np; np = np->narg.next) {
  787. if (!first)
  788. putc(' ', fp);
  789. sharg(np, fp);
  790. first = 0;
  791. }
  792. for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
  793. if (!first)
  794. putc(' ', fp);
  795. dftfd = 0;
  796. switch (np->nfile.type) {
  797. case NTO: s = ">>"+1; dftfd = 1; break;
  798. case NCLOBBER: s = ">|"; dftfd = 1; break;
  799. case NAPPEND: s = ">>"; dftfd = 1; break;
  800. case NTOFD: s = ">&"; dftfd = 1; break;
  801. case NFROM: s = "<"; break;
  802. case NFROMFD: s = "<&"; break;
  803. case NFROMTO: s = "<>"; break;
  804. default: s = "*error*"; break;
  805. }
  806. if (np->nfile.fd != dftfd)
  807. fprintf(fp, "%d", np->nfile.fd);
  808. fputs(s, fp);
  809. if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
  810. fprintf(fp, "%d", np->ndup.dupfd);
  811. } else {
  812. sharg(np->nfile.fname, fp);
  813. }
  814. first = 0;
  815. }
  816. }
  817. static void
  818. shtree(union node *n, int ind, char *pfx, FILE *fp)
  819. {
  820. struct nodelist *lp;
  821. const char *s;
  822. if (n == NULL)
  823. return;
  824. indent(ind, pfx, fp);
  825. switch (n->type) {
  826. case NSEMI:
  827. s = "; ";
  828. goto binop;
  829. case NAND:
  830. s = " && ";
  831. goto binop;
  832. case NOR:
  833. s = " || ";
  834. binop:
  835. shtree(n->nbinary.ch1, ind, NULL, fp);
  836. /* if (ind < 0) */
  837. fputs(s, fp);
  838. shtree(n->nbinary.ch2, ind, NULL, fp);
  839. break;
  840. case NCMD:
  841. shcmd(n, fp);
  842. if (ind >= 0)
  843. putc('\n', fp);
  844. break;
  845. case NPIPE:
  846. for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
  847. shcmd(lp->n, fp);
  848. if (lp->next)
  849. fputs(" | ", fp);
  850. }
  851. if (n->npipe.pipe_backgnd)
  852. fputs(" &", fp);
  853. if (ind >= 0)
  854. putc('\n', fp);
  855. break;
  856. default:
  857. fprintf(fp, "<node type %d>", n->type);
  858. if (ind >= 0)
  859. putc('\n', fp);
  860. break;
  861. }
  862. }
  863. static void
  864. showtree(union node *n)
  865. {
  866. trace_puts("showtree called\n");
  867. shtree(n, 1, NULL, stdout);
  868. }
  869. #define TRACE(param) trace_printf param
  870. #define TRACEV(param) trace_vprintf param
  871. #else
  872. #define TRACE(param)
  873. #define TRACEV(param)
  874. #endif /* DEBUG */
  875. /* ============ Parser data */
  876. /*
  877. * ash_vmsg() needs parsefile->fd, hence parsefile definition is moved up.
  878. */
  879. struct strlist {
  880. struct strlist *next;
  881. char *text;
  882. };
  883. struct alias;
  884. struct strpush {
  885. struct strpush *prev; /* preceding string on stack */
  886. char *prevstring;
  887. int prevnleft;
  888. #if ENABLE_ASH_ALIAS
  889. struct alias *ap; /* if push was associated with an alias */
  890. #endif
  891. char *string; /* remember the string since it may change */
  892. };
  893. struct parsefile {
  894. struct parsefile *prev; /* preceding file on stack */
  895. int linno; /* current line */
  896. int fd; /* file descriptor (or -1 if string) */
  897. int nleft; /* number of chars left in this line */
  898. int lleft; /* number of chars left in this buffer */
  899. char *nextc; /* next char in buffer */
  900. char *buf; /* input buffer */
  901. struct strpush *strpush; /* for pushing strings at this level */
  902. struct strpush basestrpush; /* so pushing one is fast */
  903. };
  904. static struct parsefile basepf; /* top level input file */
  905. static struct parsefile *g_parsefile = &basepf; /* current input file */
  906. static int startlinno; /* line # where last token started */
  907. static char *commandname; /* currently executing command */
  908. static struct strlist *cmdenviron; /* environment for builtin command */
  909. static uint8_t exitstatus; /* exit status of last command */
  910. /* ============ Message printing */
  911. static void
  912. ash_vmsg(const char *msg, va_list ap)
  913. {
  914. fprintf(stderr, "%s: ", arg0);
  915. if (commandname) {
  916. if (strcmp(arg0, commandname))
  917. fprintf(stderr, "%s: ", commandname);
  918. if (!iflag || g_parsefile->fd)
  919. fprintf(stderr, "line %d: ", startlinno);
  920. }
  921. vfprintf(stderr, msg, ap);
  922. outcslow('\n', stderr);
  923. }
  924. /*
  925. * Exverror is called to raise the error exception. If the second argument
  926. * is not NULL then error prints an error message using printf style
  927. * formatting. It then raises the error exception.
  928. */
  929. static void ash_vmsg_and_raise(int, const char *, va_list) NORETURN;
  930. static void
  931. ash_vmsg_and_raise(int cond, const char *msg, va_list ap)
  932. {
  933. #if DEBUG
  934. if (msg) {
  935. TRACE(("ash_vmsg_and_raise(%d, \"", cond));
  936. TRACEV((msg, ap));
  937. TRACE(("\") pid=%d\n", getpid()));
  938. } else
  939. TRACE(("ash_vmsg_and_raise(%d, NULL) pid=%d\n", cond, getpid()));
  940. if (msg)
  941. #endif
  942. ash_vmsg(msg, ap);
  943. flush_stdout_stderr();
  944. raise_exception(cond);
  945. /* NOTREACHED */
  946. }
  947. static void ash_msg_and_raise_error(const char *, ...) NORETURN;
  948. static void
  949. ash_msg_and_raise_error(const char *msg, ...)
  950. {
  951. va_list ap;
  952. va_start(ap, msg);
  953. ash_vmsg_and_raise(EXERROR, msg, ap);
  954. /* NOTREACHED */
  955. va_end(ap);
  956. }
  957. static void ash_msg_and_raise(int, const char *, ...) NORETURN;
  958. static void
  959. ash_msg_and_raise(int cond, const char *msg, ...)
  960. {
  961. va_list ap;
  962. va_start(ap, msg);
  963. ash_vmsg_and_raise(cond, msg, ap);
  964. /* NOTREACHED */
  965. va_end(ap);
  966. }
  967. /*
  968. * error/warning routines for external builtins
  969. */
  970. static void
  971. ash_msg(const char *fmt, ...)
  972. {
  973. va_list ap;
  974. va_start(ap, fmt);
  975. ash_vmsg(fmt, ap);
  976. va_end(ap);
  977. }
  978. /*
  979. * Return a string describing an error. The returned string may be a
  980. * pointer to a static buffer that will be overwritten on the next call.
  981. * Action describes the operation that got the error.
  982. */
  983. static const char *
  984. errmsg(int e, const char *em)
  985. {
  986. if (e == ENOENT || e == ENOTDIR) {
  987. return em;
  988. }
  989. return strerror(e);
  990. }
  991. /* ============ Memory allocation */
  992. /*
  993. * It appears that grabstackstr() will barf with such alignments
  994. * because stalloc() will return a string allocated in a new stackblock.
  995. */
  996. #define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
  997. enum {
  998. /* Most machines require the value returned from malloc to be aligned
  999. * in some way. The following macro will get this right
  1000. * on many machines. */
  1001. SHELL_SIZE = sizeof(union {int i; char *cp; double d; }) - 1,
  1002. /* Minimum size of a block */
  1003. MINSIZE = SHELL_ALIGN(504),
  1004. };
  1005. struct stack_block {
  1006. struct stack_block *prev;
  1007. char space[MINSIZE];
  1008. };
  1009. struct stackmark {
  1010. struct stack_block *stackp;
  1011. char *stacknxt;
  1012. size_t stacknleft;
  1013. struct stackmark *marknext;
  1014. };
  1015. struct globals_memstack {
  1016. struct stack_block *g_stackp; // = &stackbase;
  1017. struct stackmark *markp;
  1018. char *g_stacknxt; // = stackbase.space;
  1019. char *sstrend; // = stackbase.space + MINSIZE;
  1020. size_t g_stacknleft; // = MINSIZE;
  1021. int herefd; // = -1;
  1022. struct stack_block stackbase;
  1023. };
  1024. extern struct globals_memstack *const ash_ptr_to_globals_memstack;
  1025. #define G_memstack (*ash_ptr_to_globals_memstack)
  1026. #define g_stackp (G_memstack.g_stackp )
  1027. #define markp (G_memstack.markp )
  1028. #define g_stacknxt (G_memstack.g_stacknxt )
  1029. #define sstrend (G_memstack.sstrend )
  1030. #define g_stacknleft (G_memstack.g_stacknleft)
  1031. #define herefd (G_memstack.herefd )
  1032. #define stackbase (G_memstack.stackbase )
  1033. #define INIT_G_memstack() do { \
  1034. (*(struct globals_memstack**)&ash_ptr_to_globals_memstack) = xzalloc(sizeof(G_memstack)); \
  1035. barrier(); \
  1036. g_stackp = &stackbase; \
  1037. g_stacknxt = stackbase.space; \
  1038. g_stacknleft = MINSIZE; \
  1039. sstrend = stackbase.space + MINSIZE; \
  1040. herefd = -1; \
  1041. } while (0)
  1042. #define stackblock() ((void *)g_stacknxt)
  1043. #define stackblocksize() g_stacknleft
  1044. static void *
  1045. ckrealloc(void * p, size_t nbytes)
  1046. {
  1047. p = realloc(p, nbytes);
  1048. if (!p)
  1049. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  1050. return p;
  1051. }
  1052. static void *
  1053. ckmalloc(size_t nbytes)
  1054. {
  1055. return ckrealloc(NULL, nbytes);
  1056. }
  1057. static void *
  1058. ckzalloc(size_t nbytes)
  1059. {
  1060. return memset(ckmalloc(nbytes), 0, nbytes);
  1061. }
  1062. /*
  1063. * Make a copy of a string in safe storage.
  1064. */
  1065. static char *
  1066. ckstrdup(const char *s)
  1067. {
  1068. char *p = strdup(s);
  1069. if (!p)
  1070. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  1071. return p;
  1072. }
  1073. /*
  1074. * Parse trees for commands are allocated in lifo order, so we use a stack
  1075. * to make this more efficient, and also to avoid all sorts of exception
  1076. * handling code to handle interrupts in the middle of a parse.
  1077. *
  1078. * The size 504 was chosen because the Ultrix malloc handles that size
  1079. * well.
  1080. */
  1081. static void *
  1082. stalloc(size_t nbytes)
  1083. {
  1084. char *p;
  1085. size_t aligned;
  1086. aligned = SHELL_ALIGN(nbytes);
  1087. if (aligned > g_stacknleft) {
  1088. size_t len;
  1089. size_t blocksize;
  1090. struct stack_block *sp;
  1091. blocksize = aligned;
  1092. if (blocksize < MINSIZE)
  1093. blocksize = MINSIZE;
  1094. len = sizeof(struct stack_block) - MINSIZE + blocksize;
  1095. if (len < blocksize)
  1096. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  1097. INT_OFF;
  1098. sp = ckmalloc(len);
  1099. sp->prev = g_stackp;
  1100. g_stacknxt = sp->space;
  1101. g_stacknleft = blocksize;
  1102. sstrend = g_stacknxt + blocksize;
  1103. g_stackp = sp;
  1104. INT_ON;
  1105. }
  1106. p = g_stacknxt;
  1107. g_stacknxt += aligned;
  1108. g_stacknleft -= aligned;
  1109. return p;
  1110. }
  1111. static void *
  1112. stzalloc(size_t nbytes)
  1113. {
  1114. return memset(stalloc(nbytes), 0, nbytes);
  1115. }
  1116. static void
  1117. stunalloc(void *p)
  1118. {
  1119. #if DEBUG
  1120. if (!p || (g_stacknxt < (char *)p) || ((char *)p < g_stackp->space)) {
  1121. write(STDERR_FILENO, "stunalloc\n", 10);
  1122. abort();
  1123. }
  1124. #endif
  1125. g_stacknleft += g_stacknxt - (char *)p;
  1126. g_stacknxt = p;
  1127. }
  1128. /*
  1129. * Like strdup but works with the ash stack.
  1130. */
  1131. static char *
  1132. ststrdup(const char *p)
  1133. {
  1134. size_t len = strlen(p) + 1;
  1135. return memcpy(stalloc(len), p, len);
  1136. }
  1137. static void
  1138. setstackmark(struct stackmark *mark)
  1139. {
  1140. mark->stackp = g_stackp;
  1141. mark->stacknxt = g_stacknxt;
  1142. mark->stacknleft = g_stacknleft;
  1143. mark->marknext = markp;
  1144. markp = mark;
  1145. }
  1146. static void
  1147. popstackmark(struct stackmark *mark)
  1148. {
  1149. struct stack_block *sp;
  1150. if (!mark->stackp)
  1151. return;
  1152. INT_OFF;
  1153. markp = mark->marknext;
  1154. while (g_stackp != mark->stackp) {
  1155. sp = g_stackp;
  1156. g_stackp = sp->prev;
  1157. free(sp);
  1158. }
  1159. g_stacknxt = mark->stacknxt;
  1160. g_stacknleft = mark->stacknleft;
  1161. sstrend = mark->stacknxt + mark->stacknleft;
  1162. INT_ON;
  1163. }
  1164. /*
  1165. * When the parser reads in a string, it wants to stick the string on the
  1166. * stack and only adjust the stack pointer when it knows how big the
  1167. * string is. Stackblock (defined in stack.h) returns a pointer to a block
  1168. * of space on top of the stack and stackblocklen returns the length of
  1169. * this block. Growstackblock will grow this space by at least one byte,
  1170. * possibly moving it (like realloc). Grabstackblock actually allocates the
  1171. * part of the block that has been used.
  1172. */
  1173. static void
  1174. growstackblock(void)
  1175. {
  1176. size_t newlen;
  1177. newlen = g_stacknleft * 2;
  1178. if (newlen < g_stacknleft)
  1179. ash_msg_and_raise_error(bb_msg_memory_exhausted);
  1180. if (newlen < 128)
  1181. newlen += 128;
  1182. if (g_stacknxt == g_stackp->space && g_stackp != &stackbase) {
  1183. struct stack_block *oldstackp;
  1184. struct stackmark *xmark;
  1185. struct stack_block *sp;
  1186. struct stack_block *prevstackp;
  1187. size_t grosslen;
  1188. INT_OFF;
  1189. oldstackp = g_stackp;
  1190. sp = g_stackp;
  1191. prevstackp = sp->prev;
  1192. grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
  1193. sp = ckrealloc(sp, grosslen);
  1194. sp->prev = prevstackp;
  1195. g_stackp = sp;
  1196. g_stacknxt = sp->space;
  1197. g_stacknleft = newlen;
  1198. sstrend = sp->space + newlen;
  1199. /*
  1200. * Stack marks pointing to the start of the old block
  1201. * must be relocated to point to the new block
  1202. */
  1203. xmark = markp;
  1204. while (xmark != NULL && xmark->stackp == oldstackp) {
  1205. xmark->stackp = g_stackp;
  1206. xmark->stacknxt = g_stacknxt;
  1207. xmark->stacknleft = g_stacknleft;
  1208. xmark = xmark->marknext;
  1209. }
  1210. INT_ON;
  1211. } else {
  1212. char *oldspace = g_stacknxt;
  1213. size_t oldlen = g_stacknleft;
  1214. char *p = stalloc(newlen);
  1215. /* free the space we just allocated */
  1216. g_stacknxt = memcpy(p, oldspace, oldlen);
  1217. g_stacknleft += newlen;
  1218. }
  1219. }
  1220. static void
  1221. grabstackblock(size_t len)
  1222. {
  1223. len = SHELL_ALIGN(len);
  1224. g_stacknxt += len;
  1225. g_stacknleft -= len;
  1226. }
  1227. /*
  1228. * The following routines are somewhat easier to use than the above.
  1229. * The user declares a variable of type STACKSTR, which may be declared
  1230. * to be a register. The macro STARTSTACKSTR initializes things. Then
  1231. * the user uses the macro STPUTC to add characters to the string. In
  1232. * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
  1233. * grown as necessary. When the user is done, she can just leave the
  1234. * string there and refer to it using stackblock(). Or she can allocate
  1235. * the space for it using grabstackstr(). If it is necessary to allow
  1236. * someone else to use the stack temporarily and then continue to grow
  1237. * the string, the user should use grabstack to allocate the space, and
  1238. * then call ungrabstr(p) to return to the previous mode of operation.
  1239. *
  1240. * USTPUTC is like STPUTC except that it doesn't check for overflow.
  1241. * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
  1242. * is space for at least one character.
  1243. */
  1244. static void *
  1245. growstackstr(void)
  1246. {
  1247. size_t len = stackblocksize();
  1248. if (herefd >= 0 && len >= 1024) {
  1249. full_write(herefd, stackblock(), len);
  1250. return stackblock();
  1251. }
  1252. growstackblock();
  1253. return (char *)stackblock() + len;
  1254. }
  1255. /*
  1256. * Called from CHECKSTRSPACE.
  1257. */
  1258. static char *
  1259. makestrspace(size_t newlen, char *p)
  1260. {
  1261. size_t len = p - g_stacknxt;
  1262. size_t size = stackblocksize();
  1263. for (;;) {
  1264. size_t nleft;
  1265. size = stackblocksize();
  1266. nleft = size - len;
  1267. if (nleft >= newlen)
  1268. break;
  1269. growstackblock();
  1270. }
  1271. return (char *)stackblock() + len;
  1272. }
  1273. static char *
  1274. stack_nputstr(const char *s, size_t n, char *p)
  1275. {
  1276. p = makestrspace(n, p);
  1277. p = (char *)memcpy(p, s, n) + n;
  1278. return p;
  1279. }
  1280. static char *
  1281. stack_putstr(const char *s, char *p)
  1282. {
  1283. return stack_nputstr(s, strlen(s), p);
  1284. }
  1285. static char *
  1286. _STPUTC(int c, char *p)
  1287. {
  1288. if (p == sstrend)
  1289. p = growstackstr();
  1290. *p++ = c;
  1291. return p;
  1292. }
  1293. #define STARTSTACKSTR(p) ((p) = stackblock())
  1294. #define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
  1295. #define CHECKSTRSPACE(n, p) do { \
  1296. char *q = (p); \
  1297. size_t l = (n); \
  1298. size_t m = sstrend - q; \
  1299. if (l > m) \
  1300. (p) = makestrspace(l, q); \
  1301. } while (0)
  1302. #define USTPUTC(c, p) (*(p)++ = (c))
  1303. #define STACKSTRNUL(p) do { \
  1304. if ((p) == sstrend) \
  1305. (p) = growstackstr(); \
  1306. *(p) = '\0'; \
  1307. } while (0)
  1308. #define STUNPUTC(p) (--(p))
  1309. #define STTOPC(p) ((p)[-1])
  1310. #define STADJUST(amount, p) ((p) += (amount))
  1311. #define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
  1312. #define ungrabstackstr(s, p) stunalloc(s)
  1313. #define stackstrend() ((void *)sstrend)
  1314. /* ============ String helpers */
  1315. /*
  1316. * prefix -- see if pfx is a prefix of string.
  1317. */
  1318. static char *
  1319. prefix(const char *string, const char *pfx)
  1320. {
  1321. while (*pfx) {
  1322. if (*pfx++ != *string++)
  1323. return NULL;
  1324. }
  1325. return (char *) string;
  1326. }
  1327. /*
  1328. * Check for a valid number. This should be elsewhere.
  1329. */
  1330. static int
  1331. is_number(const char *p)
  1332. {
  1333. do {
  1334. if (!isdigit(*p))
  1335. return 0;
  1336. } while (*++p != '\0');
  1337. return 1;
  1338. }
  1339. /*
  1340. * Convert a string of digits to an integer, printing an error message on
  1341. * failure.
  1342. */
  1343. static int
  1344. number(const char *s)
  1345. {
  1346. if (!is_number(s))
  1347. ash_msg_and_raise_error(illnum, s);
  1348. return atoi(s);
  1349. }
  1350. /*
  1351. * Produce a possibly single quoted string suitable as input to the shell.
  1352. * The return string is allocated on the stack.
  1353. */
  1354. static char *
  1355. single_quote(const char *s)
  1356. {
  1357. char *p;
  1358. STARTSTACKSTR(p);
  1359. do {
  1360. char *q;
  1361. size_t len;
  1362. len = strchrnul(s, '\'') - s;
  1363. q = p = makestrspace(len + 3, p);
  1364. *q++ = '\'';
  1365. q = (char *)memcpy(q, s, len) + len;
  1366. *q++ = '\'';
  1367. s += len;
  1368. STADJUST(q - p, p);
  1369. len = strspn(s, "'");
  1370. if (!len)
  1371. break;
  1372. q = p = makestrspace(len + 3, p);
  1373. *q++ = '"';
  1374. q = (char *)memcpy(q, s, len) + len;
  1375. *q++ = '"';
  1376. s += len;
  1377. STADJUST(q - p, p);
  1378. } while (*s);
  1379. USTPUTC(0, p);
  1380. return stackblock();
  1381. }
  1382. /* ============ nextopt */
  1383. static char **argptr; /* argument list for builtin commands */
  1384. static char *optionarg; /* set by nextopt (like getopt) */
  1385. static char *optptr; /* used by nextopt */
  1386. /*
  1387. * XXX - should get rid of. Have all builtins use getopt(3).
  1388. * The library getopt must have the BSD extension static variable
  1389. * "optreset", otherwise it can't be used within the shell safely.
  1390. *
  1391. * Standard option processing (a la getopt) for builtin routines.
  1392. * The only argument that is passed to nextopt is the option string;
  1393. * the other arguments are unnecessary. It returns the character,
  1394. * or '\0' on end of input.
  1395. */
  1396. static int
  1397. nextopt(const char *optstring)
  1398. {
  1399. char *p;
  1400. const char *q;
  1401. char c;
  1402. p = optptr;
  1403. if (p == NULL || *p == '\0') {
  1404. /* We ate entire "-param", take next one */
  1405. p = *argptr;
  1406. if (p == NULL)
  1407. return '\0';
  1408. if (*p != '-')
  1409. return '\0';
  1410. if (*++p == '\0') /* just "-" ? */
  1411. return '\0';
  1412. argptr++;
  1413. if (LONE_DASH(p)) /* "--" ? */
  1414. return '\0';
  1415. /* p => next "-param" */
  1416. }
  1417. /* p => some option char in the middle of a "-param" */
  1418. c = *p++;
  1419. for (q = optstring; *q != c;) {
  1420. if (*q == '\0')
  1421. ash_msg_and_raise_error("illegal option -%c", c);
  1422. if (*++q == ':')
  1423. q++;
  1424. }
  1425. if (*++q == ':') {
  1426. if (*p == '\0') {
  1427. p = *argptr++;
  1428. if (p == NULL)
  1429. ash_msg_and_raise_error("no arg for -%c option", c);
  1430. }
  1431. optionarg = p;
  1432. p = NULL;
  1433. }
  1434. optptr = p;
  1435. return c;
  1436. }
  1437. /* ============ Shell variables */
  1438. /*
  1439. * The parsefile structure pointed to by the global variable parsefile
  1440. * contains information about the current file being read.
  1441. */
  1442. struct shparam {
  1443. int nparam; /* # of positional parameters (without $0) */
  1444. #if ENABLE_ASH_GETOPTS
  1445. int optind; /* next parameter to be processed by getopts */
  1446. int optoff; /* used by getopts */
  1447. #endif
  1448. unsigned char malloced; /* if parameter list dynamically allocated */
  1449. char **p; /* parameter list */
  1450. };
  1451. /*
  1452. * Free the list of positional parameters.
  1453. */
  1454. static void
  1455. freeparam(volatile struct shparam *param)
  1456. {
  1457. if (param->malloced) {
  1458. char **ap, **ap1;
  1459. ap = ap1 = param->p;
  1460. while (*ap)
  1461. free(*ap++);
  1462. free(ap1);
  1463. }
  1464. }
  1465. #if ENABLE_ASH_GETOPTS
  1466. static void getoptsreset(const char *value);
  1467. #endif
  1468. struct var {
  1469. struct var *next; /* next entry in hash list */
  1470. int flags; /* flags are defined above */
  1471. const char *text; /* name=value */
  1472. void (*func)(const char *); /* function to be called when */
  1473. /* the variable gets set/unset */
  1474. };
  1475. struct localvar {
  1476. struct localvar *next; /* next local variable in list */
  1477. struct var *vp; /* the variable that was made local */
  1478. int flags; /* saved flags */
  1479. const char *text; /* saved text */
  1480. };
  1481. /* flags */
  1482. #define VEXPORT 0x01 /* variable is exported */
  1483. #define VREADONLY 0x02 /* variable cannot be modified */
  1484. #define VSTRFIXED 0x04 /* variable struct is statically allocated */
  1485. #define VTEXTFIXED 0x08 /* text is statically allocated */
  1486. #define VSTACK 0x10 /* text is allocated on the stack */
  1487. #define VUNSET 0x20 /* the variable is not set */
  1488. #define VNOFUNC 0x40 /* don't call the callback function */
  1489. #define VNOSET 0x80 /* do not set variable - just readonly test */
  1490. #define VNOSAVE 0x100 /* when text is on the heap before setvareq */
  1491. #if ENABLE_ASH_RANDOM_SUPPORT
  1492. # define VDYNAMIC 0x200 /* dynamic variable */
  1493. #else
  1494. # define VDYNAMIC 0
  1495. #endif
  1496. #ifdef IFS_BROKEN
  1497. static const char defifsvar[] ALIGN1 = "IFS= \t\n";
  1498. #define defifs (defifsvar + 4)
  1499. #else
  1500. static const char defifs[] ALIGN1 = " \t\n";
  1501. #endif
  1502. /* Need to be before varinit_data[] */
  1503. #if ENABLE_LOCALE_SUPPORT
  1504. static void
  1505. change_lc_all(const char *value)
  1506. {
  1507. if (value && *value != '\0')
  1508. setlocale(LC_ALL, value);
  1509. }
  1510. static void
  1511. change_lc_ctype(const char *value)
  1512. {
  1513. if (value && *value != '\0')
  1514. setlocale(LC_CTYPE, value);
  1515. }
  1516. #endif
  1517. #if ENABLE_ASH_MAIL
  1518. static void chkmail(void);
  1519. static void changemail(const char *);
  1520. #endif
  1521. static void changepath(const char *);
  1522. #if ENABLE_ASH_RANDOM_SUPPORT
  1523. static void change_random(const char *);
  1524. #endif
  1525. static const struct {
  1526. int flags;
  1527. const char *text;
  1528. void (*func)(const char *);
  1529. } varinit_data[] = {
  1530. #ifdef IFS_BROKEN
  1531. { VSTRFIXED|VTEXTFIXED , defifsvar , NULL },
  1532. #else
  1533. { VSTRFIXED|VTEXTFIXED|VUNSET, "IFS\0" , NULL },
  1534. #endif
  1535. #if ENABLE_ASH_MAIL
  1536. { VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL\0" , changemail },
  1537. { VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH\0", changemail },
  1538. #endif
  1539. { VSTRFIXED|VTEXTFIXED , bb_PATH_root_path, changepath },
  1540. { VSTRFIXED|VTEXTFIXED , "PS1=$ " , NULL },
  1541. { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL },
  1542. { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL },
  1543. #if ENABLE_ASH_GETOPTS
  1544. { VSTRFIXED|VTEXTFIXED , "OPTIND=1" , getoptsreset },
  1545. #endif
  1546. #if ENABLE_ASH_RANDOM_SUPPORT
  1547. { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM\0", change_random },
  1548. #endif
  1549. #if ENABLE_LOCALE_SUPPORT
  1550. { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL\0" , change_lc_all },
  1551. { VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE\0", change_lc_ctype },
  1552. #endif
  1553. #if ENABLE_FEATURE_EDITING_SAVEHISTORY
  1554. { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE\0", NULL },
  1555. #endif
  1556. };
  1557. struct redirtab;
  1558. struct globals_var {
  1559. struct shparam shellparam; /* $@ current positional parameters */
  1560. struct redirtab *redirlist;
  1561. int g_nullredirs;
  1562. int preverrout_fd; /* save fd2 before print debug if xflag is set. */
  1563. struct var *vartab[VTABSIZE];
  1564. struct var varinit[ARRAY_SIZE(varinit_data)];
  1565. };
  1566. extern struct globals_var *const ash_ptr_to_globals_var;
  1567. #define G_var (*ash_ptr_to_globals_var)
  1568. #define shellparam (G_var.shellparam )
  1569. //#define redirlist (G_var.redirlist )
  1570. #define g_nullredirs (G_var.g_nullredirs )
  1571. #define preverrout_fd (G_var.preverrout_fd)
  1572. #define vartab (G_var.vartab )
  1573. #define varinit (G_var.varinit )
  1574. #define INIT_G_var() do { \
  1575. unsigned i; \
  1576. (*(struct globals_var**)&ash_ptr_to_globals_var) = xzalloc(sizeof(G_var)); \
  1577. barrier(); \
  1578. for (i = 0; i < ARRAY_SIZE(varinit_data); i++) { \
  1579. varinit[i].flags = varinit_data[i].flags; \
  1580. varinit[i].text = varinit_data[i].text; \
  1581. varinit[i].func = varinit_data[i].func; \
  1582. } \
  1583. } while (0)
  1584. #define vifs varinit[0]
  1585. #if ENABLE_ASH_MAIL
  1586. # define vmail (&vifs)[1]
  1587. # define vmpath (&vmail)[1]
  1588. # define vpath (&vmpath)[1]
  1589. #else
  1590. # define vpath (&vifs)[1]
  1591. #endif
  1592. #define vps1 (&vpath)[1]
  1593. #define vps2 (&vps1)[1]
  1594. #define vps4 (&vps2)[1]
  1595. #if ENABLE_ASH_GETOPTS
  1596. # define voptind (&vps4)[1]
  1597. # if ENABLE_ASH_RANDOM_SUPPORT
  1598. # define vrandom (&voptind)[1]
  1599. # endif
  1600. #else
  1601. # if ENABLE_ASH_RANDOM_SUPPORT
  1602. # define vrandom (&vps4)[1]
  1603. # endif
  1604. #endif
  1605. /*
  1606. * The following macros access the values of the above variables.
  1607. * They have to skip over the name. They return the null string
  1608. * for unset variables.
  1609. */
  1610. #define ifsval() (vifs.text + 4)
  1611. #define ifsset() ((vifs.flags & VUNSET) == 0)
  1612. #if ENABLE_ASH_MAIL
  1613. # define mailval() (vmail.text + 5)
  1614. # define mpathval() (vmpath.text + 9)
  1615. # define mpathset() ((vmpath.flags & VUNSET) == 0)
  1616. #endif
  1617. #define pathval() (vpath.text + 5)
  1618. #define ps1val() (vps1.text + 4)
  1619. #define ps2val() (vps2.text + 4)
  1620. #define ps4val() (vps4.text + 4)
  1621. #if ENABLE_ASH_GETOPTS
  1622. # define optindval() (voptind.text + 7)
  1623. #endif
  1624. #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
  1625. #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
  1626. #if ENABLE_ASH_GETOPTS
  1627. static void
  1628. getoptsreset(const char *value)
  1629. {
  1630. shellparam.optind = number(value);
  1631. shellparam.optoff = -1;
  1632. }
  1633. #endif
  1634. /*
  1635. * Return of a legal variable name (a letter or underscore followed by zero or
  1636. * more letters, underscores, and digits).
  1637. */
  1638. static char *
  1639. endofname(const char *name)
  1640. {
  1641. char *p;
  1642. p = (char *) name;
  1643. if (!is_name(*p))
  1644. return p;
  1645. while (*++p) {
  1646. if (!is_in_name(*p))
  1647. break;
  1648. }
  1649. return p;
  1650. }
  1651. /*
  1652. * Compares two strings up to the first = or '\0'. The first
  1653. * string must be terminated by '='; the second may be terminated by
  1654. * either '=' or '\0'.
  1655. */
  1656. static int
  1657. varcmp(const char *p, const char *q)
  1658. {
  1659. int c, d;
  1660. while ((c = *p) == (d = *q)) {
  1661. if (!c || c == '=')
  1662. goto out;
  1663. p++;
  1664. q++;
  1665. }
  1666. if (c == '=')
  1667. c = '\0';
  1668. if (d == '=')
  1669. d = '\0';
  1670. out:
  1671. return c - d;
  1672. }
  1673. static int
  1674. varequal(const char *a, const char *b)
  1675. {
  1676. return !varcmp(a, b);
  1677. }
  1678. /*
  1679. * Find the appropriate entry in the hash table from the name.
  1680. */
  1681. static struct var **
  1682. hashvar(const char *p)
  1683. {
  1684. unsigned hashval;
  1685. hashval = ((unsigned char) *p) << 4;
  1686. while (*p && *p != '=')
  1687. hashval += (unsigned char) *p++;
  1688. return &vartab[hashval % VTABSIZE];
  1689. }
  1690. static int
  1691. vpcmp(const void *a, const void *b)
  1692. {
  1693. return varcmp(*(const char **)a, *(const char **)b);
  1694. }
  1695. /*
  1696. * This routine initializes the builtin variables.
  1697. */
  1698. static void
  1699. initvar(void)
  1700. {
  1701. struct var *vp;
  1702. struct var *end;
  1703. struct var **vpp;
  1704. /*
  1705. * PS1 depends on uid
  1706. */
  1707. #if ENABLE_FEATURE_EDITING && ENABLE_FEATURE_EDITING_FANCY_PROMPT
  1708. vps1.text = "PS1=\\w \\$ ";
  1709. #else
  1710. if (!geteuid())
  1711. vps1.text = "PS1=# ";
  1712. #endif
  1713. vp = varinit;
  1714. end = vp + ARRAY_SIZE(varinit);
  1715. do {
  1716. vpp = hashvar(vp->text);
  1717. vp->next = *vpp;
  1718. *vpp = vp;
  1719. } while (++vp < end);
  1720. }
  1721. static struct var **
  1722. findvar(struct var **vpp, const char *name)
  1723. {
  1724. for (; *vpp; vpp = &(*vpp)->next) {
  1725. if (varequal((*vpp)->text, name)) {
  1726. break;
  1727. }
  1728. }
  1729. return vpp;
  1730. }
  1731. /*
  1732. * Find the value of a variable. Returns NULL if not set.
  1733. */
  1734. static char *
  1735. lookupvar(const char *name)
  1736. {
  1737. struct var *v;
  1738. v = *findvar(hashvar(name), name);
  1739. if (v) {
  1740. #if ENABLE_ASH_RANDOM_SUPPORT
  1741. /*
  1742. * Dynamic variables are implemented roughly the same way they are
  1743. * in bash. Namely, they're "special" so long as they aren't unset.
  1744. * As soon as they're unset, they're no longer dynamic, and dynamic
  1745. * lookup will no longer happen at that point. -- PFM.
  1746. */
  1747. if ((v->flags & VDYNAMIC))
  1748. (*v->func)(NULL);
  1749. #endif
  1750. if (!(v->flags & VUNSET))
  1751. return strchrnul(v->text, '=') + 1;
  1752. }
  1753. return NULL;
  1754. }
  1755. /*
  1756. * Search the environment of a builtin command.
  1757. */
  1758. static char *
  1759. bltinlookup(const char *name)
  1760. {
  1761. struct strlist *sp;
  1762. for (sp = cmdenviron; sp; sp = sp->next) {
  1763. if (varequal(sp->text, name))
  1764. return strchrnul(sp->text, '=') + 1;
  1765. }
  1766. return lookupvar(name);
  1767. }
  1768. /*
  1769. * Same as setvar except that the variable and value are passed in
  1770. * the first argument as name=value. Since the first argument will
  1771. * be actually stored in the table, it should not be a string that
  1772. * will go away.
  1773. * Called with interrupts off.
  1774. */
  1775. static void
  1776. setvareq(char *s, int flags)
  1777. {
  1778. struct var *vp, **vpp;
  1779. vpp = hashvar(s);
  1780. flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
  1781. vp = *findvar(vpp, s);
  1782. if (vp) {
  1783. if ((vp->flags & (VREADONLY|VDYNAMIC)) == VREADONLY) {
  1784. const char *n;
  1785. if (flags & VNOSAVE)
  1786. free(s);
  1787. n = vp->text;
  1788. ash_msg_and_raise_error("%.*s: is read only", strchrnul(n, '=') - n, n);
  1789. }
  1790. if (flags & VNOSET)
  1791. return;
  1792. if (vp->func && (flags & VNOFUNC) == 0)
  1793. (*vp->func)(strchrnul(s, '=') + 1);
  1794. if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
  1795. free((char*)vp->text);
  1796. flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
  1797. } else {
  1798. if (flags & VNOSET)
  1799. return;
  1800. /* not found */
  1801. vp = ckzalloc(sizeof(*vp));
  1802. vp->next = *vpp;
  1803. /*vp->func = NULL; - ckzalloc did it */
  1804. *vpp = vp;
  1805. }
  1806. if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
  1807. s = ckstrdup(s);
  1808. vp->text = s;
  1809. vp->flags = flags;
  1810. }
  1811. /*
  1812. * Set the value of a variable. The flags argument is ored with the
  1813. * flags of the variable. If val is NULL, the variable is unset.
  1814. */
  1815. static void
  1816. setvar(const char *name, const char *val, int flags)
  1817. {
  1818. char *p, *q;
  1819. size_t namelen;
  1820. char *nameeq;
  1821. size_t vallen;
  1822. q = endofname(name);
  1823. p = strchrnul(q, '=');
  1824. namelen = p - name;
  1825. if (!namelen || p != q)
  1826. ash_msg_and_raise_error("%.*s: bad variable name", namelen, name);
  1827. vallen = 0;
  1828. if (val == NULL) {
  1829. flags |= VUNSET;
  1830. } else {
  1831. vallen = strlen(val);
  1832. }
  1833. INT_OFF;
  1834. nameeq = ckmalloc(namelen + vallen + 2);
  1835. p = (char *)memcpy(nameeq, name, namelen) + namelen;
  1836. if (val) {
  1837. *p++ = '=';
  1838. p = (char *)memcpy(p, val, vallen) + vallen;
  1839. }
  1840. *p = '\0';
  1841. setvareq(nameeq, flags | VNOSAVE);
  1842. INT_ON;
  1843. }
  1844. #if ENABLE_ASH_GETOPTS
  1845. /*
  1846. * Safe version of setvar, returns 1 on success 0 on failure.
  1847. */
  1848. static int
  1849. setvarsafe(const char *name, const char *val, int flags)
  1850. {
  1851. int err;
  1852. volatile int saveint;
  1853. struct jmploc *volatile savehandler = exception_handler;
  1854. struct jmploc jmploc;
  1855. SAVE_INT(saveint);
  1856. if (setjmp(jmploc.loc))
  1857. err = 1;
  1858. else {
  1859. exception_handler = &jmploc;
  1860. setvar(name, val, flags);
  1861. err = 0;
  1862. }
  1863. exception_handler = savehandler;
  1864. RESTORE_INT(saveint);
  1865. return err;
  1866. }
  1867. #endif
  1868. /*
  1869. * Unset the specified variable.
  1870. */
  1871. static int
  1872. unsetvar(const char *s)
  1873. {
  1874. struct var **vpp;
  1875. struct var *vp;
  1876. int retval;
  1877. vpp = findvar(hashvar(s), s);
  1878. vp = *vpp;
  1879. retval = 2;
  1880. if (vp) {
  1881. int flags = vp->flags;
  1882. retval = 1;
  1883. if (flags & VREADONLY)
  1884. goto out;
  1885. #if ENABLE_ASH_RANDOM_SUPPORT
  1886. vp->flags &= ~VDYNAMIC;
  1887. #endif
  1888. if (flags & VUNSET)
  1889. goto ok;
  1890. if ((flags & VSTRFIXED) == 0) {
  1891. INT_OFF;
  1892. if ((flags & (VTEXTFIXED|VSTACK)) == 0)
  1893. free((char*)vp->text);
  1894. *vpp = vp->next;
  1895. free(vp);
  1896. INT_ON;
  1897. } else {
  1898. setvar(s, 0, 0);
  1899. vp->flags &= ~VEXPORT;
  1900. }
  1901. ok:
  1902. retval = 0;
  1903. }
  1904. out:
  1905. return retval;
  1906. }
  1907. /*
  1908. * Process a linked list of variable assignments.
  1909. */
  1910. static void
  1911. listsetvar(struct strlist *list_set_var, int flags)
  1912. {
  1913. struct strlist *lp = list_set_var;
  1914. if (!lp)
  1915. return;
  1916. INT_OFF;
  1917. do {
  1918. setvareq(lp->text, flags);
  1919. lp = lp->next;
  1920. } while (lp);
  1921. INT_ON;
  1922. }
  1923. /*
  1924. * Generate a list of variables satisfying the given conditions.
  1925. */
  1926. static char **
  1927. listvars(int on, int off, char ***end)
  1928. {
  1929. struct var **vpp;
  1930. struct var *vp;
  1931. char **ep;
  1932. int mask;
  1933. STARTSTACKSTR(ep);
  1934. vpp = vartab;
  1935. mask = on | off;
  1936. do {
  1937. for (vp = *vpp; vp; vp = vp->next) {
  1938. if ((vp->flags & mask) == on) {
  1939. if (ep == stackstrend())
  1940. ep = growstackstr();
  1941. *ep++ = (char *) vp->text;
  1942. }
  1943. }
  1944. } while (++vpp < vartab + VTABSIZE);
  1945. if (ep == stackstrend())
  1946. ep = growstackstr();
  1947. if (end)
  1948. *end = ep;
  1949. *ep++ = NULL;
  1950. return grabstackstr(ep);
  1951. }
  1952. /* ============ Path search helper
  1953. *
  1954. * The variable path (passed by reference) should be set to the start
  1955. * of the path before the first call; padvance will update
  1956. * this value as it proceeds. Successive calls to padvance will return
  1957. * the possible path expansions in sequence. If an option (indicated by
  1958. * a percent sign) appears in the path entry then the global variable
  1959. * pathopt will be set to point to it; otherwise pathopt will be set to
  1960. * NULL.
  1961. */
  1962. static const char *pathopt; /* set by padvance */
  1963. static char *
  1964. padvance(const char **path, const char *name)
  1965. {
  1966. const char *p;
  1967. char *q;
  1968. const char *start;
  1969. size_t len;
  1970. if (*path == NULL)
  1971. return NULL;
  1972. start = *path;
  1973. for (p = start; *p && *p != ':' && *p != '%'; p++)
  1974. continue;
  1975. len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
  1976. while (stackblocksize() < len)
  1977. growstackblock();
  1978. q = stackblock();
  1979. if (p != start) {
  1980. memcpy(q, start, p - start);
  1981. q += p - start;
  1982. *q++ = '/';
  1983. }
  1984. strcpy(q, name);
  1985. pathopt = NULL;
  1986. if (*p == '%') {
  1987. pathopt = ++p;
  1988. while (*p && *p != ':')
  1989. p++;
  1990. }
  1991. if (*p == ':')
  1992. *path = p + 1;
  1993. else
  1994. *path = NULL;
  1995. return stalloc(len);
  1996. }
  1997. /* ============ Prompt */
  1998. static smallint doprompt; /* if set, prompt the user */
  1999. static smallint needprompt; /* true if interactive and at start of line */
  2000. #if ENABLE_FEATURE_EDITING
  2001. static line_input_t *line_input_state;
  2002. static const char *cmdedit_prompt;
  2003. static void
  2004. putprompt(const char *s)
  2005. {
  2006. if (ENABLE_ASH_EXPAND_PRMT) {
  2007. free((char*)cmdedit_prompt);
  2008. cmdedit_prompt = ckstrdup(s);
  2009. return;
  2010. }
  2011. cmdedit_prompt = s;
  2012. }
  2013. #else
  2014. static void
  2015. putprompt(const char *s)
  2016. {
  2017. out2str(s);
  2018. }
  2019. #endif
  2020. #if ENABLE_ASH_EXPAND_PRMT
  2021. /* expandstr() needs parsing machinery, so it is far away ahead... */
  2022. static const char *expandstr(const char *ps);
  2023. #else
  2024. #define expandstr(s) s
  2025. #endif
  2026. static void
  2027. setprompt(int whichprompt)
  2028. {
  2029. const char *prompt;
  2030. #if ENABLE_ASH_EXPAND_PRMT
  2031. struct stackmark smark;
  2032. #endif
  2033. needprompt = 0;
  2034. switch (whichprompt) {
  2035. case 1:
  2036. prompt = ps1val();
  2037. break;
  2038. case 2:
  2039. prompt = ps2val();
  2040. break;
  2041. default: /* 0 */
  2042. prompt = nullstr;
  2043. }
  2044. #if ENABLE_ASH_EXPAND_PRMT
  2045. setstackmark(&smark);
  2046. stalloc(stackblocksize());
  2047. #endif
  2048. putprompt(expandstr(prompt));
  2049. #if ENABLE_ASH_EXPAND_PRMT
  2050. popstackmark(&smark);
  2051. #endif
  2052. }
  2053. /* ============ The cd and pwd commands */
  2054. #define CD_PHYSICAL 1
  2055. #define CD_PRINT 2
  2056. static int docd(const char *, int);
  2057. static int
  2058. cdopt(void)
  2059. {
  2060. int flags = 0;
  2061. int i, j;
  2062. j = 'L';
  2063. while ((i = nextopt("LP"))) {
  2064. if (i != j) {
  2065. flags ^= CD_PHYSICAL;
  2066. j = i;
  2067. }
  2068. }
  2069. return flags;
  2070. }
  2071. /*
  2072. * Update curdir (the name of the current directory) in response to a
  2073. * cd command.
  2074. */
  2075. static const char *
  2076. updatepwd(const char *dir)
  2077. {
  2078. char *new;
  2079. char *p;
  2080. char *cdcomppath;
  2081. const char *lim;
  2082. cdcomppath = ststrdup(dir);
  2083. STARTSTACKSTR(new);
  2084. if (*dir != '/') {
  2085. if (curdir == nullstr)
  2086. return 0;
  2087. new = stack_putstr(curdir, new);
  2088. }
  2089. new = makestrspace(strlen(dir) + 2, new);
  2090. lim = (char *)stackblock() + 1;
  2091. if (*dir != '/') {
  2092. if (new[-1] != '/')
  2093. USTPUTC('/', new);
  2094. if (new > lim && *lim == '/')
  2095. lim++;
  2096. } else {
  2097. USTPUTC('/', new);
  2098. cdcomppath++;
  2099. if (dir[1] == '/' && dir[2] != '/') {
  2100. USTPUTC('/', new);
  2101. cdcomppath++;
  2102. lim++;
  2103. }
  2104. }
  2105. p = strtok(cdcomppath, "/");
  2106. while (p) {
  2107. switch (*p) {
  2108. case '.':
  2109. if (p[1] == '.' && p[2] == '\0') {
  2110. while (new > lim) {
  2111. STUNPUTC(new);
  2112. if (new[-1] == '/')
  2113. break;
  2114. }
  2115. break;
  2116. }
  2117. if (p[1] == '\0')
  2118. break;
  2119. /* fall through */
  2120. default:
  2121. new = stack_putstr(p, new);
  2122. USTPUTC('/', new);
  2123. }
  2124. p = strtok(0, "/");
  2125. }
  2126. if (new > lim)
  2127. STUNPUTC(new);
  2128. *new = 0;
  2129. return stackblock();
  2130. }
  2131. /*
  2132. * Find out what the current directory is. If we already know the current
  2133. * directory, this routine returns immediately.
  2134. */
  2135. static char *
  2136. getpwd(void)
  2137. {
  2138. char *dir = getcwd(NULL, 0); /* huh, using glibc extension? */
  2139. return dir ? dir : nullstr;
  2140. }
  2141. static void
  2142. setpwd(const char *val, int setold)
  2143. {
  2144. char *oldcur, *dir;
  2145. oldcur = dir = curdir;
  2146. if (setold) {
  2147. setvar("OLDPWD", oldcur, VEXPORT);
  2148. }
  2149. INT_OFF;
  2150. if (physdir != nullstr) {
  2151. if (physdir != oldcur)
  2152. free(physdir);
  2153. physdir = nullstr;
  2154. }
  2155. if (oldcur == val || !val) {
  2156. char *s = getpwd();
  2157. physdir = s;
  2158. if (!val)
  2159. dir = s;
  2160. } else
  2161. dir = ckstrdup(val);
  2162. if (oldcur != dir && oldcur != nullstr) {
  2163. free(oldcur);
  2164. }
  2165. curdir = dir;
  2166. INT_ON;
  2167. setvar("PWD", dir, VEXPORT);
  2168. }
  2169. static void hashcd(void);
  2170. /*
  2171. * Actually do the chdir. We also call hashcd to let the routines in exec.c
  2172. * know that the current directory has changed.
  2173. */
  2174. static int
  2175. docd(const char *dest, int flags)
  2176. {
  2177. const char *dir = 0;
  2178. int err;
  2179. TRACE(("docd(\"%s\", %d) called\n", dest, flags));
  2180. INT_OFF;
  2181. if (!(flags & CD_PHYSICAL)) {
  2182. dir = updatepwd(dest);
  2183. if (dir)
  2184. dest = dir;
  2185. }
  2186. err = chdir(dest);
  2187. if (err)
  2188. goto out;
  2189. setpwd(dir, 1);
  2190. hashcd();
  2191. out:
  2192. INT_ON;
  2193. return err;
  2194. }
  2195. static int
  2196. cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  2197. {
  2198. const char *dest;
  2199. const char *path;
  2200. const char *p;
  2201. char c;
  2202. struct stat statb;
  2203. int flags;
  2204. flags = cdopt();
  2205. dest = *argptr;
  2206. if (!dest)
  2207. dest = bltinlookup(homestr);
  2208. else if (LONE_DASH(dest)) {
  2209. dest = bltinlookup("OLDPWD");
  2210. flags |= CD_PRINT;
  2211. }
  2212. if (!dest)
  2213. dest = nullstr;
  2214. if (*dest == '/')
  2215. goto step7;
  2216. if (*dest == '.') {
  2217. c = dest[1];
  2218. dotdot:
  2219. switch (c) {
  2220. case '\0':
  2221. case '/':
  2222. goto step6;
  2223. case '.':
  2224. c = dest[2];
  2225. if (c != '.')
  2226. goto dotdot;
  2227. }
  2228. }
  2229. if (!*dest)
  2230. dest = ".";
  2231. path = bltinlookup("CDPATH");
  2232. if (!path) {
  2233. step6:
  2234. step7:
  2235. p = dest;
  2236. goto docd;
  2237. }
  2238. do {
  2239. c = *path;
  2240. p = padvance(&path, dest);
  2241. if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
  2242. if (c && c != ':')
  2243. flags |= CD_PRINT;
  2244. docd:
  2245. if (!docd(p, flags))
  2246. goto out;
  2247. break;
  2248. }
  2249. } while (path);
  2250. ash_msg_and_raise_error("can't cd to %s", dest);
  2251. /* NOTREACHED */
  2252. out:
  2253. if (flags & CD_PRINT)
  2254. out1fmt(snlfmt, curdir);
  2255. return 0;
  2256. }
  2257. static int
  2258. pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  2259. {
  2260. int flags;
  2261. const char *dir = curdir;
  2262. flags = cdopt();
  2263. if (flags) {
  2264. if (physdir == nullstr)
  2265. setpwd(dir, 0);
  2266. dir = physdir;
  2267. }
  2268. out1fmt(snlfmt, dir);
  2269. return 0;
  2270. }
  2271. /* ============ ... */
  2272. #define IBUFSIZ COMMON_BUFSIZE
  2273. #define basebuf bb_common_bufsiz1 /* buffer for top level input file */
  2274. /* Syntax classes */
  2275. #define CWORD 0 /* character is nothing special */
  2276. #define CNL 1 /* newline character */
  2277. #define CBACK 2 /* a backslash character */
  2278. #define CSQUOTE 3 /* single quote */
  2279. #define CDQUOTE 4 /* double quote */
  2280. #define CENDQUOTE 5 /* a terminating quote */
  2281. #define CBQUOTE 6 /* backwards single quote */
  2282. #define CVAR 7 /* a dollar sign */
  2283. #define CENDVAR 8 /* a '}' character */
  2284. #define CLP 9 /* a left paren in arithmetic */
  2285. #define CRP 10 /* a right paren in arithmetic */
  2286. #define CENDFILE 11 /* end of file */
  2287. #define CCTL 12 /* like CWORD, except it must be escaped */
  2288. #define CSPCL 13 /* these terminate a word */
  2289. #define CIGN 14 /* character should be ignored */
  2290. #if ENABLE_ASH_ALIAS
  2291. #define SYNBASE 130
  2292. #define PEOF -130
  2293. #define PEOA -129
  2294. #define PEOA_OR_PEOF PEOA
  2295. #else
  2296. #define SYNBASE 129
  2297. #define PEOF -129
  2298. #define PEOA_OR_PEOF PEOF
  2299. #endif
  2300. /* number syntax index */
  2301. #define BASESYNTAX 0 /* not in quotes */
  2302. #define DQSYNTAX 1 /* in double quotes */
  2303. #define SQSYNTAX 2 /* in single quotes */
  2304. #define ARISYNTAX 3 /* in arithmetic */
  2305. #define PSSYNTAX 4 /* prompt */
  2306. #if ENABLE_ASH_OPTIMIZE_FOR_SIZE
  2307. #define USE_SIT_FUNCTION
  2308. #endif
  2309. #if ENABLE_ASH_MATH_SUPPORT
  2310. static const char S_I_T[][4] = {
  2311. #if ENABLE_ASH_ALIAS
  2312. { CSPCL, CIGN, CIGN, CIGN }, /* 0, PEOA */
  2313. #endif
  2314. { CSPCL, CWORD, CWORD, CWORD }, /* 1, ' ' */
  2315. { CNL, CNL, CNL, CNL }, /* 2, \n */
  2316. { CWORD, CCTL, CCTL, CWORD }, /* 3, !*-/:=?[]~ */
  2317. { CDQUOTE, CENDQUOTE, CWORD, CWORD }, /* 4, '"' */
  2318. { CVAR, CVAR, CWORD, CVAR }, /* 5, $ */
  2319. { CSQUOTE, CWORD, CENDQUOTE, CWORD }, /* 6, "'" */
  2320. { CSPCL, CWORD, CWORD, CLP }, /* 7, ( */
  2321. { CSPCL, CWORD, CWORD, CRP }, /* 8, ) */
  2322. { CBACK, CBACK, CCTL, CBACK }, /* 9, \ */
  2323. { CBQUOTE, CBQUOTE, CWORD, CBQUOTE }, /* 10, ` */
  2324. { CENDVAR, CENDVAR, CWORD, CENDVAR }, /* 11, } */
  2325. #ifndef USE_SIT_FUNCTION
  2326. { CENDFILE, CENDFILE, CENDFILE, CENDFILE }, /* 12, PEOF */
  2327. { CWORD, CWORD, CWORD, CWORD }, /* 13, 0-9A-Za-z */
  2328. { CCTL, CCTL, CCTL, CCTL } /* 14, CTLESC ... */
  2329. #endif
  2330. };
  2331. #else
  2332. static const char S_I_T[][3] = {
  2333. #if ENABLE_ASH_ALIAS
  2334. { CSPCL, CIGN, CIGN }, /* 0, PEOA */
  2335. #endif
  2336. { CSPCL, CWORD, CWORD }, /* 1, ' ' */
  2337. { CNL, CNL, CNL }, /* 2, \n */
  2338. { CWORD, CCTL, CCTL }, /* 3, !*-/:=?[]~ */
  2339. { CDQUOTE, CENDQUOTE, CWORD }, /* 4, '"' */
  2340. { CVAR, CVAR, CWORD }, /* 5, $ */
  2341. { CSQUOTE, CWORD, CENDQUOTE }, /* 6, "'" */
  2342. { CSPCL, CWORD, CWORD }, /* 7, ( */
  2343. { CSPCL, CWORD, CWORD }, /* 8, ) */
  2344. { CBACK, CBACK, CCTL }, /* 9, \ */
  2345. { CBQUOTE, CBQUOTE, CWORD }, /* 10, ` */
  2346. { CENDVAR, CENDVAR, CWORD }, /* 11, } */
  2347. #ifndef USE_SIT_FUNCTION
  2348. { CENDFILE, CENDFILE, CENDFILE }, /* 12, PEOF */
  2349. { CWORD, CWORD, CWORD }, /* 13, 0-9A-Za-z */
  2350. { CCTL, CCTL, CCTL } /* 14, CTLESC ... */
  2351. #endif
  2352. };
  2353. #endif /* ASH_MATH_SUPPORT */
  2354. #ifdef USE_SIT_FUNCTION
  2355. static int
  2356. SIT(int c, int syntax)
  2357. {
  2358. static const char spec_symbls[] ALIGN1 = "\t\n !\"$&'()*-/:;<=>?[\\]`|}~";
  2359. #if ENABLE_ASH_ALIAS
  2360. static const char syntax_index_table[] ALIGN1 = {
  2361. 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
  2362. 7, 8, 3, 3, 3, 3, 1, 1, /* "()*-/:;<" */
  2363. 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
  2364. 11, 3 /* "}~" */
  2365. };
  2366. #else
  2367. static const char syntax_index_table[] ALIGN1 = {
  2368. 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
  2369. 6, 7, 2, 2, 2, 2, 0, 0, /* "()*-/:;<" */
  2370. 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
  2371. 10, 2 /* "}~" */
  2372. };
  2373. #endif
  2374. const char *s;
  2375. int indx;
  2376. if (c == PEOF) /* 2^8+2 */
  2377. return CENDFILE;
  2378. #if ENABLE_ASH_ALIAS
  2379. if (c == PEOA) /* 2^8+1 */
  2380. indx = 0;
  2381. else
  2382. #endif
  2383. #define U_C(c) ((unsigned char)(c))
  2384. if ((unsigned char)c >= (unsigned char)(CTLESC)
  2385. && (unsigned char)c <= (unsigned char)(CTLQUOTEMARK)
  2386. ) {
  2387. return CCTL;
  2388. } else {
  2389. s = strchrnul(spec_symbls, c);
  2390. if (*s == '\0')
  2391. return CWORD;
  2392. indx = syntax_index_table[s - spec_symbls];
  2393. }
  2394. return S_I_T[indx][syntax];
  2395. }
  2396. #else /* !USE_SIT_FUNCTION */
  2397. #if ENABLE_ASH_ALIAS
  2398. #define CSPCL_CIGN_CIGN_CIGN 0
  2399. #define CSPCL_CWORD_CWORD_CWORD 1
  2400. #define CNL_CNL_CNL_CNL 2
  2401. #define CWORD_CCTL_CCTL_CWORD 3
  2402. #define CDQUOTE_CENDQUOTE_CWORD_CWORD 4
  2403. #define CVAR_CVAR_CWORD_CVAR 5
  2404. #define CSQUOTE_CWORD_CENDQUOTE_CWORD 6
  2405. #define CSPCL_CWORD_CWORD_CLP 7
  2406. #define CSPCL_CWORD_CWORD_CRP 8
  2407. #define CBACK_CBACK_CCTL_CBACK 9
  2408. #define CBQUOTE_CBQUOTE_CWORD_CBQUOTE 10
  2409. #define CENDVAR_CENDVAR_CWORD_CENDVAR 11
  2410. #define CENDFILE_CENDFILE_CENDFILE_CENDFILE 12
  2411. #define CWORD_CWORD_CWORD_CWORD 13
  2412. #define CCTL_CCTL_CCTL_CCTL 14
  2413. #else
  2414. #define CSPCL_CWORD_CWORD_CWORD 0
  2415. #define CNL_CNL_CNL_CNL 1
  2416. #define CWORD_CCTL_CCTL_CWORD 2
  2417. #define CDQUOTE_CENDQUOTE_CWORD_CWORD 3
  2418. #define CVAR_CVAR_CWORD_CVAR 4
  2419. #define CSQUOTE_CWORD_CENDQUOTE_CWORD 5
  2420. #define CSPCL_CWORD_CWORD_CLP 6
  2421. #define CSPCL_CWORD_CWORD_CRP 7
  2422. #define CBACK_CBACK_CCTL_CBACK 8
  2423. #define CBQUOTE_CBQUOTE_CWORD_CBQUOTE 9
  2424. #define CENDVAR_CENDVAR_CWORD_CENDVAR 10
  2425. #define CENDFILE_CENDFILE_CENDFILE_CENDFILE 11
  2426. #define CWORD_CWORD_CWORD_CWORD 12
  2427. #define CCTL_CCTL_CCTL_CCTL 13
  2428. #endif
  2429. static const char syntax_index_table[258] = {
  2430. /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
  2431. /* 0 PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
  2432. #if ENABLE_ASH_ALIAS
  2433. /* 1 PEOA */ CSPCL_CIGN_CIGN_CIGN,
  2434. #endif
  2435. /* 2 -128 0x80 */ CWORD_CWORD_CWORD_CWORD,
  2436. /* 3 -127 CTLESC */ CCTL_CCTL_CCTL_CCTL,
  2437. /* 4 -126 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
  2438. /* 5 -125 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
  2439. /* 6 -124 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
  2440. /* 7 -123 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
  2441. /* 8 -122 CTLARI */ CCTL_CCTL_CCTL_CCTL,
  2442. /* 9 -121 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
  2443. /* 10 -120 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
  2444. /* 11 -119 */ CWORD_CWORD_CWORD_CWORD,
  2445. /* 12 -118 */ CWORD_CWORD_CWORD_CWORD,
  2446. /* 13 -117 */ CWORD_CWORD_CWORD_CWORD,
  2447. /* 14 -116 */ CWORD_CWORD_CWORD_CWORD,
  2448. /* 15 -115 */ CWORD_CWORD_CWORD_CWORD,
  2449. /* 16 -114 */ CWORD_CWORD_CWORD_CWORD,
  2450. /* 17 -113 */ CWORD_CWORD_CWORD_CWORD,
  2451. /* 18 -112 */ CWORD_CWORD_CWORD_CWORD,
  2452. /* 19 -111 */ CWORD_CWORD_CWORD_CWORD,
  2453. /* 20 -110 */ CWORD_CWORD_CWORD_CWORD,
  2454. /* 21 -109 */ CWORD_CWORD_CWORD_CWORD,
  2455. /* 22 -108 */ CWORD_CWORD_CWORD_CWORD,
  2456. /* 23 -107 */ CWORD_CWORD_CWORD_CWORD,
  2457. /* 24 -106 */ CWORD_CWORD_CWORD_CWORD,
  2458. /* 25 -105 */ CWORD_CWORD_CWORD_CWORD,
  2459. /* 26 -104 */ CWORD_CWORD_CWORD_CWORD,
  2460. /* 27 -103 */ CWORD_CWORD_CWORD_CWORD,
  2461. /* 28 -102 */ CWORD_CWORD_CWORD_CWORD,
  2462. /* 29 -101 */ CWORD_CWORD_CWORD_CWORD,
  2463. /* 30 -100 */ CWORD_CWORD_CWORD_CWORD,
  2464. /* 31 -99 */ CWORD_CWORD_CWORD_CWORD,
  2465. /* 32 -98 */ CWORD_CWORD_CWORD_CWORD,
  2466. /* 33 -97 */ CWORD_CWORD_CWORD_CWORD,
  2467. /* 34 -96 */ CWORD_CWORD_CWORD_CWORD,
  2468. /* 35 -95 */ CWORD_CWORD_CWORD_CWORD,
  2469. /* 36 -94 */ CWORD_CWORD_CWORD_CWORD,
  2470. /* 37 -93 */ CWORD_CWORD_CWORD_CWORD,
  2471. /* 38 -92 */ CWORD_CWORD_CWORD_CWORD,
  2472. /* 39 -91 */ CWORD_CWORD_CWORD_CWORD,
  2473. /* 40 -90 */ CWORD_CWORD_CWORD_CWORD,
  2474. /* 41 -89 */ CWORD_CWORD_CWORD_CWORD,
  2475. /* 42 -88 */ CWORD_CWORD_CWORD_CWORD,
  2476. /* 43 -87 */ CWORD_CWORD_CWORD_CWORD,
  2477. /* 44 -86 */ CWORD_CWORD_CWORD_CWORD,
  2478. /* 45 -85 */ CWORD_CWORD_CWORD_CWORD,
  2479. /* 46 -84 */ CWORD_CWORD_CWORD_CWORD,
  2480. /* 47 -83 */ CWORD_CWORD_CWORD_CWORD,
  2481. /* 48 -82 */ CWORD_CWORD_CWORD_CWORD,
  2482. /* 49 -81 */ CWORD_CWORD_CWORD_CWORD,
  2483. /* 50 -80 */ CWORD_CWORD_CWORD_CWORD,
  2484. /* 51 -79 */ CWORD_CWORD_CWORD_CWORD,
  2485. /* 52 -78 */ CWORD_CWORD_CWORD_CWORD,
  2486. /* 53 -77 */ CWORD_CWORD_CWORD_CWORD,
  2487. /* 54 -76 */ CWORD_CWORD_CWORD_CWORD,
  2488. /* 55 -75 */ CWORD_CWORD_CWORD_CWORD,
  2489. /* 56 -74 */ CWORD_CWORD_CWORD_CWORD,
  2490. /* 57 -73 */ CWORD_CWORD_CWORD_CWORD,
  2491. /* 58 -72 */ CWORD_CWORD_CWORD_CWORD,
  2492. /* 59 -71 */ CWORD_CWORD_CWORD_CWORD,
  2493. /* 60 -70 */ CWORD_CWORD_CWORD_CWORD,
  2494. /* 61 -69 */ CWORD_CWORD_CWORD_CWORD,
  2495. /* 62 -68 */ CWORD_CWORD_CWORD_CWORD,
  2496. /* 63 -67 */ CWORD_CWORD_CWORD_CWORD,
  2497. /* 64 -66 */ CWORD_CWORD_CWORD_CWORD,
  2498. /* 65 -65 */ CWORD_CWORD_CWORD_CWORD,
  2499. /* 66 -64 */ CWORD_CWORD_CWORD_CWORD,
  2500. /* 67 -63 */ CWORD_CWORD_CWORD_CWORD,
  2501. /* 68 -62 */ CWORD_CWORD_CWORD_CWORD,
  2502. /* 69 -61 */ CWORD_CWORD_CWORD_CWORD,
  2503. /* 70 -60 */ CWORD_CWORD_CWORD_CWORD,
  2504. /* 71 -59 */ CWORD_CWORD_CWORD_CWORD,
  2505. /* 72 -58 */ CWORD_CWORD_CWORD_CWORD,
  2506. /* 73 -57 */ CWORD_CWORD_CWORD_CWORD,
  2507. /* 74 -56 */ CWORD_CWORD_CWORD_CWORD,
  2508. /* 75 -55 */ CWORD_CWORD_CWORD_CWORD,
  2509. /* 76 -54 */ CWORD_CWORD_CWORD_CWORD,
  2510. /* 77 -53 */ CWORD_CWORD_CWORD_CWORD,
  2511. /* 78 -52 */ CWORD_CWORD_CWORD_CWORD,
  2512. /* 79 -51 */ CWORD_CWORD_CWORD_CWORD,
  2513. /* 80 -50 */ CWORD_CWORD_CWORD_CWORD,
  2514. /* 81 -49 */ CWORD_CWORD_CWORD_CWORD,
  2515. /* 82 -48 */ CWORD_CWORD_CWORD_CWORD,
  2516. /* 83 -47 */ CWORD_CWORD_CWORD_CWORD,
  2517. /* 84 -46 */ CWORD_CWORD_CWORD_CWORD,
  2518. /* 85 -45 */ CWORD_CWORD_CWORD_CWORD,
  2519. /* 86 -44 */ CWORD_CWORD_CWORD_CWORD,
  2520. /* 87 -43 */ CWORD_CWORD_CWORD_CWORD,
  2521. /* 88 -42 */ CWORD_CWORD_CWORD_CWORD,
  2522. /* 89 -41 */ CWORD_CWORD_CWORD_CWORD,
  2523. /* 90 -40 */ CWORD_CWORD_CWORD_CWORD,
  2524. /* 91 -39 */ CWORD_CWORD_CWORD_CWORD,
  2525. /* 92 -38 */ CWORD_CWORD_CWORD_CWORD,
  2526. /* 93 -37 */ CWORD_CWORD_CWORD_CWORD,
  2527. /* 94 -36 */ CWORD_CWORD_CWORD_CWORD,
  2528. /* 95 -35 */ CWORD_CWORD_CWORD_CWORD,
  2529. /* 96 -34 */ CWORD_CWORD_CWORD_CWORD,
  2530. /* 97 -33 */ CWORD_CWORD_CWORD_CWORD,
  2531. /* 98 -32 */ CWORD_CWORD_CWORD_CWORD,
  2532. /* 99 -31 */ CWORD_CWORD_CWORD_CWORD,
  2533. /* 100 -30 */ CWORD_CWORD_CWORD_CWORD,
  2534. /* 101 -29 */ CWORD_CWORD_CWORD_CWORD,
  2535. /* 102 -28 */ CWORD_CWORD_CWORD_CWORD,
  2536. /* 103 -27 */ CWORD_CWORD_CWORD_CWORD,
  2537. /* 104 -26 */ CWORD_CWORD_CWORD_CWORD,
  2538. /* 105 -25 */ CWORD_CWORD_CWORD_CWORD,
  2539. /* 106 -24 */ CWORD_CWORD_CWORD_CWORD,
  2540. /* 107 -23 */ CWORD_CWORD_CWORD_CWORD,
  2541. /* 108 -22 */ CWORD_CWORD_CWORD_CWORD,
  2542. /* 109 -21 */ CWORD_CWORD_CWORD_CWORD,
  2543. /* 110 -20 */ CWORD_CWORD_CWORD_CWORD,
  2544. /* 111 -19 */ CWORD_CWORD_CWORD_CWORD,
  2545. /* 112 -18 */ CWORD_CWORD_CWORD_CWORD,
  2546. /* 113 -17 */ CWORD_CWORD_CWORD_CWORD,
  2547. /* 114 -16 */ CWORD_CWORD_CWORD_CWORD,
  2548. /* 115 -15 */ CWORD_CWORD_CWORD_CWORD,
  2549. /* 116 -14 */ CWORD_CWORD_CWORD_CWORD,
  2550. /* 117 -13 */ CWORD_CWORD_CWORD_CWORD,
  2551. /* 118 -12 */ CWORD_CWORD_CWORD_CWORD,
  2552. /* 119 -11 */ CWORD_CWORD_CWORD_CWORD,
  2553. /* 120 -10 */ CWORD_CWORD_CWORD_CWORD,
  2554. /* 121 -9 */ CWORD_CWORD_CWORD_CWORD,
  2555. /* 122 -8 */ CWORD_CWORD_CWORD_CWORD,
  2556. /* 123 -7 */ CWORD_CWORD_CWORD_CWORD,
  2557. /* 124 -6 */ CWORD_CWORD_CWORD_CWORD,
  2558. /* 125 -5 */ CWORD_CWORD_CWORD_CWORD,
  2559. /* 126 -4 */ CWORD_CWORD_CWORD_CWORD,
  2560. /* 127 -3 */ CWORD_CWORD_CWORD_CWORD,
  2561. /* 128 -2 */ CWORD_CWORD_CWORD_CWORD,
  2562. /* 129 -1 */ CWORD_CWORD_CWORD_CWORD,
  2563. /* 130 0 */ CWORD_CWORD_CWORD_CWORD,
  2564. /* 131 1 */ CWORD_CWORD_CWORD_CWORD,
  2565. /* 132 2 */ CWORD_CWORD_CWORD_CWORD,
  2566. /* 133 3 */ CWORD_CWORD_CWORD_CWORD,
  2567. /* 134 4 */ CWORD_CWORD_CWORD_CWORD,
  2568. /* 135 5 */ CWORD_CWORD_CWORD_CWORD,
  2569. /* 136 6 */ CWORD_CWORD_CWORD_CWORD,
  2570. /* 137 7 */ CWORD_CWORD_CWORD_CWORD,
  2571. /* 138 8 */ CWORD_CWORD_CWORD_CWORD,
  2572. /* 139 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
  2573. /* 140 10 "\n" */ CNL_CNL_CNL_CNL,
  2574. /* 141 11 */ CWORD_CWORD_CWORD_CWORD,
  2575. /* 142 12 */ CWORD_CWORD_CWORD_CWORD,
  2576. /* 143 13 */ CWORD_CWORD_CWORD_CWORD,
  2577. /* 144 14 */ CWORD_CWORD_CWORD_CWORD,
  2578. /* 145 15 */ CWORD_CWORD_CWORD_CWORD,
  2579. /* 146 16 */ CWORD_CWORD_CWORD_CWORD,
  2580. /* 147 17 */ CWORD_CWORD_CWORD_CWORD,
  2581. /* 148 18 */ CWORD_CWORD_CWORD_CWORD,
  2582. /* 149 19 */ CWORD_CWORD_CWORD_CWORD,
  2583. /* 150 20 */ CWORD_CWORD_CWORD_CWORD,
  2584. /* 151 21 */ CWORD_CWORD_CWORD_CWORD,
  2585. /* 152 22 */ CWORD_CWORD_CWORD_CWORD,
  2586. /* 153 23 */ CWORD_CWORD_CWORD_CWORD,
  2587. /* 154 24 */ CWORD_CWORD_CWORD_CWORD,
  2588. /* 155 25 */ CWORD_CWORD_CWORD_CWORD,
  2589. /* 156 26 */ CWORD_CWORD_CWORD_CWORD,
  2590. /* 157 27 */ CWORD_CWORD_CWORD_CWORD,
  2591. /* 158 28 */ CWORD_CWORD_CWORD_CWORD,
  2592. /* 159 29 */ CWORD_CWORD_CWORD_CWORD,
  2593. /* 160 30 */ CWORD_CWORD_CWORD_CWORD,
  2594. /* 161 31 */ CWORD_CWORD_CWORD_CWORD,
  2595. /* 162 32 " " */ CSPCL_CWORD_CWORD_CWORD,
  2596. /* 163 33 "!" */ CWORD_CCTL_CCTL_CWORD,
  2597. /* 164 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
  2598. /* 165 35 "#" */ CWORD_CWORD_CWORD_CWORD,
  2599. /* 166 36 "$" */ CVAR_CVAR_CWORD_CVAR,
  2600. /* 167 37 "%" */ CWORD_CWORD_CWORD_CWORD,
  2601. /* 168 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
  2602. /* 169 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
  2603. /* 170 40 "(" */ CSPCL_CWORD_CWORD_CLP,
  2604. /* 171 41 ")" */ CSPCL_CWORD_CWORD_CRP,
  2605. /* 172 42 "*" */ CWORD_CCTL_CCTL_CWORD,
  2606. /* 173 43 "+" */ CWORD_CWORD_CWORD_CWORD,
  2607. /* 174 44 "," */ CWORD_CWORD_CWORD_CWORD,
  2608. /* 175 45 "-" */ CWORD_CCTL_CCTL_CWORD,
  2609. /* 176 46 "." */ CWORD_CWORD_CWORD_CWORD,
  2610. /* 177 47 "/" */ CWORD_CCTL_CCTL_CWORD,
  2611. /* 178 48 "0" */ CWORD_CWORD_CWORD_CWORD,
  2612. /* 179 49 "1" */ CWORD_CWORD_CWORD_CWORD,
  2613. /* 180 50 "2" */ CWORD_CWORD_CWORD_CWORD,
  2614. /* 181 51 "3" */ CWORD_CWORD_CWORD_CWORD,
  2615. /* 182 52 "4" */ CWORD_CWORD_CWORD_CWORD,
  2616. /* 183 53 "5" */ CWORD_CWORD_CWORD_CWORD,
  2617. /* 184 54 "6" */ CWORD_CWORD_CWORD_CWORD,
  2618. /* 185 55 "7" */ CWORD_CWORD_CWORD_CWORD,
  2619. /* 186 56 "8" */ CWORD_CWORD_CWORD_CWORD,
  2620. /* 187 57 "9" */ CWORD_CWORD_CWORD_CWORD,
  2621. /* 188 58 ":" */ CWORD_CCTL_CCTL_CWORD,
  2622. /* 189 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
  2623. /* 190 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
  2624. /* 191 61 "=" */ CWORD_CCTL_CCTL_CWORD,
  2625. /* 192 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
  2626. /* 193 63 "?" */ CWORD_CCTL_CCTL_CWORD,
  2627. /* 194 64 "@" */ CWORD_CWORD_CWORD_CWORD,
  2628. /* 195 65 "A" */ CWORD_CWORD_CWORD_CWORD,
  2629. /* 196 66 "B" */ CWORD_CWORD_CWORD_CWORD,
  2630. /* 197 67 "C" */ CWORD_CWORD_CWORD_CWORD,
  2631. /* 198 68 "D" */ CWORD_CWORD_CWORD_CWORD,
  2632. /* 199 69 "E" */ CWORD_CWORD_CWORD_CWORD,
  2633. /* 200 70 "F" */ CWORD_CWORD_CWORD_CWORD,
  2634. /* 201 71 "G" */ CWORD_CWORD_CWORD_CWORD,
  2635. /* 202 72 "H" */ CWORD_CWORD_CWORD_CWORD,
  2636. /* 203 73 "I" */ CWORD_CWORD_CWORD_CWORD,
  2637. /* 204 74 "J" */ CWORD_CWORD_CWORD_CWORD,
  2638. /* 205 75 "K" */ CWORD_CWORD_CWORD_CWORD,
  2639. /* 206 76 "L" */ CWORD_CWORD_CWORD_CWORD,
  2640. /* 207 77 "M" */ CWORD_CWORD_CWORD_CWORD,
  2641. /* 208 78 "N" */ CWORD_CWORD_CWORD_CWORD,
  2642. /* 209 79 "O" */ CWORD_CWORD_CWORD_CWORD,
  2643. /* 210 80 "P" */ CWORD_CWORD_CWORD_CWORD,
  2644. /* 211 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
  2645. /* 212 82 "R" */ CWORD_CWORD_CWORD_CWORD,
  2646. /* 213 83 "S" */ CWORD_CWORD_CWORD_CWORD,
  2647. /* 214 84 "T" */ CWORD_CWORD_CWORD_CWORD,
  2648. /* 215 85 "U" */ CWORD_CWORD_CWORD_CWORD,
  2649. /* 216 86 "V" */ CWORD_CWORD_CWORD_CWORD,
  2650. /* 217 87 "W" */ CWORD_CWORD_CWORD_CWORD,
  2651. /* 218 88 "X" */ CWORD_CWORD_CWORD_CWORD,
  2652. /* 219 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
  2653. /* 220 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
  2654. /* 221 91 "[" */ CWORD_CCTL_CCTL_CWORD,
  2655. /* 222 92 "\" */ CBACK_CBACK_CCTL_CBACK,
  2656. /* 223 93 "]" */ CWORD_CCTL_CCTL_CWORD,
  2657. /* 224 94 "^" */ CWORD_CWORD_CWORD_CWORD,
  2658. /* 225 95 "_" */ CWORD_CWORD_CWORD_CWORD,
  2659. /* 226 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
  2660. /* 227 97 "a" */ CWORD_CWORD_CWORD_CWORD,
  2661. /* 228 98 "b" */ CWORD_CWORD_CWORD_CWORD,
  2662. /* 229 99 "c" */ CWORD_CWORD_CWORD_CWORD,
  2663. /* 230 100 "d" */ CWORD_CWORD_CWORD_CWORD,
  2664. /* 231 101 "e" */ CWORD_CWORD_CWORD_CWORD,
  2665. /* 232 102 "f" */ CWORD_CWORD_CWORD_CWORD,
  2666. /* 233 103 "g" */ CWORD_CWORD_CWORD_CWORD,
  2667. /* 234 104 "h" */ CWORD_CWORD_CWORD_CWORD,
  2668. /* 235 105 "i" */ CWORD_CWORD_CWORD_CWORD,
  2669. /* 236 106 "j" */ CWORD_CWORD_CWORD_CWORD,
  2670. /* 237 107 "k" */ CWORD_CWORD_CWORD_CWORD,
  2671. /* 238 108 "l" */ CWORD_CWORD_CWORD_CWORD,
  2672. /* 239 109 "m" */ CWORD_CWORD_CWORD_CWORD,
  2673. /* 240 110 "n" */ CWORD_CWORD_CWORD_CWORD,
  2674. /* 241 111 "o" */ CWORD_CWORD_CWORD_CWORD,
  2675. /* 242 112 "p" */ CWORD_CWORD_CWORD_CWORD,
  2676. /* 243 113 "q" */ CWORD_CWORD_CWORD_CWORD,
  2677. /* 244 114 "r" */ CWORD_CWORD_CWORD_CWORD,
  2678. /* 245 115 "s" */ CWORD_CWORD_CWORD_CWORD,
  2679. /* 246 116 "t" */ CWORD_CWORD_CWORD_CWORD,
  2680. /* 247 117 "u" */ CWORD_CWORD_CWORD_CWORD,
  2681. /* 248 118 "v" */ CWORD_CWORD_CWORD_CWORD,
  2682. /* 249 119 "w" */ CWORD_CWORD_CWORD_CWORD,
  2683. /* 250 120 "x" */ CWORD_CWORD_CWORD_CWORD,
  2684. /* 251 121 "y" */ CWORD_CWORD_CWORD_CWORD,
  2685. /* 252 122 "z" */ CWORD_CWORD_CWORD_CWORD,
  2686. /* 253 123 "{" */ CWORD_CWORD_CWORD_CWORD,
  2687. /* 254 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
  2688. /* 255 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
  2689. /* 256 126 "~" */ CWORD_CCTL_CCTL_CWORD,
  2690. /* 257 127 */ CWORD_CWORD_CWORD_CWORD,
  2691. };
  2692. #define SIT(c, syntax) (S_I_T[(int)syntax_index_table[((int)c)+SYNBASE]][syntax])
  2693. #endif /* USE_SIT_FUNCTION */
  2694. /* ============ Alias handling */
  2695. #if ENABLE_ASH_ALIAS
  2696. #define ALIASINUSE 1
  2697. #define ALIASDEAD 2
  2698. struct alias {
  2699. struct alias *next;
  2700. char *name;
  2701. char *val;
  2702. int flag;
  2703. };
  2704. static struct alias **atab; // [ATABSIZE];
  2705. #define INIT_G_alias() do { \
  2706. atab = xzalloc(ATABSIZE * sizeof(atab[0])); \
  2707. } while (0)
  2708. static struct alias **
  2709. __lookupalias(const char *name) {
  2710. unsigned int hashval;
  2711. struct alias **app;
  2712. const char *p;
  2713. unsigned int ch;
  2714. p = name;
  2715. ch = (unsigned char)*p;
  2716. hashval = ch << 4;
  2717. while (ch) {
  2718. hashval += ch;
  2719. ch = (unsigned char)*++p;
  2720. }
  2721. app = &atab[hashval % ATABSIZE];
  2722. for (; *app; app = &(*app)->next) {
  2723. if (strcmp(name, (*app)->name) == 0) {
  2724. break;
  2725. }
  2726. }
  2727. return app;
  2728. }
  2729. static struct alias *
  2730. lookupalias(const char *name, int check)
  2731. {
  2732. struct alias *ap = *__lookupalias(name);
  2733. if (check && ap && (ap->flag & ALIASINUSE))
  2734. return NULL;
  2735. return ap;
  2736. }
  2737. static struct alias *
  2738. freealias(struct alias *ap)
  2739. {
  2740. struct alias *next;
  2741. if (ap->flag & ALIASINUSE) {
  2742. ap->flag |= ALIASDEAD;
  2743. return ap;
  2744. }
  2745. next = ap->next;
  2746. free(ap->name);
  2747. free(ap->val);
  2748. free(ap);
  2749. return next;
  2750. }
  2751. static void
  2752. setalias(const char *name, const char *val)
  2753. {
  2754. struct alias *ap, **app;
  2755. app = __lookupalias(name);
  2756. ap = *app;
  2757. INT_OFF;
  2758. if (ap) {
  2759. if (!(ap->flag & ALIASINUSE)) {
  2760. free(ap->val);
  2761. }
  2762. ap->val = ckstrdup(val);
  2763. ap->flag &= ~ALIASDEAD;
  2764. } else {
  2765. /* not found */
  2766. ap = ckzalloc(sizeof(struct alias));
  2767. ap->name = ckstrdup(name);
  2768. ap->val = ckstrdup(val);
  2769. /*ap->flag = 0; - ckzalloc did it */
  2770. /*ap->next = NULL;*/
  2771. *app = ap;
  2772. }
  2773. INT_ON;
  2774. }
  2775. static int
  2776. unalias(const char *name)
  2777. {
  2778. struct alias **app;
  2779. app = __lookupalias(name);
  2780. if (*app) {
  2781. INT_OFF;
  2782. *app = freealias(*app);
  2783. INT_ON;
  2784. return 0;
  2785. }
  2786. return 1;
  2787. }
  2788. static void
  2789. rmaliases(void)
  2790. {
  2791. struct alias *ap, **app;
  2792. int i;
  2793. INT_OFF;
  2794. for (i = 0; i < ATABSIZE; i++) {
  2795. app = &atab[i];
  2796. for (ap = *app; ap; ap = *app) {
  2797. *app = freealias(*app);
  2798. if (ap == *app) {
  2799. app = &ap->next;
  2800. }
  2801. }
  2802. }
  2803. INT_ON;
  2804. }
  2805. static void
  2806. printalias(const struct alias *ap)
  2807. {
  2808. out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
  2809. }
  2810. /*
  2811. * TODO - sort output
  2812. */
  2813. static int
  2814. aliascmd(int argc UNUSED_PARAM, char **argv)
  2815. {
  2816. char *n, *v;
  2817. int ret = 0;
  2818. struct alias *ap;
  2819. if (!argv[1]) {
  2820. int i;
  2821. for (i = 0; i < ATABSIZE; i++) {
  2822. for (ap = atab[i]; ap; ap = ap->next) {
  2823. printalias(ap);
  2824. }
  2825. }
  2826. return 0;
  2827. }
  2828. while ((n = *++argv) != NULL) {
  2829. v = strchr(n+1, '=');
  2830. if (v == NULL) { /* n+1: funny ksh stuff */
  2831. ap = *__lookupalias(n);
  2832. if (ap == NULL) {
  2833. fprintf(stderr, "%s: %s not found\n", "alias", n);
  2834. ret = 1;
  2835. } else
  2836. printalias(ap);
  2837. } else {
  2838. *v++ = '\0';
  2839. setalias(n, v);
  2840. }
  2841. }
  2842. return ret;
  2843. }
  2844. static int
  2845. unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  2846. {
  2847. int i;
  2848. while ((i = nextopt("a")) != '\0') {
  2849. if (i == 'a') {
  2850. rmaliases();
  2851. return 0;
  2852. }
  2853. }
  2854. for (i = 0; *argptr; argptr++) {
  2855. if (unalias(*argptr)) {
  2856. fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
  2857. i = 1;
  2858. }
  2859. }
  2860. return i;
  2861. }
  2862. #endif /* ASH_ALIAS */
  2863. /* ============ jobs.c */
  2864. /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
  2865. #define FORK_FG 0
  2866. #define FORK_BG 1
  2867. #define FORK_NOJOB 2
  2868. /* mode flags for showjob(s) */
  2869. #define SHOW_PGID 0x01 /* only show pgid - for jobs -p */
  2870. #define SHOW_PID 0x04 /* include process pid */
  2871. #define SHOW_CHANGED 0x08 /* only jobs whose state has changed */
  2872. /*
  2873. * A job structure contains information about a job. A job is either a
  2874. * single process or a set of processes contained in a pipeline. In the
  2875. * latter case, pidlist will be non-NULL, and will point to a -1 terminated
  2876. * array of pids.
  2877. */
  2878. struct procstat {
  2879. pid_t pid; /* process id */
  2880. int status; /* last process status from wait() */
  2881. char *cmd; /* text of command being run */
  2882. };
  2883. struct job {
  2884. struct procstat ps0; /* status of process */
  2885. struct procstat *ps; /* status or processes when more than one */
  2886. #if JOBS
  2887. int stopstatus; /* status of a stopped job */
  2888. #endif
  2889. uint32_t
  2890. nprocs: 16, /* number of processes */
  2891. state: 8,
  2892. #define JOBRUNNING 0 /* at least one proc running */
  2893. #define JOBSTOPPED 1 /* all procs are stopped */
  2894. #define JOBDONE 2 /* all procs are completed */
  2895. #if JOBS
  2896. sigint: 1, /* job was killed by SIGINT */
  2897. jobctl: 1, /* job running under job control */
  2898. #endif
  2899. waited: 1, /* true if this entry has been waited for */
  2900. used: 1, /* true if this entry is in used */
  2901. changed: 1; /* true if status has changed */
  2902. struct job *prev_job; /* previous job */
  2903. };
  2904. static struct job *makejob(/*union node *,*/ int);
  2905. #if !JOBS
  2906. #define forkshell(job, node, mode) forkshell(job, mode)
  2907. #endif
  2908. static int forkshell(struct job *, union node *, int);
  2909. static int waitforjob(struct job *);
  2910. #if !JOBS
  2911. enum { doing_jobctl = 0 };
  2912. #define setjobctl(on) do {} while (0)
  2913. #else
  2914. static smallint doing_jobctl; //references:8
  2915. static void setjobctl(int);
  2916. #endif
  2917. /*
  2918. * Set the signal handler for the specified signal. The routine figures
  2919. * out what it should be set to.
  2920. */
  2921. static void
  2922. setsignal(int signo)
  2923. {
  2924. int action;
  2925. char *t, tsig;
  2926. struct sigaction act;
  2927. t = trap[signo];
  2928. action = S_IGN;
  2929. if (t == NULL)
  2930. action = S_DFL;
  2931. else if (*t != '\0')
  2932. action = S_CATCH;
  2933. if (rootshell && action == S_DFL) {
  2934. switch (signo) {
  2935. case SIGINT:
  2936. if (iflag || minusc || sflag == 0)
  2937. action = S_CATCH;
  2938. break;
  2939. case SIGQUIT:
  2940. #if DEBUG
  2941. if (debug)
  2942. break;
  2943. #endif
  2944. /* FALLTHROUGH */
  2945. case SIGTERM:
  2946. if (iflag)
  2947. action = S_IGN;
  2948. break;
  2949. #if JOBS
  2950. case SIGTSTP:
  2951. case SIGTTOU:
  2952. if (mflag)
  2953. action = S_IGN;
  2954. break;
  2955. #endif
  2956. }
  2957. }
  2958. t = &sigmode[signo - 1];
  2959. tsig = *t;
  2960. if (tsig == 0) {
  2961. /*
  2962. * current setting unknown
  2963. */
  2964. if (sigaction(signo, NULL, &act) == -1) {
  2965. /*
  2966. * Pretend it worked; maybe we should give a warning
  2967. * here, but other shells don't. We don't alter
  2968. * sigmode, so that we retry every time.
  2969. */
  2970. return;
  2971. }
  2972. tsig = S_RESET; /* force to be set */
  2973. if (act.sa_handler == SIG_IGN) {
  2974. tsig = S_HARD_IGN;
  2975. if (mflag
  2976. && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)
  2977. ) {
  2978. tsig = S_IGN; /* don't hard ignore these */
  2979. }
  2980. }
  2981. }
  2982. if (tsig == S_HARD_IGN || tsig == action)
  2983. return;
  2984. act.sa_handler = SIG_DFL;
  2985. switch (action) {
  2986. case S_CATCH:
  2987. act.sa_handler = onsig;
  2988. break;
  2989. case S_IGN:
  2990. act.sa_handler = SIG_IGN;
  2991. break;
  2992. }
  2993. *t = action;
  2994. act.sa_flags = 0;
  2995. sigfillset(&act.sa_mask);
  2996. sigaction_set(signo, &act);
  2997. }
  2998. /* mode flags for set_curjob */
  2999. #define CUR_DELETE 2
  3000. #define CUR_RUNNING 1
  3001. #define CUR_STOPPED 0
  3002. /* mode flags for dowait */
  3003. #define DOWAIT_NONBLOCK WNOHANG
  3004. #define DOWAIT_BLOCK 0
  3005. #if JOBS
  3006. /* pgrp of shell on invocation */
  3007. static int initialpgrp; //references:2
  3008. static int ttyfd = -1; //5
  3009. #endif
  3010. /* array of jobs */
  3011. static struct job *jobtab; //5
  3012. /* size of array */
  3013. static unsigned njobs; //4
  3014. /* current job */
  3015. static struct job *curjob; //lots
  3016. /* number of presumed living untracked jobs */
  3017. static int jobless; //4
  3018. static void
  3019. set_curjob(struct job *jp, unsigned mode)
  3020. {
  3021. struct job *jp1;
  3022. struct job **jpp, **curp;
  3023. /* first remove from list */
  3024. jpp = curp = &curjob;
  3025. do {
  3026. jp1 = *jpp;
  3027. if (jp1 == jp)
  3028. break;
  3029. jpp = &jp1->prev_job;
  3030. } while (1);
  3031. *jpp = jp1->prev_job;
  3032. /* Then re-insert in correct position */
  3033. jpp = curp;
  3034. switch (mode) {
  3035. default:
  3036. #if DEBUG
  3037. abort();
  3038. #endif
  3039. case CUR_DELETE:
  3040. /* job being deleted */
  3041. break;
  3042. case CUR_RUNNING:
  3043. /* newly created job or backgrounded job,
  3044. put after all stopped jobs. */
  3045. do {
  3046. jp1 = *jpp;
  3047. #if JOBS
  3048. if (!jp1 || jp1->state != JOBSTOPPED)
  3049. #endif
  3050. break;
  3051. jpp = &jp1->prev_job;
  3052. } while (1);
  3053. /* FALLTHROUGH */
  3054. #if JOBS
  3055. case CUR_STOPPED:
  3056. #endif
  3057. /* newly stopped job - becomes curjob */
  3058. jp->prev_job = *jpp;
  3059. *jpp = jp;
  3060. break;
  3061. }
  3062. }
  3063. #if JOBS || DEBUG
  3064. static int
  3065. jobno(const struct job *jp)
  3066. {
  3067. return jp - jobtab + 1;
  3068. }
  3069. #endif
  3070. /*
  3071. * Convert a job name to a job structure.
  3072. */
  3073. #if !JOBS
  3074. #define getjob(name, getctl) getjob(name)
  3075. #endif
  3076. static struct job *
  3077. getjob(const char *name, int getctl)
  3078. {
  3079. struct job *jp;
  3080. struct job *found;
  3081. const char *err_msg = "No such job: %s";
  3082. unsigned num;
  3083. int c;
  3084. const char *p;
  3085. char *(*match)(const char *, const char *);
  3086. jp = curjob;
  3087. p = name;
  3088. if (!p)
  3089. goto currentjob;
  3090. if (*p != '%')
  3091. goto err;
  3092. c = *++p;
  3093. if (!c)
  3094. goto currentjob;
  3095. if (!p[1]) {
  3096. if (c == '+' || c == '%') {
  3097. currentjob:
  3098. err_msg = "No current job";
  3099. goto check;
  3100. }
  3101. if (c == '-') {
  3102. if (jp)
  3103. jp = jp->prev_job;
  3104. err_msg = "No previous job";
  3105. check:
  3106. if (!jp)
  3107. goto err;
  3108. goto gotit;
  3109. }
  3110. }
  3111. if (is_number(p)) {
  3112. // TODO: number() instead? It does error checking...
  3113. num = atoi(p);
  3114. if (num < njobs) {
  3115. jp = jobtab + num - 1;
  3116. if (jp->used)
  3117. goto gotit;
  3118. goto err;
  3119. }
  3120. }
  3121. match = prefix;
  3122. if (*p == '?') {
  3123. match = strstr;
  3124. p++;
  3125. }
  3126. found = 0;
  3127. while (1) {
  3128. if (!jp)
  3129. goto err;
  3130. if (match(jp->ps[0].cmd, p)) {
  3131. if (found)
  3132. goto err;
  3133. found = jp;
  3134. err_msg = "%s: ambiguous";
  3135. }
  3136. jp = jp->prev_job;
  3137. }
  3138. gotit:
  3139. #if JOBS
  3140. err_msg = "job %s not created under job control";
  3141. if (getctl && jp->jobctl == 0)
  3142. goto err;
  3143. #endif
  3144. return jp;
  3145. err:
  3146. ash_msg_and_raise_error(err_msg, name);
  3147. }
  3148. /*
  3149. * Mark a job structure as unused.
  3150. */
  3151. static void
  3152. freejob(struct job *jp)
  3153. {
  3154. struct procstat *ps;
  3155. int i;
  3156. INT_OFF;
  3157. for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
  3158. if (ps->cmd != nullstr)
  3159. free(ps->cmd);
  3160. }
  3161. if (jp->ps != &jp->ps0)
  3162. free(jp->ps);
  3163. jp->used = 0;
  3164. set_curjob(jp, CUR_DELETE);
  3165. INT_ON;
  3166. }
  3167. #if JOBS
  3168. static void
  3169. xtcsetpgrp(int fd, pid_t pgrp)
  3170. {
  3171. if (tcsetpgrp(fd, pgrp))
  3172. ash_msg_and_raise_error("can't set tty process group (%m)");
  3173. }
  3174. /*
  3175. * Turn job control on and off.
  3176. *
  3177. * Note: This code assumes that the third arg to ioctl is a character
  3178. * pointer, which is true on Berkeley systems but not System V. Since
  3179. * System V doesn't have job control yet, this isn't a problem now.
  3180. *
  3181. * Called with interrupts off.
  3182. */
  3183. static void
  3184. setjobctl(int on)
  3185. {
  3186. int fd;
  3187. int pgrp;
  3188. if (on == doing_jobctl || rootshell == 0)
  3189. return;
  3190. if (on) {
  3191. int ofd;
  3192. ofd = fd = open(_PATH_TTY, O_RDWR);
  3193. if (fd < 0) {
  3194. /* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
  3195. * That sometimes helps to acquire controlling tty.
  3196. * Obviously, a workaround for bugs when someone
  3197. * failed to provide a controlling tty to bash! :) */
  3198. fd = 2;
  3199. while (!isatty(fd))
  3200. if (--fd < 0)
  3201. goto out;
  3202. }
  3203. fd = fcntl(fd, F_DUPFD, 10);
  3204. if (ofd >= 0)
  3205. close(ofd);
  3206. if (fd < 0)
  3207. goto out;
  3208. /* fd is a tty at this point */
  3209. close_on_exec_on(fd);
  3210. do { /* while we are in the background */
  3211. pgrp = tcgetpgrp(fd);
  3212. if (pgrp < 0) {
  3213. out:
  3214. ash_msg("can't access tty; job control turned off");
  3215. mflag = on = 0;
  3216. goto close;
  3217. }
  3218. if (pgrp == getpgrp())
  3219. break;
  3220. killpg(0, SIGTTIN);
  3221. } while (1);
  3222. initialpgrp = pgrp;
  3223. setsignal(SIGTSTP);
  3224. setsignal(SIGTTOU);
  3225. setsignal(SIGTTIN);
  3226. pgrp = rootpid;
  3227. setpgid(0, pgrp);
  3228. xtcsetpgrp(fd, pgrp);
  3229. } else {
  3230. /* turning job control off */
  3231. fd = ttyfd;
  3232. pgrp = initialpgrp;
  3233. /* was xtcsetpgrp, but this can make exiting ash
  3234. * loop forever if pty is already deleted */
  3235. tcsetpgrp(fd, pgrp);
  3236. setpgid(0, pgrp);
  3237. setsignal(SIGTSTP);
  3238. setsignal(SIGTTOU);
  3239. setsignal(SIGTTIN);
  3240. close:
  3241. if (fd >= 0)
  3242. close(fd);
  3243. fd = -1;
  3244. }
  3245. ttyfd = fd;
  3246. doing_jobctl = on;
  3247. }
  3248. static int
  3249. killcmd(int argc, char **argv)
  3250. {
  3251. int i = 1;
  3252. if (argv[1] && strcmp(argv[1], "-l") != 0) {
  3253. do {
  3254. if (argv[i][0] == '%') {
  3255. struct job *jp = getjob(argv[i], 0);
  3256. unsigned pid = jp->ps[0].pid;
  3257. /* Enough space for ' -NNN<nul>' */
  3258. argv[i] = alloca(sizeof(int)*3 + 3);
  3259. /* kill_main has matching code to expect
  3260. * leading space. Needed to not confuse
  3261. * negative pids with "kill -SIGNAL_NO" syntax */
  3262. sprintf(argv[i], " -%u", pid);
  3263. }
  3264. } while (argv[++i]);
  3265. }
  3266. return kill_main(argc, argv);
  3267. }
  3268. static void
  3269. showpipe(struct job *jp, FILE *out)
  3270. {
  3271. struct procstat *sp;
  3272. struct procstat *spend;
  3273. spend = jp->ps + jp->nprocs;
  3274. for (sp = jp->ps + 1; sp < spend; sp++)
  3275. fprintf(out, " | %s", sp->cmd);
  3276. outcslow('\n', out);
  3277. flush_stdout_stderr();
  3278. }
  3279. static int
  3280. restartjob(struct job *jp, int mode)
  3281. {
  3282. struct procstat *ps;
  3283. int i;
  3284. int status;
  3285. pid_t pgid;
  3286. INT_OFF;
  3287. if (jp->state == JOBDONE)
  3288. goto out;
  3289. jp->state = JOBRUNNING;
  3290. pgid = jp->ps->pid;
  3291. if (mode == FORK_FG)
  3292. xtcsetpgrp(ttyfd, pgid);
  3293. killpg(pgid, SIGCONT);
  3294. ps = jp->ps;
  3295. i = jp->nprocs;
  3296. do {
  3297. if (WIFSTOPPED(ps->status)) {
  3298. ps->status = -1;
  3299. }
  3300. ps++;
  3301. } while (--i);
  3302. out:
  3303. status = (mode == FORK_FG) ? waitforjob(jp) : 0;
  3304. INT_ON;
  3305. return status;
  3306. }
  3307. static int
  3308. fg_bgcmd(int argc UNUSED_PARAM, char **argv)
  3309. {
  3310. struct job *jp;
  3311. FILE *out;
  3312. int mode;
  3313. int retval;
  3314. mode = (**argv == 'f') ? FORK_FG : FORK_BG;
  3315. nextopt(nullstr);
  3316. argv = argptr;
  3317. out = stdout;
  3318. do {
  3319. jp = getjob(*argv, 1);
  3320. if (mode == FORK_BG) {
  3321. set_curjob(jp, CUR_RUNNING);
  3322. fprintf(out, "[%d] ", jobno(jp));
  3323. }
  3324. outstr(jp->ps->cmd, out);
  3325. showpipe(jp, out);
  3326. retval = restartjob(jp, mode);
  3327. } while (*argv && *++argv);
  3328. return retval;
  3329. }
  3330. #endif
  3331. static int
  3332. sprint_status(char *s, int status, int sigonly)
  3333. {
  3334. int col;
  3335. int st;
  3336. col = 0;
  3337. if (!WIFEXITED(status)) {
  3338. #if JOBS
  3339. if (WIFSTOPPED(status))
  3340. st = WSTOPSIG(status);
  3341. else
  3342. #endif
  3343. st = WTERMSIG(status);
  3344. if (sigonly) {
  3345. if (st == SIGINT || st == SIGPIPE)
  3346. goto out;
  3347. #if JOBS
  3348. if (WIFSTOPPED(status))
  3349. goto out;
  3350. #endif
  3351. }
  3352. st &= 0x7f;
  3353. col = fmtstr(s, 32, strsignal(st));
  3354. if (WCOREDUMP(status)) {
  3355. col += fmtstr(s + col, 16, " (core dumped)");
  3356. }
  3357. } else if (!sigonly) {
  3358. st = WEXITSTATUS(status);
  3359. if (st)
  3360. col = fmtstr(s, 16, "Done(%d)", st);
  3361. else
  3362. col = fmtstr(s, 16, "Done");
  3363. }
  3364. out:
  3365. return col;
  3366. }
  3367. /*
  3368. * Do a wait system call. If job control is compiled in, we accept
  3369. * stopped processes. If block is zero, we return a value of zero
  3370. * rather than blocking.
  3371. *
  3372. * System V doesn't have a non-blocking wait system call. It does
  3373. * have a SIGCLD signal that is sent to a process when one of it's
  3374. * children dies. The obvious way to use SIGCLD would be to install
  3375. * a handler for SIGCLD which simply bumped a counter when a SIGCLD
  3376. * was received, and have waitproc bump another counter when it got
  3377. * the status of a process. Waitproc would then know that a wait
  3378. * system call would not block if the two counters were different.
  3379. * This approach doesn't work because if a process has children that
  3380. * have not been waited for, System V will send it a SIGCLD when it
  3381. * installs a signal handler for SIGCLD. What this means is that when
  3382. * a child exits, the shell will be sent SIGCLD signals continuously
  3383. * until is runs out of stack space, unless it does a wait call before
  3384. * restoring the signal handler. The code below takes advantage of
  3385. * this (mis)feature by installing a signal handler for SIGCLD and
  3386. * then checking to see whether it was called. If there are any
  3387. * children to be waited for, it will be.
  3388. *
  3389. * If neither SYSV nor BSD is defined, we don't implement nonblocking
  3390. * waits at all. In this case, the user will not be informed when
  3391. * a background process until the next time she runs a real program
  3392. * (as opposed to running a builtin command or just typing return),
  3393. * and the jobs command may give out of date information.
  3394. */
  3395. static int
  3396. waitproc(int wait_flags, int *status)
  3397. {
  3398. #if JOBS
  3399. if (doing_jobctl)
  3400. wait_flags |= WUNTRACED;
  3401. #endif
  3402. /* NB: _not_ safe_waitpid, we need to detect EINTR */
  3403. return waitpid(-1, status, wait_flags);
  3404. }
  3405. /*
  3406. * Wait for a process to terminate.
  3407. */
  3408. static int
  3409. dowait(int wait_flags, struct job *job)
  3410. {
  3411. int pid;
  3412. int status;
  3413. struct job *jp;
  3414. struct job *thisjob;
  3415. int state;
  3416. TRACE(("dowait(%d) called\n", wait_flags));
  3417. pid = waitproc(wait_flags, &status);
  3418. TRACE(("wait returns pid=%d, status=%d\n", pid, status));
  3419. if (pid <= 0) {
  3420. /* If we were doing blocking wait and (probably) got EINTR,
  3421. * check for pending sigs received while waiting.
  3422. * (NB: can be moved into callers if needed) */
  3423. if (wait_flags == DOWAIT_BLOCK && pendingsig)
  3424. raise_exception(EXSIG);
  3425. return pid;
  3426. }
  3427. INT_OFF;
  3428. thisjob = NULL;
  3429. for (jp = curjob; jp; jp = jp->prev_job) {
  3430. struct procstat *sp;
  3431. struct procstat *spend;
  3432. if (jp->state == JOBDONE)
  3433. continue;
  3434. state = JOBDONE;
  3435. spend = jp->ps + jp->nprocs;
  3436. sp = jp->ps;
  3437. do {
  3438. if (sp->pid == pid) {
  3439. TRACE(("Job %d: changing status of proc %d "
  3440. "from 0x%x to 0x%x\n",
  3441. jobno(jp), pid, sp->status, status));
  3442. sp->status = status;
  3443. thisjob = jp;
  3444. }
  3445. if (sp->status == -1)
  3446. state = JOBRUNNING;
  3447. #if JOBS
  3448. if (state == JOBRUNNING)
  3449. continue;
  3450. if (WIFSTOPPED(sp->status)) {
  3451. jp->stopstatus = sp->status;
  3452. state = JOBSTOPPED;
  3453. }
  3454. #endif
  3455. } while (++sp < spend);
  3456. if (thisjob)
  3457. goto gotjob;
  3458. }
  3459. #if JOBS
  3460. if (!WIFSTOPPED(status))
  3461. #endif
  3462. jobless--;
  3463. goto out;
  3464. gotjob:
  3465. if (state != JOBRUNNING) {
  3466. thisjob->changed = 1;
  3467. if (thisjob->state != state) {
  3468. TRACE(("Job %d: changing state from %d to %d\n",
  3469. jobno(thisjob), thisjob->state, state));
  3470. thisjob->state = state;
  3471. #if JOBS
  3472. if (state == JOBSTOPPED) {
  3473. set_curjob(thisjob, CUR_STOPPED);
  3474. }
  3475. #endif
  3476. }
  3477. }
  3478. out:
  3479. INT_ON;
  3480. if (thisjob && thisjob == job) {
  3481. char s[48 + 1];
  3482. int len;
  3483. len = sprint_status(s, status, 1);
  3484. if (len) {
  3485. s[len] = '\n';
  3486. s[len + 1] = '\0';
  3487. out2str(s);
  3488. }
  3489. }
  3490. return pid;
  3491. }
  3492. #if JOBS
  3493. static void
  3494. showjob(FILE *out, struct job *jp, int mode)
  3495. {
  3496. struct procstat *ps;
  3497. struct procstat *psend;
  3498. int col;
  3499. int indent_col;
  3500. char s[80];
  3501. ps = jp->ps;
  3502. if (mode & SHOW_PGID) {
  3503. /* just output process (group) id of pipeline */
  3504. fprintf(out, "%d\n", ps->pid);
  3505. return;
  3506. }
  3507. col = fmtstr(s, 16, "[%d] ", jobno(jp));
  3508. indent_col = col;
  3509. if (jp == curjob)
  3510. s[col - 2] = '+';
  3511. else if (curjob && jp == curjob->prev_job)
  3512. s[col - 2] = '-';
  3513. if (mode & SHOW_PID)
  3514. col += fmtstr(s + col, 16, "%d ", ps->pid);
  3515. psend = ps + jp->nprocs;
  3516. if (jp->state == JOBRUNNING) {
  3517. strcpy(s + col, "Running");
  3518. col += sizeof("Running") - 1;
  3519. } else {
  3520. int status = psend[-1].status;
  3521. if (jp->state == JOBSTOPPED)
  3522. status = jp->stopstatus;
  3523. col += sprint_status(s + col, status, 0);
  3524. }
  3525. goto start;
  3526. do {
  3527. /* for each process */
  3528. col = fmtstr(s, 48, " |\n%*c%d ", indent_col, ' ', ps->pid) - 3;
  3529. start:
  3530. fprintf(out, "%s%*c%s",
  3531. s, 33 - col >= 0 ? 33 - col : 0, ' ', ps->cmd
  3532. );
  3533. if (!(mode & SHOW_PID)) {
  3534. showpipe(jp, out);
  3535. break;
  3536. }
  3537. if (++ps == psend) {
  3538. outcslow('\n', out);
  3539. break;
  3540. }
  3541. } while (1);
  3542. jp->changed = 0;
  3543. if (jp->state == JOBDONE) {
  3544. TRACE(("showjob: freeing job %d\n", jobno(jp)));
  3545. freejob(jp);
  3546. }
  3547. }
  3548. /*
  3549. * Print a list of jobs. If "change" is nonzero, only print jobs whose
  3550. * statuses have changed since the last call to showjobs.
  3551. */
  3552. static void
  3553. showjobs(FILE *out, int mode)
  3554. {
  3555. struct job *jp;
  3556. TRACE(("showjobs(%x) called\n", mode));
  3557. /* If not even one job changed, there is nothing to do */
  3558. while (dowait(DOWAIT_NONBLOCK, NULL) > 0)
  3559. continue;
  3560. for (jp = curjob; jp; jp = jp->prev_job) {
  3561. if (!(mode & SHOW_CHANGED) || jp->changed) {
  3562. showjob(out, jp, mode);
  3563. }
  3564. }
  3565. }
  3566. static int
  3567. jobscmd(int argc UNUSED_PARAM, char **argv)
  3568. {
  3569. int mode, m;
  3570. mode = 0;
  3571. while ((m = nextopt("lp"))) {
  3572. if (m == 'l')
  3573. mode = SHOW_PID;
  3574. else
  3575. mode = SHOW_PGID;
  3576. }
  3577. argv = argptr;
  3578. if (*argv) {
  3579. do
  3580. showjob(stdout, getjob(*argv,0), mode);
  3581. while (*++argv);
  3582. } else
  3583. showjobs(stdout, mode);
  3584. return 0;
  3585. }
  3586. #endif /* JOBS */
  3587. static int
  3588. getstatus(struct job *job)
  3589. {
  3590. int status;
  3591. int retval;
  3592. status = job->ps[job->nprocs - 1].status;
  3593. retval = WEXITSTATUS(status);
  3594. if (!WIFEXITED(status)) {
  3595. #if JOBS
  3596. retval = WSTOPSIG(status);
  3597. if (!WIFSTOPPED(status))
  3598. #endif
  3599. {
  3600. /* XXX: limits number of signals */
  3601. retval = WTERMSIG(status);
  3602. #if JOBS
  3603. if (retval == SIGINT)
  3604. job->sigint = 1;
  3605. #endif
  3606. }
  3607. retval += 128;
  3608. }
  3609. TRACE(("getstatus: job %d, nproc %d, status %x, retval %x\n",
  3610. jobno(job), job->nprocs, status, retval));
  3611. return retval;
  3612. }
  3613. static int
  3614. waitcmd(int argc UNUSED_PARAM, char **argv)
  3615. {
  3616. struct job *job;
  3617. int retval;
  3618. struct job *jp;
  3619. // exsig++;
  3620. // xbarrier();
  3621. if (pendingsig)
  3622. raise_exception(EXSIG);
  3623. nextopt(nullstr);
  3624. retval = 0;
  3625. argv = argptr;
  3626. if (!*argv) {
  3627. /* wait for all jobs */
  3628. for (;;) {
  3629. jp = curjob;
  3630. while (1) {
  3631. if (!jp) /* no running procs */
  3632. goto ret;
  3633. if (jp->state == JOBRUNNING)
  3634. break;
  3635. jp->waited = 1;
  3636. jp = jp->prev_job;
  3637. }
  3638. dowait(DOWAIT_BLOCK, NULL);
  3639. }
  3640. }
  3641. retval = 127;
  3642. do {
  3643. if (**argv != '%') {
  3644. pid_t pid = number(*argv);
  3645. job = curjob;
  3646. while (1) {
  3647. if (!job)
  3648. goto repeat;
  3649. if (job->ps[job->nprocs - 1].pid == pid)
  3650. break;
  3651. job = job->prev_job;
  3652. }
  3653. } else
  3654. job = getjob(*argv, 0);
  3655. /* loop until process terminated or stopped */
  3656. while (job->state == JOBRUNNING)
  3657. dowait(DOWAIT_BLOCK, NULL);
  3658. job->waited = 1;
  3659. retval = getstatus(job);
  3660. repeat:
  3661. ;
  3662. } while (*++argv);
  3663. ret:
  3664. return retval;
  3665. }
  3666. static struct job *
  3667. growjobtab(void)
  3668. {
  3669. size_t len;
  3670. ptrdiff_t offset;
  3671. struct job *jp, *jq;
  3672. len = njobs * sizeof(*jp);
  3673. jq = jobtab;
  3674. jp = ckrealloc(jq, len + 4 * sizeof(*jp));
  3675. offset = (char *)jp - (char *)jq;
  3676. if (offset) {
  3677. /* Relocate pointers */
  3678. size_t l = len;
  3679. jq = (struct job *)((char *)jq + l);
  3680. while (l) {
  3681. l -= sizeof(*jp);
  3682. jq--;
  3683. #define joff(p) ((struct job *)((char *)(p) + l))
  3684. #define jmove(p) (p) = (void *)((char *)(p) + offset)
  3685. if (joff(jp)->ps == &jq->ps0)
  3686. jmove(joff(jp)->ps);
  3687. if (joff(jp)->prev_job)
  3688. jmove(joff(jp)->prev_job);
  3689. }
  3690. if (curjob)
  3691. jmove(curjob);
  3692. #undef joff
  3693. #undef jmove
  3694. }
  3695. njobs += 4;
  3696. jobtab = jp;
  3697. jp = (struct job *)((char *)jp + len);
  3698. jq = jp + 3;
  3699. do {
  3700. jq->used = 0;
  3701. } while (--jq >= jp);
  3702. return jp;
  3703. }
  3704. /*
  3705. * Return a new job structure.
  3706. * Called with interrupts off.
  3707. */
  3708. static struct job *
  3709. makejob(/*union node *node,*/ int nprocs)
  3710. {
  3711. int i;
  3712. struct job *jp;
  3713. for (i = njobs, jp = jobtab; ; jp++) {
  3714. if (--i < 0) {
  3715. jp = growjobtab();
  3716. break;
  3717. }
  3718. if (jp->used == 0)
  3719. break;
  3720. if (jp->state != JOBDONE || !jp->waited)
  3721. continue;
  3722. #if JOBS
  3723. if (doing_jobctl)
  3724. continue;
  3725. #endif
  3726. freejob(jp);
  3727. break;
  3728. }
  3729. memset(jp, 0, sizeof(*jp));
  3730. #if JOBS
  3731. /* jp->jobctl is a bitfield.
  3732. * "jp->jobctl |= jobctl" likely to give awful code */
  3733. if (doing_jobctl)
  3734. jp->jobctl = 1;
  3735. #endif
  3736. jp->prev_job = curjob;
  3737. curjob = jp;
  3738. jp->used = 1;
  3739. jp->ps = &jp->ps0;
  3740. if (nprocs > 1) {
  3741. jp->ps = ckmalloc(nprocs * sizeof(struct procstat));
  3742. }
  3743. TRACE(("makejob(%d) returns %%%d\n", nprocs,
  3744. jobno(jp)));
  3745. return jp;
  3746. }
  3747. #if JOBS
  3748. /*
  3749. * Return a string identifying a command (to be printed by the
  3750. * jobs command).
  3751. */
  3752. static char *cmdnextc;
  3753. static void
  3754. cmdputs(const char *s)
  3755. {
  3756. static const char vstype[VSTYPE + 1][3] = {
  3757. "", "}", "-", "+", "?", "=",
  3758. "%", "%%", "#", "##"
  3759. USE_ASH_BASH_COMPAT(, ":", "/", "//")
  3760. };
  3761. const char *p, *str;
  3762. char c, cc[2] = " ";
  3763. char *nextc;
  3764. int subtype = 0;
  3765. int quoted = 0;
  3766. nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
  3767. p = s;
  3768. while ((c = *p++) != 0) {
  3769. str = NULL;
  3770. switch (c) {
  3771. case CTLESC:
  3772. c = *p++;
  3773. break;
  3774. case CTLVAR:
  3775. subtype = *p++;
  3776. if ((subtype & VSTYPE) == VSLENGTH)
  3777. str = "${#";
  3778. else
  3779. str = "${";
  3780. if (!(subtype & VSQUOTE) == !(quoted & 1))
  3781. goto dostr;
  3782. quoted ^= 1;
  3783. c = '"';
  3784. break;
  3785. case CTLENDVAR:
  3786. str = "\"}" + !(quoted & 1);
  3787. quoted >>= 1;
  3788. subtype = 0;
  3789. goto dostr;
  3790. case CTLBACKQ:
  3791. str = "$(...)";
  3792. goto dostr;
  3793. case CTLBACKQ+CTLQUOTE:
  3794. str = "\"$(...)\"";
  3795. goto dostr;
  3796. #if ENABLE_ASH_MATH_SUPPORT
  3797. case CTLARI:
  3798. str = "$((";
  3799. goto dostr;
  3800. case CTLENDARI:
  3801. str = "))";
  3802. goto dostr;
  3803. #endif
  3804. case CTLQUOTEMARK:
  3805. quoted ^= 1;
  3806. c = '"';
  3807. break;
  3808. case '=':
  3809. if (subtype == 0)
  3810. break;
  3811. if ((subtype & VSTYPE) != VSNORMAL)
  3812. quoted <<= 1;
  3813. str = vstype[subtype & VSTYPE];
  3814. if (subtype & VSNUL)
  3815. c = ':';
  3816. else
  3817. goto checkstr;
  3818. break;
  3819. case '\'':
  3820. case '\\':
  3821. case '"':
  3822. case '$':
  3823. /* These can only happen inside quotes */
  3824. cc[0] = c;
  3825. str = cc;
  3826. c = '\\';
  3827. break;
  3828. default:
  3829. break;
  3830. }
  3831. USTPUTC(c, nextc);
  3832. checkstr:
  3833. if (!str)
  3834. continue;
  3835. dostr:
  3836. while ((c = *str++)) {
  3837. USTPUTC(c, nextc);
  3838. }
  3839. }
  3840. if (quoted & 1) {
  3841. USTPUTC('"', nextc);
  3842. }
  3843. *nextc = 0;
  3844. cmdnextc = nextc;
  3845. }
  3846. /* cmdtxt() and cmdlist() call each other */
  3847. static void cmdtxt(union node *n);
  3848. static void
  3849. cmdlist(union node *np, int sep)
  3850. {
  3851. for (; np; np = np->narg.next) {
  3852. if (!sep)
  3853. cmdputs(" ");
  3854. cmdtxt(np);
  3855. if (sep && np->narg.next)
  3856. cmdputs(" ");
  3857. }
  3858. }
  3859. static void
  3860. cmdtxt(union node *n)
  3861. {
  3862. union node *np;
  3863. struct nodelist *lp;
  3864. const char *p;
  3865. if (!n)
  3866. return;
  3867. switch (n->type) {
  3868. default:
  3869. #if DEBUG
  3870. abort();
  3871. #endif
  3872. case NPIPE:
  3873. lp = n->npipe.cmdlist;
  3874. for (;;) {
  3875. cmdtxt(lp->n);
  3876. lp = lp->next;
  3877. if (!lp)
  3878. break;
  3879. cmdputs(" | ");
  3880. }
  3881. break;
  3882. case NSEMI:
  3883. p = "; ";
  3884. goto binop;
  3885. case NAND:
  3886. p = " && ";
  3887. goto binop;
  3888. case NOR:
  3889. p = " || ";
  3890. binop:
  3891. cmdtxt(n->nbinary.ch1);
  3892. cmdputs(p);
  3893. n = n->nbinary.ch2;
  3894. goto donode;
  3895. case NREDIR:
  3896. case NBACKGND:
  3897. n = n->nredir.n;
  3898. goto donode;
  3899. case NNOT:
  3900. cmdputs("!");
  3901. n = n->nnot.com;
  3902. donode:
  3903. cmdtxt(n);
  3904. break;
  3905. case NIF:
  3906. cmdputs("if ");
  3907. cmdtxt(n->nif.test);
  3908. cmdputs("; then ");
  3909. n = n->nif.ifpart;
  3910. if (n->nif.elsepart) {
  3911. cmdtxt(n);
  3912. cmdputs("; else ");
  3913. n = n->nif.elsepart;
  3914. }
  3915. p = "; fi";
  3916. goto dotail;
  3917. case NSUBSHELL:
  3918. cmdputs("(");
  3919. n = n->nredir.n;
  3920. p = ")";
  3921. goto dotail;
  3922. case NWHILE:
  3923. p = "while ";
  3924. goto until;
  3925. case NUNTIL:
  3926. p = "until ";
  3927. until:
  3928. cmdputs(p);
  3929. cmdtxt(n->nbinary.ch1);
  3930. n = n->nbinary.ch2;
  3931. p = "; done";
  3932. dodo:
  3933. cmdputs("; do ");
  3934. dotail:
  3935. cmdtxt(n);
  3936. goto dotail2;
  3937. case NFOR:
  3938. cmdputs("for ");
  3939. cmdputs(n->nfor.var);
  3940. cmdputs(" in ");
  3941. cmdlist(n->nfor.args, 1);
  3942. n = n->nfor.body;
  3943. p = "; done";
  3944. goto dodo;
  3945. case NDEFUN:
  3946. cmdputs(n->narg.text);
  3947. p = "() { ... }";
  3948. goto dotail2;
  3949. case NCMD:
  3950. cmdlist(n->ncmd.args, 1);
  3951. cmdlist(n->ncmd.redirect, 0);
  3952. break;
  3953. case NARG:
  3954. p = n->narg.text;
  3955. dotail2:
  3956. cmdputs(p);
  3957. break;
  3958. case NHERE:
  3959. case NXHERE:
  3960. p = "<<...";
  3961. goto dotail2;
  3962. case NCASE:
  3963. cmdputs("case ");
  3964. cmdputs(n->ncase.expr->narg.text);
  3965. cmdputs(" in ");
  3966. for (np = n->ncase.cases; np; np = np->nclist.next) {
  3967. cmdtxt(np->nclist.pattern);
  3968. cmdputs(") ");
  3969. cmdtxt(np->nclist.body);
  3970. cmdputs(";; ");
  3971. }
  3972. p = "esac";
  3973. goto dotail2;
  3974. case NTO:
  3975. p = ">";
  3976. goto redir;
  3977. case NCLOBBER:
  3978. p = ">|";
  3979. goto redir;
  3980. case NAPPEND:
  3981. p = ">>";
  3982. goto redir;
  3983. case NTOFD:
  3984. p = ">&";
  3985. goto redir;
  3986. case NFROM:
  3987. p = "<";
  3988. goto redir;
  3989. case NFROMFD:
  3990. p = "<&";
  3991. goto redir;
  3992. case NFROMTO:
  3993. p = "<>";
  3994. redir:
  3995. cmdputs(utoa(n->nfile.fd));
  3996. cmdputs(p);
  3997. if (n->type == NTOFD || n->type == NFROMFD) {
  3998. cmdputs(utoa(n->ndup.dupfd));
  3999. break;
  4000. }
  4001. n = n->nfile.fname;
  4002. goto donode;
  4003. }
  4004. }
  4005. static char *
  4006. commandtext(union node *n)
  4007. {
  4008. char *name;
  4009. STARTSTACKSTR(cmdnextc);
  4010. cmdtxt(n);
  4011. name = stackblock();
  4012. TRACE(("commandtext: name %p, end %p\n\t\"%s\"\n",
  4013. name, cmdnextc, cmdnextc));
  4014. return ckstrdup(name);
  4015. }
  4016. #endif /* JOBS */
  4017. /*
  4018. * Fork off a subshell. If we are doing job control, give the subshell its
  4019. * own process group. Jp is a job structure that the job is to be added to.
  4020. * N is the command that will be evaluated by the child. Both jp and n may
  4021. * be NULL. The mode parameter can be one of the following:
  4022. * FORK_FG - Fork off a foreground process.
  4023. * FORK_BG - Fork off a background process.
  4024. * FORK_NOJOB - Like FORK_FG, but don't give the process its own
  4025. * process group even if job control is on.
  4026. *
  4027. * When job control is turned off, background processes have their standard
  4028. * input redirected to /dev/null (except for the second and later processes
  4029. * in a pipeline).
  4030. *
  4031. * Called with interrupts off.
  4032. */
  4033. /*
  4034. * Clear traps on a fork.
  4035. */
  4036. static void
  4037. clear_traps(void)
  4038. {
  4039. char **tp;
  4040. for (tp = trap; tp < &trap[NSIG]; tp++) {
  4041. if (*tp && **tp) { /* trap not NULL or "" (SIG_IGN) */
  4042. INT_OFF;
  4043. free(*tp);
  4044. *tp = NULL;
  4045. if (tp != &trap[0])
  4046. setsignal(tp - trap);
  4047. INT_ON;
  4048. }
  4049. }
  4050. }
  4051. /* Lives far away from here, needed for forkchild */
  4052. static void closescript(void);
  4053. /* Called after fork(), in child */
  4054. static void
  4055. forkchild(struct job *jp, /*union node *n,*/ int mode)
  4056. {
  4057. int oldlvl;
  4058. TRACE(("Child shell %d\n", getpid()));
  4059. oldlvl = shlvl;
  4060. shlvl++;
  4061. closescript();
  4062. clear_traps();
  4063. #if JOBS
  4064. /* do job control only in root shell */
  4065. doing_jobctl = 0;
  4066. if (mode != FORK_NOJOB && jp->jobctl && !oldlvl) {
  4067. pid_t pgrp;
  4068. if (jp->nprocs == 0)
  4069. pgrp = getpid();
  4070. else
  4071. pgrp = jp->ps[0].pid;
  4072. /* This can fail because we are doing it in the parent also */
  4073. (void)setpgid(0, pgrp);
  4074. if (mode == FORK_FG)
  4075. xtcsetpgrp(ttyfd, pgrp);
  4076. setsignal(SIGTSTP);
  4077. setsignal(SIGTTOU);
  4078. } else
  4079. #endif
  4080. if (mode == FORK_BG) {
  4081. ignoresig(SIGINT);
  4082. ignoresig(SIGQUIT);
  4083. if (jp->nprocs == 0) {
  4084. close(0);
  4085. if (open(bb_dev_null, O_RDONLY) != 0)
  4086. ash_msg_and_raise_error("can't open %s", bb_dev_null);
  4087. }
  4088. }
  4089. if (!oldlvl && iflag) {
  4090. setsignal(SIGINT);
  4091. setsignal(SIGQUIT);
  4092. setsignal(SIGTERM);
  4093. }
  4094. for (jp = curjob; jp; jp = jp->prev_job)
  4095. freejob(jp);
  4096. jobless = 0;
  4097. }
  4098. /* Called after fork(), in parent */
  4099. #if !JOBS
  4100. #define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
  4101. #endif
  4102. static void
  4103. forkparent(struct job *jp, union node *n, int mode, pid_t pid)
  4104. {
  4105. TRACE(("In parent shell: child = %d\n", pid));
  4106. if (!jp) {
  4107. while (jobless && dowait(DOWAIT_NONBLOCK, NULL) > 0)
  4108. continue;
  4109. jobless++;
  4110. return;
  4111. }
  4112. #if JOBS
  4113. if (mode != FORK_NOJOB && jp->jobctl) {
  4114. int pgrp;
  4115. if (jp->nprocs == 0)
  4116. pgrp = pid;
  4117. else
  4118. pgrp = jp->ps[0].pid;
  4119. /* This can fail because we are doing it in the child also */
  4120. setpgid(pid, pgrp);
  4121. }
  4122. #endif
  4123. if (mode == FORK_BG) {
  4124. backgndpid = pid; /* set $! */
  4125. set_curjob(jp, CUR_RUNNING);
  4126. }
  4127. if (jp) {
  4128. struct procstat *ps = &jp->ps[jp->nprocs++];
  4129. ps->pid = pid;
  4130. ps->status = -1;
  4131. ps->cmd = nullstr;
  4132. #if JOBS
  4133. if (doing_jobctl && n)
  4134. ps->cmd = commandtext(n);
  4135. #endif
  4136. }
  4137. }
  4138. static int
  4139. forkshell(struct job *jp, union node *n, int mode)
  4140. {
  4141. int pid;
  4142. TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
  4143. pid = fork();
  4144. if (pid < 0) {
  4145. TRACE(("Fork failed, errno=%d", errno));
  4146. if (jp)
  4147. freejob(jp);
  4148. ash_msg_and_raise_error("can't fork");
  4149. }
  4150. if (pid == 0)
  4151. forkchild(jp, /*n,*/ mode);
  4152. else
  4153. forkparent(jp, n, mode, pid);
  4154. return pid;
  4155. }
  4156. /*
  4157. * Wait for job to finish.
  4158. *
  4159. * Under job control we have the problem that while a child process is
  4160. * running interrupts generated by the user are sent to the child but not
  4161. * to the shell. This means that an infinite loop started by an inter-
  4162. * active user may be hard to kill. With job control turned off, an
  4163. * interactive user may place an interactive program inside a loop. If
  4164. * the interactive program catches interrupts, the user doesn't want
  4165. * these interrupts to also abort the loop. The approach we take here
  4166. * is to have the shell ignore interrupt signals while waiting for a
  4167. * foreground process to terminate, and then send itself an interrupt
  4168. * signal if the child process was terminated by an interrupt signal.
  4169. * Unfortunately, some programs want to do a bit of cleanup and then
  4170. * exit on interrupt; unless these processes terminate themselves by
  4171. * sending a signal to themselves (instead of calling exit) they will
  4172. * confuse this approach.
  4173. *
  4174. * Called with interrupts off.
  4175. */
  4176. static int
  4177. waitforjob(struct job *jp)
  4178. {
  4179. int st;
  4180. TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
  4181. while (jp->state == JOBRUNNING) {
  4182. dowait(DOWAIT_BLOCK, jp);
  4183. }
  4184. st = getstatus(jp);
  4185. #if JOBS
  4186. if (jp->jobctl) {
  4187. xtcsetpgrp(ttyfd, rootpid);
  4188. /*
  4189. * This is truly gross.
  4190. * If we're doing job control, then we did a TIOCSPGRP which
  4191. * caused us (the shell) to no longer be in the controlling
  4192. * session -- so we wouldn't have seen any ^C/SIGINT. So, we
  4193. * intuit from the subprocess exit status whether a SIGINT
  4194. * occurred, and if so interrupt ourselves. Yuck. - mycroft
  4195. */
  4196. if (jp->sigint) /* TODO: do the same with all signals */
  4197. raise(SIGINT); /* ... by raise(jp->sig) instead? */
  4198. }
  4199. if (jp->state == JOBDONE)
  4200. #endif
  4201. freejob(jp);
  4202. return st;
  4203. }
  4204. /*
  4205. * return 1 if there are stopped jobs, otherwise 0
  4206. */
  4207. static int
  4208. stoppedjobs(void)
  4209. {
  4210. struct job *jp;
  4211. int retval;
  4212. retval = 0;
  4213. if (job_warning)
  4214. goto out;
  4215. jp = curjob;
  4216. if (jp && jp->state == JOBSTOPPED) {
  4217. out2str("You have stopped jobs.\n");
  4218. job_warning = 2;
  4219. retval++;
  4220. }
  4221. out:
  4222. return retval;
  4223. }
  4224. /* ============ redir.c
  4225. *
  4226. * Code for dealing with input/output redirection.
  4227. */
  4228. #define EMPTY -2 /* marks an unused slot in redirtab */
  4229. #define CLOSED -3 /* marks a slot of previously-closed fd */
  4230. /*
  4231. * Open a file in noclobber mode.
  4232. * The code was copied from bash.
  4233. */
  4234. static int
  4235. noclobberopen(const char *fname)
  4236. {
  4237. int r, fd;
  4238. struct stat finfo, finfo2;
  4239. /*
  4240. * If the file exists and is a regular file, return an error
  4241. * immediately.
  4242. */
  4243. r = stat(fname, &finfo);
  4244. if (r == 0 && S_ISREG(finfo.st_mode)) {
  4245. errno = EEXIST;
  4246. return -1;
  4247. }
  4248. /*
  4249. * If the file was not present (r != 0), make sure we open it
  4250. * exclusively so that if it is created before we open it, our open
  4251. * will fail. Make sure that we do not truncate an existing file.
  4252. * Note that we don't turn on O_EXCL unless the stat failed -- if the
  4253. * file was not a regular file, we leave O_EXCL off.
  4254. */
  4255. if (r != 0)
  4256. return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
  4257. fd = open(fname, O_WRONLY|O_CREAT, 0666);
  4258. /* If the open failed, return the file descriptor right away. */
  4259. if (fd < 0)
  4260. return fd;
  4261. /*
  4262. * OK, the open succeeded, but the file may have been changed from a
  4263. * non-regular file to a regular file between the stat and the open.
  4264. * We are assuming that the O_EXCL open handles the case where FILENAME
  4265. * did not exist and is symlinked to an existing file between the stat
  4266. * and open.
  4267. */
  4268. /*
  4269. * If we can open it and fstat the file descriptor, and neither check
  4270. * revealed that it was a regular file, and the file has not been
  4271. * replaced, return the file descriptor.
  4272. */
  4273. if (fstat(fd, &finfo2) == 0 && !S_ISREG(finfo2.st_mode)
  4274. && finfo.st_dev == finfo2.st_dev && finfo.st_ino == finfo2.st_ino)
  4275. return fd;
  4276. /* The file has been replaced. badness. */
  4277. close(fd);
  4278. errno = EEXIST;
  4279. return -1;
  4280. }
  4281. /*
  4282. * Handle here documents. Normally we fork off a process to write the
  4283. * data to a pipe. If the document is short, we can stuff the data in
  4284. * the pipe without forking.
  4285. */
  4286. /* openhere needs this forward reference */
  4287. static void expandhere(union node *arg, int fd);
  4288. static int
  4289. openhere(union node *redir)
  4290. {
  4291. int pip[2];
  4292. size_t len = 0;
  4293. if (pipe(pip) < 0)
  4294. ash_msg_and_raise_error("pipe call failed");
  4295. if (redir->type == NHERE) {
  4296. len = strlen(redir->nhere.doc->narg.text);
  4297. if (len <= PIPE_BUF) {
  4298. full_write(pip[1], redir->nhere.doc->narg.text, len);
  4299. goto out;
  4300. }
  4301. }
  4302. if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
  4303. /* child */
  4304. close(pip[0]);
  4305. signal(SIGINT, SIG_IGN);
  4306. signal(SIGQUIT, SIG_IGN);
  4307. signal(SIGHUP, SIG_IGN);
  4308. #ifdef SIGTSTP
  4309. signal(SIGTSTP, SIG_IGN);
  4310. #endif
  4311. signal(SIGPIPE, SIG_DFL);
  4312. if (redir->type == NHERE)
  4313. full_write(pip[1], redir->nhere.doc->narg.text, len);
  4314. else /* NXHERE */
  4315. expandhere(redir->nhere.doc, pip[1]);
  4316. _exit(EXIT_SUCCESS);
  4317. }
  4318. out:
  4319. close(pip[1]);
  4320. return pip[0];
  4321. }
  4322. static int
  4323. openredirect(union node *redir)
  4324. {
  4325. char *fname;
  4326. int f;
  4327. switch (redir->nfile.type) {
  4328. case NFROM:
  4329. fname = redir->nfile.expfname;
  4330. f = open(fname, O_RDONLY);
  4331. if (f < 0)
  4332. goto eopen;
  4333. break;
  4334. case NFROMTO:
  4335. fname = redir->nfile.expfname;
  4336. f = open(fname, O_RDWR|O_CREAT|O_TRUNC, 0666);
  4337. if (f < 0)
  4338. goto ecreate;
  4339. break;
  4340. case NTO:
  4341. /* Take care of noclobber mode. */
  4342. if (Cflag) {
  4343. fname = redir->nfile.expfname;
  4344. f = noclobberopen(fname);
  4345. if (f < 0)
  4346. goto ecreate;
  4347. break;
  4348. }
  4349. /* FALLTHROUGH */
  4350. case NCLOBBER:
  4351. fname = redir->nfile.expfname;
  4352. f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
  4353. if (f < 0)
  4354. goto ecreate;
  4355. break;
  4356. case NAPPEND:
  4357. fname = redir->nfile.expfname;
  4358. f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
  4359. if (f < 0)
  4360. goto ecreate;
  4361. break;
  4362. default:
  4363. #if DEBUG
  4364. abort();
  4365. #endif
  4366. /* Fall through to eliminate warning. */
  4367. /* Our single caller does this itself */
  4368. // case NTOFD:
  4369. // case NFROMFD:
  4370. // f = -1;
  4371. // break;
  4372. case NHERE:
  4373. case NXHERE:
  4374. f = openhere(redir);
  4375. break;
  4376. }
  4377. return f;
  4378. ecreate:
  4379. ash_msg_and_raise_error("can't create %s: %s", fname, errmsg(errno, "nonexistent directory"));
  4380. eopen:
  4381. ash_msg_and_raise_error("can't open %s: %s", fname, errmsg(errno, "no such file"));
  4382. }
  4383. /*
  4384. * Copy a file descriptor to be >= to. Returns -1
  4385. * if the source file descriptor is closed, EMPTY if there are no unused
  4386. * file descriptors left.
  4387. */
  4388. /* 0x800..00: bit to set in "to" to request dup2 instead of fcntl(F_DUPFD).
  4389. * old code was doing close(to) prior to copyfd() to achieve the same */
  4390. enum {
  4391. COPYFD_EXACT = (int)~(INT_MAX),
  4392. COPYFD_RESTORE = (int)((unsigned)COPYFD_EXACT >> 1),
  4393. };
  4394. static int
  4395. copyfd(int from, int to)
  4396. {
  4397. int newfd;
  4398. if (to & COPYFD_EXACT) {
  4399. to &= ~COPYFD_EXACT;
  4400. /*if (from != to)*/
  4401. newfd = dup2(from, to);
  4402. } else {
  4403. newfd = fcntl(from, F_DUPFD, to);
  4404. }
  4405. if (newfd < 0) {
  4406. if (errno == EMFILE)
  4407. return EMPTY;
  4408. /* Happens when source fd is not open: try "echo >&99" */
  4409. ash_msg_and_raise_error("%d: %m", from);
  4410. }
  4411. return newfd;
  4412. }
  4413. /* Struct def and variable are moved down to the first usage site */
  4414. struct two_fd_t {
  4415. int orig, copy;
  4416. };
  4417. struct redirtab {
  4418. struct redirtab *next;
  4419. int nullredirs;
  4420. int pair_count;
  4421. struct two_fd_t two_fd[0];
  4422. };
  4423. #define redirlist (G_var.redirlist)
  4424. static int need_to_remember(struct redirtab *rp, int fd)
  4425. {
  4426. int i;
  4427. if (!rp) /* remembering was not requested */
  4428. return 0;
  4429. for (i = 0; i < rp->pair_count; i++) {
  4430. if (rp->two_fd[i].orig == fd) {
  4431. /* already remembered */
  4432. return 0;
  4433. }
  4434. }
  4435. return 1;
  4436. }
  4437. /* "hidden" fd is a fd used to read scripts, or a copy of such */
  4438. static int is_hidden_fd(struct redirtab *rp, int fd)
  4439. {
  4440. int i;
  4441. struct parsefile *pf;
  4442. if (fd == -1)
  4443. return 0;
  4444. pf = g_parsefile;
  4445. while (pf) {
  4446. if (fd == pf->fd) {
  4447. return 1;
  4448. }
  4449. pf = pf->prev;
  4450. }
  4451. if (!rp)
  4452. return 0;
  4453. fd |= COPYFD_RESTORE;
  4454. for (i = 0; i < rp->pair_count; i++) {
  4455. if (rp->two_fd[i].copy == fd) {
  4456. return 1;
  4457. }
  4458. }
  4459. return 0;
  4460. }
  4461. /*
  4462. * Process a list of redirection commands. If the REDIR_PUSH flag is set,
  4463. * old file descriptors are stashed away so that the redirection can be
  4464. * undone by calling popredir. If the REDIR_BACKQ flag is set, then the
  4465. * standard output, and the standard error if it becomes a duplicate of
  4466. * stdout, is saved in memory.
  4467. */
  4468. /* flags passed to redirect */
  4469. #define REDIR_PUSH 01 /* save previous values of file descriptors */
  4470. #define REDIR_SAVEFD2 03 /* set preverrout */
  4471. static void
  4472. redirect(union node *redir, int flags)
  4473. {
  4474. struct redirtab *sv;
  4475. int sv_pos;
  4476. int i;
  4477. int fd;
  4478. int newfd;
  4479. int copied_fd2 = -1;
  4480. g_nullredirs++;
  4481. if (!redir) {
  4482. return;
  4483. }
  4484. sv = NULL;
  4485. sv_pos = 0;
  4486. INT_OFF;
  4487. if (flags & REDIR_PUSH) {
  4488. union node *tmp = redir;
  4489. do {
  4490. sv_pos++;
  4491. tmp = tmp->nfile.next;
  4492. } while (tmp);
  4493. sv = ckmalloc(sizeof(*sv) + sv_pos * sizeof(sv->two_fd[0]));
  4494. sv->next = redirlist;
  4495. sv->pair_count = sv_pos;
  4496. redirlist = sv;
  4497. sv->nullredirs = g_nullredirs - 1;
  4498. g_nullredirs = 0;
  4499. while (sv_pos > 0) {
  4500. sv_pos--;
  4501. sv->two_fd[sv_pos].orig = sv->two_fd[sv_pos].copy = EMPTY;
  4502. }
  4503. }
  4504. do {
  4505. fd = redir->nfile.fd;
  4506. if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
  4507. int right_fd = redir->ndup.dupfd;
  4508. /* redirect from/to same file descriptor? */
  4509. if (right_fd == fd)
  4510. continue;
  4511. /* echo >&10 and 10 is a fd opened to the sh script? */
  4512. if (is_hidden_fd(sv, right_fd)) {
  4513. errno = EBADF; /* as if it is closed */
  4514. ash_msg_and_raise_error("%d: %m", right_fd);
  4515. }
  4516. newfd = -1;
  4517. } else {
  4518. newfd = openredirect(redir); /* always >= 0 */
  4519. if (fd == newfd) {
  4520. /* Descriptor wasn't open before redirect.
  4521. * Mark it for close in the future */
  4522. if (need_to_remember(sv, fd)) {
  4523. goto remember_to_close;
  4524. }
  4525. continue;
  4526. }
  4527. }
  4528. if (need_to_remember(sv, fd)) {
  4529. /* Copy old descriptor */
  4530. i = fcntl(fd, F_DUPFD, 10);
  4531. /* You'd expect copy to be CLOEXECed. Currently these extra "saved" fds
  4532. * are closed in popredir() in the child, preventing them from leaking
  4533. * into child. (popredir() also cleans up the mess in case of failures)
  4534. */
  4535. if (i == -1) {
  4536. i = errno;
  4537. if (i != EBADF) {
  4538. /* Strange error (e.g. "too many files" EMFILE?) */
  4539. if (newfd >= 0)
  4540. close(newfd);
  4541. errno = i;
  4542. ash_msg_and_raise_error("%d: %m", fd);
  4543. /* NOTREACHED */
  4544. }
  4545. /* EBADF: it is not open - good, remember to close it */
  4546. remember_to_close:
  4547. i = CLOSED;
  4548. } else { /* fd is open, save its copy */
  4549. /* "exec fd>&-" should not close fds
  4550. * which point to script file(s).
  4551. * Force them to be restored afterwards */
  4552. if (is_hidden_fd(sv, fd))
  4553. i |= COPYFD_RESTORE;
  4554. }
  4555. if (fd == 2)
  4556. copied_fd2 = i;
  4557. sv->two_fd[sv_pos].orig = fd;
  4558. sv->two_fd[sv_pos].copy = i;
  4559. sv_pos++;
  4560. }
  4561. if (newfd < 0) {
  4562. /* NTOFD/NFROMFD: copy redir->ndup.dupfd to fd */
  4563. if (redir->ndup.dupfd < 0) { /* "fd>&-" */
  4564. close(fd);
  4565. } else {
  4566. copyfd(redir->ndup.dupfd, fd | COPYFD_EXACT);
  4567. }
  4568. } else if (fd != newfd) { /* move newfd to fd */
  4569. copyfd(newfd, fd | COPYFD_EXACT);
  4570. close(newfd);
  4571. }
  4572. } while ((redir = redir->nfile.next) != NULL);
  4573. INT_ON;
  4574. if ((flags & REDIR_SAVEFD2) && copied_fd2 >= 0)
  4575. preverrout_fd = copied_fd2;
  4576. }
  4577. /*
  4578. * Undo the effects of the last redirection.
  4579. */
  4580. static void
  4581. popredir(int drop, int restore)
  4582. {
  4583. struct redirtab *rp;
  4584. int i;
  4585. if (--g_nullredirs >= 0)
  4586. return;
  4587. INT_OFF;
  4588. rp = redirlist;
  4589. for (i = 0; i < rp->pair_count; i++) {
  4590. int fd = rp->two_fd[i].orig;
  4591. int copy = rp->two_fd[i].copy;
  4592. if (copy == CLOSED) {
  4593. if (!drop)
  4594. close(fd);
  4595. continue;
  4596. }
  4597. if (copy != EMPTY) {
  4598. if (!drop || (restore && (copy & COPYFD_RESTORE))) {
  4599. copy &= ~COPYFD_RESTORE;
  4600. /*close(fd);*/
  4601. copyfd(copy, fd | COPYFD_EXACT);
  4602. }
  4603. close(copy);
  4604. }
  4605. }
  4606. redirlist = rp->next;
  4607. g_nullredirs = rp->nullredirs;
  4608. free(rp);
  4609. INT_ON;
  4610. }
  4611. /*
  4612. * Undo all redirections. Called on error or interrupt.
  4613. */
  4614. /*
  4615. * Discard all saved file descriptors.
  4616. */
  4617. static void
  4618. clearredir(int drop)
  4619. {
  4620. for (;;) {
  4621. g_nullredirs = 0;
  4622. if (!redirlist)
  4623. break;
  4624. popredir(drop, /*restore:*/ 0);
  4625. }
  4626. }
  4627. static int
  4628. redirectsafe(union node *redir, int flags)
  4629. {
  4630. int err;
  4631. volatile int saveint;
  4632. struct jmploc *volatile savehandler = exception_handler;
  4633. struct jmploc jmploc;
  4634. SAVE_INT(saveint);
  4635. /* "echo 9>/dev/null; echo >&9; echo result: $?" - result should be 1, not 2! */
  4636. err = setjmp(jmploc.loc); // huh?? was = setjmp(jmploc.loc) * 2;
  4637. if (!err) {
  4638. exception_handler = &jmploc;
  4639. redirect(redir, flags);
  4640. }
  4641. exception_handler = savehandler;
  4642. if (err && exception != EXERROR)
  4643. longjmp(exception_handler->loc, 1);
  4644. RESTORE_INT(saveint);
  4645. return err;
  4646. }
  4647. /* ============ Routines to expand arguments to commands
  4648. *
  4649. * We have to deal with backquotes, shell variables, and file metacharacters.
  4650. */
  4651. #if ENABLE_ASH_MATH_SUPPORT_64
  4652. typedef int64_t arith_t;
  4653. #define arith_t_type long long
  4654. #else
  4655. typedef long arith_t;
  4656. #define arith_t_type long
  4657. #endif
  4658. #if ENABLE_ASH_MATH_SUPPORT
  4659. static arith_t dash_arith(const char *);
  4660. static arith_t arith(const char *expr, int *perrcode);
  4661. #endif
  4662. /*
  4663. * expandarg flags
  4664. */
  4665. #define EXP_FULL 0x1 /* perform word splitting & file globbing */
  4666. #define EXP_TILDE 0x2 /* do normal tilde expansion */
  4667. #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
  4668. #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
  4669. #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
  4670. #define EXP_RECORD 0x20 /* need to record arguments for ifs breakup */
  4671. #define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
  4672. #define EXP_WORD 0x80 /* expand word in parameter expansion */
  4673. #define EXP_QWORD 0x100 /* expand word in quoted parameter expansion */
  4674. /*
  4675. * _rmescape() flags
  4676. */
  4677. #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
  4678. #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
  4679. #define RMESCAPE_QUOTED 0x4 /* Remove CTLESC unless in quotes */
  4680. #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
  4681. #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
  4682. /*
  4683. * Structure specifying which parts of the string should be searched
  4684. * for IFS characters.
  4685. */
  4686. struct ifsregion {
  4687. struct ifsregion *next; /* next region in list */
  4688. int begoff; /* offset of start of region */
  4689. int endoff; /* offset of end of region */
  4690. int nulonly; /* search for nul bytes only */
  4691. };
  4692. struct arglist {
  4693. struct strlist *list;
  4694. struct strlist **lastp;
  4695. };
  4696. /* output of current string */
  4697. static char *expdest;
  4698. /* list of back quote expressions */
  4699. static struct nodelist *argbackq;
  4700. /* first struct in list of ifs regions */
  4701. static struct ifsregion ifsfirst;
  4702. /* last struct in list */
  4703. static struct ifsregion *ifslastp;
  4704. /* holds expanded arg list */
  4705. static struct arglist exparg;
  4706. /*
  4707. * Our own itoa().
  4708. */
  4709. static int
  4710. cvtnum(arith_t num)
  4711. {
  4712. int len;
  4713. expdest = makestrspace(32, expdest);
  4714. #if ENABLE_ASH_MATH_SUPPORT_64
  4715. len = fmtstr(expdest, 32, "%lld", (long long) num);
  4716. #else
  4717. len = fmtstr(expdest, 32, "%ld", num);
  4718. #endif
  4719. STADJUST(len, expdest);
  4720. return len;
  4721. }
  4722. static size_t
  4723. esclen(const char *start, const char *p)
  4724. {
  4725. size_t esc = 0;
  4726. while (p > start && *--p == CTLESC) {
  4727. esc++;
  4728. }
  4729. return esc;
  4730. }
  4731. /*
  4732. * Remove any CTLESC characters from a string.
  4733. */
  4734. static char *
  4735. _rmescapes(char *str, int flag)
  4736. {
  4737. static const char qchars[] ALIGN1 = { CTLESC, CTLQUOTEMARK, '\0' };
  4738. char *p, *q, *r;
  4739. unsigned inquotes;
  4740. int notescaped;
  4741. int globbing;
  4742. p = strpbrk(str, qchars);
  4743. if (!p) {
  4744. return str;
  4745. }
  4746. q = p;
  4747. r = str;
  4748. if (flag & RMESCAPE_ALLOC) {
  4749. size_t len = p - str;
  4750. size_t fulllen = len + strlen(p) + 1;
  4751. if (flag & RMESCAPE_GROW) {
  4752. r = makestrspace(fulllen, expdest);
  4753. } else if (flag & RMESCAPE_HEAP) {
  4754. r = ckmalloc(fulllen);
  4755. } else {
  4756. r = stalloc(fulllen);
  4757. }
  4758. q = r;
  4759. if (len > 0) {
  4760. q = (char *)memcpy(q, str, len) + len;
  4761. }
  4762. }
  4763. inquotes = (flag & RMESCAPE_QUOTED) ^ RMESCAPE_QUOTED;
  4764. globbing = flag & RMESCAPE_GLOB;
  4765. notescaped = globbing;
  4766. while (*p) {
  4767. if (*p == CTLQUOTEMARK) {
  4768. inquotes = ~inquotes;
  4769. p++;
  4770. notescaped = globbing;
  4771. continue;
  4772. }
  4773. if (*p == '\\') {
  4774. /* naked back slash */
  4775. notescaped = 0;
  4776. goto copy;
  4777. }
  4778. if (*p == CTLESC) {
  4779. p++;
  4780. if (notescaped && inquotes && *p != '/') {
  4781. *q++ = '\\';
  4782. }
  4783. }
  4784. notescaped = globbing;
  4785. copy:
  4786. *q++ = *p++;
  4787. }
  4788. *q = '\0';
  4789. if (flag & RMESCAPE_GROW) {
  4790. expdest = r;
  4791. STADJUST(q - r + 1, expdest);
  4792. }
  4793. return r;
  4794. }
  4795. #define rmescapes(p) _rmescapes((p), 0)
  4796. #define pmatch(a, b) !fnmatch((a), (b), 0)
  4797. /*
  4798. * Prepare a pattern for a expmeta (internal glob(3)) call.
  4799. *
  4800. * Returns an stalloced string.
  4801. */
  4802. static char *
  4803. preglob(const char *pattern, int quoted, int flag)
  4804. {
  4805. flag |= RMESCAPE_GLOB;
  4806. if (quoted) {
  4807. flag |= RMESCAPE_QUOTED;
  4808. }
  4809. return _rmescapes((char *)pattern, flag);
  4810. }
  4811. /*
  4812. * Put a string on the stack.
  4813. */
  4814. static void
  4815. memtodest(const char *p, size_t len, int syntax, int quotes)
  4816. {
  4817. char *q = expdest;
  4818. q = makestrspace(len * 2, q);
  4819. while (len--) {
  4820. int c = signed_char2int(*p++);
  4821. if (!c)
  4822. continue;
  4823. if (quotes && (SIT(c, syntax) == CCTL || SIT(c, syntax) == CBACK))
  4824. USTPUTC(CTLESC, q);
  4825. USTPUTC(c, q);
  4826. }
  4827. expdest = q;
  4828. }
  4829. static void
  4830. strtodest(const char *p, int syntax, int quotes)
  4831. {
  4832. memtodest(p, strlen(p), syntax, quotes);
  4833. }
  4834. /*
  4835. * Record the fact that we have to scan this region of the
  4836. * string for IFS characters.
  4837. */
  4838. static void
  4839. recordregion(int start, int end, int nulonly)
  4840. {
  4841. struct ifsregion *ifsp;
  4842. if (ifslastp == NULL) {
  4843. ifsp = &ifsfirst;
  4844. } else {
  4845. INT_OFF;
  4846. ifsp = ckzalloc(sizeof(*ifsp));
  4847. /*ifsp->next = NULL; - ckzalloc did it */
  4848. ifslastp->next = ifsp;
  4849. INT_ON;
  4850. }
  4851. ifslastp = ifsp;
  4852. ifslastp->begoff = start;
  4853. ifslastp->endoff = end;
  4854. ifslastp->nulonly = nulonly;
  4855. }
  4856. static void
  4857. removerecordregions(int endoff)
  4858. {
  4859. if (ifslastp == NULL)
  4860. return;
  4861. if (ifsfirst.endoff > endoff) {
  4862. while (ifsfirst.next != NULL) {
  4863. struct ifsregion *ifsp;
  4864. INT_OFF;
  4865. ifsp = ifsfirst.next->next;
  4866. free(ifsfirst.next);
  4867. ifsfirst.next = ifsp;
  4868. INT_ON;
  4869. }
  4870. if (ifsfirst.begoff > endoff)
  4871. ifslastp = NULL;
  4872. else {
  4873. ifslastp = &ifsfirst;
  4874. ifsfirst.endoff = endoff;
  4875. }
  4876. return;
  4877. }
  4878. ifslastp = &ifsfirst;
  4879. while (ifslastp->next && ifslastp->next->begoff < endoff)
  4880. ifslastp=ifslastp->next;
  4881. while (ifslastp->next != NULL) {
  4882. struct ifsregion *ifsp;
  4883. INT_OFF;
  4884. ifsp = ifslastp->next->next;
  4885. free(ifslastp->next);
  4886. ifslastp->next = ifsp;
  4887. INT_ON;
  4888. }
  4889. if (ifslastp->endoff > endoff)
  4890. ifslastp->endoff = endoff;
  4891. }
  4892. static char *
  4893. exptilde(char *startp, char *p, int flag)
  4894. {
  4895. char c;
  4896. char *name;
  4897. struct passwd *pw;
  4898. const char *home;
  4899. int quotes = flag & (EXP_FULL | EXP_CASE);
  4900. int startloc;
  4901. name = p + 1;
  4902. while ((c = *++p) != '\0') {
  4903. switch (c) {
  4904. case CTLESC:
  4905. return startp;
  4906. case CTLQUOTEMARK:
  4907. return startp;
  4908. case ':':
  4909. if (flag & EXP_VARTILDE)
  4910. goto done;
  4911. break;
  4912. case '/':
  4913. case CTLENDVAR:
  4914. goto done;
  4915. }
  4916. }
  4917. done:
  4918. *p = '\0';
  4919. if (*name == '\0') {
  4920. home = lookupvar(homestr);
  4921. } else {
  4922. pw = getpwnam(name);
  4923. if (pw == NULL)
  4924. goto lose;
  4925. home = pw->pw_dir;
  4926. }
  4927. if (!home || !*home)
  4928. goto lose;
  4929. *p = c;
  4930. startloc = expdest - (char *)stackblock();
  4931. strtodest(home, SQSYNTAX, quotes);
  4932. recordregion(startloc, expdest - (char *)stackblock(), 0);
  4933. return p;
  4934. lose:
  4935. *p = c;
  4936. return startp;
  4937. }
  4938. /*
  4939. * Execute a command inside back quotes. If it's a builtin command, we
  4940. * want to save its output in a block obtained from malloc. Otherwise
  4941. * we fork off a subprocess and get the output of the command via a pipe.
  4942. * Should be called with interrupts off.
  4943. */
  4944. struct backcmd { /* result of evalbackcmd */
  4945. int fd; /* file descriptor to read from */
  4946. int nleft; /* number of chars in buffer */
  4947. char *buf; /* buffer */
  4948. struct job *jp; /* job structure for command */
  4949. };
  4950. /* These forward decls are needed to use "eval" code for backticks handling: */
  4951. static uint8_t back_exitstatus; /* exit status of backquoted command */
  4952. #define EV_EXIT 01 /* exit after evaluating tree */
  4953. static void evaltree(union node *, int);
  4954. static void
  4955. evalbackcmd(union node *n, struct backcmd *result)
  4956. {
  4957. int saveherefd;
  4958. result->fd = -1;
  4959. result->buf = NULL;
  4960. result->nleft = 0;
  4961. result->jp = NULL;
  4962. if (n == NULL) {
  4963. goto out;
  4964. }
  4965. saveherefd = herefd;
  4966. herefd = -1;
  4967. {
  4968. int pip[2];
  4969. struct job *jp;
  4970. if (pipe(pip) < 0)
  4971. ash_msg_and_raise_error("pipe call failed");
  4972. jp = makejob(/*n,*/ 1);
  4973. if (forkshell(jp, n, FORK_NOJOB) == 0) {
  4974. FORCE_INT_ON;
  4975. close(pip[0]);
  4976. if (pip[1] != 1) {
  4977. /*close(1);*/
  4978. copyfd(pip[1], 1 | COPYFD_EXACT);
  4979. close(pip[1]);
  4980. }
  4981. eflag = 0;
  4982. evaltree(n, EV_EXIT); /* actually evaltreenr... */
  4983. /* NOTREACHED */
  4984. }
  4985. close(pip[1]);
  4986. result->fd = pip[0];
  4987. result->jp = jp;
  4988. }
  4989. herefd = saveherefd;
  4990. out:
  4991. TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
  4992. result->fd, result->buf, result->nleft, result->jp));
  4993. }
  4994. /*
  4995. * Expand stuff in backwards quotes.
  4996. */
  4997. static void
  4998. expbackq(union node *cmd, int quoted, int quotes)
  4999. {
  5000. struct backcmd in;
  5001. int i;
  5002. char buf[128];
  5003. char *p;
  5004. char *dest;
  5005. int startloc;
  5006. int syntax = quoted ? DQSYNTAX : BASESYNTAX;
  5007. struct stackmark smark;
  5008. INT_OFF;
  5009. setstackmark(&smark);
  5010. dest = expdest;
  5011. startloc = dest - (char *)stackblock();
  5012. grabstackstr(dest);
  5013. evalbackcmd(cmd, &in);
  5014. popstackmark(&smark);
  5015. p = in.buf;
  5016. i = in.nleft;
  5017. if (i == 0)
  5018. goto read;
  5019. for (;;) {
  5020. memtodest(p, i, syntax, quotes);
  5021. read:
  5022. if (in.fd < 0)
  5023. break;
  5024. i = nonblock_safe_read(in.fd, buf, sizeof(buf));
  5025. TRACE(("expbackq: read returns %d\n", i));
  5026. if (i <= 0)
  5027. break;
  5028. p = buf;
  5029. }
  5030. free(in.buf);
  5031. if (in.fd >= 0) {
  5032. close(in.fd);
  5033. back_exitstatus = waitforjob(in.jp);
  5034. }
  5035. INT_ON;
  5036. /* Eat all trailing newlines */
  5037. dest = expdest;
  5038. for (; dest > (char *)stackblock() && dest[-1] == '\n';)
  5039. STUNPUTC(dest);
  5040. expdest = dest;
  5041. if (quoted == 0)
  5042. recordregion(startloc, dest - (char *)stackblock(), 0);
  5043. TRACE(("evalbackq: size=%d: \"%.*s\"\n",
  5044. (dest - (char *)stackblock()) - startloc,
  5045. (dest - (char *)stackblock()) - startloc,
  5046. stackblock() + startloc));
  5047. }
  5048. #if ENABLE_ASH_MATH_SUPPORT
  5049. /*
  5050. * Expand arithmetic expression. Backup to start of expression,
  5051. * evaluate, place result in (backed up) result, adjust string position.
  5052. */
  5053. static void
  5054. expari(int quotes)
  5055. {
  5056. char *p, *start;
  5057. int begoff;
  5058. int flag;
  5059. int len;
  5060. /* ifsfree(); */
  5061. /*
  5062. * This routine is slightly over-complicated for
  5063. * efficiency. Next we scan backwards looking for the
  5064. * start of arithmetic.
  5065. */
  5066. start = stackblock();
  5067. p = expdest - 1;
  5068. *p = '\0';
  5069. p--;
  5070. do {
  5071. int esc;
  5072. while (*p != CTLARI) {
  5073. p--;
  5074. #if DEBUG
  5075. if (p < start) {
  5076. ash_msg_and_raise_error("missing CTLARI (shouldn't happen)");
  5077. }
  5078. #endif
  5079. }
  5080. esc = esclen(start, p);
  5081. if (!(esc % 2)) {
  5082. break;
  5083. }
  5084. p -= esc + 1;
  5085. } while (1);
  5086. begoff = p - start;
  5087. removerecordregions(begoff);
  5088. flag = p[1];
  5089. expdest = p;
  5090. if (quotes)
  5091. rmescapes(p + 2);
  5092. len = cvtnum(dash_arith(p + 2));
  5093. if (flag != '"')
  5094. recordregion(begoff, begoff + len, 0);
  5095. }
  5096. #endif
  5097. /* argstr needs it */
  5098. static char *evalvar(char *p, int flag, struct strlist *var_str_list);
  5099. /*
  5100. * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
  5101. * characters to allow for further processing. Otherwise treat
  5102. * $@ like $* since no splitting will be performed.
  5103. *
  5104. * var_str_list (can be NULL) is a list of "VAR=val" strings which take precedence
  5105. * over shell varables. Needed for "A=a B=$A; echo $B" case - we use it
  5106. * for correct expansion of "B=$A" word.
  5107. */
  5108. static void
  5109. argstr(char *p, int flag, struct strlist *var_str_list)
  5110. {
  5111. static const char spclchars[] ALIGN1 = {
  5112. '=',
  5113. ':',
  5114. CTLQUOTEMARK,
  5115. CTLENDVAR,
  5116. CTLESC,
  5117. CTLVAR,
  5118. CTLBACKQ,
  5119. CTLBACKQ | CTLQUOTE,
  5120. #if ENABLE_ASH_MATH_SUPPORT
  5121. CTLENDARI,
  5122. #endif
  5123. 0
  5124. };
  5125. const char *reject = spclchars;
  5126. int c;
  5127. int quotes = flag & (EXP_FULL | EXP_CASE); /* do CTLESC */
  5128. int breakall = flag & EXP_WORD;
  5129. int inquotes;
  5130. size_t length;
  5131. int startloc;
  5132. if (!(flag & EXP_VARTILDE)) {
  5133. reject += 2;
  5134. } else if (flag & EXP_VARTILDE2) {
  5135. reject++;
  5136. }
  5137. inquotes = 0;
  5138. length = 0;
  5139. if (flag & EXP_TILDE) {
  5140. char *q;
  5141. flag &= ~EXP_TILDE;
  5142. tilde:
  5143. q = p;
  5144. if (*q == CTLESC && (flag & EXP_QWORD))
  5145. q++;
  5146. if (*q == '~')
  5147. p = exptilde(p, q, flag);
  5148. }
  5149. start:
  5150. startloc = expdest - (char *)stackblock();
  5151. for (;;) {
  5152. length += strcspn(p + length, reject);
  5153. c = p[length];
  5154. if (c && (!(c & 0x80)
  5155. #if ENABLE_ASH_MATH_SUPPORT
  5156. || c == CTLENDARI
  5157. #endif
  5158. )) {
  5159. /* c == '=' || c == ':' || c == CTLENDARI */
  5160. length++;
  5161. }
  5162. if (length > 0) {
  5163. int newloc;
  5164. expdest = stack_nputstr(p, length, expdest);
  5165. newloc = expdest - (char *)stackblock();
  5166. if (breakall && !inquotes && newloc > startloc) {
  5167. recordregion(startloc, newloc, 0);
  5168. }
  5169. startloc = newloc;
  5170. }
  5171. p += length + 1;
  5172. length = 0;
  5173. switch (c) {
  5174. case '\0':
  5175. goto breakloop;
  5176. case '=':
  5177. if (flag & EXP_VARTILDE2) {
  5178. p--;
  5179. continue;
  5180. }
  5181. flag |= EXP_VARTILDE2;
  5182. reject++;
  5183. /* fall through */
  5184. case ':':
  5185. /*
  5186. * sort of a hack - expand tildes in variable
  5187. * assignments (after the first '=' and after ':'s).
  5188. */
  5189. if (*--p == '~') {
  5190. goto tilde;
  5191. }
  5192. continue;
  5193. }
  5194. switch (c) {
  5195. case CTLENDVAR: /* ??? */
  5196. goto breakloop;
  5197. case CTLQUOTEMARK:
  5198. /* "$@" syntax adherence hack */
  5199. if (
  5200. !inquotes &&
  5201. !memcmp(p, dolatstr, 4) &&
  5202. (p[4] == CTLQUOTEMARK || (
  5203. p[4] == CTLENDVAR &&
  5204. p[5] == CTLQUOTEMARK
  5205. ))
  5206. ) {
  5207. p = evalvar(p + 1, flag, /* var_str_list: */ NULL) + 1;
  5208. goto start;
  5209. }
  5210. inquotes = !inquotes;
  5211. addquote:
  5212. if (quotes) {
  5213. p--;
  5214. length++;
  5215. startloc++;
  5216. }
  5217. break;
  5218. case CTLESC:
  5219. startloc++;
  5220. length++;
  5221. goto addquote;
  5222. case CTLVAR:
  5223. p = evalvar(p, flag, var_str_list);
  5224. goto start;
  5225. case CTLBACKQ:
  5226. c = 0;
  5227. case CTLBACKQ|CTLQUOTE:
  5228. expbackq(argbackq->n, c, quotes);
  5229. argbackq = argbackq->next;
  5230. goto start;
  5231. #if ENABLE_ASH_MATH_SUPPORT
  5232. case CTLENDARI:
  5233. p--;
  5234. expari(quotes);
  5235. goto start;
  5236. #endif
  5237. }
  5238. }
  5239. breakloop:
  5240. ;
  5241. }
  5242. static char *
  5243. scanleft(char *startp, char *rmesc, char *rmescend UNUSED_PARAM, char *str, int quotes,
  5244. int zero)
  5245. {
  5246. // This commented out code was added by James Simmons <jsimmons@infradead.org>
  5247. // as part of a larger change when he added support for ${var/a/b}.
  5248. // However, it broke # and % operators:
  5249. //
  5250. //var=ababcdcd
  5251. // ok bad
  5252. //echo ${var#ab} abcdcd abcdcd
  5253. //echo ${var##ab} abcdcd abcdcd
  5254. //echo ${var#a*b} abcdcd ababcdcd (!)
  5255. //echo ${var##a*b} cdcd cdcd
  5256. //echo ${var#?} babcdcd ababcdcd (!)
  5257. //echo ${var##?} babcdcd babcdcd
  5258. //echo ${var#*} ababcdcd babcdcd (!)
  5259. //echo ${var##*}
  5260. //echo ${var%cd} ababcd ababcd
  5261. //echo ${var%%cd} ababcd abab (!)
  5262. //echo ${var%c*d} ababcd ababcd
  5263. //echo ${var%%c*d} abab ababcdcd (!)
  5264. //echo ${var%?} ababcdc ababcdc
  5265. //echo ${var%%?} ababcdc ababcdcd (!)
  5266. //echo ${var%*} ababcdcd ababcdcd
  5267. //echo ${var%%*}
  5268. //
  5269. // Commenting it back out helped. Remove it completely if it really
  5270. // is not needed.
  5271. char *loc, *loc2; //, *full;
  5272. char c;
  5273. loc = startp;
  5274. loc2 = rmesc;
  5275. do {
  5276. int match; // = strlen(str);
  5277. const char *s = loc2;
  5278. c = *loc2;
  5279. if (zero) {
  5280. *loc2 = '\0';
  5281. s = rmesc;
  5282. }
  5283. match = pmatch(str, s); // this line was deleted
  5284. // // chop off end if its '*'
  5285. // full = strrchr(str, '*');
  5286. // if (full && full != str)
  5287. // match--;
  5288. //
  5289. // // If str starts with '*' replace with s.
  5290. // if ((*str == '*') && strlen(s) >= match) {
  5291. // full = xstrdup(s);
  5292. // strncpy(full+strlen(s)-match+1, str+1, match-1);
  5293. // } else
  5294. // full = xstrndup(str, match);
  5295. // match = strncmp(s, full, strlen(full));
  5296. // free(full);
  5297. //
  5298. *loc2 = c;
  5299. if (match) // if (!match)
  5300. return loc;
  5301. if (quotes && *loc == CTLESC)
  5302. loc++;
  5303. loc++;
  5304. loc2++;
  5305. } while (c);
  5306. return 0;
  5307. }
  5308. static char *
  5309. scanright(char *startp, char *rmesc, char *rmescend, char *str, int quotes,
  5310. int zero)
  5311. {
  5312. int esc = 0;
  5313. char *loc;
  5314. char *loc2;
  5315. for (loc = str - 1, loc2 = rmescend; loc >= startp; loc2--) {
  5316. int match;
  5317. char c = *loc2;
  5318. const char *s = loc2;
  5319. if (zero) {
  5320. *loc2 = '\0';
  5321. s = rmesc;
  5322. }
  5323. match = pmatch(str, s);
  5324. *loc2 = c;
  5325. if (match)
  5326. return loc;
  5327. loc--;
  5328. if (quotes) {
  5329. if (--esc < 0) {
  5330. esc = esclen(startp, loc);
  5331. }
  5332. if (esc % 2) {
  5333. esc--;
  5334. loc--;
  5335. }
  5336. }
  5337. }
  5338. return 0;
  5339. }
  5340. static void varunset(const char *, const char *, const char *, int) NORETURN;
  5341. static void
  5342. varunset(const char *end, const char *var, const char *umsg, int varflags)
  5343. {
  5344. const char *msg;
  5345. const char *tail;
  5346. tail = nullstr;
  5347. msg = "parameter not set";
  5348. if (umsg) {
  5349. if (*end == CTLENDVAR) {
  5350. if (varflags & VSNUL)
  5351. tail = " or null";
  5352. } else
  5353. msg = umsg;
  5354. }
  5355. ash_msg_and_raise_error("%.*s: %s%s", end - var - 1, var, msg, tail);
  5356. }
  5357. #if ENABLE_ASH_BASH_COMPAT
  5358. static char *
  5359. parse_sub_pattern(char *arg, int inquotes)
  5360. {
  5361. char *idx, *repl = NULL;
  5362. unsigned char c;
  5363. idx = arg;
  5364. while (1) {
  5365. c = *arg;
  5366. if (!c)
  5367. break;
  5368. if (c == '/') {
  5369. /* Only the first '/' seen is our separator */
  5370. if (!repl) {
  5371. repl = idx + 1;
  5372. c = '\0';
  5373. }
  5374. }
  5375. *idx++ = c;
  5376. if (!inquotes && c == '\\' && arg[1] == '\\')
  5377. arg++; /* skip both \\, not just first one */
  5378. arg++;
  5379. }
  5380. *idx = c; /* NUL */
  5381. return repl;
  5382. }
  5383. #endif /* ENABLE_ASH_BASH_COMPAT */
  5384. static const char *
  5385. subevalvar(char *p, char *str, int strloc, int subtype,
  5386. int startloc, int varflags, int quotes, struct strlist *var_str_list)
  5387. {
  5388. struct nodelist *saveargbackq = argbackq;
  5389. char *startp;
  5390. char *loc;
  5391. char *rmesc, *rmescend;
  5392. USE_ASH_BASH_COMPAT(char *repl = NULL;)
  5393. USE_ASH_BASH_COMPAT(char null = '\0';)
  5394. USE_ASH_BASH_COMPAT(int pos, len, orig_len;)
  5395. int saveherefd = herefd;
  5396. int amount, workloc, resetloc;
  5397. int zero;
  5398. char *(*scan)(char*, char*, char*, char*, int, int);
  5399. herefd = -1;
  5400. argstr(p, (subtype != VSASSIGN && subtype != VSQUESTION) ? EXP_CASE : 0,
  5401. var_str_list);
  5402. STPUTC('\0', expdest);
  5403. herefd = saveherefd;
  5404. argbackq = saveargbackq;
  5405. startp = (char *)stackblock() + startloc;
  5406. switch (subtype) {
  5407. case VSASSIGN:
  5408. setvar(str, startp, 0);
  5409. amount = startp - expdest;
  5410. STADJUST(amount, expdest);
  5411. return startp;
  5412. #if ENABLE_ASH_BASH_COMPAT
  5413. case VSSUBSTR:
  5414. loc = str = stackblock() + strloc;
  5415. // TODO: number() instead? It does error checking...
  5416. pos = atoi(loc);
  5417. len = str - startp - 1;
  5418. /* *loc != '\0', guaranteed by parser */
  5419. if (quotes) {
  5420. char *ptr;
  5421. /* We must adjust the length by the number of escapes we find. */
  5422. for (ptr = startp; ptr < (str - 1); ptr++) {
  5423. if(*ptr == CTLESC) {
  5424. len--;
  5425. ptr++;
  5426. }
  5427. }
  5428. }
  5429. orig_len = len;
  5430. if (*loc++ == ':') {
  5431. // TODO: number() instead? It does error checking...
  5432. len = atoi(loc);
  5433. } else {
  5434. len = orig_len;
  5435. while (*loc && *loc != ':')
  5436. loc++;
  5437. if (*loc++ == ':')
  5438. // TODO: number() instead? It does error checking...
  5439. len = atoi(loc);
  5440. }
  5441. if (pos >= orig_len) {
  5442. pos = 0;
  5443. len = 0;
  5444. }
  5445. if (len > (orig_len - pos))
  5446. len = orig_len - pos;
  5447. for (str = startp; pos; str++, pos--) {
  5448. if (quotes && *str == CTLESC)
  5449. str++;
  5450. }
  5451. for (loc = startp; len; len--) {
  5452. if (quotes && *str == CTLESC)
  5453. *loc++ = *str++;
  5454. *loc++ = *str++;
  5455. }
  5456. *loc = '\0';
  5457. amount = loc - expdest;
  5458. STADJUST(amount, expdest);
  5459. return loc;
  5460. #endif
  5461. case VSQUESTION:
  5462. varunset(p, str, startp, varflags);
  5463. /* NOTREACHED */
  5464. }
  5465. resetloc = expdest - (char *)stackblock();
  5466. /* We'll comeback here if we grow the stack while handling
  5467. * a VSREPLACE or VSREPLACEALL, since our pointers into the
  5468. * stack will need rebasing, and we'll need to remove our work
  5469. * areas each time
  5470. */
  5471. USE_ASH_BASH_COMPAT(restart:)
  5472. amount = expdest - ((char *)stackblock() + resetloc);
  5473. STADJUST(-amount, expdest);
  5474. startp = (char *)stackblock() + startloc;
  5475. rmesc = startp;
  5476. rmescend = (char *)stackblock() + strloc;
  5477. if (quotes) {
  5478. rmesc = _rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
  5479. if (rmesc != startp) {
  5480. rmescend = expdest;
  5481. startp = (char *)stackblock() + startloc;
  5482. }
  5483. }
  5484. rmescend--;
  5485. str = (char *)stackblock() + strloc;
  5486. preglob(str, varflags & VSQUOTE, 0);
  5487. workloc = expdest - (char *)stackblock();
  5488. #if ENABLE_ASH_BASH_COMPAT
  5489. if (subtype == VSREPLACE || subtype == VSREPLACEALL) {
  5490. char *idx, *end, *restart_detect;
  5491. if(!repl) {
  5492. repl = parse_sub_pattern(str, varflags & VSQUOTE);
  5493. if (!repl)
  5494. repl = &null;
  5495. }
  5496. /* If there's no pattern to match, return the expansion unmolested */
  5497. if (*str == '\0')
  5498. return 0;
  5499. len = 0;
  5500. idx = startp;
  5501. end = str - 1;
  5502. while (idx < end) {
  5503. loc = scanright(idx, rmesc, rmescend, str, quotes, 1);
  5504. if (!loc) {
  5505. /* No match, advance */
  5506. restart_detect = stackblock();
  5507. STPUTC(*idx, expdest);
  5508. if (quotes && *idx == CTLESC) {
  5509. idx++;
  5510. len++;
  5511. STPUTC(*idx, expdest);
  5512. }
  5513. if (stackblock() != restart_detect)
  5514. goto restart;
  5515. idx++;
  5516. len++;
  5517. rmesc++;
  5518. continue;
  5519. }
  5520. if (subtype == VSREPLACEALL) {
  5521. while (idx < loc) {
  5522. if (quotes && *idx == CTLESC)
  5523. idx++;
  5524. idx++;
  5525. rmesc++;
  5526. }
  5527. } else
  5528. idx = loc;
  5529. for (loc = repl; *loc; loc++) {
  5530. restart_detect = stackblock();
  5531. STPUTC(*loc, expdest);
  5532. if (stackblock() != restart_detect)
  5533. goto restart;
  5534. len++;
  5535. }
  5536. if (subtype == VSREPLACE) {
  5537. while (*idx) {
  5538. restart_detect = stackblock();
  5539. STPUTC(*idx, expdest);
  5540. if (stackblock() != restart_detect)
  5541. goto restart;
  5542. len++;
  5543. idx++;
  5544. }
  5545. break;
  5546. }
  5547. }
  5548. /* We've put the replaced text into a buffer at workloc, now
  5549. * move it to the right place and adjust the stack.
  5550. */
  5551. startp = stackblock() + startloc;
  5552. STPUTC('\0', expdest);
  5553. memmove(startp, stackblock() + workloc, len);
  5554. startp[len++] = '\0';
  5555. amount = expdest - ((char *)stackblock() + startloc + len - 1);
  5556. STADJUST(-amount, expdest);
  5557. return startp;
  5558. }
  5559. #endif /* ENABLE_ASH_BASH_COMPAT */
  5560. subtype -= VSTRIMRIGHT;
  5561. #if DEBUG
  5562. if (subtype < 0 || subtype > 7)
  5563. abort();
  5564. #endif
  5565. /* zero = subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX */
  5566. zero = subtype >> 1;
  5567. /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
  5568. scan = (subtype & 1) ^ zero ? scanleft : scanright;
  5569. loc = scan(startp, rmesc, rmescend, str, quotes, zero);
  5570. if (loc) {
  5571. if (zero) {
  5572. memmove(startp, loc, str - loc);
  5573. loc = startp + (str - loc) - 1;
  5574. }
  5575. *loc = '\0';
  5576. amount = loc - expdest;
  5577. STADJUST(amount, expdest);
  5578. }
  5579. return loc;
  5580. }
  5581. /*
  5582. * Add the value of a specialized variable to the stack string.
  5583. */
  5584. static ssize_t
  5585. varvalue(char *name, int varflags, int flags, struct strlist *var_str_list)
  5586. {
  5587. int num;
  5588. char *p;
  5589. int i;
  5590. int sep = 0;
  5591. int sepq = 0;
  5592. ssize_t len = 0;
  5593. char **ap;
  5594. int syntax;
  5595. int quoted = varflags & VSQUOTE;
  5596. int subtype = varflags & VSTYPE;
  5597. int quotes = flags & (EXP_FULL | EXP_CASE);
  5598. if (quoted && (flags & EXP_FULL))
  5599. sep = 1 << CHAR_BIT;
  5600. syntax = quoted ? DQSYNTAX : BASESYNTAX;
  5601. switch (*name) {
  5602. case '$':
  5603. num = rootpid;
  5604. goto numvar;
  5605. case '?':
  5606. num = exitstatus;
  5607. goto numvar;
  5608. case '#':
  5609. num = shellparam.nparam;
  5610. goto numvar;
  5611. case '!':
  5612. num = backgndpid;
  5613. if (num == 0)
  5614. return -1;
  5615. numvar:
  5616. len = cvtnum(num);
  5617. break;
  5618. case '-':
  5619. p = makestrspace(NOPTS, expdest);
  5620. for (i = NOPTS - 1; i >= 0; i--) {
  5621. if (optlist[i]) {
  5622. USTPUTC(optletters(i), p);
  5623. len++;
  5624. }
  5625. }
  5626. expdest = p;
  5627. break;
  5628. case '@':
  5629. if (sep)
  5630. goto param;
  5631. /* fall through */
  5632. case '*':
  5633. sep = ifsset() ? signed_char2int(ifsval()[0]) : ' ';
  5634. if (quotes && (SIT(sep, syntax) == CCTL || SIT(sep, syntax) == CBACK))
  5635. sepq = 1;
  5636. param:
  5637. ap = shellparam.p;
  5638. if (!ap)
  5639. return -1;
  5640. while ((p = *ap++)) {
  5641. size_t partlen;
  5642. partlen = strlen(p);
  5643. len += partlen;
  5644. if (!(subtype == VSPLUS || subtype == VSLENGTH))
  5645. memtodest(p, partlen, syntax, quotes);
  5646. if (*ap && sep) {
  5647. char *q;
  5648. len++;
  5649. if (subtype == VSPLUS || subtype == VSLENGTH) {
  5650. continue;
  5651. }
  5652. q = expdest;
  5653. if (sepq)
  5654. STPUTC(CTLESC, q);
  5655. STPUTC(sep, q);
  5656. expdest = q;
  5657. }
  5658. }
  5659. return len;
  5660. case '0':
  5661. case '1':
  5662. case '2':
  5663. case '3':
  5664. case '4':
  5665. case '5':
  5666. case '6':
  5667. case '7':
  5668. case '8':
  5669. case '9':
  5670. // TODO: number() instead? It does error checking...
  5671. num = atoi(name);
  5672. if (num < 0 || num > shellparam.nparam)
  5673. return -1;
  5674. p = num ? shellparam.p[num - 1] : arg0;
  5675. goto value;
  5676. default:
  5677. /* NB: name has form "VAR=..." */
  5678. /* "A=a B=$A" case: var_str_list is a list of "A=a" strings
  5679. * which should be considered before we check variables. */
  5680. if (var_str_list) {
  5681. unsigned name_len = (strchrnul(name, '=') - name) + 1;
  5682. p = NULL;
  5683. do {
  5684. char *str, *eq;
  5685. str = var_str_list->text;
  5686. eq = strchr(str, '=');
  5687. if (!eq) /* stop at first non-assignment */
  5688. break;
  5689. eq++;
  5690. if (name_len == (unsigned)(eq - str)
  5691. && strncmp(str, name, name_len) == 0) {
  5692. p = eq;
  5693. /* goto value; - WRONG! */
  5694. /* think "A=1 A=2 B=$A" */
  5695. }
  5696. var_str_list = var_str_list->next;
  5697. } while (var_str_list);
  5698. if (p)
  5699. goto value;
  5700. }
  5701. p = lookupvar(name);
  5702. value:
  5703. if (!p)
  5704. return -1;
  5705. len = strlen(p);
  5706. if (!(subtype == VSPLUS || subtype == VSLENGTH))
  5707. memtodest(p, len, syntax, quotes);
  5708. return len;
  5709. }
  5710. if (subtype == VSPLUS || subtype == VSLENGTH)
  5711. STADJUST(-len, expdest);
  5712. return len;
  5713. }
  5714. /*
  5715. * Expand a variable, and return a pointer to the next character in the
  5716. * input string.
  5717. */
  5718. static char *
  5719. evalvar(char *p, int flag, struct strlist *var_str_list)
  5720. {
  5721. char varflags;
  5722. char subtype;
  5723. char quoted;
  5724. char easy;
  5725. char *var;
  5726. int patloc;
  5727. int startloc;
  5728. ssize_t varlen;
  5729. varflags = *p++;
  5730. subtype = varflags & VSTYPE;
  5731. quoted = varflags & VSQUOTE;
  5732. var = p;
  5733. easy = (!quoted || (*var == '@' && shellparam.nparam));
  5734. startloc = expdest - (char *)stackblock();
  5735. p = strchr(p, '=') + 1;
  5736. again:
  5737. varlen = varvalue(var, varflags, flag, var_str_list);
  5738. if (varflags & VSNUL)
  5739. varlen--;
  5740. if (subtype == VSPLUS) {
  5741. varlen = -1 - varlen;
  5742. goto vsplus;
  5743. }
  5744. if (subtype == VSMINUS) {
  5745. vsplus:
  5746. if (varlen < 0) {
  5747. argstr(
  5748. p, flag | EXP_TILDE |
  5749. (quoted ? EXP_QWORD : EXP_WORD),
  5750. var_str_list
  5751. );
  5752. goto end;
  5753. }
  5754. if (easy)
  5755. goto record;
  5756. goto end;
  5757. }
  5758. if (subtype == VSASSIGN || subtype == VSQUESTION) {
  5759. if (varlen < 0) {
  5760. if (subevalvar(p, var, /* strloc: */ 0,
  5761. subtype, startloc, varflags,
  5762. /* quotes: */ 0,
  5763. var_str_list)
  5764. ) {
  5765. varflags &= ~VSNUL;
  5766. /*
  5767. * Remove any recorded regions beyond
  5768. * start of variable
  5769. */
  5770. removerecordregions(startloc);
  5771. goto again;
  5772. }
  5773. goto end;
  5774. }
  5775. if (easy)
  5776. goto record;
  5777. goto end;
  5778. }
  5779. if (varlen < 0 && uflag)
  5780. varunset(p, var, 0, 0);
  5781. if (subtype == VSLENGTH) {
  5782. cvtnum(varlen > 0 ? varlen : 0);
  5783. goto record;
  5784. }
  5785. if (subtype == VSNORMAL) {
  5786. if (easy)
  5787. goto record;
  5788. goto end;
  5789. }
  5790. #if DEBUG
  5791. switch (subtype) {
  5792. case VSTRIMLEFT:
  5793. case VSTRIMLEFTMAX:
  5794. case VSTRIMRIGHT:
  5795. case VSTRIMRIGHTMAX:
  5796. #if ENABLE_ASH_BASH_COMPAT
  5797. case VSSUBSTR:
  5798. case VSREPLACE:
  5799. case VSREPLACEALL:
  5800. #endif
  5801. break;
  5802. default:
  5803. abort();
  5804. }
  5805. #endif
  5806. if (varlen >= 0) {
  5807. /*
  5808. * Terminate the string and start recording the pattern
  5809. * right after it
  5810. */
  5811. STPUTC('\0', expdest);
  5812. patloc = expdest - (char *)stackblock();
  5813. if (0 == subevalvar(p, /* str: */ NULL, patloc, subtype,
  5814. startloc, varflags,
  5815. /* quotes: */ flag & (EXP_FULL | EXP_CASE),
  5816. var_str_list)
  5817. ) {
  5818. int amount = expdest - (
  5819. (char *)stackblock() + patloc - 1
  5820. );
  5821. STADJUST(-amount, expdest);
  5822. }
  5823. /* Remove any recorded regions beyond start of variable */
  5824. removerecordregions(startloc);
  5825. record:
  5826. recordregion(startloc, expdest - (char *)stackblock(), quoted);
  5827. }
  5828. end:
  5829. if (subtype != VSNORMAL) { /* skip to end of alternative */
  5830. int nesting = 1;
  5831. for (;;) {
  5832. char c = *p++;
  5833. if (c == CTLESC)
  5834. p++;
  5835. else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
  5836. if (varlen >= 0)
  5837. argbackq = argbackq->next;
  5838. } else if (c == CTLVAR) {
  5839. if ((*p++ & VSTYPE) != VSNORMAL)
  5840. nesting++;
  5841. } else if (c == CTLENDVAR) {
  5842. if (--nesting == 0)
  5843. break;
  5844. }
  5845. }
  5846. }
  5847. return p;
  5848. }
  5849. /*
  5850. * Break the argument string into pieces based upon IFS and add the
  5851. * strings to the argument list. The regions of the string to be
  5852. * searched for IFS characters have been stored by recordregion.
  5853. */
  5854. static void
  5855. ifsbreakup(char *string, struct arglist *arglist)
  5856. {
  5857. struct ifsregion *ifsp;
  5858. struct strlist *sp;
  5859. char *start;
  5860. char *p;
  5861. char *q;
  5862. const char *ifs, *realifs;
  5863. int ifsspc;
  5864. int nulonly;
  5865. start = string;
  5866. if (ifslastp != NULL) {
  5867. ifsspc = 0;
  5868. nulonly = 0;
  5869. realifs = ifsset() ? ifsval() : defifs;
  5870. ifsp = &ifsfirst;
  5871. do {
  5872. p = string + ifsp->begoff;
  5873. nulonly = ifsp->nulonly;
  5874. ifs = nulonly ? nullstr : realifs;
  5875. ifsspc = 0;
  5876. while (p < string + ifsp->endoff) {
  5877. q = p;
  5878. if (*p == CTLESC)
  5879. p++;
  5880. if (!strchr(ifs, *p)) {
  5881. p++;
  5882. continue;
  5883. }
  5884. if (!nulonly)
  5885. ifsspc = (strchr(defifs, *p) != NULL);
  5886. /* Ignore IFS whitespace at start */
  5887. if (q == start && ifsspc) {
  5888. p++;
  5889. start = p;
  5890. continue;
  5891. }
  5892. *q = '\0';
  5893. sp = stzalloc(sizeof(*sp));
  5894. sp->text = start;
  5895. *arglist->lastp = sp;
  5896. arglist->lastp = &sp->next;
  5897. p++;
  5898. if (!nulonly) {
  5899. for (;;) {
  5900. if (p >= string + ifsp->endoff) {
  5901. break;
  5902. }
  5903. q = p;
  5904. if (*p == CTLESC)
  5905. p++;
  5906. if (strchr(ifs, *p) == NULL) {
  5907. p = q;
  5908. break;
  5909. }
  5910. if (strchr(defifs, *p) == NULL) {
  5911. if (ifsspc) {
  5912. p++;
  5913. ifsspc = 0;
  5914. } else {
  5915. p = q;
  5916. break;
  5917. }
  5918. } else
  5919. p++;
  5920. }
  5921. }
  5922. start = p;
  5923. } /* while */
  5924. ifsp = ifsp->next;
  5925. } while (ifsp != NULL);
  5926. if (nulonly)
  5927. goto add;
  5928. }
  5929. if (!*start)
  5930. return;
  5931. add:
  5932. sp = stzalloc(sizeof(*sp));
  5933. sp->text = start;
  5934. *arglist->lastp = sp;
  5935. arglist->lastp = &sp->next;
  5936. }
  5937. static void
  5938. ifsfree(void)
  5939. {
  5940. struct ifsregion *p;
  5941. INT_OFF;
  5942. p = ifsfirst.next;
  5943. do {
  5944. struct ifsregion *ifsp;
  5945. ifsp = p->next;
  5946. free(p);
  5947. p = ifsp;
  5948. } while (p);
  5949. ifslastp = NULL;
  5950. ifsfirst.next = NULL;
  5951. INT_ON;
  5952. }
  5953. /*
  5954. * Add a file name to the list.
  5955. */
  5956. static void
  5957. addfname(const char *name)
  5958. {
  5959. struct strlist *sp;
  5960. sp = stzalloc(sizeof(*sp));
  5961. sp->text = ststrdup(name);
  5962. *exparg.lastp = sp;
  5963. exparg.lastp = &sp->next;
  5964. }
  5965. static char *expdir;
  5966. /*
  5967. * Do metacharacter (i.e. *, ?, [...]) expansion.
  5968. */
  5969. static void
  5970. expmeta(char *enddir, char *name)
  5971. {
  5972. char *p;
  5973. const char *cp;
  5974. char *start;
  5975. char *endname;
  5976. int metaflag;
  5977. struct stat statb;
  5978. DIR *dirp;
  5979. struct dirent *dp;
  5980. int atend;
  5981. int matchdot;
  5982. metaflag = 0;
  5983. start = name;
  5984. for (p = name; *p; p++) {
  5985. if (*p == '*' || *p == '?')
  5986. metaflag = 1;
  5987. else if (*p == '[') {
  5988. char *q = p + 1;
  5989. if (*q == '!')
  5990. q++;
  5991. for (;;) {
  5992. if (*q == '\\')
  5993. q++;
  5994. if (*q == '/' || *q == '\0')
  5995. break;
  5996. if (*++q == ']') {
  5997. metaflag = 1;
  5998. break;
  5999. }
  6000. }
  6001. } else if (*p == '\\')
  6002. p++;
  6003. else if (*p == '/') {
  6004. if (metaflag)
  6005. goto out;
  6006. start = p + 1;
  6007. }
  6008. }
  6009. out:
  6010. if (metaflag == 0) { /* we've reached the end of the file name */
  6011. if (enddir != expdir)
  6012. metaflag++;
  6013. p = name;
  6014. do {
  6015. if (*p == '\\')
  6016. p++;
  6017. *enddir++ = *p;
  6018. } while (*p++);
  6019. if (metaflag == 0 || lstat(expdir, &statb) >= 0)
  6020. addfname(expdir);
  6021. return;
  6022. }
  6023. endname = p;
  6024. if (name < start) {
  6025. p = name;
  6026. do {
  6027. if (*p == '\\')
  6028. p++;
  6029. *enddir++ = *p++;
  6030. } while (p < start);
  6031. }
  6032. if (enddir == expdir) {
  6033. cp = ".";
  6034. } else if (enddir == expdir + 1 && *expdir == '/') {
  6035. cp = "/";
  6036. } else {
  6037. cp = expdir;
  6038. enddir[-1] = '\0';
  6039. }
  6040. dirp = opendir(cp);
  6041. if (dirp == NULL)
  6042. return;
  6043. if (enddir != expdir)
  6044. enddir[-1] = '/';
  6045. if (*endname == 0) {
  6046. atend = 1;
  6047. } else {
  6048. atend = 0;
  6049. *endname++ = '\0';
  6050. }
  6051. matchdot = 0;
  6052. p = start;
  6053. if (*p == '\\')
  6054. p++;
  6055. if (*p == '.')
  6056. matchdot++;
  6057. while (!intpending && (dp = readdir(dirp)) != NULL) {
  6058. if (dp->d_name[0] == '.' && !matchdot)
  6059. continue;
  6060. if (pmatch(start, dp->d_name)) {
  6061. if (atend) {
  6062. strcpy(enddir, dp->d_name);
  6063. addfname(expdir);
  6064. } else {
  6065. for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
  6066. continue;
  6067. p[-1] = '/';
  6068. expmeta(p, endname);
  6069. }
  6070. }
  6071. }
  6072. closedir(dirp);
  6073. if (!atend)
  6074. endname[-1] = '/';
  6075. }
  6076. static struct strlist *
  6077. msort(struct strlist *list, int len)
  6078. {
  6079. struct strlist *p, *q = NULL;
  6080. struct strlist **lpp;
  6081. int half;
  6082. int n;
  6083. if (len <= 1)
  6084. return list;
  6085. half = len >> 1;
  6086. p = list;
  6087. for (n = half; --n >= 0;) {
  6088. q = p;
  6089. p = p->next;
  6090. }
  6091. q->next = NULL; /* terminate first half of list */
  6092. q = msort(list, half); /* sort first half of list */
  6093. p = msort(p, len - half); /* sort second half */
  6094. lpp = &list;
  6095. for (;;) {
  6096. #if ENABLE_LOCALE_SUPPORT
  6097. if (strcoll(p->text, q->text) < 0)
  6098. #else
  6099. if (strcmp(p->text, q->text) < 0)
  6100. #endif
  6101. {
  6102. *lpp = p;
  6103. lpp = &p->next;
  6104. p = *lpp;
  6105. if (p == NULL) {
  6106. *lpp = q;
  6107. break;
  6108. }
  6109. } else {
  6110. *lpp = q;
  6111. lpp = &q->next;
  6112. q = *lpp;
  6113. if (q == NULL) {
  6114. *lpp = p;
  6115. break;
  6116. }
  6117. }
  6118. }
  6119. return list;
  6120. }
  6121. /*
  6122. * Sort the results of file name expansion. It calculates the number of
  6123. * strings to sort and then calls msort (short for merge sort) to do the
  6124. * work.
  6125. */
  6126. static struct strlist *
  6127. expsort(struct strlist *str)
  6128. {
  6129. int len;
  6130. struct strlist *sp;
  6131. len = 0;
  6132. for (sp = str; sp; sp = sp->next)
  6133. len++;
  6134. return msort(str, len);
  6135. }
  6136. static void
  6137. expandmeta(struct strlist *str /*, int flag*/)
  6138. {
  6139. static const char metachars[] ALIGN1 = {
  6140. '*', '?', '[', 0
  6141. };
  6142. /* TODO - EXP_REDIR */
  6143. while (str) {
  6144. struct strlist **savelastp;
  6145. struct strlist *sp;
  6146. char *p;
  6147. if (fflag)
  6148. goto nometa;
  6149. if (!strpbrk(str->text, metachars))
  6150. goto nometa;
  6151. savelastp = exparg.lastp;
  6152. INT_OFF;
  6153. p = preglob(str->text, 0, RMESCAPE_ALLOC | RMESCAPE_HEAP);
  6154. {
  6155. int i = strlen(str->text);
  6156. expdir = ckmalloc(i < 2048 ? 2048 : i); /* XXX */
  6157. }
  6158. expmeta(expdir, p);
  6159. free(expdir);
  6160. if (p != str->text)
  6161. free(p);
  6162. INT_ON;
  6163. if (exparg.lastp == savelastp) {
  6164. /*
  6165. * no matches
  6166. */
  6167. nometa:
  6168. *exparg.lastp = str;
  6169. rmescapes(str->text);
  6170. exparg.lastp = &str->next;
  6171. } else {
  6172. *exparg.lastp = NULL;
  6173. *savelastp = sp = expsort(*savelastp);
  6174. while (sp->next != NULL)
  6175. sp = sp->next;
  6176. exparg.lastp = &sp->next;
  6177. }
  6178. str = str->next;
  6179. }
  6180. }
  6181. /*
  6182. * Perform variable substitution and command substitution on an argument,
  6183. * placing the resulting list of arguments in arglist. If EXP_FULL is true,
  6184. * perform splitting and file name expansion. When arglist is NULL, perform
  6185. * here document expansion.
  6186. */
  6187. static void
  6188. expandarg(union node *arg, struct arglist *arglist, int flag)
  6189. {
  6190. struct strlist *sp;
  6191. char *p;
  6192. argbackq = arg->narg.backquote;
  6193. STARTSTACKSTR(expdest);
  6194. ifsfirst.next = NULL;
  6195. ifslastp = NULL;
  6196. argstr(arg->narg.text, flag,
  6197. /* var_str_list: */ arglist ? arglist->list : NULL);
  6198. p = _STPUTC('\0', expdest);
  6199. expdest = p - 1;
  6200. if (arglist == NULL) {
  6201. return; /* here document expanded */
  6202. }
  6203. p = grabstackstr(p);
  6204. exparg.lastp = &exparg.list;
  6205. /*
  6206. * TODO - EXP_REDIR
  6207. */
  6208. if (flag & EXP_FULL) {
  6209. ifsbreakup(p, &exparg);
  6210. *exparg.lastp = NULL;
  6211. exparg.lastp = &exparg.list;
  6212. expandmeta(exparg.list /*, flag*/);
  6213. } else {
  6214. if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
  6215. rmescapes(p);
  6216. sp = stzalloc(sizeof(*sp));
  6217. sp->text = p;
  6218. *exparg.lastp = sp;
  6219. exparg.lastp = &sp->next;
  6220. }
  6221. if (ifsfirst.next)
  6222. ifsfree();
  6223. *exparg.lastp = NULL;
  6224. if (exparg.list) {
  6225. *arglist->lastp = exparg.list;
  6226. arglist->lastp = exparg.lastp;
  6227. }
  6228. }
  6229. /*
  6230. * Expand shell variables and backquotes inside a here document.
  6231. */
  6232. static void
  6233. expandhere(union node *arg, int fd)
  6234. {
  6235. herefd = fd;
  6236. expandarg(arg, (struct arglist *)NULL, 0);
  6237. full_write(fd, stackblock(), expdest - (char *)stackblock());
  6238. }
  6239. /*
  6240. * Returns true if the pattern matches the string.
  6241. */
  6242. static int
  6243. patmatch(char *pattern, const char *string)
  6244. {
  6245. return pmatch(preglob(pattern, 0, 0), string);
  6246. }
  6247. /*
  6248. * See if a pattern matches in a case statement.
  6249. */
  6250. static int
  6251. casematch(union node *pattern, char *val)
  6252. {
  6253. struct stackmark smark;
  6254. int result;
  6255. setstackmark(&smark);
  6256. argbackq = pattern->narg.backquote;
  6257. STARTSTACKSTR(expdest);
  6258. ifslastp = NULL;
  6259. argstr(pattern->narg.text, EXP_TILDE | EXP_CASE,
  6260. /* var_str_list: */ NULL);
  6261. STACKSTRNUL(expdest);
  6262. result = patmatch(stackblock(), val);
  6263. popstackmark(&smark);
  6264. return result;
  6265. }
  6266. /* ============ find_command */
  6267. struct builtincmd {
  6268. const char *name;
  6269. int (*builtin)(int, char **);
  6270. /* unsigned flags; */
  6271. };
  6272. #define IS_BUILTIN_SPECIAL(b) ((b)->name[0] & 1)
  6273. /* "regular" builtins always take precedence over commands,
  6274. * regardless of PATH=....%builtin... position */
  6275. #define IS_BUILTIN_REGULAR(b) ((b)->name[0] & 2)
  6276. #define IS_BUILTIN_ASSIGN(b) ((b)->name[0] & 4)
  6277. struct cmdentry {
  6278. smallint cmdtype; /* CMDxxx */
  6279. union param {
  6280. int index;
  6281. /* index >= 0 for commands without path (slashes) */
  6282. /* (TODO: what exactly does the value mean? PATH position?) */
  6283. /* index == -1 for commands with slashes */
  6284. /* index == (-2 - applet_no) for NOFORK applets */
  6285. const struct builtincmd *cmd;
  6286. struct funcnode *func;
  6287. } u;
  6288. };
  6289. /* values of cmdtype */
  6290. #define CMDUNKNOWN -1 /* no entry in table for command */
  6291. #define CMDNORMAL 0 /* command is an executable program */
  6292. #define CMDFUNCTION 1 /* command is a shell function */
  6293. #define CMDBUILTIN 2 /* command is a shell builtin */
  6294. /* action to find_command() */
  6295. #define DO_ERR 0x01 /* prints errors */
  6296. #define DO_ABS 0x02 /* checks absolute paths */
  6297. #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
  6298. #define DO_ALTPATH 0x08 /* using alternate path */
  6299. #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
  6300. static void find_command(char *, struct cmdentry *, int, const char *);
  6301. /* ============ Hashing commands */
  6302. /*
  6303. * When commands are first encountered, they are entered in a hash table.
  6304. * This ensures that a full path search will not have to be done for them
  6305. * on each invocation.
  6306. *
  6307. * We should investigate converting to a linear search, even though that
  6308. * would make the command name "hash" a misnomer.
  6309. */
  6310. struct tblentry {
  6311. struct tblentry *next; /* next entry in hash chain */
  6312. union param param; /* definition of builtin function */
  6313. smallint cmdtype; /* CMDxxx */
  6314. char rehash; /* if set, cd done since entry created */
  6315. char cmdname[1]; /* name of command */
  6316. };
  6317. static struct tblentry **cmdtable;
  6318. #define INIT_G_cmdtable() do { \
  6319. cmdtable = xzalloc(CMDTABLESIZE * sizeof(cmdtable[0])); \
  6320. } while (0)
  6321. static int builtinloc = -1; /* index in path of %builtin, or -1 */
  6322. static void
  6323. tryexec(USE_FEATURE_SH_STANDALONE(int applet_no,) char *cmd, char **argv, char **envp)
  6324. {
  6325. int repeated = 0;
  6326. #if ENABLE_FEATURE_SH_STANDALONE
  6327. if (applet_no >= 0) {
  6328. if (APPLET_IS_NOEXEC(applet_no)) {
  6329. while (*envp)
  6330. putenv(*envp++);
  6331. run_applet_no_and_exit(applet_no, argv);
  6332. }
  6333. /* re-exec ourselves with the new arguments */
  6334. execve(bb_busybox_exec_path, argv, envp);
  6335. /* If they called chroot or otherwise made the binary no longer
  6336. * executable, fall through */
  6337. }
  6338. #endif
  6339. repeat:
  6340. #ifdef SYSV
  6341. do {
  6342. execve(cmd, argv, envp);
  6343. } while (errno == EINTR);
  6344. #else
  6345. execve(cmd, argv, envp);
  6346. #endif
  6347. if (repeated) {
  6348. free(argv);
  6349. return;
  6350. }
  6351. if (errno == ENOEXEC) {
  6352. char **ap;
  6353. char **new;
  6354. for (ap = argv; *ap; ap++)
  6355. continue;
  6356. ap = new = ckmalloc((ap - argv + 2) * sizeof(ap[0]));
  6357. ap[1] = cmd;
  6358. ap[0] = cmd = (char *)DEFAULT_SHELL;
  6359. ap += 2;
  6360. argv++;
  6361. while ((*ap++ = *argv++) != NULL)
  6362. continue;
  6363. argv = new;
  6364. repeated++;
  6365. goto repeat;
  6366. }
  6367. }
  6368. /*
  6369. * Exec a program. Never returns. If you change this routine, you may
  6370. * have to change the find_command routine as well.
  6371. */
  6372. static void shellexec(char **, const char *, int) NORETURN;
  6373. static void
  6374. shellexec(char **argv, const char *path, int idx)
  6375. {
  6376. char *cmdname;
  6377. int e;
  6378. char **envp;
  6379. int exerrno;
  6380. #if ENABLE_FEATURE_SH_STANDALONE
  6381. int applet_no = -1;
  6382. #endif
  6383. clearredir(/*drop:*/ 1);
  6384. envp = listvars(VEXPORT, VUNSET, 0);
  6385. if (strchr(argv[0], '/') != NULL
  6386. #if ENABLE_FEATURE_SH_STANDALONE
  6387. || (applet_no = find_applet_by_name(argv[0])) >= 0
  6388. #endif
  6389. ) {
  6390. tryexec(USE_FEATURE_SH_STANDALONE(applet_no,) argv[0], argv, envp);
  6391. e = errno;
  6392. } else {
  6393. e = ENOENT;
  6394. while ((cmdname = padvance(&path, argv[0])) != NULL) {
  6395. if (--idx < 0 && pathopt == NULL) {
  6396. tryexec(USE_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
  6397. if (errno != ENOENT && errno != ENOTDIR)
  6398. e = errno;
  6399. }
  6400. stunalloc(cmdname);
  6401. }
  6402. }
  6403. /* Map to POSIX errors */
  6404. switch (e) {
  6405. case EACCES:
  6406. exerrno = 126;
  6407. break;
  6408. case ENOENT:
  6409. exerrno = 127;
  6410. break;
  6411. default:
  6412. exerrno = 2;
  6413. break;
  6414. }
  6415. exitstatus = exerrno;
  6416. TRACE(("shellexec failed for %s, errno %d, suppressint %d\n",
  6417. argv[0], e, suppressint));
  6418. ash_msg_and_raise(EXEXEC, "%s: %s", argv[0], errmsg(e, "not found"));
  6419. /* NOTREACHED */
  6420. }
  6421. static void
  6422. printentry(struct tblentry *cmdp)
  6423. {
  6424. int idx;
  6425. const char *path;
  6426. char *name;
  6427. idx = cmdp->param.index;
  6428. path = pathval();
  6429. do {
  6430. name = padvance(&path, cmdp->cmdname);
  6431. stunalloc(name);
  6432. } while (--idx >= 0);
  6433. out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
  6434. }
  6435. /*
  6436. * Clear out command entries. The argument specifies the first entry in
  6437. * PATH which has changed.
  6438. */
  6439. static void
  6440. clearcmdentry(int firstchange)
  6441. {
  6442. struct tblentry **tblp;
  6443. struct tblentry **pp;
  6444. struct tblentry *cmdp;
  6445. INT_OFF;
  6446. for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
  6447. pp = tblp;
  6448. while ((cmdp = *pp) != NULL) {
  6449. if ((cmdp->cmdtype == CMDNORMAL &&
  6450. cmdp->param.index >= firstchange)
  6451. || (cmdp->cmdtype == CMDBUILTIN &&
  6452. builtinloc >= firstchange)
  6453. ) {
  6454. *pp = cmdp->next;
  6455. free(cmdp);
  6456. } else {
  6457. pp = &cmdp->next;
  6458. }
  6459. }
  6460. }
  6461. INT_ON;
  6462. }
  6463. /*
  6464. * Locate a command in the command hash table. If "add" is nonzero,
  6465. * add the command to the table if it is not already present. The
  6466. * variable "lastcmdentry" is set to point to the address of the link
  6467. * pointing to the entry, so that delete_cmd_entry can delete the
  6468. * entry.
  6469. *
  6470. * Interrupts must be off if called with add != 0.
  6471. */
  6472. static struct tblentry **lastcmdentry;
  6473. static struct tblentry *
  6474. cmdlookup(const char *name, int add)
  6475. {
  6476. unsigned int hashval;
  6477. const char *p;
  6478. struct tblentry *cmdp;
  6479. struct tblentry **pp;
  6480. p = name;
  6481. hashval = (unsigned char)*p << 4;
  6482. while (*p)
  6483. hashval += (unsigned char)*p++;
  6484. hashval &= 0x7FFF;
  6485. pp = &cmdtable[hashval % CMDTABLESIZE];
  6486. for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
  6487. if (strcmp(cmdp->cmdname, name) == 0)
  6488. break;
  6489. pp = &cmdp->next;
  6490. }
  6491. if (add && cmdp == NULL) {
  6492. cmdp = *pp = ckzalloc(sizeof(struct tblentry)
  6493. + strlen(name)
  6494. /* + 1 - already done because
  6495. * tblentry::cmdname is char[1] */);
  6496. /*cmdp->next = NULL; - ckzalloc did it */
  6497. cmdp->cmdtype = CMDUNKNOWN;
  6498. strcpy(cmdp->cmdname, name);
  6499. }
  6500. lastcmdentry = pp;
  6501. return cmdp;
  6502. }
  6503. /*
  6504. * Delete the command entry returned on the last lookup.
  6505. */
  6506. static void
  6507. delete_cmd_entry(void)
  6508. {
  6509. struct tblentry *cmdp;
  6510. INT_OFF;
  6511. cmdp = *lastcmdentry;
  6512. *lastcmdentry = cmdp->next;
  6513. if (cmdp->cmdtype == CMDFUNCTION)
  6514. freefunc(cmdp->param.func);
  6515. free(cmdp);
  6516. INT_ON;
  6517. }
  6518. /*
  6519. * Add a new command entry, replacing any existing command entry for
  6520. * the same name - except special builtins.
  6521. */
  6522. static void
  6523. addcmdentry(char *name, struct cmdentry *entry)
  6524. {
  6525. struct tblentry *cmdp;
  6526. cmdp = cmdlookup(name, 1);
  6527. if (cmdp->cmdtype == CMDFUNCTION) {
  6528. freefunc(cmdp->param.func);
  6529. }
  6530. cmdp->cmdtype = entry->cmdtype;
  6531. cmdp->param = entry->u;
  6532. cmdp->rehash = 0;
  6533. }
  6534. static int
  6535. hashcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  6536. {
  6537. struct tblentry **pp;
  6538. struct tblentry *cmdp;
  6539. int c;
  6540. struct cmdentry entry;
  6541. char *name;
  6542. if (nextopt("r") != '\0') {
  6543. clearcmdentry(0);
  6544. return 0;
  6545. }
  6546. if (*argptr == NULL) {
  6547. for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
  6548. for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
  6549. if (cmdp->cmdtype == CMDNORMAL)
  6550. printentry(cmdp);
  6551. }
  6552. }
  6553. return 0;
  6554. }
  6555. c = 0;
  6556. while ((name = *argptr) != NULL) {
  6557. cmdp = cmdlookup(name, 0);
  6558. if (cmdp != NULL
  6559. && (cmdp->cmdtype == CMDNORMAL
  6560. || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
  6561. ) {
  6562. delete_cmd_entry();
  6563. }
  6564. find_command(name, &entry, DO_ERR, pathval());
  6565. if (entry.cmdtype == CMDUNKNOWN)
  6566. c = 1;
  6567. argptr++;
  6568. }
  6569. return c;
  6570. }
  6571. /*
  6572. * Called when a cd is done. Marks all commands so the next time they
  6573. * are executed they will be rehashed.
  6574. */
  6575. static void
  6576. hashcd(void)
  6577. {
  6578. struct tblentry **pp;
  6579. struct tblentry *cmdp;
  6580. for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
  6581. for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
  6582. if (cmdp->cmdtype == CMDNORMAL
  6583. || (cmdp->cmdtype == CMDBUILTIN
  6584. && !IS_BUILTIN_REGULAR(cmdp->param.cmd)
  6585. && builtinloc > 0)
  6586. ) {
  6587. cmdp->rehash = 1;
  6588. }
  6589. }
  6590. }
  6591. }
  6592. /*
  6593. * Fix command hash table when PATH changed.
  6594. * Called before PATH is changed. The argument is the new value of PATH;
  6595. * pathval() still returns the old value at this point.
  6596. * Called with interrupts off.
  6597. */
  6598. static void
  6599. changepath(const char *new)
  6600. {
  6601. const char *old;
  6602. int firstchange;
  6603. int idx;
  6604. int idx_bltin;
  6605. old = pathval();
  6606. firstchange = 9999; /* assume no change */
  6607. idx = 0;
  6608. idx_bltin = -1;
  6609. for (;;) {
  6610. if (*old != *new) {
  6611. firstchange = idx;
  6612. if ((*old == '\0' && *new == ':')
  6613. || (*old == ':' && *new == '\0'))
  6614. firstchange++;
  6615. old = new; /* ignore subsequent differences */
  6616. }
  6617. if (*new == '\0')
  6618. break;
  6619. if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
  6620. idx_bltin = idx;
  6621. if (*new == ':')
  6622. idx++;
  6623. new++, old++;
  6624. }
  6625. if (builtinloc < 0 && idx_bltin >= 0)
  6626. builtinloc = idx_bltin; /* zap builtins */
  6627. if (builtinloc >= 0 && idx_bltin < 0)
  6628. firstchange = 0;
  6629. clearcmdentry(firstchange);
  6630. builtinloc = idx_bltin;
  6631. }
  6632. #define TEOF 0
  6633. #define TNL 1
  6634. #define TREDIR 2
  6635. #define TWORD 3
  6636. #define TSEMI 4
  6637. #define TBACKGND 5
  6638. #define TAND 6
  6639. #define TOR 7
  6640. #define TPIPE 8
  6641. #define TLP 9
  6642. #define TRP 10
  6643. #define TENDCASE 11
  6644. #define TENDBQUOTE 12
  6645. #define TNOT 13
  6646. #define TCASE 14
  6647. #define TDO 15
  6648. #define TDONE 16
  6649. #define TELIF 17
  6650. #define TELSE 18
  6651. #define TESAC 19
  6652. #define TFI 20
  6653. #define TFOR 21
  6654. #define TIF 22
  6655. #define TIN 23
  6656. #define TTHEN 24
  6657. #define TUNTIL 25
  6658. #define TWHILE 26
  6659. #define TBEGIN 27
  6660. #define TEND 28
  6661. typedef smallint token_id_t;
  6662. /* first char is indicating which tokens mark the end of a list */
  6663. static const char *const tokname_array[] = {
  6664. "\1end of file",
  6665. "\0newline",
  6666. "\0redirection",
  6667. "\0word",
  6668. "\0;",
  6669. "\0&",
  6670. "\0&&",
  6671. "\0||",
  6672. "\0|",
  6673. "\0(",
  6674. "\1)",
  6675. "\1;;",
  6676. "\1`",
  6677. #define KWDOFFSET 13
  6678. /* the following are keywords */
  6679. "\0!",
  6680. "\0case",
  6681. "\1do",
  6682. "\1done",
  6683. "\1elif",
  6684. "\1else",
  6685. "\1esac",
  6686. "\1fi",
  6687. "\0for",
  6688. "\0if",
  6689. "\0in",
  6690. "\1then",
  6691. "\0until",
  6692. "\0while",
  6693. "\0{",
  6694. "\1}",
  6695. };
  6696. static const char *
  6697. tokname(int tok)
  6698. {
  6699. static char buf[16];
  6700. //try this:
  6701. //if (tok < TSEMI) return tokname_array[tok] + 1;
  6702. //sprintf(buf, "\"%s\"", tokname_array[tok] + 1);
  6703. //return buf;
  6704. if (tok >= TSEMI)
  6705. buf[0] = '"';
  6706. sprintf(buf + (tok >= TSEMI), "%s%c",
  6707. tokname_array[tok] + 1, (tok >= TSEMI ? '"' : 0));
  6708. return buf;
  6709. }
  6710. /* Wrapper around strcmp for qsort/bsearch/... */
  6711. static int
  6712. pstrcmp(const void *a, const void *b)
  6713. {
  6714. return strcmp((char*) a, (*(char**) b) + 1);
  6715. }
  6716. static const char *const *
  6717. findkwd(const char *s)
  6718. {
  6719. return bsearch(s, tokname_array + KWDOFFSET,
  6720. ARRAY_SIZE(tokname_array) - KWDOFFSET,
  6721. sizeof(tokname_array[0]), pstrcmp);
  6722. }
  6723. /*
  6724. * Locate and print what a word is...
  6725. */
  6726. static int
  6727. describe_command(char *command, int describe_command_verbose)
  6728. {
  6729. struct cmdentry entry;
  6730. struct tblentry *cmdp;
  6731. #if ENABLE_ASH_ALIAS
  6732. const struct alias *ap;
  6733. #endif
  6734. const char *path = pathval();
  6735. if (describe_command_verbose) {
  6736. out1str(command);
  6737. }
  6738. /* First look at the keywords */
  6739. if (findkwd(command)) {
  6740. out1str(describe_command_verbose ? " is a shell keyword" : command);
  6741. goto out;
  6742. }
  6743. #if ENABLE_ASH_ALIAS
  6744. /* Then look at the aliases */
  6745. ap = lookupalias(command, 0);
  6746. if (ap != NULL) {
  6747. if (!describe_command_verbose) {
  6748. out1str("alias ");
  6749. printalias(ap);
  6750. return 0;
  6751. }
  6752. out1fmt(" is an alias for %s", ap->val);
  6753. goto out;
  6754. }
  6755. #endif
  6756. /* Then check if it is a tracked alias */
  6757. cmdp = cmdlookup(command, 0);
  6758. if (cmdp != NULL) {
  6759. entry.cmdtype = cmdp->cmdtype;
  6760. entry.u = cmdp->param;
  6761. } else {
  6762. /* Finally use brute force */
  6763. find_command(command, &entry, DO_ABS, path);
  6764. }
  6765. switch (entry.cmdtype) {
  6766. case CMDNORMAL: {
  6767. int j = entry.u.index;
  6768. char *p;
  6769. if (j < 0) {
  6770. p = command;
  6771. } else {
  6772. do {
  6773. p = padvance(&path, command);
  6774. stunalloc(p);
  6775. } while (--j >= 0);
  6776. }
  6777. if (describe_command_verbose) {
  6778. out1fmt(" is%s %s",
  6779. (cmdp ? " a tracked alias for" : nullstr), p
  6780. );
  6781. } else {
  6782. out1str(p);
  6783. }
  6784. break;
  6785. }
  6786. case CMDFUNCTION:
  6787. if (describe_command_verbose) {
  6788. out1str(" is a shell function");
  6789. } else {
  6790. out1str(command);
  6791. }
  6792. break;
  6793. case CMDBUILTIN:
  6794. if (describe_command_verbose) {
  6795. out1fmt(" is a %sshell builtin",
  6796. IS_BUILTIN_SPECIAL(entry.u.cmd) ?
  6797. "special " : nullstr
  6798. );
  6799. } else {
  6800. out1str(command);
  6801. }
  6802. break;
  6803. default:
  6804. if (describe_command_verbose) {
  6805. out1str(": not found\n");
  6806. }
  6807. return 127;
  6808. }
  6809. out:
  6810. outstr("\n", stdout);
  6811. return 0;
  6812. }
  6813. static int
  6814. typecmd(int argc UNUSED_PARAM, char **argv)
  6815. {
  6816. int i = 1;
  6817. int err = 0;
  6818. int verbose = 1;
  6819. /* type -p ... ? (we don't bother checking for 'p') */
  6820. if (argv[1] && argv[1][0] == '-') {
  6821. i++;
  6822. verbose = 0;
  6823. }
  6824. while (argv[i]) {
  6825. err |= describe_command(argv[i++], verbose);
  6826. }
  6827. return err;
  6828. }
  6829. #if ENABLE_ASH_CMDCMD
  6830. static int
  6831. commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  6832. {
  6833. int c;
  6834. enum {
  6835. VERIFY_BRIEF = 1,
  6836. VERIFY_VERBOSE = 2,
  6837. } verify = 0;
  6838. while ((c = nextopt("pvV")) != '\0')
  6839. if (c == 'V')
  6840. verify |= VERIFY_VERBOSE;
  6841. else if (c == 'v')
  6842. verify |= VERIFY_BRIEF;
  6843. #if DEBUG
  6844. else if (c != 'p')
  6845. abort();
  6846. #endif
  6847. /* Mimic bash: just "command -v" doesn't complain, it's a nop */
  6848. if (verify && (*argptr != NULL)) {
  6849. return describe_command(*argptr, verify - VERIFY_BRIEF);
  6850. }
  6851. return 0;
  6852. }
  6853. #endif
  6854. /* ============ eval.c */
  6855. static int funcblocksize; /* size of structures in function */
  6856. static int funcstringsize; /* size of strings in node */
  6857. static void *funcblock; /* block to allocate function from */
  6858. static char *funcstring; /* block to allocate strings from */
  6859. /* flags in argument to evaltree */
  6860. #define EV_EXIT 01 /* exit after evaluating tree */
  6861. #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
  6862. #define EV_BACKCMD 04 /* command executing within back quotes */
  6863. static const short nodesize[26] = {
  6864. SHELL_ALIGN(sizeof(struct ncmd)),
  6865. SHELL_ALIGN(sizeof(struct npipe)),
  6866. SHELL_ALIGN(sizeof(struct nredir)),
  6867. SHELL_ALIGN(sizeof(struct nredir)),
  6868. SHELL_ALIGN(sizeof(struct nredir)),
  6869. SHELL_ALIGN(sizeof(struct nbinary)),
  6870. SHELL_ALIGN(sizeof(struct nbinary)),
  6871. SHELL_ALIGN(sizeof(struct nbinary)),
  6872. SHELL_ALIGN(sizeof(struct nif)),
  6873. SHELL_ALIGN(sizeof(struct nbinary)),
  6874. SHELL_ALIGN(sizeof(struct nbinary)),
  6875. SHELL_ALIGN(sizeof(struct nfor)),
  6876. SHELL_ALIGN(sizeof(struct ncase)),
  6877. SHELL_ALIGN(sizeof(struct nclist)),
  6878. SHELL_ALIGN(sizeof(struct narg)),
  6879. SHELL_ALIGN(sizeof(struct narg)),
  6880. SHELL_ALIGN(sizeof(struct nfile)),
  6881. SHELL_ALIGN(sizeof(struct nfile)),
  6882. SHELL_ALIGN(sizeof(struct nfile)),
  6883. SHELL_ALIGN(sizeof(struct nfile)),
  6884. SHELL_ALIGN(sizeof(struct nfile)),
  6885. SHELL_ALIGN(sizeof(struct ndup)),
  6886. SHELL_ALIGN(sizeof(struct ndup)),
  6887. SHELL_ALIGN(sizeof(struct nhere)),
  6888. SHELL_ALIGN(sizeof(struct nhere)),
  6889. SHELL_ALIGN(sizeof(struct nnot)),
  6890. };
  6891. static void calcsize(union node *n);
  6892. static void
  6893. sizenodelist(struct nodelist *lp)
  6894. {
  6895. while (lp) {
  6896. funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
  6897. calcsize(lp->n);
  6898. lp = lp->next;
  6899. }
  6900. }
  6901. static void
  6902. calcsize(union node *n)
  6903. {
  6904. if (n == NULL)
  6905. return;
  6906. funcblocksize += nodesize[n->type];
  6907. switch (n->type) {
  6908. case NCMD:
  6909. calcsize(n->ncmd.redirect);
  6910. calcsize(n->ncmd.args);
  6911. calcsize(n->ncmd.assign);
  6912. break;
  6913. case NPIPE:
  6914. sizenodelist(n->npipe.cmdlist);
  6915. break;
  6916. case NREDIR:
  6917. case NBACKGND:
  6918. case NSUBSHELL:
  6919. calcsize(n->nredir.redirect);
  6920. calcsize(n->nredir.n);
  6921. break;
  6922. case NAND:
  6923. case NOR:
  6924. case NSEMI:
  6925. case NWHILE:
  6926. case NUNTIL:
  6927. calcsize(n->nbinary.ch2);
  6928. calcsize(n->nbinary.ch1);
  6929. break;
  6930. case NIF:
  6931. calcsize(n->nif.elsepart);
  6932. calcsize(n->nif.ifpart);
  6933. calcsize(n->nif.test);
  6934. break;
  6935. case NFOR:
  6936. funcstringsize += strlen(n->nfor.var) + 1;
  6937. calcsize(n->nfor.body);
  6938. calcsize(n->nfor.args);
  6939. break;
  6940. case NCASE:
  6941. calcsize(n->ncase.cases);
  6942. calcsize(n->ncase.expr);
  6943. break;
  6944. case NCLIST:
  6945. calcsize(n->nclist.body);
  6946. calcsize(n->nclist.pattern);
  6947. calcsize(n->nclist.next);
  6948. break;
  6949. case NDEFUN:
  6950. case NARG:
  6951. sizenodelist(n->narg.backquote);
  6952. funcstringsize += strlen(n->narg.text) + 1;
  6953. calcsize(n->narg.next);
  6954. break;
  6955. case NTO:
  6956. case NCLOBBER:
  6957. case NFROM:
  6958. case NFROMTO:
  6959. case NAPPEND:
  6960. calcsize(n->nfile.fname);
  6961. calcsize(n->nfile.next);
  6962. break;
  6963. case NTOFD:
  6964. case NFROMFD:
  6965. calcsize(n->ndup.vname);
  6966. calcsize(n->ndup.next);
  6967. break;
  6968. case NHERE:
  6969. case NXHERE:
  6970. calcsize(n->nhere.doc);
  6971. calcsize(n->nhere.next);
  6972. break;
  6973. case NNOT:
  6974. calcsize(n->nnot.com);
  6975. break;
  6976. };
  6977. }
  6978. static char *
  6979. nodeckstrdup(char *s)
  6980. {
  6981. char *rtn = funcstring;
  6982. strcpy(funcstring, s);
  6983. funcstring += strlen(s) + 1;
  6984. return rtn;
  6985. }
  6986. static union node *copynode(union node *);
  6987. static struct nodelist *
  6988. copynodelist(struct nodelist *lp)
  6989. {
  6990. struct nodelist *start;
  6991. struct nodelist **lpp;
  6992. lpp = &start;
  6993. while (lp) {
  6994. *lpp = funcblock;
  6995. funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
  6996. (*lpp)->n = copynode(lp->n);
  6997. lp = lp->next;
  6998. lpp = &(*lpp)->next;
  6999. }
  7000. *lpp = NULL;
  7001. return start;
  7002. }
  7003. static union node *
  7004. copynode(union node *n)
  7005. {
  7006. union node *new;
  7007. if (n == NULL)
  7008. return NULL;
  7009. new = funcblock;
  7010. funcblock = (char *) funcblock + nodesize[n->type];
  7011. switch (n->type) {
  7012. case NCMD:
  7013. new->ncmd.redirect = copynode(n->ncmd.redirect);
  7014. new->ncmd.args = copynode(n->ncmd.args);
  7015. new->ncmd.assign = copynode(n->ncmd.assign);
  7016. break;
  7017. case NPIPE:
  7018. new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
  7019. new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
  7020. break;
  7021. case NREDIR:
  7022. case NBACKGND:
  7023. case NSUBSHELL:
  7024. new->nredir.redirect = copynode(n->nredir.redirect);
  7025. new->nredir.n = copynode(n->nredir.n);
  7026. break;
  7027. case NAND:
  7028. case NOR:
  7029. case NSEMI:
  7030. case NWHILE:
  7031. case NUNTIL:
  7032. new->nbinary.ch2 = copynode(n->nbinary.ch2);
  7033. new->nbinary.ch1 = copynode(n->nbinary.ch1);
  7034. break;
  7035. case NIF:
  7036. new->nif.elsepart = copynode(n->nif.elsepart);
  7037. new->nif.ifpart = copynode(n->nif.ifpart);
  7038. new->nif.test = copynode(n->nif.test);
  7039. break;
  7040. case NFOR:
  7041. new->nfor.var = nodeckstrdup(n->nfor.var);
  7042. new->nfor.body = copynode(n->nfor.body);
  7043. new->nfor.args = copynode(n->nfor.args);
  7044. break;
  7045. case NCASE:
  7046. new->ncase.cases = copynode(n->ncase.cases);
  7047. new->ncase.expr = copynode(n->ncase.expr);
  7048. break;
  7049. case NCLIST:
  7050. new->nclist.body = copynode(n->nclist.body);
  7051. new->nclist.pattern = copynode(n->nclist.pattern);
  7052. new->nclist.next = copynode(n->nclist.next);
  7053. break;
  7054. case NDEFUN:
  7055. case NARG:
  7056. new->narg.backquote = copynodelist(n->narg.backquote);
  7057. new->narg.text = nodeckstrdup(n->narg.text);
  7058. new->narg.next = copynode(n->narg.next);
  7059. break;
  7060. case NTO:
  7061. case NCLOBBER:
  7062. case NFROM:
  7063. case NFROMTO:
  7064. case NAPPEND:
  7065. new->nfile.fname = copynode(n->nfile.fname);
  7066. new->nfile.fd = n->nfile.fd;
  7067. new->nfile.next = copynode(n->nfile.next);
  7068. break;
  7069. case NTOFD:
  7070. case NFROMFD:
  7071. new->ndup.vname = copynode(n->ndup.vname);
  7072. new->ndup.dupfd = n->ndup.dupfd;
  7073. new->ndup.fd = n->ndup.fd;
  7074. new->ndup.next = copynode(n->ndup.next);
  7075. break;
  7076. case NHERE:
  7077. case NXHERE:
  7078. new->nhere.doc = copynode(n->nhere.doc);
  7079. new->nhere.fd = n->nhere.fd;
  7080. new->nhere.next = copynode(n->nhere.next);
  7081. break;
  7082. case NNOT:
  7083. new->nnot.com = copynode(n->nnot.com);
  7084. break;
  7085. };
  7086. new->type = n->type;
  7087. return new;
  7088. }
  7089. /*
  7090. * Make a copy of a parse tree.
  7091. */
  7092. static struct funcnode *
  7093. copyfunc(union node *n)
  7094. {
  7095. struct funcnode *f;
  7096. size_t blocksize;
  7097. funcblocksize = offsetof(struct funcnode, n);
  7098. funcstringsize = 0;
  7099. calcsize(n);
  7100. blocksize = funcblocksize;
  7101. f = ckmalloc(blocksize + funcstringsize);
  7102. funcblock = (char *) f + offsetof(struct funcnode, n);
  7103. funcstring = (char *) f + blocksize;
  7104. copynode(n);
  7105. f->count = 0;
  7106. return f;
  7107. }
  7108. /*
  7109. * Define a shell function.
  7110. */
  7111. static void
  7112. defun(char *name, union node *func)
  7113. {
  7114. struct cmdentry entry;
  7115. INT_OFF;
  7116. entry.cmdtype = CMDFUNCTION;
  7117. entry.u.func = copyfunc(func);
  7118. addcmdentry(name, &entry);
  7119. INT_ON;
  7120. }
  7121. static int evalskip; /* set if we are skipping commands */
  7122. /* reasons for skipping commands (see comment on breakcmd routine) */
  7123. #define SKIPBREAK (1 << 0)
  7124. #define SKIPCONT (1 << 1)
  7125. #define SKIPFUNC (1 << 2)
  7126. #define SKIPFILE (1 << 3)
  7127. #define SKIPEVAL (1 << 4)
  7128. static int skipcount; /* number of levels to skip */
  7129. static int funcnest; /* depth of function calls */
  7130. static int loopnest; /* current loop nesting level */
  7131. /* forward decl way out to parsing code - dotrap needs it */
  7132. static int evalstring(char *s, int mask);
  7133. /*
  7134. * Called to execute a trap. Perhaps we should avoid entering new trap
  7135. * handlers while we are executing a trap handler.
  7136. */
  7137. static int
  7138. dotrap(void)
  7139. {
  7140. char *p;
  7141. char *q;
  7142. int i;
  7143. int savestatus;
  7144. int skip;
  7145. savestatus = exitstatus;
  7146. pendingsig = 0;
  7147. xbarrier();
  7148. for (i = 1, q = gotsig; i < NSIG; i++, q++) {
  7149. if (!*q)
  7150. continue;
  7151. *q = '\0';
  7152. p = trap[i];
  7153. if (!p)
  7154. continue;
  7155. skip = evalstring(p, SKIPEVAL);
  7156. exitstatus = savestatus;
  7157. if (skip)
  7158. return skip;
  7159. }
  7160. return 0;
  7161. }
  7162. /* forward declarations - evaluation is fairly recursive business... */
  7163. static void evalloop(union node *, int);
  7164. static void evalfor(union node *, int);
  7165. static void evalcase(union node *, int);
  7166. static void evalsubshell(union node *, int);
  7167. static void expredir(union node *);
  7168. static void evalpipe(union node *, int);
  7169. static void evalcommand(union node *, int);
  7170. static int evalbltin(const struct builtincmd *, int, char **);
  7171. static void prehash(union node *);
  7172. /*
  7173. * Evaluate a parse tree. The value is left in the global variable
  7174. * exitstatus.
  7175. */
  7176. static void
  7177. evaltree(union node *n, int flags)
  7178. {
  7179. struct jmploc *volatile savehandler = exception_handler;
  7180. struct jmploc jmploc;
  7181. int checkexit = 0;
  7182. void (*evalfn)(union node *, int);
  7183. int status;
  7184. if (n == NULL) {
  7185. TRACE(("evaltree(NULL) called\n"));
  7186. goto out1;
  7187. }
  7188. TRACE(("pid %d, evaltree(%p: %d, %d) called\n",
  7189. getpid(), n, n->type, flags));
  7190. exception_handler = &jmploc;
  7191. {
  7192. int err = setjmp(jmploc.loc);
  7193. if (err) {
  7194. /* if it was a signal, check for trap handlers */
  7195. if (exception == EXSIG)
  7196. goto out;
  7197. /* continue on the way out */
  7198. exception_handler = savehandler;
  7199. longjmp(exception_handler->loc, err);
  7200. }
  7201. }
  7202. switch (n->type) {
  7203. default:
  7204. #if DEBUG
  7205. out1fmt("Node type = %d\n", n->type);
  7206. fflush(stdout);
  7207. break;
  7208. #endif
  7209. case NNOT:
  7210. evaltree(n->nnot.com, EV_TESTED);
  7211. status = !exitstatus;
  7212. goto setstatus;
  7213. case NREDIR:
  7214. expredir(n->nredir.redirect);
  7215. status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
  7216. if (!status) {
  7217. evaltree(n->nredir.n, flags & EV_TESTED);
  7218. status = exitstatus;
  7219. }
  7220. popredir(/*drop:*/ 0, /*restore:*/ 0 /* not sure */);
  7221. goto setstatus;
  7222. case NCMD:
  7223. evalfn = evalcommand;
  7224. checkexit:
  7225. if (eflag && !(flags & EV_TESTED))
  7226. checkexit = ~0;
  7227. goto calleval;
  7228. case NFOR:
  7229. evalfn = evalfor;
  7230. goto calleval;
  7231. case NWHILE:
  7232. case NUNTIL:
  7233. evalfn = evalloop;
  7234. goto calleval;
  7235. case NSUBSHELL:
  7236. case NBACKGND:
  7237. evalfn = evalsubshell;
  7238. goto calleval;
  7239. case NPIPE:
  7240. evalfn = evalpipe;
  7241. goto checkexit;
  7242. case NCASE:
  7243. evalfn = evalcase;
  7244. goto calleval;
  7245. case NAND:
  7246. case NOR:
  7247. case NSEMI: {
  7248. #if NAND + 1 != NOR
  7249. #error NAND + 1 != NOR
  7250. #endif
  7251. #if NOR + 1 != NSEMI
  7252. #error NOR + 1 != NSEMI
  7253. #endif
  7254. unsigned is_or = n->type - NAND;
  7255. evaltree(
  7256. n->nbinary.ch1,
  7257. (flags | ((is_or >> 1) - 1)) & EV_TESTED
  7258. );
  7259. if (!exitstatus == is_or)
  7260. break;
  7261. if (!evalskip) {
  7262. n = n->nbinary.ch2;
  7263. evaln:
  7264. evalfn = evaltree;
  7265. calleval:
  7266. evalfn(n, flags);
  7267. break;
  7268. }
  7269. break;
  7270. }
  7271. case NIF:
  7272. evaltree(n->nif.test, EV_TESTED);
  7273. if (evalskip)
  7274. break;
  7275. if (exitstatus == 0) {
  7276. n = n->nif.ifpart;
  7277. goto evaln;
  7278. } else if (n->nif.elsepart) {
  7279. n = n->nif.elsepart;
  7280. goto evaln;
  7281. }
  7282. goto success;
  7283. case NDEFUN:
  7284. defun(n->narg.text, n->narg.next);
  7285. success:
  7286. status = 0;
  7287. setstatus:
  7288. exitstatus = status;
  7289. break;
  7290. }
  7291. out:
  7292. exception_handler = savehandler;
  7293. out1:
  7294. if (checkexit & exitstatus)
  7295. evalskip |= SKIPEVAL;
  7296. else if (pendingsig && dotrap())
  7297. goto exexit;
  7298. if (flags & EV_EXIT) {
  7299. exexit:
  7300. raise_exception(EXEXIT);
  7301. }
  7302. }
  7303. #if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
  7304. static
  7305. #endif
  7306. void evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
  7307. static void
  7308. evalloop(union node *n, int flags)
  7309. {
  7310. int status;
  7311. loopnest++;
  7312. status = 0;
  7313. flags &= EV_TESTED;
  7314. for (;;) {
  7315. int i;
  7316. evaltree(n->nbinary.ch1, EV_TESTED);
  7317. if (evalskip) {
  7318. skipping:
  7319. if (evalskip == SKIPCONT && --skipcount <= 0) {
  7320. evalskip = 0;
  7321. continue;
  7322. }
  7323. if (evalskip == SKIPBREAK && --skipcount <= 0)
  7324. evalskip = 0;
  7325. break;
  7326. }
  7327. i = exitstatus;
  7328. if (n->type != NWHILE)
  7329. i = !i;
  7330. if (i != 0)
  7331. break;
  7332. evaltree(n->nbinary.ch2, flags);
  7333. status = exitstatus;
  7334. if (evalskip)
  7335. goto skipping;
  7336. }
  7337. loopnest--;
  7338. exitstatus = status;
  7339. }
  7340. static void
  7341. evalfor(union node *n, int flags)
  7342. {
  7343. struct arglist arglist;
  7344. union node *argp;
  7345. struct strlist *sp;
  7346. struct stackmark smark;
  7347. setstackmark(&smark);
  7348. arglist.list = NULL;
  7349. arglist.lastp = &arglist.list;
  7350. for (argp = n->nfor.args; argp; argp = argp->narg.next) {
  7351. expandarg(argp, &arglist, EXP_FULL | EXP_TILDE | EXP_RECORD);
  7352. /* XXX */
  7353. if (evalskip)
  7354. goto out;
  7355. }
  7356. *arglist.lastp = NULL;
  7357. exitstatus = 0;
  7358. loopnest++;
  7359. flags &= EV_TESTED;
  7360. for (sp = arglist.list; sp; sp = sp->next) {
  7361. setvar(n->nfor.var, sp->text, 0);
  7362. evaltree(n->nfor.body, flags);
  7363. if (evalskip) {
  7364. if (evalskip == SKIPCONT && --skipcount <= 0) {
  7365. evalskip = 0;
  7366. continue;
  7367. }
  7368. if (evalskip == SKIPBREAK && --skipcount <= 0)
  7369. evalskip = 0;
  7370. break;
  7371. }
  7372. }
  7373. loopnest--;
  7374. out:
  7375. popstackmark(&smark);
  7376. }
  7377. static void
  7378. evalcase(union node *n, int flags)
  7379. {
  7380. union node *cp;
  7381. union node *patp;
  7382. struct arglist arglist;
  7383. struct stackmark smark;
  7384. setstackmark(&smark);
  7385. arglist.list = NULL;
  7386. arglist.lastp = &arglist.list;
  7387. expandarg(n->ncase.expr, &arglist, EXP_TILDE);
  7388. exitstatus = 0;
  7389. for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
  7390. for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
  7391. if (casematch(patp, arglist.list->text)) {
  7392. if (evalskip == 0) {
  7393. evaltree(cp->nclist.body, flags);
  7394. }
  7395. goto out;
  7396. }
  7397. }
  7398. }
  7399. out:
  7400. popstackmark(&smark);
  7401. }
  7402. /*
  7403. * Kick off a subshell to evaluate a tree.
  7404. */
  7405. static void
  7406. evalsubshell(union node *n, int flags)
  7407. {
  7408. struct job *jp;
  7409. int backgnd = (n->type == NBACKGND);
  7410. int status;
  7411. expredir(n->nredir.redirect);
  7412. if (!backgnd && flags & EV_EXIT && !trap[0])
  7413. goto nofork;
  7414. INT_OFF;
  7415. jp = makejob(/*n,*/ 1);
  7416. if (forkshell(jp, n, backgnd) == 0) {
  7417. INT_ON;
  7418. flags |= EV_EXIT;
  7419. if (backgnd)
  7420. flags &=~ EV_TESTED;
  7421. nofork:
  7422. redirect(n->nredir.redirect, 0);
  7423. evaltreenr(n->nredir.n, flags);
  7424. /* never returns */
  7425. }
  7426. status = 0;
  7427. if (!backgnd)
  7428. status = waitforjob(jp);
  7429. exitstatus = status;
  7430. INT_ON;
  7431. }
  7432. /*
  7433. * Compute the names of the files in a redirection list.
  7434. */
  7435. static void fixredir(union node *, const char *, int);
  7436. static void
  7437. expredir(union node *n)
  7438. {
  7439. union node *redir;
  7440. for (redir = n; redir; redir = redir->nfile.next) {
  7441. struct arglist fn;
  7442. fn.list = NULL;
  7443. fn.lastp = &fn.list;
  7444. switch (redir->type) {
  7445. case NFROMTO:
  7446. case NFROM:
  7447. case NTO:
  7448. case NCLOBBER:
  7449. case NAPPEND:
  7450. expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
  7451. redir->nfile.expfname = fn.list->text;
  7452. break;
  7453. case NFROMFD:
  7454. case NTOFD:
  7455. if (redir->ndup.vname) {
  7456. expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
  7457. if (fn.list == NULL)
  7458. ash_msg_and_raise_error("redir error");
  7459. fixredir(redir, fn.list->text, 1);
  7460. }
  7461. break;
  7462. }
  7463. }
  7464. }
  7465. /*
  7466. * Evaluate a pipeline. All the processes in the pipeline are children
  7467. * of the process creating the pipeline. (This differs from some versions
  7468. * of the shell, which make the last process in a pipeline the parent
  7469. * of all the rest.)
  7470. */
  7471. static void
  7472. evalpipe(union node *n, int flags)
  7473. {
  7474. struct job *jp;
  7475. struct nodelist *lp;
  7476. int pipelen;
  7477. int prevfd;
  7478. int pip[2];
  7479. TRACE(("evalpipe(0x%lx) called\n", (long)n));
  7480. pipelen = 0;
  7481. for (lp = n->npipe.cmdlist; lp; lp = lp->next)
  7482. pipelen++;
  7483. flags |= EV_EXIT;
  7484. INT_OFF;
  7485. jp = makejob(/*n,*/ pipelen);
  7486. prevfd = -1;
  7487. for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
  7488. prehash(lp->n);
  7489. pip[1] = -1;
  7490. if (lp->next) {
  7491. if (pipe(pip) < 0) {
  7492. close(prevfd);
  7493. ash_msg_and_raise_error("pipe call failed");
  7494. }
  7495. }
  7496. if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
  7497. INT_ON;
  7498. if (pip[1] >= 0) {
  7499. close(pip[0]);
  7500. }
  7501. if (prevfd > 0) {
  7502. dup2(prevfd, 0);
  7503. close(prevfd);
  7504. }
  7505. if (pip[1] > 1) {
  7506. dup2(pip[1], 1);
  7507. close(pip[1]);
  7508. }
  7509. evaltreenr(lp->n, flags);
  7510. /* never returns */
  7511. }
  7512. if (prevfd >= 0)
  7513. close(prevfd);
  7514. prevfd = pip[0];
  7515. close(pip[1]);
  7516. }
  7517. if (n->npipe.pipe_backgnd == 0) {
  7518. exitstatus = waitforjob(jp);
  7519. TRACE(("evalpipe: job done exit status %d\n", exitstatus));
  7520. }
  7521. INT_ON;
  7522. }
  7523. /*
  7524. * Controls whether the shell is interactive or not.
  7525. */
  7526. static void
  7527. setinteractive(int on)
  7528. {
  7529. static smallint is_interactive;
  7530. if (++on == is_interactive)
  7531. return;
  7532. is_interactive = on;
  7533. setsignal(SIGINT);
  7534. setsignal(SIGQUIT);
  7535. setsignal(SIGTERM);
  7536. #if !ENABLE_FEATURE_SH_EXTRA_QUIET
  7537. if (is_interactive > 1) {
  7538. /* Looks like they want an interactive shell */
  7539. static smallint did_banner;
  7540. if (!did_banner) {
  7541. out1fmt(
  7542. "\n\n"
  7543. "%s built-in shell (ash)\n"
  7544. "Enter 'help' for a list of built-in commands."
  7545. "\n\n",
  7546. bb_banner);
  7547. did_banner = 1;
  7548. }
  7549. }
  7550. #endif
  7551. }
  7552. static void
  7553. optschanged(void)
  7554. {
  7555. #if DEBUG
  7556. opentrace();
  7557. #endif
  7558. setinteractive(iflag);
  7559. setjobctl(mflag);
  7560. #if ENABLE_FEATURE_EDITING_VI
  7561. if (viflag)
  7562. line_input_state->flags |= VI_MODE;
  7563. else
  7564. line_input_state->flags &= ~VI_MODE;
  7565. #else
  7566. viflag = 0; /* forcibly keep the option off */
  7567. #endif
  7568. }
  7569. static struct localvar *localvars;
  7570. /*
  7571. * Called after a function returns.
  7572. * Interrupts must be off.
  7573. */
  7574. static void
  7575. poplocalvars(void)
  7576. {
  7577. struct localvar *lvp;
  7578. struct var *vp;
  7579. while ((lvp = localvars) != NULL) {
  7580. localvars = lvp->next;
  7581. vp = lvp->vp;
  7582. TRACE(("poplocalvar %s", vp ? vp->text : "-"));
  7583. if (vp == NULL) { /* $- saved */
  7584. memcpy(optlist, lvp->text, sizeof(optlist));
  7585. free((char*)lvp->text);
  7586. optschanged();
  7587. } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
  7588. unsetvar(vp->text);
  7589. } else {
  7590. if (vp->func)
  7591. (*vp->func)(strchrnul(lvp->text, '=') + 1);
  7592. if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
  7593. free((char*)vp->text);
  7594. vp->flags = lvp->flags;
  7595. vp->text = lvp->text;
  7596. }
  7597. free(lvp);
  7598. }
  7599. }
  7600. static int
  7601. evalfun(struct funcnode *func, int argc, char **argv, int flags)
  7602. {
  7603. volatile struct shparam saveparam;
  7604. struct localvar *volatile savelocalvars;
  7605. struct jmploc *volatile savehandler;
  7606. struct jmploc jmploc;
  7607. int e;
  7608. saveparam = shellparam;
  7609. savelocalvars = localvars;
  7610. e = setjmp(jmploc.loc);
  7611. if (e) {
  7612. goto funcdone;
  7613. }
  7614. INT_OFF;
  7615. savehandler = exception_handler;
  7616. exception_handler = &jmploc;
  7617. localvars = NULL;
  7618. shellparam.malloced = 0;
  7619. func->count++;
  7620. funcnest++;
  7621. INT_ON;
  7622. shellparam.nparam = argc - 1;
  7623. shellparam.p = argv + 1;
  7624. #if ENABLE_ASH_GETOPTS
  7625. shellparam.optind = 1;
  7626. shellparam.optoff = -1;
  7627. #endif
  7628. evaltree(&func->n, flags & EV_TESTED);
  7629. funcdone:
  7630. INT_OFF;
  7631. funcnest--;
  7632. freefunc(func);
  7633. poplocalvars();
  7634. localvars = savelocalvars;
  7635. freeparam(&shellparam);
  7636. shellparam = saveparam;
  7637. exception_handler = savehandler;
  7638. INT_ON;
  7639. evalskip &= ~SKIPFUNC;
  7640. return e;
  7641. }
  7642. #if ENABLE_ASH_CMDCMD
  7643. static char **
  7644. parse_command_args(char **argv, const char **path)
  7645. {
  7646. char *cp, c;
  7647. for (;;) {
  7648. cp = *++argv;
  7649. if (!cp)
  7650. return 0;
  7651. if (*cp++ != '-')
  7652. break;
  7653. c = *cp++;
  7654. if (!c)
  7655. break;
  7656. if (c == '-' && !*cp) {
  7657. argv++;
  7658. break;
  7659. }
  7660. do {
  7661. switch (c) {
  7662. case 'p':
  7663. *path = bb_default_path;
  7664. break;
  7665. default:
  7666. /* run 'typecmd' for other options */
  7667. return 0;
  7668. }
  7669. c = *cp++;
  7670. } while (c);
  7671. }
  7672. return argv;
  7673. }
  7674. #endif
  7675. /*
  7676. * Make a variable a local variable. When a variable is made local, it's
  7677. * value and flags are saved in a localvar structure. The saved values
  7678. * will be restored when the shell function returns. We handle the name
  7679. * "-" as a special case.
  7680. */
  7681. static void
  7682. mklocal(char *name)
  7683. {
  7684. struct localvar *lvp;
  7685. struct var **vpp;
  7686. struct var *vp;
  7687. INT_OFF;
  7688. lvp = ckzalloc(sizeof(struct localvar));
  7689. if (LONE_DASH(name)) {
  7690. char *p;
  7691. p = ckmalloc(sizeof(optlist));
  7692. lvp->text = memcpy(p, optlist, sizeof(optlist));
  7693. vp = NULL;
  7694. } else {
  7695. char *eq;
  7696. vpp = hashvar(name);
  7697. vp = *findvar(vpp, name);
  7698. eq = strchr(name, '=');
  7699. if (vp == NULL) {
  7700. if (eq)
  7701. setvareq(name, VSTRFIXED);
  7702. else
  7703. setvar(name, NULL, VSTRFIXED);
  7704. vp = *vpp; /* the new variable */
  7705. lvp->flags = VUNSET;
  7706. } else {
  7707. lvp->text = vp->text;
  7708. lvp->flags = vp->flags;
  7709. vp->flags |= VSTRFIXED|VTEXTFIXED;
  7710. if (eq)
  7711. setvareq(name, 0);
  7712. }
  7713. }
  7714. lvp->vp = vp;
  7715. lvp->next = localvars;
  7716. localvars = lvp;
  7717. INT_ON;
  7718. }
  7719. /*
  7720. * The "local" command.
  7721. */
  7722. static int
  7723. localcmd(int argc UNUSED_PARAM, char **argv)
  7724. {
  7725. char *name;
  7726. argv = argptr;
  7727. while ((name = *argv++) != NULL) {
  7728. mklocal(name);
  7729. }
  7730. return 0;
  7731. }
  7732. static int
  7733. falsecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  7734. {
  7735. return 1;
  7736. }
  7737. static int
  7738. truecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  7739. {
  7740. return 0;
  7741. }
  7742. static int
  7743. execcmd(int argc UNUSED_PARAM, char **argv)
  7744. {
  7745. if (argv[1]) {
  7746. iflag = 0; /* exit on error */
  7747. mflag = 0;
  7748. optschanged();
  7749. shellexec(argv + 1, pathval(), 0);
  7750. }
  7751. return 0;
  7752. }
  7753. /*
  7754. * The return command.
  7755. */
  7756. static int
  7757. returncmd(int argc UNUSED_PARAM, char **argv)
  7758. {
  7759. /*
  7760. * If called outside a function, do what ksh does;
  7761. * skip the rest of the file.
  7762. */
  7763. evalskip = funcnest ? SKIPFUNC : SKIPFILE;
  7764. return argv[1] ? number(argv[1]) : exitstatus;
  7765. }
  7766. /* Forward declarations for builtintab[] */
  7767. static int breakcmd(int, char **);
  7768. static int dotcmd(int, char **);
  7769. static int evalcmd(int, char **);
  7770. static int exitcmd(int, char **);
  7771. static int exportcmd(int, char **);
  7772. #if ENABLE_ASH_GETOPTS
  7773. static int getoptscmd(int, char **);
  7774. #endif
  7775. #if !ENABLE_FEATURE_SH_EXTRA_QUIET
  7776. static int helpcmd(int, char **);
  7777. #endif
  7778. #if ENABLE_ASH_MATH_SUPPORT
  7779. static int letcmd(int, char **);
  7780. #endif
  7781. static int readcmd(int, char **);
  7782. static int setcmd(int, char **);
  7783. static int shiftcmd(int, char **);
  7784. static int timescmd(int, char **);
  7785. static int trapcmd(int, char **);
  7786. static int umaskcmd(int, char **);
  7787. static int unsetcmd(int, char **);
  7788. static int ulimitcmd(int, char **);
  7789. #define BUILTIN_NOSPEC "0"
  7790. #define BUILTIN_SPECIAL "1"
  7791. #define BUILTIN_REGULAR "2"
  7792. #define BUILTIN_SPEC_REG "3"
  7793. #define BUILTIN_ASSIGN "4"
  7794. #define BUILTIN_SPEC_ASSG "5"
  7795. #define BUILTIN_REG_ASSG "6"
  7796. #define BUILTIN_SPEC_REG_ASSG "7"
  7797. /* We do not handle [[ expr ]] bashism bash-compatibly,
  7798. * we make it a synonym of [ expr ].
  7799. * Basically, word splitting and pathname expansion should NOT be performed
  7800. * Examples:
  7801. * no word splitting: a="a b"; [[ $a = "a b" ]]; echo $? should print "0"
  7802. * no pathname expansion: [[ /bin/m* = "/bin/m*" ]]; echo $? should print "0"
  7803. * Additional operators:
  7804. * || and && should work as -o and -a
  7805. * =~ regexp match
  7806. * Apart from the above, [[ expr ]] should work as [ expr ]
  7807. */
  7808. #define echocmd echo_main
  7809. #define printfcmd printf_main
  7810. #define testcmd test_main
  7811. /* Keep these in proper order since it is searched via bsearch() */
  7812. static const struct builtincmd builtintab[] = {
  7813. { BUILTIN_SPEC_REG ".", dotcmd },
  7814. { BUILTIN_SPEC_REG ":", truecmd },
  7815. #if ENABLE_ASH_BUILTIN_TEST
  7816. { BUILTIN_REGULAR "[", testcmd },
  7817. #if ENABLE_ASH_BASH_COMPAT
  7818. { BUILTIN_REGULAR "[[", testcmd },
  7819. #endif
  7820. #endif
  7821. #if ENABLE_ASH_ALIAS
  7822. { BUILTIN_REG_ASSG "alias", aliascmd },
  7823. #endif
  7824. #if JOBS
  7825. { BUILTIN_REGULAR "bg", fg_bgcmd },
  7826. #endif
  7827. { BUILTIN_SPEC_REG "break", breakcmd },
  7828. { BUILTIN_REGULAR "cd", cdcmd },
  7829. { BUILTIN_NOSPEC "chdir", cdcmd },
  7830. #if ENABLE_ASH_CMDCMD
  7831. { BUILTIN_REGULAR "command", commandcmd },
  7832. #endif
  7833. { BUILTIN_SPEC_REG "continue", breakcmd },
  7834. #if ENABLE_ASH_BUILTIN_ECHO
  7835. { BUILTIN_REGULAR "echo", echocmd },
  7836. #endif
  7837. { BUILTIN_SPEC_REG "eval", evalcmd },
  7838. { BUILTIN_SPEC_REG "exec", execcmd },
  7839. { BUILTIN_SPEC_REG "exit", exitcmd },
  7840. { BUILTIN_SPEC_REG_ASSG "export", exportcmd },
  7841. { BUILTIN_REGULAR "false", falsecmd },
  7842. #if JOBS
  7843. { BUILTIN_REGULAR "fg", fg_bgcmd },
  7844. #endif
  7845. #if ENABLE_ASH_GETOPTS
  7846. { BUILTIN_REGULAR "getopts", getoptscmd },
  7847. #endif
  7848. { BUILTIN_NOSPEC "hash", hashcmd },
  7849. #if !ENABLE_FEATURE_SH_EXTRA_QUIET
  7850. { BUILTIN_NOSPEC "help", helpcmd },
  7851. #endif
  7852. #if JOBS
  7853. { BUILTIN_REGULAR "jobs", jobscmd },
  7854. { BUILTIN_REGULAR "kill", killcmd },
  7855. #endif
  7856. #if ENABLE_ASH_MATH_SUPPORT
  7857. { BUILTIN_NOSPEC "let", letcmd },
  7858. #endif
  7859. { BUILTIN_ASSIGN "local", localcmd },
  7860. #if ENABLE_ASH_BUILTIN_PRINTF
  7861. { BUILTIN_REGULAR "printf", printfcmd },
  7862. #endif
  7863. { BUILTIN_NOSPEC "pwd", pwdcmd },
  7864. { BUILTIN_REGULAR "read", readcmd },
  7865. { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
  7866. { BUILTIN_SPEC_REG "return", returncmd },
  7867. { BUILTIN_SPEC_REG "set", setcmd },
  7868. { BUILTIN_SPEC_REG "shift", shiftcmd },
  7869. { BUILTIN_SPEC_REG "source", dotcmd },
  7870. #if ENABLE_ASH_BUILTIN_TEST
  7871. { BUILTIN_REGULAR "test", testcmd },
  7872. #endif
  7873. { BUILTIN_SPEC_REG "times", timescmd },
  7874. { BUILTIN_SPEC_REG "trap", trapcmd },
  7875. { BUILTIN_REGULAR "true", truecmd },
  7876. { BUILTIN_NOSPEC "type", typecmd },
  7877. { BUILTIN_NOSPEC "ulimit", ulimitcmd },
  7878. { BUILTIN_REGULAR "umask", umaskcmd },
  7879. #if ENABLE_ASH_ALIAS
  7880. { BUILTIN_REGULAR "unalias", unaliascmd },
  7881. #endif
  7882. { BUILTIN_SPEC_REG "unset", unsetcmd },
  7883. { BUILTIN_REGULAR "wait", waitcmd },
  7884. };
  7885. /* Should match the above table! */
  7886. #define COMMANDCMD (builtintab + \
  7887. 2 + \
  7888. 1 * ENABLE_ASH_BUILTIN_TEST + \
  7889. 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
  7890. 1 * ENABLE_ASH_ALIAS + \
  7891. 1 * ENABLE_ASH_JOB_CONTROL + \
  7892. 3)
  7893. #define EXECCMD (builtintab + \
  7894. 2 + \
  7895. 1 * ENABLE_ASH_BUILTIN_TEST + \
  7896. 1 * ENABLE_ASH_BUILTIN_TEST * ENABLE_ASH_BASH_COMPAT + \
  7897. 1 * ENABLE_ASH_ALIAS + \
  7898. 1 * ENABLE_ASH_JOB_CONTROL + \
  7899. 3 + \
  7900. 1 * ENABLE_ASH_CMDCMD + \
  7901. 1 + \
  7902. ENABLE_ASH_BUILTIN_ECHO + \
  7903. 1)
  7904. /*
  7905. * Search the table of builtin commands.
  7906. */
  7907. static struct builtincmd *
  7908. find_builtin(const char *name)
  7909. {
  7910. struct builtincmd *bp;
  7911. bp = bsearch(
  7912. name, builtintab, ARRAY_SIZE(builtintab), sizeof(builtintab[0]),
  7913. pstrcmp
  7914. );
  7915. return bp;
  7916. }
  7917. /*
  7918. * Execute a simple command.
  7919. */
  7920. static int
  7921. isassignment(const char *p)
  7922. {
  7923. const char *q = endofname(p);
  7924. if (p == q)
  7925. return 0;
  7926. return *q == '=';
  7927. }
  7928. static int
  7929. bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  7930. {
  7931. /* Preserve exitstatus of a previous possible redirection
  7932. * as POSIX mandates */
  7933. return back_exitstatus;
  7934. }
  7935. static void
  7936. evalcommand(union node *cmd, int flags)
  7937. {
  7938. static const struct builtincmd null_bltin = {
  7939. "\0\0", bltincmd /* why three NULs? */
  7940. };
  7941. struct stackmark smark;
  7942. union node *argp;
  7943. struct arglist arglist;
  7944. struct arglist varlist;
  7945. char **argv;
  7946. int argc;
  7947. const struct strlist *sp;
  7948. struct cmdentry cmdentry;
  7949. struct job *jp;
  7950. char *lastarg;
  7951. const char *path;
  7952. int spclbltin;
  7953. int status;
  7954. char **nargv;
  7955. struct builtincmd *bcmd;
  7956. smallint cmd_is_exec;
  7957. smallint pseudovarflag = 0;
  7958. /* First expand the arguments. */
  7959. TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
  7960. setstackmark(&smark);
  7961. back_exitstatus = 0;
  7962. cmdentry.cmdtype = CMDBUILTIN;
  7963. cmdentry.u.cmd = &null_bltin;
  7964. varlist.lastp = &varlist.list;
  7965. *varlist.lastp = NULL;
  7966. arglist.lastp = &arglist.list;
  7967. *arglist.lastp = NULL;
  7968. argc = 0;
  7969. if (cmd->ncmd.args) {
  7970. bcmd = find_builtin(cmd->ncmd.args->narg.text);
  7971. pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
  7972. }
  7973. for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
  7974. struct strlist **spp;
  7975. spp = arglist.lastp;
  7976. if (pseudovarflag && isassignment(argp->narg.text))
  7977. expandarg(argp, &arglist, EXP_VARTILDE);
  7978. else
  7979. expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
  7980. for (sp = *spp; sp; sp = sp->next)
  7981. argc++;
  7982. }
  7983. argv = nargv = stalloc(sizeof(char *) * (argc + 1));
  7984. for (sp = arglist.list; sp; sp = sp->next) {
  7985. TRACE(("evalcommand arg: %s\n", sp->text));
  7986. *nargv++ = sp->text;
  7987. }
  7988. *nargv = NULL;
  7989. lastarg = NULL;
  7990. if (iflag && funcnest == 0 && argc > 0)
  7991. lastarg = nargv[-1];
  7992. preverrout_fd = 2;
  7993. expredir(cmd->ncmd.redirect);
  7994. status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH | REDIR_SAVEFD2);
  7995. path = vpath.text;
  7996. for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
  7997. struct strlist **spp;
  7998. char *p;
  7999. spp = varlist.lastp;
  8000. expandarg(argp, &varlist, EXP_VARTILDE);
  8001. /*
  8002. * Modify the command lookup path, if a PATH= assignment
  8003. * is present
  8004. */
  8005. p = (*spp)->text;
  8006. if (varequal(p, path))
  8007. path = p;
  8008. }
  8009. /* Print the command if xflag is set. */
  8010. if (xflag) {
  8011. int n;
  8012. const char *p = " %s";
  8013. p++;
  8014. fdprintf(preverrout_fd, p, expandstr(ps4val()));
  8015. sp = varlist.list;
  8016. for (n = 0; n < 2; n++) {
  8017. while (sp) {
  8018. fdprintf(preverrout_fd, p, sp->text);
  8019. sp = sp->next;
  8020. if (*p == '%') {
  8021. p--;
  8022. }
  8023. }
  8024. sp = arglist.list;
  8025. }
  8026. safe_write(preverrout_fd, "\n", 1);
  8027. }
  8028. cmd_is_exec = 0;
  8029. spclbltin = -1;
  8030. /* Now locate the command. */
  8031. if (argc) {
  8032. const char *oldpath;
  8033. int cmd_flag = DO_ERR;
  8034. path += 5;
  8035. oldpath = path;
  8036. for (;;) {
  8037. find_command(argv[0], &cmdentry, cmd_flag, path);
  8038. if (cmdentry.cmdtype == CMDUNKNOWN) {
  8039. flush_stderr();
  8040. status = 127;
  8041. goto bail;
  8042. }
  8043. /* implement bltin and command here */
  8044. if (cmdentry.cmdtype != CMDBUILTIN)
  8045. break;
  8046. if (spclbltin < 0)
  8047. spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
  8048. if (cmdentry.u.cmd == EXECCMD)
  8049. cmd_is_exec = 1;
  8050. #if ENABLE_ASH_CMDCMD
  8051. if (cmdentry.u.cmd == COMMANDCMD) {
  8052. path = oldpath;
  8053. nargv = parse_command_args(argv, &path);
  8054. if (!nargv)
  8055. break;
  8056. argc -= nargv - argv;
  8057. argv = nargv;
  8058. cmd_flag |= DO_NOFUNC;
  8059. } else
  8060. #endif
  8061. break;
  8062. }
  8063. }
  8064. if (status) {
  8065. /* We have a redirection error. */
  8066. if (spclbltin > 0)
  8067. raise_exception(EXERROR);
  8068. bail:
  8069. exitstatus = status;
  8070. goto out;
  8071. }
  8072. /* Execute the command. */
  8073. switch (cmdentry.cmdtype) {
  8074. default:
  8075. #if ENABLE_FEATURE_SH_NOFORK
  8076. {
  8077. /* find_command() encodes applet_no as (-2 - applet_no) */
  8078. int applet_no = (- cmdentry.u.index - 2);
  8079. if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
  8080. listsetvar(varlist.list, VEXPORT|VSTACK);
  8081. /* run <applet>_main() */
  8082. exitstatus = run_nofork_applet(applet_no, argv);
  8083. break;
  8084. }
  8085. }
  8086. #endif
  8087. /* Fork off a child process if necessary. */
  8088. if (!(flags & EV_EXIT) || trap[0]) {
  8089. INT_OFF;
  8090. jp = makejob(/*cmd,*/ 1);
  8091. if (forkshell(jp, cmd, FORK_FG) != 0) {
  8092. exitstatus = waitforjob(jp);
  8093. INT_ON;
  8094. break;
  8095. }
  8096. FORCE_INT_ON;
  8097. }
  8098. listsetvar(varlist.list, VEXPORT|VSTACK);
  8099. shellexec(argv, path, cmdentry.u.index);
  8100. /* NOTREACHED */
  8101. case CMDBUILTIN:
  8102. cmdenviron = varlist.list;
  8103. if (cmdenviron) {
  8104. struct strlist *list = cmdenviron;
  8105. int i = VNOSET;
  8106. if (spclbltin > 0 || argc == 0) {
  8107. i = 0;
  8108. if (cmd_is_exec && argc > 1)
  8109. i = VEXPORT;
  8110. }
  8111. listsetvar(list, i);
  8112. }
  8113. if (evalbltin(cmdentry.u.cmd, argc, argv)) {
  8114. int exit_status;
  8115. int i = exception;
  8116. if (i == EXEXIT)
  8117. goto raise;
  8118. exit_status = 2;
  8119. if (i == EXINT)
  8120. exit_status = 128 + SIGINT;
  8121. if (i == EXSIG)
  8122. exit_status = 128 + pendingsig;
  8123. exitstatus = exit_status;
  8124. if (i == EXINT || spclbltin > 0) {
  8125. raise:
  8126. longjmp(exception_handler->loc, 1);
  8127. }
  8128. FORCE_INT_ON;
  8129. }
  8130. break;
  8131. case CMDFUNCTION:
  8132. listsetvar(varlist.list, 0);
  8133. if (evalfun(cmdentry.u.func, argc, argv, flags))
  8134. goto raise;
  8135. break;
  8136. }
  8137. out:
  8138. popredir(/*drop:*/ cmd_is_exec, /*restore:*/ cmd_is_exec);
  8139. if (lastarg) {
  8140. /* dsl: I think this is intended to be used to support
  8141. * '_' in 'vi' command mode during line editing...
  8142. * However I implemented that within libedit itself.
  8143. */
  8144. setvar("_", lastarg, 0);
  8145. }
  8146. popstackmark(&smark);
  8147. }
  8148. static int
  8149. evalbltin(const struct builtincmd *cmd, int argc, char **argv)
  8150. {
  8151. char *volatile savecmdname;
  8152. struct jmploc *volatile savehandler;
  8153. struct jmploc jmploc;
  8154. int i;
  8155. savecmdname = commandname;
  8156. i = setjmp(jmploc.loc);
  8157. if (i)
  8158. goto cmddone;
  8159. savehandler = exception_handler;
  8160. exception_handler = &jmploc;
  8161. commandname = argv[0];
  8162. argptr = argv + 1;
  8163. optptr = NULL; /* initialize nextopt */
  8164. exitstatus = (*cmd->builtin)(argc, argv);
  8165. flush_stdout_stderr();
  8166. cmddone:
  8167. exitstatus |= ferror(stdout);
  8168. clearerr(stdout);
  8169. commandname = savecmdname;
  8170. // exsig = 0;
  8171. exception_handler = savehandler;
  8172. return i;
  8173. }
  8174. static int
  8175. goodname(const char *p)
  8176. {
  8177. return !*endofname(p);
  8178. }
  8179. /*
  8180. * Search for a command. This is called before we fork so that the
  8181. * location of the command will be available in the parent as well as
  8182. * the child. The check for "goodname" is an overly conservative
  8183. * check that the name will not be subject to expansion.
  8184. */
  8185. static void
  8186. prehash(union node *n)
  8187. {
  8188. struct cmdentry entry;
  8189. if (n->type == NCMD && n->ncmd.args && goodname(n->ncmd.args->narg.text))
  8190. find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
  8191. }
  8192. /* ============ Builtin commands
  8193. *
  8194. * Builtin commands whose functions are closely tied to evaluation
  8195. * are implemented here.
  8196. */
  8197. /*
  8198. * Handle break and continue commands. Break, continue, and return are
  8199. * all handled by setting the evalskip flag. The evaluation routines
  8200. * above all check this flag, and if it is set they start skipping
  8201. * commands rather than executing them. The variable skipcount is
  8202. * the number of loops to break/continue, or the number of function
  8203. * levels to return. (The latter is always 1.) It should probably
  8204. * be an error to break out of more loops than exist, but it isn't
  8205. * in the standard shell so we don't make it one here.
  8206. */
  8207. static int
  8208. breakcmd(int argc UNUSED_PARAM, char **argv)
  8209. {
  8210. int n = argv[1] ? number(argv[1]) : 1;
  8211. if (n <= 0)
  8212. ash_msg_and_raise_error(illnum, argv[1]);
  8213. if (n > loopnest)
  8214. n = loopnest;
  8215. if (n > 0) {
  8216. evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
  8217. skipcount = n;
  8218. }
  8219. return 0;
  8220. }
  8221. /* ============ input.c
  8222. *
  8223. * This implements the input routines used by the parser.
  8224. */
  8225. #define EOF_NLEFT -99 /* value of parsenleft when EOF pushed back */
  8226. enum {
  8227. INPUT_PUSH_FILE = 1,
  8228. INPUT_NOFILE_OK = 2,
  8229. };
  8230. static int plinno = 1; /* input line number */
  8231. /* number of characters left in input buffer */
  8232. static int parsenleft; /* copy of parsefile->nleft */
  8233. static int parselleft; /* copy of parsefile->lleft */
  8234. /* next character in input buffer */
  8235. static char *parsenextc; /* copy of parsefile->nextc */
  8236. static smallint checkkwd;
  8237. /* values of checkkwd variable */
  8238. #define CHKALIAS 0x1
  8239. #define CHKKWD 0x2
  8240. #define CHKNL 0x4
  8241. static void
  8242. popstring(void)
  8243. {
  8244. struct strpush *sp = g_parsefile->strpush;
  8245. INT_OFF;
  8246. #if ENABLE_ASH_ALIAS
  8247. if (sp->ap) {
  8248. if (parsenextc[-1] == ' ' || parsenextc[-1] == '\t') {
  8249. checkkwd |= CHKALIAS;
  8250. }
  8251. if (sp->string != sp->ap->val) {
  8252. free(sp->string);
  8253. }
  8254. sp->ap->flag &= ~ALIASINUSE;
  8255. if (sp->ap->flag & ALIASDEAD) {
  8256. unalias(sp->ap->name);
  8257. }
  8258. }
  8259. #endif
  8260. parsenextc = sp->prevstring;
  8261. parsenleft = sp->prevnleft;
  8262. /*dprintf("*** calling popstring: restoring to '%s'\n", parsenextc);*/
  8263. g_parsefile->strpush = sp->prev;
  8264. if (sp != &(g_parsefile->basestrpush))
  8265. free(sp);
  8266. INT_ON;
  8267. }
  8268. static int
  8269. preadfd(void)
  8270. {
  8271. int nr;
  8272. char *buf = g_parsefile->buf;
  8273. parsenextc = buf;
  8274. #if ENABLE_FEATURE_EDITING
  8275. retry:
  8276. if (!iflag || g_parsefile->fd)
  8277. nr = nonblock_safe_read(g_parsefile->fd, buf, BUFSIZ - 1);
  8278. else {
  8279. #if ENABLE_FEATURE_TAB_COMPLETION
  8280. line_input_state->path_lookup = pathval();
  8281. #endif
  8282. nr = read_line_input(cmdedit_prompt, buf, BUFSIZ, line_input_state);
  8283. if (nr == 0) {
  8284. /* Ctrl+C pressed */
  8285. if (trap[SIGINT]) {
  8286. buf[0] = '\n';
  8287. buf[1] = '\0';
  8288. raise(SIGINT);
  8289. return 1;
  8290. }
  8291. goto retry;
  8292. }
  8293. if (nr < 0 && errno == 0) {
  8294. /* Ctrl+D pressed */
  8295. nr = 0;
  8296. }
  8297. }
  8298. #else
  8299. nr = nonblock_safe_read(g_parsefile->fd, buf, BUFSIZ - 1);
  8300. #endif
  8301. #if 0
  8302. /* nonblock_safe_read() handles this problem */
  8303. if (nr < 0) {
  8304. if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
  8305. int flags = fcntl(0, F_GETFL);
  8306. if (flags >= 0 && (flags & O_NONBLOCK)) {
  8307. flags &= ~O_NONBLOCK;
  8308. if (fcntl(0, F_SETFL, flags) >= 0) {
  8309. out2str("sh: turning off NDELAY mode\n");
  8310. goto retry;
  8311. }
  8312. }
  8313. }
  8314. }
  8315. #endif
  8316. return nr;
  8317. }
  8318. /*
  8319. * Refill the input buffer and return the next input character:
  8320. *
  8321. * 1) If a string was pushed back on the input, pop it;
  8322. * 2) If an EOF was pushed back (parsenleft == EOF_NLEFT) or we are reading
  8323. * from a string so we can't refill the buffer, return EOF.
  8324. * 3) If the is more stuff in this buffer, use it else call read to fill it.
  8325. * 4) Process input up to the next newline, deleting nul characters.
  8326. */
  8327. static int
  8328. preadbuffer(void)
  8329. {
  8330. char *q;
  8331. int more;
  8332. char savec;
  8333. while (g_parsefile->strpush) {
  8334. #if ENABLE_ASH_ALIAS
  8335. if (parsenleft == -1 && g_parsefile->strpush->ap &&
  8336. parsenextc[-1] != ' ' && parsenextc[-1] != '\t') {
  8337. return PEOA;
  8338. }
  8339. #endif
  8340. popstring();
  8341. if (--parsenleft >= 0)
  8342. return signed_char2int(*parsenextc++);
  8343. }
  8344. if (parsenleft == EOF_NLEFT || g_parsefile->buf == NULL)
  8345. return PEOF;
  8346. flush_stdout_stderr();
  8347. more = parselleft;
  8348. if (more <= 0) {
  8349. again:
  8350. more = preadfd();
  8351. if (more <= 0) {
  8352. parselleft = parsenleft = EOF_NLEFT;
  8353. return PEOF;
  8354. }
  8355. }
  8356. q = parsenextc;
  8357. /* delete nul characters */
  8358. for (;;) {
  8359. int c;
  8360. more--;
  8361. c = *q;
  8362. if (!c)
  8363. memmove(q, q + 1, more);
  8364. else {
  8365. q++;
  8366. if (c == '\n') {
  8367. parsenleft = q - parsenextc - 1;
  8368. break;
  8369. }
  8370. }
  8371. if (more <= 0) {
  8372. parsenleft = q - parsenextc - 1;
  8373. if (parsenleft < 0)
  8374. goto again;
  8375. break;
  8376. }
  8377. }
  8378. parselleft = more;
  8379. savec = *q;
  8380. *q = '\0';
  8381. if (vflag) {
  8382. out2str(parsenextc);
  8383. }
  8384. *q = savec;
  8385. return signed_char2int(*parsenextc++);
  8386. }
  8387. #define pgetc_as_macro() (--parsenleft >= 0? signed_char2int(*parsenextc++) : preadbuffer())
  8388. static int
  8389. pgetc(void)
  8390. {
  8391. return pgetc_as_macro();
  8392. }
  8393. #if ENABLE_ASH_OPTIMIZE_FOR_SIZE
  8394. #define pgetc_macro() pgetc()
  8395. #else
  8396. #define pgetc_macro() pgetc_as_macro()
  8397. #endif
  8398. /*
  8399. * Same as pgetc(), but ignores PEOA.
  8400. */
  8401. #if ENABLE_ASH_ALIAS
  8402. static int
  8403. pgetc2(void)
  8404. {
  8405. int c;
  8406. do {
  8407. c = pgetc_macro();
  8408. } while (c == PEOA);
  8409. return c;
  8410. }
  8411. #else
  8412. static int
  8413. pgetc2(void)
  8414. {
  8415. return pgetc_macro();
  8416. }
  8417. #endif
  8418. /*
  8419. * Read a line from the script.
  8420. */
  8421. static char *
  8422. pfgets(char *line, int len)
  8423. {
  8424. char *p = line;
  8425. int nleft = len;
  8426. int c;
  8427. while (--nleft > 0) {
  8428. c = pgetc2();
  8429. if (c == PEOF) {
  8430. if (p == line)
  8431. return NULL;
  8432. break;
  8433. }
  8434. *p++ = c;
  8435. if (c == '\n')
  8436. break;
  8437. }
  8438. *p = '\0';
  8439. return line;
  8440. }
  8441. /*
  8442. * Undo the last call to pgetc. Only one character may be pushed back.
  8443. * PEOF may be pushed back.
  8444. */
  8445. static void
  8446. pungetc(void)
  8447. {
  8448. parsenleft++;
  8449. parsenextc--;
  8450. }
  8451. /*
  8452. * Push a string back onto the input at this current parsefile level.
  8453. * We handle aliases this way.
  8454. */
  8455. #if !ENABLE_ASH_ALIAS
  8456. #define pushstring(s, ap) pushstring(s)
  8457. #endif
  8458. static void
  8459. pushstring(char *s, struct alias *ap)
  8460. {
  8461. struct strpush *sp;
  8462. size_t len;
  8463. len = strlen(s);
  8464. INT_OFF;
  8465. /*dprintf("*** calling pushstring: %s, %d\n", s, len);*/
  8466. if (g_parsefile->strpush) {
  8467. sp = ckzalloc(sizeof(struct strpush));
  8468. sp->prev = g_parsefile->strpush;
  8469. g_parsefile->strpush = sp;
  8470. } else
  8471. sp = g_parsefile->strpush = &(g_parsefile->basestrpush);
  8472. sp->prevstring = parsenextc;
  8473. sp->prevnleft = parsenleft;
  8474. #if ENABLE_ASH_ALIAS
  8475. sp->ap = ap;
  8476. if (ap) {
  8477. ap->flag |= ALIASINUSE;
  8478. sp->string = s;
  8479. }
  8480. #endif
  8481. parsenextc = s;
  8482. parsenleft = len;
  8483. INT_ON;
  8484. }
  8485. /*
  8486. * To handle the "." command, a stack of input files is used. Pushfile
  8487. * adds a new entry to the stack and popfile restores the previous level.
  8488. */
  8489. static void
  8490. pushfile(void)
  8491. {
  8492. struct parsefile *pf;
  8493. g_parsefile->nleft = parsenleft;
  8494. g_parsefile->lleft = parselleft;
  8495. g_parsefile->nextc = parsenextc;
  8496. g_parsefile->linno = plinno;
  8497. pf = ckzalloc(sizeof(*pf));
  8498. pf->prev = g_parsefile;
  8499. pf->fd = -1;
  8500. /*pf->strpush = NULL; - ckzalloc did it */
  8501. /*pf->basestrpush.prev = NULL;*/
  8502. g_parsefile = pf;
  8503. }
  8504. static void
  8505. popfile(void)
  8506. {
  8507. struct parsefile *pf = g_parsefile;
  8508. INT_OFF;
  8509. if (pf->fd >= 0)
  8510. close(pf->fd);
  8511. free(pf->buf);
  8512. while (pf->strpush)
  8513. popstring();
  8514. g_parsefile = pf->prev;
  8515. free(pf);
  8516. parsenleft = g_parsefile->nleft;
  8517. parselleft = g_parsefile->lleft;
  8518. parsenextc = g_parsefile->nextc;
  8519. plinno = g_parsefile->linno;
  8520. INT_ON;
  8521. }
  8522. /*
  8523. * Return to top level.
  8524. */
  8525. static void
  8526. popallfiles(void)
  8527. {
  8528. while (g_parsefile != &basepf)
  8529. popfile();
  8530. }
  8531. /*
  8532. * Close the file(s) that the shell is reading commands from. Called
  8533. * after a fork is done.
  8534. */
  8535. static void
  8536. closescript(void)
  8537. {
  8538. popallfiles();
  8539. if (g_parsefile->fd > 0) {
  8540. close(g_parsefile->fd);
  8541. g_parsefile->fd = 0;
  8542. }
  8543. }
  8544. /*
  8545. * Like setinputfile, but takes an open file descriptor. Call this with
  8546. * interrupts off.
  8547. */
  8548. static void
  8549. setinputfd(int fd, int push)
  8550. {
  8551. close_on_exec_on(fd);
  8552. if (push) {
  8553. pushfile();
  8554. g_parsefile->buf = 0;
  8555. }
  8556. g_parsefile->fd = fd;
  8557. if (g_parsefile->buf == NULL)
  8558. g_parsefile->buf = ckmalloc(IBUFSIZ);
  8559. parselleft = parsenleft = 0;
  8560. plinno = 1;
  8561. }
  8562. /*
  8563. * Set the input to take input from a file. If push is set, push the
  8564. * old input onto the stack first.
  8565. */
  8566. static int
  8567. setinputfile(const char *fname, int flags)
  8568. {
  8569. int fd;
  8570. int fd2;
  8571. INT_OFF;
  8572. fd = open(fname, O_RDONLY);
  8573. if (fd < 0) {
  8574. if (flags & INPUT_NOFILE_OK)
  8575. goto out;
  8576. ash_msg_and_raise_error("can't open %s", fname);
  8577. }
  8578. if (fd < 10) {
  8579. fd2 = copyfd(fd, 10);
  8580. close(fd);
  8581. if (fd2 < 0)
  8582. ash_msg_and_raise_error("out of file descriptors");
  8583. fd = fd2;
  8584. }
  8585. setinputfd(fd, flags & INPUT_PUSH_FILE);
  8586. out:
  8587. INT_ON;
  8588. return fd;
  8589. }
  8590. /*
  8591. * Like setinputfile, but takes input from a string.
  8592. */
  8593. static void
  8594. setinputstring(char *string)
  8595. {
  8596. INT_OFF;
  8597. pushfile();
  8598. parsenextc = string;
  8599. parsenleft = strlen(string);
  8600. g_parsefile->buf = NULL;
  8601. plinno = 1;
  8602. INT_ON;
  8603. }
  8604. /* ============ mail.c
  8605. *
  8606. * Routines to check for mail.
  8607. */
  8608. #if ENABLE_ASH_MAIL
  8609. #define MAXMBOXES 10
  8610. /* times of mailboxes */
  8611. static time_t mailtime[MAXMBOXES];
  8612. /* Set if MAIL or MAILPATH is changed. */
  8613. static smallint mail_var_path_changed;
  8614. /*
  8615. * Print appropriate message(s) if mail has arrived.
  8616. * If mail_var_path_changed is set,
  8617. * then the value of MAIL has mail_var_path_changed,
  8618. * so we just update the values.
  8619. */
  8620. static void
  8621. chkmail(void)
  8622. {
  8623. const char *mpath;
  8624. char *p;
  8625. char *q;
  8626. time_t *mtp;
  8627. struct stackmark smark;
  8628. struct stat statb;
  8629. setstackmark(&smark);
  8630. mpath = mpathset() ? mpathval() : mailval();
  8631. for (mtp = mailtime; mtp < mailtime + MAXMBOXES; mtp++) {
  8632. p = padvance(&mpath, nullstr);
  8633. if (p == NULL)
  8634. break;
  8635. if (*p == '\0')
  8636. continue;
  8637. for (q = p; *q; q++)
  8638. continue;
  8639. #if DEBUG
  8640. if (q[-1] != '/')
  8641. abort();
  8642. #endif
  8643. q[-1] = '\0'; /* delete trailing '/' */
  8644. if (stat(p, &statb) < 0) {
  8645. *mtp = 0;
  8646. continue;
  8647. }
  8648. if (!mail_var_path_changed && statb.st_mtime != *mtp) {
  8649. fprintf(
  8650. stderr, snlfmt,
  8651. pathopt ? pathopt : "you have mail"
  8652. );
  8653. }
  8654. *mtp = statb.st_mtime;
  8655. }
  8656. mail_var_path_changed = 0;
  8657. popstackmark(&smark);
  8658. }
  8659. static void
  8660. changemail(const char *val UNUSED_PARAM)
  8661. {
  8662. mail_var_path_changed = 1;
  8663. }
  8664. #endif /* ASH_MAIL */
  8665. /* ============ ??? */
  8666. /*
  8667. * Set the shell parameters.
  8668. */
  8669. static void
  8670. setparam(char **argv)
  8671. {
  8672. char **newparam;
  8673. char **ap;
  8674. int nparam;
  8675. for (nparam = 0; argv[nparam]; nparam++)
  8676. continue;
  8677. ap = newparam = ckmalloc((nparam + 1) * sizeof(*ap));
  8678. while (*argv) {
  8679. *ap++ = ckstrdup(*argv++);
  8680. }
  8681. *ap = NULL;
  8682. freeparam(&shellparam);
  8683. shellparam.malloced = 1;
  8684. shellparam.nparam = nparam;
  8685. shellparam.p = newparam;
  8686. #if ENABLE_ASH_GETOPTS
  8687. shellparam.optind = 1;
  8688. shellparam.optoff = -1;
  8689. #endif
  8690. }
  8691. /*
  8692. * Process shell options. The global variable argptr contains a pointer
  8693. * to the argument list; we advance it past the options.
  8694. *
  8695. * SUSv3 section 2.8.1 "Consequences of Shell Errors" says:
  8696. * For a non-interactive shell, an error condition encountered
  8697. * by a special built-in ... shall cause the shell to write a diagnostic message
  8698. * to standard error and exit as shown in the following table:
  8699. * Error Special Built-In
  8700. * ...
  8701. * Utility syntax error (option or operand error) Shall exit
  8702. * ...
  8703. * However, in bug 1142 (http://busybox.net/bugs/view.php?id=1142)
  8704. * we see that bash does not do that (set "finishes" with error code 1 instead,
  8705. * and shell continues), and people rely on this behavior!
  8706. * Testcase:
  8707. * set -o barfoo 2>/dev/null
  8708. * echo $?
  8709. *
  8710. * Oh well. Let's mimic that.
  8711. */
  8712. static int
  8713. plus_minus_o(char *name, int val)
  8714. {
  8715. int i;
  8716. if (name) {
  8717. for (i = 0; i < NOPTS; i++) {
  8718. if (strcmp(name, optnames(i)) == 0) {
  8719. optlist[i] = val;
  8720. return 0;
  8721. }
  8722. }
  8723. ash_msg("illegal option %co %s", val ? '-' : '+', name);
  8724. return 1;
  8725. }
  8726. for (i = 0; i < NOPTS; i++) {
  8727. if (val) {
  8728. out1fmt("%-16s%s\n", optnames(i), optlist[i] ? "on" : "off");
  8729. } else {
  8730. out1fmt("set %co %s\n", optlist[i] ? '-' : '+', optnames(i));
  8731. }
  8732. }
  8733. return 0;
  8734. }
  8735. static void
  8736. setoption(int flag, int val)
  8737. {
  8738. int i;
  8739. for (i = 0; i < NOPTS; i++) {
  8740. if (optletters(i) == flag) {
  8741. optlist[i] = val;
  8742. return;
  8743. }
  8744. }
  8745. ash_msg_and_raise_error("illegal option %c%c", val ? '-' : '+', flag);
  8746. /* NOTREACHED */
  8747. }
  8748. static int
  8749. options(int cmdline)
  8750. {
  8751. char *p;
  8752. int val;
  8753. int c;
  8754. if (cmdline)
  8755. minusc = NULL;
  8756. while ((p = *argptr) != NULL) {
  8757. c = *p++;
  8758. if (c != '-' && c != '+')
  8759. break;
  8760. argptr++;
  8761. val = 0; /* val = 0 if c == '+' */
  8762. if (c == '-') {
  8763. val = 1;
  8764. if (p[0] == '\0' || LONE_DASH(p)) {
  8765. if (!cmdline) {
  8766. /* "-" means turn off -x and -v */
  8767. if (p[0] == '\0')
  8768. xflag = vflag = 0;
  8769. /* "--" means reset params */
  8770. else if (*argptr == NULL)
  8771. setparam(argptr);
  8772. }
  8773. break; /* "-" or "--" terminates options */
  8774. }
  8775. }
  8776. /* first char was + or - */
  8777. while ((c = *p++) != '\0') {
  8778. /* bash 3.2 indeed handles -c CMD and +c CMD the same */
  8779. if (c == 'c' && cmdline) {
  8780. minusc = p; /* command is after shell args */
  8781. } else if (c == 'o') {
  8782. if (plus_minus_o(*argptr, val)) {
  8783. /* it already printed err message */
  8784. return 1; /* error */
  8785. }
  8786. if (*argptr)
  8787. argptr++;
  8788. } else if (cmdline && (c == 'l')) { /* -l or +l == --login */
  8789. isloginsh = 1;
  8790. /* bash does not accept +-login, we also won't */
  8791. } else if (cmdline && val && (c == '-')) { /* long options */
  8792. if (strcmp(p, "login") == 0)
  8793. isloginsh = 1;
  8794. break;
  8795. } else {
  8796. setoption(c, val);
  8797. }
  8798. }
  8799. }
  8800. return 0;
  8801. }
  8802. /*
  8803. * The shift builtin command.
  8804. */
  8805. static int
  8806. shiftcmd(int argc UNUSED_PARAM, char **argv)
  8807. {
  8808. int n;
  8809. char **ap1, **ap2;
  8810. n = 1;
  8811. if (argv[1])
  8812. n = number(argv[1]);
  8813. if (n > shellparam.nparam)
  8814. n = 0; /* bash compat, was = shellparam.nparam; */
  8815. INT_OFF;
  8816. shellparam.nparam -= n;
  8817. for (ap1 = shellparam.p; --n >= 0; ap1++) {
  8818. if (shellparam.malloced)
  8819. free(*ap1);
  8820. }
  8821. ap2 = shellparam.p;
  8822. while ((*ap2++ = *ap1++) != NULL)
  8823. continue;
  8824. #if ENABLE_ASH_GETOPTS
  8825. shellparam.optind = 1;
  8826. shellparam.optoff = -1;
  8827. #endif
  8828. INT_ON;
  8829. return 0;
  8830. }
  8831. /*
  8832. * POSIX requires that 'set' (but not export or readonly) output the
  8833. * variables in lexicographic order - by the locale's collating order (sigh).
  8834. * Maybe we could keep them in an ordered balanced binary tree
  8835. * instead of hashed lists.
  8836. * For now just roll 'em through qsort for printing...
  8837. */
  8838. static int
  8839. showvars(const char *sep_prefix, int on, int off)
  8840. {
  8841. const char *sep;
  8842. char **ep, **epend;
  8843. ep = listvars(on, off, &epend);
  8844. qsort(ep, epend - ep, sizeof(char *), vpcmp);
  8845. sep = *sep_prefix ? " " : sep_prefix;
  8846. for (; ep < epend; ep++) {
  8847. const char *p;
  8848. const char *q;
  8849. p = strchrnul(*ep, '=');
  8850. q = nullstr;
  8851. if (*p)
  8852. q = single_quote(++p);
  8853. out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
  8854. }
  8855. return 0;
  8856. }
  8857. /*
  8858. * The set command builtin.
  8859. */
  8860. static int
  8861. setcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  8862. {
  8863. int retval;
  8864. if (!argv[1])
  8865. return showvars(nullstr, 0, VUNSET);
  8866. INT_OFF;
  8867. retval = 1;
  8868. if (!options(0)) { /* if no parse error... */
  8869. retval = 0;
  8870. optschanged();
  8871. if (*argptr != NULL) {
  8872. setparam(argptr);
  8873. }
  8874. }
  8875. INT_ON;
  8876. return retval;
  8877. }
  8878. #if ENABLE_ASH_RANDOM_SUPPORT
  8879. static void
  8880. change_random(const char *value)
  8881. {
  8882. /* Galois LFSR parameter */
  8883. /* Taps at 32 31 29 1: */
  8884. enum { MASK = 0x8000000b };
  8885. /* Another example - taps at 32 31 30 10: */
  8886. /* MASK = 0x00400007 */
  8887. if (value == NULL) {
  8888. /* "get", generate */
  8889. uint32_t t;
  8890. /* LCG has period of 2^32 and alternating lowest bit */
  8891. random_LCG = 1664525 * random_LCG + 1013904223;
  8892. /* Galois LFSR has period of 2^32-1 = 3 * 5 * 17 * 257 * 65537 */
  8893. t = (random_galois_LFSR << 1);
  8894. if (random_galois_LFSR < 0) /* if we just shifted 1 out of msb... */
  8895. t ^= MASK;
  8896. random_galois_LFSR = t;
  8897. /* Both are weak, combining them gives better randomness
  8898. * and ~2^64 period. & 0x7fff is probably bash compat
  8899. * for $RANDOM range. Combining with subtraction is
  8900. * just for fun. + and ^ would work equally well. */
  8901. t = (t - random_LCG) & 0x7fff;
  8902. /* set without recursion */
  8903. setvar(vrandom.text, utoa(t), VNOFUNC);
  8904. vrandom.flags &= ~VNOFUNC;
  8905. } else {
  8906. /* set/reset */
  8907. random_galois_LFSR = random_LCG = strtoul(value, (char **)NULL, 10);
  8908. }
  8909. }
  8910. #endif
  8911. #if ENABLE_ASH_GETOPTS
  8912. static int
  8913. getopts(char *optstr, char *optvar, char **optfirst, int *param_optind, int *optoff)
  8914. {
  8915. char *p, *q;
  8916. char c = '?';
  8917. int done = 0;
  8918. int err = 0;
  8919. char s[12];
  8920. char **optnext;
  8921. if (*param_optind < 1)
  8922. return 1;
  8923. optnext = optfirst + *param_optind - 1;
  8924. if (*param_optind <= 1 || *optoff < 0 || (int)strlen(optnext[-1]) < *optoff)
  8925. p = NULL;
  8926. else
  8927. p = optnext[-1] + *optoff;
  8928. if (p == NULL || *p == '\0') {
  8929. /* Current word is done, advance */
  8930. p = *optnext;
  8931. if (p == NULL || *p != '-' || *++p == '\0') {
  8932. atend:
  8933. p = NULL;
  8934. done = 1;
  8935. goto out;
  8936. }
  8937. optnext++;
  8938. if (LONE_DASH(p)) /* check for "--" */
  8939. goto atend;
  8940. }
  8941. c = *p++;
  8942. for (q = optstr; *q != c;) {
  8943. if (*q == '\0') {
  8944. if (optstr[0] == ':') {
  8945. s[0] = c;
  8946. s[1] = '\0';
  8947. err |= setvarsafe("OPTARG", s, 0);
  8948. } else {
  8949. fprintf(stderr, "Illegal option -%c\n", c);
  8950. unsetvar("OPTARG");
  8951. }
  8952. c = '?';
  8953. goto out;
  8954. }
  8955. if (*++q == ':')
  8956. q++;
  8957. }
  8958. if (*++q == ':') {
  8959. if (*p == '\0' && (p = *optnext) == NULL) {
  8960. if (optstr[0] == ':') {
  8961. s[0] = c;
  8962. s[1] = '\0';
  8963. err |= setvarsafe("OPTARG", s, 0);
  8964. c = ':';
  8965. } else {
  8966. fprintf(stderr, "No arg for -%c option\n", c);
  8967. unsetvar("OPTARG");
  8968. c = '?';
  8969. }
  8970. goto out;
  8971. }
  8972. if (p == *optnext)
  8973. optnext++;
  8974. err |= setvarsafe("OPTARG", p, 0);
  8975. p = NULL;
  8976. } else
  8977. err |= setvarsafe("OPTARG", nullstr, 0);
  8978. out:
  8979. *optoff = p ? p - *(optnext - 1) : -1;
  8980. *param_optind = optnext - optfirst + 1;
  8981. fmtstr(s, sizeof(s), "%d", *param_optind);
  8982. err |= setvarsafe("OPTIND", s, VNOFUNC);
  8983. s[0] = c;
  8984. s[1] = '\0';
  8985. err |= setvarsafe(optvar, s, 0);
  8986. if (err) {
  8987. *param_optind = 1;
  8988. *optoff = -1;
  8989. flush_stdout_stderr();
  8990. raise_exception(EXERROR);
  8991. }
  8992. return done;
  8993. }
  8994. /*
  8995. * The getopts builtin. Shellparam.optnext points to the next argument
  8996. * to be processed. Shellparam.optptr points to the next character to
  8997. * be processed in the current argument. If shellparam.optnext is NULL,
  8998. * then it's the first time getopts has been called.
  8999. */
  9000. static int
  9001. getoptscmd(int argc, char **argv)
  9002. {
  9003. char **optbase;
  9004. if (argc < 3)
  9005. ash_msg_and_raise_error("usage: getopts optstring var [arg]");
  9006. if (argc == 3) {
  9007. optbase = shellparam.p;
  9008. if (shellparam.optind > shellparam.nparam + 1) {
  9009. shellparam.optind = 1;
  9010. shellparam.optoff = -1;
  9011. }
  9012. } else {
  9013. optbase = &argv[3];
  9014. if (shellparam.optind > argc - 2) {
  9015. shellparam.optind = 1;
  9016. shellparam.optoff = -1;
  9017. }
  9018. }
  9019. return getopts(argv[1], argv[2], optbase, &shellparam.optind,
  9020. &shellparam.optoff);
  9021. }
  9022. #endif /* ASH_GETOPTS */
  9023. /* ============ Shell parser */
  9024. struct heredoc {
  9025. struct heredoc *next; /* next here document in list */
  9026. union node *here; /* redirection node */
  9027. char *eofmark; /* string indicating end of input */
  9028. smallint striptabs; /* if set, strip leading tabs */
  9029. };
  9030. static smallint tokpushback; /* last token pushed back */
  9031. static smallint parsebackquote; /* nonzero if we are inside backquotes */
  9032. static smallint quoteflag; /* set if (part of) last token was quoted */
  9033. static token_id_t lasttoken; /* last token read (integer id Txxx) */
  9034. static struct heredoc *heredoclist; /* list of here documents to read */
  9035. static char *wordtext; /* text of last word returned by readtoken */
  9036. static struct nodelist *backquotelist;
  9037. static union node *redirnode;
  9038. static struct heredoc *heredoc;
  9039. /*
  9040. * NEOF is returned by parsecmd when it encounters an end of file. It
  9041. * must be distinct from NULL, so we use the address of a variable that
  9042. * happens to be handy.
  9043. */
  9044. #define NEOF ((union node *)&tokpushback)
  9045. static void raise_error_syntax(const char *) NORETURN;
  9046. static void
  9047. raise_error_syntax(const char *msg)
  9048. {
  9049. ash_msg_and_raise_error("syntax error: %s", msg);
  9050. /* NOTREACHED */
  9051. }
  9052. /*
  9053. * Called when an unexpected token is read during the parse. The argument
  9054. * is the token that is expected, or -1 if more than one type of token can
  9055. * occur at this point.
  9056. */
  9057. static void raise_error_unexpected_syntax(int) NORETURN;
  9058. static void
  9059. raise_error_unexpected_syntax(int token)
  9060. {
  9061. char msg[64];
  9062. int l;
  9063. l = sprintf(msg, "%s unexpected", tokname(lasttoken));
  9064. if (token >= 0)
  9065. sprintf(msg + l, " (expecting %s)", tokname(token));
  9066. raise_error_syntax(msg);
  9067. /* NOTREACHED */
  9068. }
  9069. #define EOFMARKLEN 79
  9070. /* parsing is heavily cross-recursive, need these forward decls */
  9071. static union node *andor(void);
  9072. static union node *pipeline(void);
  9073. static union node *parse_command(void);
  9074. static void parseheredoc(void);
  9075. static char peektoken(void);
  9076. static int readtoken(void);
  9077. static union node *
  9078. list(int nlflag)
  9079. {
  9080. union node *n1, *n2, *n3;
  9081. int tok;
  9082. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  9083. if (nlflag == 2 && peektoken())
  9084. return NULL;
  9085. n1 = NULL;
  9086. for (;;) {
  9087. n2 = andor();
  9088. tok = readtoken();
  9089. if (tok == TBACKGND) {
  9090. if (n2->type == NPIPE) {
  9091. n2->npipe.pipe_backgnd = 1;
  9092. } else {
  9093. if (n2->type != NREDIR) {
  9094. n3 = stzalloc(sizeof(struct nredir));
  9095. n3->nredir.n = n2;
  9096. /*n3->nredir.redirect = NULL; - stzalloc did it */
  9097. n2 = n3;
  9098. }
  9099. n2->type = NBACKGND;
  9100. }
  9101. }
  9102. if (n1 == NULL) {
  9103. n1 = n2;
  9104. } else {
  9105. n3 = stzalloc(sizeof(struct nbinary));
  9106. n3->type = NSEMI;
  9107. n3->nbinary.ch1 = n1;
  9108. n3->nbinary.ch2 = n2;
  9109. n1 = n3;
  9110. }
  9111. switch (tok) {
  9112. case TBACKGND:
  9113. case TSEMI:
  9114. tok = readtoken();
  9115. /* fall through */
  9116. case TNL:
  9117. if (tok == TNL) {
  9118. parseheredoc();
  9119. if (nlflag == 1)
  9120. return n1;
  9121. } else {
  9122. tokpushback = 1;
  9123. }
  9124. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  9125. if (peektoken())
  9126. return n1;
  9127. break;
  9128. case TEOF:
  9129. if (heredoclist)
  9130. parseheredoc();
  9131. else
  9132. pungetc(); /* push back EOF on input */
  9133. return n1;
  9134. default:
  9135. if (nlflag == 1)
  9136. raise_error_unexpected_syntax(-1);
  9137. tokpushback = 1;
  9138. return n1;
  9139. }
  9140. }
  9141. }
  9142. static union node *
  9143. andor(void)
  9144. {
  9145. union node *n1, *n2, *n3;
  9146. int t;
  9147. n1 = pipeline();
  9148. for (;;) {
  9149. t = readtoken();
  9150. if (t == TAND) {
  9151. t = NAND;
  9152. } else if (t == TOR) {
  9153. t = NOR;
  9154. } else {
  9155. tokpushback = 1;
  9156. return n1;
  9157. }
  9158. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  9159. n2 = pipeline();
  9160. n3 = stzalloc(sizeof(struct nbinary));
  9161. n3->type = t;
  9162. n3->nbinary.ch1 = n1;
  9163. n3->nbinary.ch2 = n2;
  9164. n1 = n3;
  9165. }
  9166. }
  9167. static union node *
  9168. pipeline(void)
  9169. {
  9170. union node *n1, *n2, *pipenode;
  9171. struct nodelist *lp, *prev;
  9172. int negate;
  9173. negate = 0;
  9174. TRACE(("pipeline: entered\n"));
  9175. if (readtoken() == TNOT) {
  9176. negate = !negate;
  9177. checkkwd = CHKKWD | CHKALIAS;
  9178. } else
  9179. tokpushback = 1;
  9180. n1 = parse_command();
  9181. if (readtoken() == TPIPE) {
  9182. pipenode = stzalloc(sizeof(struct npipe));
  9183. pipenode->type = NPIPE;
  9184. /*pipenode->npipe.pipe_backgnd = 0; - stzalloc did it */
  9185. lp = stzalloc(sizeof(struct nodelist));
  9186. pipenode->npipe.cmdlist = lp;
  9187. lp->n = n1;
  9188. do {
  9189. prev = lp;
  9190. lp = stzalloc(sizeof(struct nodelist));
  9191. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  9192. lp->n = parse_command();
  9193. prev->next = lp;
  9194. } while (readtoken() == TPIPE);
  9195. lp->next = NULL;
  9196. n1 = pipenode;
  9197. }
  9198. tokpushback = 1;
  9199. if (negate) {
  9200. n2 = stzalloc(sizeof(struct nnot));
  9201. n2->type = NNOT;
  9202. n2->nnot.com = n1;
  9203. return n2;
  9204. }
  9205. return n1;
  9206. }
  9207. static union node *
  9208. makename(void)
  9209. {
  9210. union node *n;
  9211. n = stzalloc(sizeof(struct narg));
  9212. n->type = NARG;
  9213. /*n->narg.next = NULL; - stzalloc did it */
  9214. n->narg.text = wordtext;
  9215. n->narg.backquote = backquotelist;
  9216. return n;
  9217. }
  9218. static void
  9219. fixredir(union node *n, const char *text, int err)
  9220. {
  9221. int fd;
  9222. TRACE(("Fix redir %s %d\n", text, err));
  9223. if (!err)
  9224. n->ndup.vname = NULL;
  9225. fd = bb_strtou(text, NULL, 10);
  9226. if (!errno && fd >= 0)
  9227. n->ndup.dupfd = fd;
  9228. else if (LONE_DASH(text))
  9229. n->ndup.dupfd = -1;
  9230. else {
  9231. if (err)
  9232. raise_error_syntax("Bad fd number");
  9233. n->ndup.vname = makename();
  9234. }
  9235. }
  9236. /*
  9237. * Returns true if the text contains nothing to expand (no dollar signs
  9238. * or backquotes).
  9239. */
  9240. static int
  9241. noexpand(char *text)
  9242. {
  9243. char *p;
  9244. char c;
  9245. p = text;
  9246. while ((c = *p++) != '\0') {
  9247. if (c == CTLQUOTEMARK)
  9248. continue;
  9249. if (c == CTLESC)
  9250. p++;
  9251. else if (SIT(c, BASESYNTAX) == CCTL)
  9252. return 0;
  9253. }
  9254. return 1;
  9255. }
  9256. static void
  9257. parsefname(void)
  9258. {
  9259. union node *n = redirnode;
  9260. if (readtoken() != TWORD)
  9261. raise_error_unexpected_syntax(-1);
  9262. if (n->type == NHERE) {
  9263. struct heredoc *here = heredoc;
  9264. struct heredoc *p;
  9265. int i;
  9266. if (quoteflag == 0)
  9267. n->type = NXHERE;
  9268. TRACE(("Here document %d\n", n->type));
  9269. if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
  9270. raise_error_syntax("Illegal eof marker for << redirection");
  9271. rmescapes(wordtext);
  9272. here->eofmark = wordtext;
  9273. here->next = NULL;
  9274. if (heredoclist == NULL)
  9275. heredoclist = here;
  9276. else {
  9277. for (p = heredoclist; p->next; p = p->next)
  9278. continue;
  9279. p->next = here;
  9280. }
  9281. } else if (n->type == NTOFD || n->type == NFROMFD) {
  9282. fixredir(n, wordtext, 0);
  9283. } else {
  9284. n->nfile.fname = makename();
  9285. }
  9286. }
  9287. static union node *
  9288. simplecmd(void)
  9289. {
  9290. union node *args, **app;
  9291. union node *n = NULL;
  9292. union node *vars, **vpp;
  9293. union node **rpp, *redir;
  9294. int savecheckkwd;
  9295. #if ENABLE_ASH_BASH_COMPAT
  9296. smallint double_brackets_flag = 0;
  9297. #endif
  9298. args = NULL;
  9299. app = &args;
  9300. vars = NULL;
  9301. vpp = &vars;
  9302. redir = NULL;
  9303. rpp = &redir;
  9304. savecheckkwd = CHKALIAS;
  9305. for (;;) {
  9306. int t;
  9307. checkkwd = savecheckkwd;
  9308. t = readtoken();
  9309. switch (t) {
  9310. #if ENABLE_ASH_BASH_COMPAT
  9311. case TAND: /* "&&" */
  9312. case TOR: /* "||" */
  9313. if (!double_brackets_flag) {
  9314. tokpushback = 1;
  9315. goto out;
  9316. }
  9317. wordtext = (char *) (t == TAND ? "-a" : "-o");
  9318. #endif
  9319. case TWORD:
  9320. n = stzalloc(sizeof(struct narg));
  9321. n->type = NARG;
  9322. /*n->narg.next = NULL; - stzalloc did it */
  9323. n->narg.text = wordtext;
  9324. #if ENABLE_ASH_BASH_COMPAT
  9325. if (strcmp("[[", wordtext) == 0)
  9326. double_brackets_flag = 1;
  9327. else if (strcmp("]]", wordtext) == 0)
  9328. double_brackets_flag = 0;
  9329. #endif
  9330. n->narg.backquote = backquotelist;
  9331. if (savecheckkwd && isassignment(wordtext)) {
  9332. *vpp = n;
  9333. vpp = &n->narg.next;
  9334. } else {
  9335. *app = n;
  9336. app = &n->narg.next;
  9337. savecheckkwd = 0;
  9338. }
  9339. break;
  9340. case TREDIR:
  9341. *rpp = n = redirnode;
  9342. rpp = &n->nfile.next;
  9343. parsefname(); /* read name of redirection file */
  9344. break;
  9345. case TLP:
  9346. if (args && app == &args->narg.next
  9347. && !vars && !redir
  9348. ) {
  9349. struct builtincmd *bcmd;
  9350. const char *name;
  9351. /* We have a function */
  9352. if (readtoken() != TRP)
  9353. raise_error_unexpected_syntax(TRP);
  9354. name = n->narg.text;
  9355. if (!goodname(name)
  9356. || ((bcmd = find_builtin(name)) && IS_BUILTIN_SPECIAL(bcmd))
  9357. ) {
  9358. raise_error_syntax("Bad function name");
  9359. }
  9360. n->type = NDEFUN;
  9361. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  9362. n->narg.next = parse_command();
  9363. return n;
  9364. }
  9365. /* fall through */
  9366. default:
  9367. tokpushback = 1;
  9368. goto out;
  9369. }
  9370. }
  9371. out:
  9372. *app = NULL;
  9373. *vpp = NULL;
  9374. *rpp = NULL;
  9375. n = stzalloc(sizeof(struct ncmd));
  9376. n->type = NCMD;
  9377. n->ncmd.args = args;
  9378. n->ncmd.assign = vars;
  9379. n->ncmd.redirect = redir;
  9380. return n;
  9381. }
  9382. static union node *
  9383. parse_command(void)
  9384. {
  9385. union node *n1, *n2;
  9386. union node *ap, **app;
  9387. union node *cp, **cpp;
  9388. union node *redir, **rpp;
  9389. union node **rpp2;
  9390. int t;
  9391. redir = NULL;
  9392. rpp2 = &redir;
  9393. switch (readtoken()) {
  9394. default:
  9395. raise_error_unexpected_syntax(-1);
  9396. /* NOTREACHED */
  9397. case TIF:
  9398. n1 = stzalloc(sizeof(struct nif));
  9399. n1->type = NIF;
  9400. n1->nif.test = list(0);
  9401. if (readtoken() != TTHEN)
  9402. raise_error_unexpected_syntax(TTHEN);
  9403. n1->nif.ifpart = list(0);
  9404. n2 = n1;
  9405. while (readtoken() == TELIF) {
  9406. n2->nif.elsepart = stzalloc(sizeof(struct nif));
  9407. n2 = n2->nif.elsepart;
  9408. n2->type = NIF;
  9409. n2->nif.test = list(0);
  9410. if (readtoken() != TTHEN)
  9411. raise_error_unexpected_syntax(TTHEN);
  9412. n2->nif.ifpart = list(0);
  9413. }
  9414. if (lasttoken == TELSE)
  9415. n2->nif.elsepart = list(0);
  9416. else {
  9417. n2->nif.elsepart = NULL;
  9418. tokpushback = 1;
  9419. }
  9420. t = TFI;
  9421. break;
  9422. case TWHILE:
  9423. case TUNTIL: {
  9424. int got;
  9425. n1 = stzalloc(sizeof(struct nbinary));
  9426. n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
  9427. n1->nbinary.ch1 = list(0);
  9428. got = readtoken();
  9429. if (got != TDO) {
  9430. TRACE(("expecting DO got %s %s\n", tokname(got),
  9431. got == TWORD ? wordtext : ""));
  9432. raise_error_unexpected_syntax(TDO);
  9433. }
  9434. n1->nbinary.ch2 = list(0);
  9435. t = TDONE;
  9436. break;
  9437. }
  9438. case TFOR:
  9439. if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
  9440. raise_error_syntax("Bad for loop variable");
  9441. n1 = stzalloc(sizeof(struct nfor));
  9442. n1->type = NFOR;
  9443. n1->nfor.var = wordtext;
  9444. checkkwd = CHKKWD | CHKALIAS;
  9445. if (readtoken() == TIN) {
  9446. app = &ap;
  9447. while (readtoken() == TWORD) {
  9448. n2 = stzalloc(sizeof(struct narg));
  9449. n2->type = NARG;
  9450. /*n2->narg.next = NULL; - stzalloc did it */
  9451. n2->narg.text = wordtext;
  9452. n2->narg.backquote = backquotelist;
  9453. *app = n2;
  9454. app = &n2->narg.next;
  9455. }
  9456. *app = NULL;
  9457. n1->nfor.args = ap;
  9458. if (lasttoken != TNL && lasttoken != TSEMI)
  9459. raise_error_unexpected_syntax(-1);
  9460. } else {
  9461. n2 = stzalloc(sizeof(struct narg));
  9462. n2->type = NARG;
  9463. /*n2->narg.next = NULL; - stzalloc did it */
  9464. n2->narg.text = (char *)dolatstr;
  9465. /*n2->narg.backquote = NULL;*/
  9466. n1->nfor.args = n2;
  9467. /*
  9468. * Newline or semicolon here is optional (but note
  9469. * that the original Bourne shell only allowed NL).
  9470. */
  9471. if (lasttoken != TNL && lasttoken != TSEMI)
  9472. tokpushback = 1;
  9473. }
  9474. checkkwd = CHKNL | CHKKWD | CHKALIAS;
  9475. if (readtoken() != TDO)
  9476. raise_error_unexpected_syntax(TDO);
  9477. n1->nfor.body = list(0);
  9478. t = TDONE;
  9479. break;
  9480. case TCASE:
  9481. n1 = stzalloc(sizeof(struct ncase));
  9482. n1->type = NCASE;
  9483. if (readtoken() != TWORD)
  9484. raise_error_unexpected_syntax(TWORD);
  9485. n1->ncase.expr = n2 = stzalloc(sizeof(struct narg));
  9486. n2->type = NARG;
  9487. /*n2->narg.next = NULL; - stzalloc did it */
  9488. n2->narg.text = wordtext;
  9489. n2->narg.backquote = backquotelist;
  9490. do {
  9491. checkkwd = CHKKWD | CHKALIAS;
  9492. } while (readtoken() == TNL);
  9493. if (lasttoken != TIN)
  9494. raise_error_unexpected_syntax(TIN);
  9495. cpp = &n1->ncase.cases;
  9496. next_case:
  9497. checkkwd = CHKNL | CHKKWD;
  9498. t = readtoken();
  9499. while (t != TESAC) {
  9500. if (lasttoken == TLP)
  9501. readtoken();
  9502. *cpp = cp = stzalloc(sizeof(struct nclist));
  9503. cp->type = NCLIST;
  9504. app = &cp->nclist.pattern;
  9505. for (;;) {
  9506. *app = ap = stzalloc(sizeof(struct narg));
  9507. ap->type = NARG;
  9508. /*ap->narg.next = NULL; - stzalloc did it */
  9509. ap->narg.text = wordtext;
  9510. ap->narg.backquote = backquotelist;
  9511. if (readtoken() != TPIPE)
  9512. break;
  9513. app = &ap->narg.next;
  9514. readtoken();
  9515. }
  9516. //ap->narg.next = NULL;
  9517. if (lasttoken != TRP)
  9518. raise_error_unexpected_syntax(TRP);
  9519. cp->nclist.body = list(2);
  9520. cpp = &cp->nclist.next;
  9521. checkkwd = CHKNL | CHKKWD;
  9522. t = readtoken();
  9523. if (t != TESAC) {
  9524. if (t != TENDCASE)
  9525. raise_error_unexpected_syntax(TENDCASE);
  9526. goto next_case;
  9527. }
  9528. }
  9529. *cpp = NULL;
  9530. goto redir;
  9531. case TLP:
  9532. n1 = stzalloc(sizeof(struct nredir));
  9533. n1->type = NSUBSHELL;
  9534. n1->nredir.n = list(0);
  9535. /*n1->nredir.redirect = NULL; - stzalloc did it */
  9536. t = TRP;
  9537. break;
  9538. case TBEGIN:
  9539. n1 = list(0);
  9540. t = TEND;
  9541. break;
  9542. case TWORD:
  9543. case TREDIR:
  9544. tokpushback = 1;
  9545. return simplecmd();
  9546. }
  9547. if (readtoken() != t)
  9548. raise_error_unexpected_syntax(t);
  9549. redir:
  9550. /* Now check for redirection which may follow command */
  9551. checkkwd = CHKKWD | CHKALIAS;
  9552. rpp = rpp2;
  9553. while (readtoken() == TREDIR) {
  9554. *rpp = n2 = redirnode;
  9555. rpp = &n2->nfile.next;
  9556. parsefname();
  9557. }
  9558. tokpushback = 1;
  9559. *rpp = NULL;
  9560. if (redir) {
  9561. if (n1->type != NSUBSHELL) {
  9562. n2 = stzalloc(sizeof(struct nredir));
  9563. n2->type = NREDIR;
  9564. n2->nredir.n = n1;
  9565. n1 = n2;
  9566. }
  9567. n1->nredir.redirect = redir;
  9568. }
  9569. return n1;
  9570. }
  9571. #if ENABLE_ASH_BASH_COMPAT
  9572. static int decode_dollar_squote(void)
  9573. {
  9574. static const char C_escapes[] ALIGN1 = "nrbtfav""x\\01234567";
  9575. int c, cnt;
  9576. char *p;
  9577. char buf[4];
  9578. c = pgetc();
  9579. p = strchr(C_escapes, c);
  9580. if (p) {
  9581. buf[0] = c;
  9582. p = buf;
  9583. cnt = 3;
  9584. if ((unsigned char)(c - '0') <= 7) { /* \ooo */
  9585. do {
  9586. c = pgetc();
  9587. *++p = c;
  9588. } while ((unsigned char)(c - '0') <= 7 && --cnt);
  9589. pungetc();
  9590. } else if (c == 'x') { /* \xHH */
  9591. do {
  9592. c = pgetc();
  9593. *++p = c;
  9594. } while (isxdigit(c) && --cnt);
  9595. pungetc();
  9596. if (cnt == 3) { /* \x but next char is "bad" */
  9597. c = 'x';
  9598. goto unrecognized;
  9599. }
  9600. } else { /* simple seq like \\ or \t */
  9601. p++;
  9602. }
  9603. *p = '\0';
  9604. p = buf;
  9605. c = bb_process_escape_sequence((void*)&p);
  9606. } else { /* unrecognized "\z": print both chars unless ' or " */
  9607. if (c != '\'' && c != '"') {
  9608. unrecognized:
  9609. c |= 0x100; /* "please encode \, then me" */
  9610. }
  9611. }
  9612. return c;
  9613. }
  9614. #endif
  9615. /*
  9616. * If eofmark is NULL, read a word or a redirection symbol. If eofmark
  9617. * is not NULL, read a here document. In the latter case, eofmark is the
  9618. * word which marks the end of the document and striptabs is true if
  9619. * leading tabs should be stripped from the document. The argument firstc
  9620. * is the first character of the input token or document.
  9621. *
  9622. * Because C does not have internal subroutines, I have simulated them
  9623. * using goto's to implement the subroutine linkage. The following macros
  9624. * will run code that appears at the end of readtoken1.
  9625. */
  9626. #define CHECKEND() {goto checkend; checkend_return:;}
  9627. #define PARSEREDIR() {goto parseredir; parseredir_return:;}
  9628. #define PARSESUB() {goto parsesub; parsesub_return:;}
  9629. #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
  9630. #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
  9631. #define PARSEARITH() {goto parsearith; parsearith_return:;}
  9632. static int
  9633. readtoken1(int firstc, int syntax, char *eofmark, int striptabs)
  9634. {
  9635. /* NB: syntax parameter fits into smallint */
  9636. int c = firstc;
  9637. char *out;
  9638. int len;
  9639. char line[EOFMARKLEN + 1];
  9640. struct nodelist *bqlist;
  9641. smallint quotef;
  9642. smallint dblquote;
  9643. smallint oldstyle;
  9644. smallint prevsyntax; /* syntax before arithmetic */
  9645. #if ENABLE_ASH_EXPAND_PRMT
  9646. smallint pssyntax; /* we are expanding a prompt string */
  9647. #endif
  9648. int varnest; /* levels of variables expansion */
  9649. int arinest; /* levels of arithmetic expansion */
  9650. int parenlevel; /* levels of parens in arithmetic */
  9651. int dqvarnest; /* levels of variables expansion within double quotes */
  9652. USE_ASH_BASH_COMPAT(smallint bash_dollar_squote = 0;)
  9653. #if __GNUC__
  9654. /* Avoid longjmp clobbering */
  9655. (void) &out;
  9656. (void) &quotef;
  9657. (void) &dblquote;
  9658. (void) &varnest;
  9659. (void) &arinest;
  9660. (void) &parenlevel;
  9661. (void) &dqvarnest;
  9662. (void) &oldstyle;
  9663. (void) &prevsyntax;
  9664. (void) &syntax;
  9665. #endif
  9666. startlinno = plinno;
  9667. bqlist = NULL;
  9668. quotef = 0;
  9669. oldstyle = 0;
  9670. prevsyntax = 0;
  9671. #if ENABLE_ASH_EXPAND_PRMT
  9672. pssyntax = (syntax == PSSYNTAX);
  9673. if (pssyntax)
  9674. syntax = DQSYNTAX;
  9675. #endif
  9676. dblquote = (syntax == DQSYNTAX);
  9677. varnest = 0;
  9678. arinest = 0;
  9679. parenlevel = 0;
  9680. dqvarnest = 0;
  9681. STARTSTACKSTR(out);
  9682. loop: { /* for each line, until end of word */
  9683. CHECKEND(); /* set c to PEOF if at end of here document */
  9684. for (;;) { /* until end of line or end of word */
  9685. CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
  9686. switch (SIT(c, syntax)) {
  9687. case CNL: /* '\n' */
  9688. if (syntax == BASESYNTAX)
  9689. goto endword; /* exit outer loop */
  9690. USTPUTC(c, out);
  9691. plinno++;
  9692. if (doprompt)
  9693. setprompt(2);
  9694. c = pgetc();
  9695. goto loop; /* continue outer loop */
  9696. case CWORD:
  9697. USTPUTC(c, out);
  9698. break;
  9699. case CCTL:
  9700. if (eofmark == NULL || dblquote)
  9701. USTPUTC(CTLESC, out);
  9702. #if ENABLE_ASH_BASH_COMPAT
  9703. if (c == '\\' && bash_dollar_squote) {
  9704. c = decode_dollar_squote();
  9705. if (c & 0x100) {
  9706. USTPUTC('\\', out);
  9707. c = (unsigned char)c;
  9708. }
  9709. }
  9710. #endif
  9711. USTPUTC(c, out);
  9712. break;
  9713. case CBACK: /* backslash */
  9714. c = pgetc2();
  9715. if (c == PEOF) {
  9716. USTPUTC(CTLESC, out);
  9717. USTPUTC('\\', out);
  9718. pungetc();
  9719. } else if (c == '\n') {
  9720. if (doprompt)
  9721. setprompt(2);
  9722. } else {
  9723. #if ENABLE_ASH_EXPAND_PRMT
  9724. if (c == '$' && pssyntax) {
  9725. USTPUTC(CTLESC, out);
  9726. USTPUTC('\\', out);
  9727. }
  9728. #endif
  9729. if (dblquote && c != '\\'
  9730. && c != '`' && c != '$'
  9731. && (c != '"' || eofmark != NULL)
  9732. ) {
  9733. USTPUTC(CTLESC, out);
  9734. USTPUTC('\\', out);
  9735. }
  9736. if (SIT(c, SQSYNTAX) == CCTL)
  9737. USTPUTC(CTLESC, out);
  9738. USTPUTC(c, out);
  9739. quotef = 1;
  9740. }
  9741. break;
  9742. case CSQUOTE:
  9743. syntax = SQSYNTAX;
  9744. quotemark:
  9745. if (eofmark == NULL) {
  9746. USTPUTC(CTLQUOTEMARK, out);
  9747. }
  9748. break;
  9749. case CDQUOTE:
  9750. syntax = DQSYNTAX;
  9751. dblquote = 1;
  9752. goto quotemark;
  9753. case CENDQUOTE:
  9754. USE_ASH_BASH_COMPAT(bash_dollar_squote = 0;)
  9755. if (eofmark != NULL && arinest == 0
  9756. && varnest == 0
  9757. ) {
  9758. USTPUTC(c, out);
  9759. } else {
  9760. if (dqvarnest == 0) {
  9761. syntax = BASESYNTAX;
  9762. dblquote = 0;
  9763. }
  9764. quotef = 1;
  9765. goto quotemark;
  9766. }
  9767. break;
  9768. case CVAR: /* '$' */
  9769. PARSESUB(); /* parse substitution */
  9770. break;
  9771. case CENDVAR: /* '}' */
  9772. if (varnest > 0) {
  9773. varnest--;
  9774. if (dqvarnest > 0) {
  9775. dqvarnest--;
  9776. }
  9777. USTPUTC(CTLENDVAR, out);
  9778. } else {
  9779. USTPUTC(c, out);
  9780. }
  9781. break;
  9782. #if ENABLE_ASH_MATH_SUPPORT
  9783. case CLP: /* '(' in arithmetic */
  9784. parenlevel++;
  9785. USTPUTC(c, out);
  9786. break;
  9787. case CRP: /* ')' in arithmetic */
  9788. if (parenlevel > 0) {
  9789. USTPUTC(c, out);
  9790. --parenlevel;
  9791. } else {
  9792. if (pgetc() == ')') {
  9793. if (--arinest == 0) {
  9794. USTPUTC(CTLENDARI, out);
  9795. syntax = prevsyntax;
  9796. dblquote = (syntax == DQSYNTAX);
  9797. } else
  9798. USTPUTC(')', out);
  9799. } else {
  9800. /*
  9801. * unbalanced parens
  9802. * (don't 2nd guess - no error)
  9803. */
  9804. pungetc();
  9805. USTPUTC(')', out);
  9806. }
  9807. }
  9808. break;
  9809. #endif
  9810. case CBQUOTE: /* '`' */
  9811. PARSEBACKQOLD();
  9812. break;
  9813. case CENDFILE:
  9814. goto endword; /* exit outer loop */
  9815. case CIGN:
  9816. break;
  9817. default:
  9818. if (varnest == 0)
  9819. goto endword; /* exit outer loop */
  9820. #if ENABLE_ASH_ALIAS
  9821. if (c != PEOA)
  9822. #endif
  9823. USTPUTC(c, out);
  9824. }
  9825. c = pgetc_macro();
  9826. } /* for (;;) */
  9827. }
  9828. endword:
  9829. #if ENABLE_ASH_MATH_SUPPORT
  9830. if (syntax == ARISYNTAX)
  9831. raise_error_syntax("Missing '))'");
  9832. #endif
  9833. if (syntax != BASESYNTAX && !parsebackquote && eofmark == NULL)
  9834. raise_error_syntax("Unterminated quoted string");
  9835. if (varnest != 0) {
  9836. startlinno = plinno;
  9837. /* { */
  9838. raise_error_syntax("Missing '}'");
  9839. }
  9840. USTPUTC('\0', out);
  9841. len = out - (char *)stackblock();
  9842. out = stackblock();
  9843. if (eofmark == NULL) {
  9844. if ((c == '>' || c == '<') && quotef == 0) {
  9845. int maxlen = 9 + 1; /* max 9 digit fd#: 999999999 */
  9846. char *np = out;
  9847. while (--maxlen && isdigit(*np))
  9848. np++;
  9849. if (*np == '\0') {
  9850. PARSEREDIR(); /* passed as params: out, c */
  9851. lasttoken = TREDIR;
  9852. return lasttoken;
  9853. }
  9854. /* else: non-number X seen, interpret it
  9855. * as "NNNX>file" = "NNNX >file" */
  9856. }
  9857. pungetc();
  9858. }
  9859. quoteflag = quotef;
  9860. backquotelist = bqlist;
  9861. grabstackblock(len);
  9862. wordtext = out;
  9863. lasttoken = TWORD;
  9864. return lasttoken;
  9865. /* end of readtoken routine */
  9866. /*
  9867. * Check to see whether we are at the end of the here document. When this
  9868. * is called, c is set to the first character of the next input line. If
  9869. * we are at the end of the here document, this routine sets the c to PEOF.
  9870. */
  9871. checkend: {
  9872. if (eofmark) {
  9873. #if ENABLE_ASH_ALIAS
  9874. if (c == PEOA) {
  9875. c = pgetc2();
  9876. }
  9877. #endif
  9878. if (striptabs) {
  9879. while (c == '\t') {
  9880. c = pgetc2();
  9881. }
  9882. }
  9883. if (c == *eofmark) {
  9884. if (pfgets(line, sizeof(line)) != NULL) {
  9885. char *p, *q;
  9886. p = line;
  9887. for (q = eofmark + 1; *q && *p == *q; p++, q++)
  9888. continue;
  9889. if (*p == '\n' && *q == '\0') {
  9890. c = PEOF;
  9891. plinno++;
  9892. needprompt = doprompt;
  9893. } else {
  9894. pushstring(line, NULL);
  9895. }
  9896. }
  9897. }
  9898. }
  9899. goto checkend_return;
  9900. }
  9901. /*
  9902. * Parse a redirection operator. The variable "out" points to a string
  9903. * specifying the fd to be redirected. The variable "c" contains the
  9904. * first character of the redirection operator.
  9905. */
  9906. parseredir: {
  9907. /* out is already checked to be a valid number or "" */
  9908. int fd = (*out == '\0' ? -1 : atoi(out));
  9909. union node *np;
  9910. np = stzalloc(sizeof(struct nfile));
  9911. if (c == '>') {
  9912. np->nfile.fd = 1;
  9913. c = pgetc();
  9914. if (c == '>')
  9915. np->type = NAPPEND;
  9916. else if (c == '|')
  9917. np->type = NCLOBBER;
  9918. else if (c == '&')
  9919. np->type = NTOFD;
  9920. else {
  9921. np->type = NTO;
  9922. pungetc();
  9923. }
  9924. } else { /* c == '<' */
  9925. /*np->nfile.fd = 0; - stzalloc did it */
  9926. c = pgetc();
  9927. switch (c) {
  9928. case '<':
  9929. if (sizeof(struct nfile) != sizeof(struct nhere)) {
  9930. np = stzalloc(sizeof(struct nhere));
  9931. /*np->nfile.fd = 0; - stzalloc did it */
  9932. }
  9933. np->type = NHERE;
  9934. heredoc = stzalloc(sizeof(struct heredoc));
  9935. heredoc->here = np;
  9936. c = pgetc();
  9937. if (c == '-') {
  9938. heredoc->striptabs = 1;
  9939. } else {
  9940. /*heredoc->striptabs = 0; - stzalloc did it */
  9941. pungetc();
  9942. }
  9943. break;
  9944. case '&':
  9945. np->type = NFROMFD;
  9946. break;
  9947. case '>':
  9948. np->type = NFROMTO;
  9949. break;
  9950. default:
  9951. np->type = NFROM;
  9952. pungetc();
  9953. break;
  9954. }
  9955. }
  9956. if (fd >= 0)
  9957. np->nfile.fd = fd;
  9958. redirnode = np;
  9959. goto parseredir_return;
  9960. }
  9961. /*
  9962. * Parse a substitution. At this point, we have read the dollar sign
  9963. * and nothing else.
  9964. */
  9965. /* is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
  9966. * (assuming ascii char codes, as the original implementation did) */
  9967. #define is_special(c) \
  9968. (((unsigned)(c) - 33 < 32) \
  9969. && ((0xc1ff920dU >> ((unsigned)(c) - 33)) & 1))
  9970. parsesub: {
  9971. int subtype;
  9972. int typeloc;
  9973. int flags;
  9974. char *p;
  9975. static const char types[] ALIGN1 = "}-+?=";
  9976. c = pgetc();
  9977. if (c <= PEOA_OR_PEOF
  9978. || (c != '(' && c != '{' && !is_name(c) && !is_special(c))
  9979. ) {
  9980. #if ENABLE_ASH_BASH_COMPAT
  9981. if (c == '\'')
  9982. bash_dollar_squote = 1;
  9983. else
  9984. #endif
  9985. USTPUTC('$', out);
  9986. pungetc();
  9987. } else if (c == '(') { /* $(command) or $((arith)) */
  9988. if (pgetc() == '(') {
  9989. #if ENABLE_ASH_MATH_SUPPORT
  9990. PARSEARITH();
  9991. #else
  9992. raise_error_syntax("you disabled math support for $((arith)) syntax");
  9993. #endif
  9994. } else {
  9995. pungetc();
  9996. PARSEBACKQNEW();
  9997. }
  9998. } else {
  9999. USTPUTC(CTLVAR, out);
  10000. typeloc = out - (char *)stackblock();
  10001. USTPUTC(VSNORMAL, out);
  10002. subtype = VSNORMAL;
  10003. if (c == '{') {
  10004. c = pgetc();
  10005. if (c == '#') {
  10006. c = pgetc();
  10007. if (c == '}')
  10008. c = '#';
  10009. else
  10010. subtype = VSLENGTH;
  10011. } else
  10012. subtype = 0;
  10013. }
  10014. if (c > PEOA_OR_PEOF && is_name(c)) {
  10015. do {
  10016. STPUTC(c, out);
  10017. c = pgetc();
  10018. } while (c > PEOA_OR_PEOF && is_in_name(c));
  10019. } else if (isdigit(c)) {
  10020. do {
  10021. STPUTC(c, out);
  10022. c = pgetc();
  10023. } while (isdigit(c));
  10024. } else if (is_special(c)) {
  10025. USTPUTC(c, out);
  10026. c = pgetc();
  10027. } else
  10028. badsub: raise_error_syntax("Bad substitution");
  10029. STPUTC('=', out);
  10030. flags = 0;
  10031. if (subtype == 0) {
  10032. switch (c) {
  10033. case ':':
  10034. c = pgetc();
  10035. #if ENABLE_ASH_BASH_COMPAT
  10036. if (c == ':' || c == '$' || isdigit(c)) {
  10037. pungetc();
  10038. subtype = VSSUBSTR;
  10039. break;
  10040. }
  10041. #endif
  10042. flags = VSNUL;
  10043. /*FALLTHROUGH*/
  10044. default:
  10045. p = strchr(types, c);
  10046. if (p == NULL)
  10047. goto badsub;
  10048. subtype = p - types + VSNORMAL;
  10049. break;
  10050. case '%':
  10051. case '#': {
  10052. int cc = c;
  10053. subtype = c == '#' ? VSTRIMLEFT : VSTRIMRIGHT;
  10054. c = pgetc();
  10055. if (c == cc)
  10056. subtype++;
  10057. else
  10058. pungetc();
  10059. break;
  10060. }
  10061. #if ENABLE_ASH_BASH_COMPAT
  10062. case '/':
  10063. subtype = VSREPLACE;
  10064. c = pgetc();
  10065. if (c == '/')
  10066. subtype++; /* VSREPLACEALL */
  10067. else
  10068. pungetc();
  10069. break;
  10070. #endif
  10071. }
  10072. } else {
  10073. pungetc();
  10074. }
  10075. if (dblquote || arinest)
  10076. flags |= VSQUOTE;
  10077. *((char *)stackblock() + typeloc) = subtype | flags;
  10078. if (subtype != VSNORMAL) {
  10079. varnest++;
  10080. if (dblquote || arinest) {
  10081. dqvarnest++;
  10082. }
  10083. }
  10084. }
  10085. goto parsesub_return;
  10086. }
  10087. /*
  10088. * Called to parse command substitutions. Newstyle is set if the command
  10089. * is enclosed inside $(...); nlpp is a pointer to the head of the linked
  10090. * list of commands (passed by reference), and savelen is the number of
  10091. * characters on the top of the stack which must be preserved.
  10092. */
  10093. parsebackq: {
  10094. struct nodelist **nlpp;
  10095. smallint savepbq;
  10096. union node *n;
  10097. char *volatile str;
  10098. struct jmploc jmploc;
  10099. struct jmploc *volatile savehandler;
  10100. size_t savelen;
  10101. smallint saveprompt = 0;
  10102. #ifdef __GNUC__
  10103. (void) &saveprompt;
  10104. #endif
  10105. savepbq = parsebackquote;
  10106. if (setjmp(jmploc.loc)) {
  10107. free(str);
  10108. parsebackquote = 0;
  10109. exception_handler = savehandler;
  10110. longjmp(exception_handler->loc, 1);
  10111. }
  10112. INT_OFF;
  10113. str = NULL;
  10114. savelen = out - (char *)stackblock();
  10115. if (savelen > 0) {
  10116. str = ckmalloc(savelen);
  10117. memcpy(str, stackblock(), savelen);
  10118. }
  10119. savehandler = exception_handler;
  10120. exception_handler = &jmploc;
  10121. INT_ON;
  10122. if (oldstyle) {
  10123. /* We must read until the closing backquote, giving special
  10124. treatment to some slashes, and then push the string and
  10125. reread it as input, interpreting it normally. */
  10126. char *pout;
  10127. int pc;
  10128. size_t psavelen;
  10129. char *pstr;
  10130. STARTSTACKSTR(pout);
  10131. for (;;) {
  10132. if (needprompt) {
  10133. setprompt(2);
  10134. }
  10135. pc = pgetc();
  10136. switch (pc) {
  10137. case '`':
  10138. goto done;
  10139. case '\\':
  10140. pc = pgetc();
  10141. if (pc == '\n') {
  10142. plinno++;
  10143. if (doprompt)
  10144. setprompt(2);
  10145. /*
  10146. * If eating a newline, avoid putting
  10147. * the newline into the new character
  10148. * stream (via the STPUTC after the
  10149. * switch).
  10150. */
  10151. continue;
  10152. }
  10153. if (pc != '\\' && pc != '`' && pc != '$'
  10154. && (!dblquote || pc != '"'))
  10155. STPUTC('\\', pout);
  10156. if (pc > PEOA_OR_PEOF) {
  10157. break;
  10158. }
  10159. /* fall through */
  10160. case PEOF:
  10161. #if ENABLE_ASH_ALIAS
  10162. case PEOA:
  10163. #endif
  10164. startlinno = plinno;
  10165. raise_error_syntax("EOF in backquote substitution");
  10166. case '\n':
  10167. plinno++;
  10168. needprompt = doprompt;
  10169. break;
  10170. default:
  10171. break;
  10172. }
  10173. STPUTC(pc, pout);
  10174. }
  10175. done:
  10176. STPUTC('\0', pout);
  10177. psavelen = pout - (char *)stackblock();
  10178. if (psavelen > 0) {
  10179. pstr = grabstackstr(pout);
  10180. setinputstring(pstr);
  10181. }
  10182. }
  10183. nlpp = &bqlist;
  10184. while (*nlpp)
  10185. nlpp = &(*nlpp)->next;
  10186. *nlpp = stzalloc(sizeof(**nlpp));
  10187. /* (*nlpp)->next = NULL; - stzalloc did it */
  10188. parsebackquote = oldstyle;
  10189. if (oldstyle) {
  10190. saveprompt = doprompt;
  10191. doprompt = 0;
  10192. }
  10193. n = list(2);
  10194. if (oldstyle)
  10195. doprompt = saveprompt;
  10196. else if (readtoken() != TRP)
  10197. raise_error_unexpected_syntax(TRP);
  10198. (*nlpp)->n = n;
  10199. if (oldstyle) {
  10200. /*
  10201. * Start reading from old file again, ignoring any pushed back
  10202. * tokens left from the backquote parsing
  10203. */
  10204. popfile();
  10205. tokpushback = 0;
  10206. }
  10207. while (stackblocksize() <= savelen)
  10208. growstackblock();
  10209. STARTSTACKSTR(out);
  10210. if (str) {
  10211. memcpy(out, str, savelen);
  10212. STADJUST(savelen, out);
  10213. INT_OFF;
  10214. free(str);
  10215. str = NULL;
  10216. INT_ON;
  10217. }
  10218. parsebackquote = savepbq;
  10219. exception_handler = savehandler;
  10220. if (arinest || dblquote)
  10221. USTPUTC(CTLBACKQ | CTLQUOTE, out);
  10222. else
  10223. USTPUTC(CTLBACKQ, out);
  10224. if (oldstyle)
  10225. goto parsebackq_oldreturn;
  10226. goto parsebackq_newreturn;
  10227. }
  10228. #if ENABLE_ASH_MATH_SUPPORT
  10229. /*
  10230. * Parse an arithmetic expansion (indicate start of one and set state)
  10231. */
  10232. parsearith: {
  10233. if (++arinest == 1) {
  10234. prevsyntax = syntax;
  10235. syntax = ARISYNTAX;
  10236. USTPUTC(CTLARI, out);
  10237. if (dblquote)
  10238. USTPUTC('"', out);
  10239. else
  10240. USTPUTC(' ', out);
  10241. } else {
  10242. /*
  10243. * we collapse embedded arithmetic expansion to
  10244. * parenthesis, which should be equivalent
  10245. */
  10246. USTPUTC('(', out);
  10247. }
  10248. goto parsearith_return;
  10249. }
  10250. #endif
  10251. } /* end of readtoken */
  10252. /*
  10253. * Read the next input token.
  10254. * If the token is a word, we set backquotelist to the list of cmds in
  10255. * backquotes. We set quoteflag to true if any part of the word was
  10256. * quoted.
  10257. * If the token is TREDIR, then we set redirnode to a structure containing
  10258. * the redirection.
  10259. * In all cases, the variable startlinno is set to the number of the line
  10260. * on which the token starts.
  10261. *
  10262. * [Change comment: here documents and internal procedures]
  10263. * [Readtoken shouldn't have any arguments. Perhaps we should make the
  10264. * word parsing code into a separate routine. In this case, readtoken
  10265. * doesn't need to have any internal procedures, but parseword does.
  10266. * We could also make parseoperator in essence the main routine, and
  10267. * have parseword (readtoken1?) handle both words and redirection.]
  10268. */
  10269. #define NEW_xxreadtoken
  10270. #ifdef NEW_xxreadtoken
  10271. /* singles must be first! */
  10272. static const char xxreadtoken_chars[7] ALIGN1 = {
  10273. '\n', '(', ')', '&', '|', ';', 0
  10274. };
  10275. static const char xxreadtoken_tokens[] ALIGN1 = {
  10276. TNL, TLP, TRP, /* only single occurrence allowed */
  10277. TBACKGND, TPIPE, TSEMI, /* if single occurrence */
  10278. TEOF, /* corresponds to trailing nul */
  10279. TAND, TOR, TENDCASE /* if double occurrence */
  10280. };
  10281. #define xxreadtoken_doubles \
  10282. (sizeof(xxreadtoken_tokens) - sizeof(xxreadtoken_chars))
  10283. #define xxreadtoken_singles \
  10284. (sizeof(xxreadtoken_chars) - xxreadtoken_doubles - 1)
  10285. static int
  10286. xxreadtoken(void)
  10287. {
  10288. int c;
  10289. if (tokpushback) {
  10290. tokpushback = 0;
  10291. return lasttoken;
  10292. }
  10293. if (needprompt) {
  10294. setprompt(2);
  10295. }
  10296. startlinno = plinno;
  10297. for (;;) { /* until token or start of word found */
  10298. c = pgetc_macro();
  10299. if ((c != ' ') && (c != '\t')
  10300. #if ENABLE_ASH_ALIAS
  10301. && (c != PEOA)
  10302. #endif
  10303. ) {
  10304. if (c == '#') {
  10305. while ((c = pgetc()) != '\n' && c != PEOF)
  10306. continue;
  10307. pungetc();
  10308. } else if (c == '\\') {
  10309. if (pgetc() != '\n') {
  10310. pungetc();
  10311. goto READTOKEN1;
  10312. }
  10313. startlinno = ++plinno;
  10314. if (doprompt)
  10315. setprompt(2);
  10316. } else {
  10317. const char *p
  10318. = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
  10319. if (c != PEOF) {
  10320. if (c == '\n') {
  10321. plinno++;
  10322. needprompt = doprompt;
  10323. }
  10324. p = strchr(xxreadtoken_chars, c);
  10325. if (p == NULL) {
  10326. READTOKEN1:
  10327. return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
  10328. }
  10329. if ((size_t)(p - xxreadtoken_chars) >= xxreadtoken_singles) {
  10330. if (pgetc() == *p) { /* double occurrence? */
  10331. p += xxreadtoken_doubles + 1;
  10332. } else {
  10333. pungetc();
  10334. }
  10335. }
  10336. }
  10337. lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
  10338. return lasttoken;
  10339. }
  10340. }
  10341. } /* for */
  10342. }
  10343. #else
  10344. #define RETURN(token) return lasttoken = token
  10345. static int
  10346. xxreadtoken(void)
  10347. {
  10348. int c;
  10349. if (tokpushback) {
  10350. tokpushback = 0;
  10351. return lasttoken;
  10352. }
  10353. if (needprompt) {
  10354. setprompt(2);
  10355. }
  10356. startlinno = plinno;
  10357. for (;;) { /* until token or start of word found */
  10358. c = pgetc_macro();
  10359. switch (c) {
  10360. case ' ': case '\t':
  10361. #if ENABLE_ASH_ALIAS
  10362. case PEOA:
  10363. #endif
  10364. continue;
  10365. case '#':
  10366. while ((c = pgetc()) != '\n' && c != PEOF)
  10367. continue;
  10368. pungetc();
  10369. continue;
  10370. case '\\':
  10371. if (pgetc() == '\n') {
  10372. startlinno = ++plinno;
  10373. if (doprompt)
  10374. setprompt(2);
  10375. continue;
  10376. }
  10377. pungetc();
  10378. goto breakloop;
  10379. case '\n':
  10380. plinno++;
  10381. needprompt = doprompt;
  10382. RETURN(TNL);
  10383. case PEOF:
  10384. RETURN(TEOF);
  10385. case '&':
  10386. if (pgetc() == '&')
  10387. RETURN(TAND);
  10388. pungetc();
  10389. RETURN(TBACKGND);
  10390. case '|':
  10391. if (pgetc() == '|')
  10392. RETURN(TOR);
  10393. pungetc();
  10394. RETURN(TPIPE);
  10395. case ';':
  10396. if (pgetc() == ';')
  10397. RETURN(TENDCASE);
  10398. pungetc();
  10399. RETURN(TSEMI);
  10400. case '(':
  10401. RETURN(TLP);
  10402. case ')':
  10403. RETURN(TRP);
  10404. default:
  10405. goto breakloop;
  10406. }
  10407. }
  10408. breakloop:
  10409. return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
  10410. #undef RETURN
  10411. }
  10412. #endif /* NEW_xxreadtoken */
  10413. static int
  10414. readtoken(void)
  10415. {
  10416. int t;
  10417. #if DEBUG
  10418. smallint alreadyseen = tokpushback;
  10419. #endif
  10420. #if ENABLE_ASH_ALIAS
  10421. top:
  10422. #endif
  10423. t = xxreadtoken();
  10424. /*
  10425. * eat newlines
  10426. */
  10427. if (checkkwd & CHKNL) {
  10428. while (t == TNL) {
  10429. parseheredoc();
  10430. t = xxreadtoken();
  10431. }
  10432. }
  10433. if (t != TWORD || quoteflag) {
  10434. goto out;
  10435. }
  10436. /*
  10437. * check for keywords
  10438. */
  10439. if (checkkwd & CHKKWD) {
  10440. const char *const *pp;
  10441. pp = findkwd(wordtext);
  10442. if (pp) {
  10443. lasttoken = t = pp - tokname_array;
  10444. TRACE(("keyword %s recognized\n", tokname(t)));
  10445. goto out;
  10446. }
  10447. }
  10448. if (checkkwd & CHKALIAS) {
  10449. #if ENABLE_ASH_ALIAS
  10450. struct alias *ap;
  10451. ap = lookupalias(wordtext, 1);
  10452. if (ap != NULL) {
  10453. if (*ap->val) {
  10454. pushstring(ap->val, ap);
  10455. }
  10456. goto top;
  10457. }
  10458. #endif
  10459. }
  10460. out:
  10461. checkkwd = 0;
  10462. #if DEBUG
  10463. if (!alreadyseen)
  10464. TRACE(("token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
  10465. else
  10466. TRACE(("reread token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
  10467. #endif
  10468. return t;
  10469. }
  10470. static char
  10471. peektoken(void)
  10472. {
  10473. int t;
  10474. t = readtoken();
  10475. tokpushback = 1;
  10476. return tokname_array[t][0];
  10477. }
  10478. /*
  10479. * Read and parse a command. Returns NEOF on end of file. (NULL is a
  10480. * valid parse tree indicating a blank line.)
  10481. */
  10482. static union node *
  10483. parsecmd(int interact)
  10484. {
  10485. int t;
  10486. tokpushback = 0;
  10487. doprompt = interact;
  10488. if (doprompt)
  10489. setprompt(doprompt);
  10490. needprompt = 0;
  10491. t = readtoken();
  10492. if (t == TEOF)
  10493. return NEOF;
  10494. if (t == TNL)
  10495. return NULL;
  10496. tokpushback = 1;
  10497. return list(1);
  10498. }
  10499. /*
  10500. * Input any here documents.
  10501. */
  10502. static void
  10503. parseheredoc(void)
  10504. {
  10505. struct heredoc *here;
  10506. union node *n;
  10507. here = heredoclist;
  10508. heredoclist = NULL;
  10509. while (here) {
  10510. if (needprompt) {
  10511. setprompt(2);
  10512. }
  10513. readtoken1(pgetc(), here->here->type == NHERE? SQSYNTAX : DQSYNTAX,
  10514. here->eofmark, here->striptabs);
  10515. n = stzalloc(sizeof(struct narg));
  10516. n->narg.type = NARG;
  10517. /*n->narg.next = NULL; - stzalloc did it */
  10518. n->narg.text = wordtext;
  10519. n->narg.backquote = backquotelist;
  10520. here->here->nhere.doc = n;
  10521. here = here->next;
  10522. }
  10523. }
  10524. /*
  10525. * called by editline -- any expansions to the prompt should be added here.
  10526. */
  10527. #if ENABLE_ASH_EXPAND_PRMT
  10528. static const char *
  10529. expandstr(const char *ps)
  10530. {
  10531. union node n;
  10532. /* XXX Fix (char *) cast. */
  10533. setinputstring((char *)ps);
  10534. readtoken1(pgetc(), PSSYNTAX, nullstr, 0);
  10535. popfile();
  10536. n.narg.type = NARG;
  10537. n.narg.next = NULL;
  10538. n.narg.text = wordtext;
  10539. n.narg.backquote = backquotelist;
  10540. expandarg(&n, NULL, 0);
  10541. return stackblock();
  10542. }
  10543. #endif
  10544. /*
  10545. * Execute a command or commands contained in a string.
  10546. */
  10547. static int
  10548. evalstring(char *s, int mask)
  10549. {
  10550. union node *n;
  10551. struct stackmark smark;
  10552. int skip;
  10553. setinputstring(s);
  10554. setstackmark(&smark);
  10555. skip = 0;
  10556. while ((n = parsecmd(0)) != NEOF) {
  10557. evaltree(n, 0);
  10558. popstackmark(&smark);
  10559. skip = evalskip;
  10560. if (skip)
  10561. break;
  10562. }
  10563. popfile();
  10564. skip &= mask;
  10565. evalskip = skip;
  10566. return skip;
  10567. }
  10568. /*
  10569. * The eval command.
  10570. */
  10571. static int
  10572. evalcmd(int argc UNUSED_PARAM, char **argv)
  10573. {
  10574. char *p;
  10575. char *concat;
  10576. if (argv[1]) {
  10577. p = argv[1];
  10578. argv += 2;
  10579. if (argv[0]) {
  10580. STARTSTACKSTR(concat);
  10581. for (;;) {
  10582. concat = stack_putstr(p, concat);
  10583. p = *argv++;
  10584. if (p == NULL)
  10585. break;
  10586. STPUTC(' ', concat);
  10587. }
  10588. STPUTC('\0', concat);
  10589. p = grabstackstr(concat);
  10590. }
  10591. evalstring(p, ~SKIPEVAL);
  10592. }
  10593. return exitstatus;
  10594. }
  10595. /*
  10596. * Read and execute commands. "Top" is nonzero for the top level command
  10597. * loop; it turns on prompting if the shell is interactive.
  10598. */
  10599. static int
  10600. cmdloop(int top)
  10601. {
  10602. union node *n;
  10603. struct stackmark smark;
  10604. int inter;
  10605. int numeof = 0;
  10606. TRACE(("cmdloop(%d) called\n", top));
  10607. for (;;) {
  10608. int skip;
  10609. setstackmark(&smark);
  10610. #if JOBS
  10611. if (doing_jobctl)
  10612. showjobs(stderr, SHOW_CHANGED);
  10613. #endif
  10614. inter = 0;
  10615. if (iflag && top) {
  10616. inter++;
  10617. #if ENABLE_ASH_MAIL
  10618. chkmail();
  10619. #endif
  10620. }
  10621. n = parsecmd(inter);
  10622. /* showtree(n); DEBUG */
  10623. if (n == NEOF) {
  10624. if (!top || numeof >= 50)
  10625. break;
  10626. if (!stoppedjobs()) {
  10627. if (!Iflag)
  10628. break;
  10629. out2str("\nUse \"exit\" to leave shell.\n");
  10630. }
  10631. numeof++;
  10632. } else if (nflag == 0) {
  10633. /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
  10634. job_warning >>= 1;
  10635. numeof = 0;
  10636. evaltree(n, 0);
  10637. }
  10638. popstackmark(&smark);
  10639. skip = evalskip;
  10640. if (skip) {
  10641. evalskip = 0;
  10642. return skip & SKIPEVAL;
  10643. }
  10644. }
  10645. return 0;
  10646. }
  10647. /*
  10648. * Take commands from a file. To be compatible we should do a path
  10649. * search for the file, which is necessary to find sub-commands.
  10650. */
  10651. static char *
  10652. find_dot_file(char *name)
  10653. {
  10654. char *fullname;
  10655. const char *path = pathval();
  10656. struct stat statb;
  10657. /* don't try this for absolute or relative paths */
  10658. if (strchr(name, '/'))
  10659. return name;
  10660. while ((fullname = padvance(&path, name)) != NULL) {
  10661. if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
  10662. /*
  10663. * Don't bother freeing here, since it will
  10664. * be freed by the caller.
  10665. */
  10666. return fullname;
  10667. }
  10668. stunalloc(fullname);
  10669. }
  10670. /* not found in the PATH */
  10671. ash_msg_and_raise_error("%s: not found", name);
  10672. /* NOTREACHED */
  10673. }
  10674. static int
  10675. dotcmd(int argc, char **argv)
  10676. {
  10677. struct strlist *sp;
  10678. volatile struct shparam saveparam;
  10679. int status = 0;
  10680. for (sp = cmdenviron; sp; sp = sp->next)
  10681. setvareq(ckstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
  10682. if (argv[1]) { /* That's what SVR2 does */
  10683. char *fullname = find_dot_file(argv[1]);
  10684. argv += 2;
  10685. argc -= 2;
  10686. if (argc) { /* argc > 0, argv[0] != NULL */
  10687. saveparam = shellparam;
  10688. shellparam.malloced = 0;
  10689. shellparam.nparam = argc;
  10690. shellparam.p = argv;
  10691. };
  10692. setinputfile(fullname, INPUT_PUSH_FILE);
  10693. commandname = fullname;
  10694. cmdloop(0);
  10695. popfile();
  10696. if (argc) {
  10697. freeparam(&shellparam);
  10698. shellparam = saveparam;
  10699. };
  10700. status = exitstatus;
  10701. }
  10702. return status;
  10703. }
  10704. static int
  10705. exitcmd(int argc UNUSED_PARAM, char **argv)
  10706. {
  10707. if (stoppedjobs())
  10708. return 0;
  10709. if (argv[1])
  10710. exitstatus = number(argv[1]);
  10711. raise_exception(EXEXIT);
  10712. /* NOTREACHED */
  10713. }
  10714. /*
  10715. * Read a file containing shell functions.
  10716. */
  10717. static void
  10718. readcmdfile(char *name)
  10719. {
  10720. setinputfile(name, INPUT_PUSH_FILE);
  10721. cmdloop(0);
  10722. popfile();
  10723. }
  10724. /* ============ find_command inplementation */
  10725. /*
  10726. * Resolve a command name. If you change this routine, you may have to
  10727. * change the shellexec routine as well.
  10728. */
  10729. static void
  10730. find_command(char *name, struct cmdentry *entry, int act, const char *path)
  10731. {
  10732. struct tblentry *cmdp;
  10733. int idx;
  10734. int prev;
  10735. char *fullname;
  10736. struct stat statb;
  10737. int e;
  10738. int updatetbl;
  10739. struct builtincmd *bcmd;
  10740. /* If name contains a slash, don't use PATH or hash table */
  10741. if (strchr(name, '/') != NULL) {
  10742. entry->u.index = -1;
  10743. if (act & DO_ABS) {
  10744. while (stat(name, &statb) < 0) {
  10745. #ifdef SYSV
  10746. if (errno == EINTR)
  10747. continue;
  10748. #endif
  10749. entry->cmdtype = CMDUNKNOWN;
  10750. return;
  10751. }
  10752. }
  10753. entry->cmdtype = CMDNORMAL;
  10754. return;
  10755. }
  10756. /* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
  10757. updatetbl = (path == pathval());
  10758. if (!updatetbl) {
  10759. act |= DO_ALTPATH;
  10760. if (strstr(path, "%builtin") != NULL)
  10761. act |= DO_ALTBLTIN;
  10762. }
  10763. /* If name is in the table, check answer will be ok */
  10764. cmdp = cmdlookup(name, 0);
  10765. if (cmdp != NULL) {
  10766. int bit;
  10767. switch (cmdp->cmdtype) {
  10768. default:
  10769. #if DEBUG
  10770. abort();
  10771. #endif
  10772. case CMDNORMAL:
  10773. bit = DO_ALTPATH;
  10774. break;
  10775. case CMDFUNCTION:
  10776. bit = DO_NOFUNC;
  10777. break;
  10778. case CMDBUILTIN:
  10779. bit = DO_ALTBLTIN;
  10780. break;
  10781. }
  10782. if (act & bit) {
  10783. updatetbl = 0;
  10784. cmdp = NULL;
  10785. } else if (cmdp->rehash == 0)
  10786. /* if not invalidated by cd, we're done */
  10787. goto success;
  10788. }
  10789. /* If %builtin not in path, check for builtin next */
  10790. bcmd = find_builtin(name);
  10791. if (bcmd) {
  10792. if (IS_BUILTIN_REGULAR(bcmd))
  10793. goto builtin_success;
  10794. if (act & DO_ALTPATH) {
  10795. if (!(act & DO_ALTBLTIN))
  10796. goto builtin_success;
  10797. } else if (builtinloc <= 0) {
  10798. goto builtin_success;
  10799. }
  10800. }
  10801. #if ENABLE_FEATURE_SH_STANDALONE
  10802. {
  10803. int applet_no = find_applet_by_name(name);
  10804. if (applet_no >= 0) {
  10805. entry->cmdtype = CMDNORMAL;
  10806. entry->u.index = -2 - applet_no;
  10807. return;
  10808. }
  10809. }
  10810. #endif
  10811. /* We have to search path. */
  10812. prev = -1; /* where to start */
  10813. if (cmdp && cmdp->rehash) { /* doing a rehash */
  10814. if (cmdp->cmdtype == CMDBUILTIN)
  10815. prev = builtinloc;
  10816. else
  10817. prev = cmdp->param.index;
  10818. }
  10819. e = ENOENT;
  10820. idx = -1;
  10821. loop:
  10822. while ((fullname = padvance(&path, name)) != NULL) {
  10823. stunalloc(fullname);
  10824. /* NB: code below will still use fullname
  10825. * despite it being "unallocated" */
  10826. idx++;
  10827. if (pathopt) {
  10828. if (prefix(pathopt, "builtin")) {
  10829. if (bcmd)
  10830. goto builtin_success;
  10831. continue;
  10832. }
  10833. if ((act & DO_NOFUNC)
  10834. || !prefix(pathopt, "func")
  10835. ) { /* ignore unimplemented options */
  10836. continue;
  10837. }
  10838. }
  10839. /* if rehash, don't redo absolute path names */
  10840. if (fullname[0] == '/' && idx <= prev) {
  10841. if (idx < prev)
  10842. continue;
  10843. TRACE(("searchexec \"%s\": no change\n", name));
  10844. goto success;
  10845. }
  10846. while (stat(fullname, &statb) < 0) {
  10847. #ifdef SYSV
  10848. if (errno == EINTR)
  10849. continue;
  10850. #endif
  10851. if (errno != ENOENT && errno != ENOTDIR)
  10852. e = errno;
  10853. goto loop;
  10854. }
  10855. e = EACCES; /* if we fail, this will be the error */
  10856. if (!S_ISREG(statb.st_mode))
  10857. continue;
  10858. if (pathopt) { /* this is a %func directory */
  10859. stalloc(strlen(fullname) + 1);
  10860. /* NB: stalloc will return space pointed by fullname
  10861. * (because we don't have any intervening allocations
  10862. * between stunalloc above and this stalloc) */
  10863. readcmdfile(fullname);
  10864. cmdp = cmdlookup(name, 0);
  10865. if (cmdp == NULL || cmdp->cmdtype != CMDFUNCTION)
  10866. ash_msg_and_raise_error("%s not defined in %s", name, fullname);
  10867. stunalloc(fullname);
  10868. goto success;
  10869. }
  10870. TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
  10871. if (!updatetbl) {
  10872. entry->cmdtype = CMDNORMAL;
  10873. entry->u.index = idx;
  10874. return;
  10875. }
  10876. INT_OFF;
  10877. cmdp = cmdlookup(name, 1);
  10878. cmdp->cmdtype = CMDNORMAL;
  10879. cmdp->param.index = idx;
  10880. INT_ON;
  10881. goto success;
  10882. }
  10883. /* We failed. If there was an entry for this command, delete it */
  10884. if (cmdp && updatetbl)
  10885. delete_cmd_entry();
  10886. if (act & DO_ERR)
  10887. ash_msg("%s: %s", name, errmsg(e, "not found"));
  10888. entry->cmdtype = CMDUNKNOWN;
  10889. return;
  10890. builtin_success:
  10891. if (!updatetbl) {
  10892. entry->cmdtype = CMDBUILTIN;
  10893. entry->u.cmd = bcmd;
  10894. return;
  10895. }
  10896. INT_OFF;
  10897. cmdp = cmdlookup(name, 1);
  10898. cmdp->cmdtype = CMDBUILTIN;
  10899. cmdp->param.cmd = bcmd;
  10900. INT_ON;
  10901. success:
  10902. cmdp->rehash = 0;
  10903. entry->cmdtype = cmdp->cmdtype;
  10904. entry->u = cmdp->param;
  10905. }
  10906. /* ============ trap.c */
  10907. /*
  10908. * The trap builtin.
  10909. */
  10910. static int
  10911. trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  10912. {
  10913. char *action;
  10914. char **ap;
  10915. int signo;
  10916. nextopt(nullstr);
  10917. ap = argptr;
  10918. if (!*ap) {
  10919. for (signo = 0; signo < NSIG; signo++) {
  10920. if (trap[signo] != NULL) {
  10921. out1fmt("trap -- %s %s\n",
  10922. single_quote(trap[signo]),
  10923. get_signame(signo));
  10924. }
  10925. }
  10926. return 0;
  10927. }
  10928. action = NULL;
  10929. if (ap[1])
  10930. action = *ap++;
  10931. while (*ap) {
  10932. signo = get_signum(*ap);
  10933. if (signo < 0)
  10934. ash_msg_and_raise_error("%s: bad trap", *ap);
  10935. INT_OFF;
  10936. if (action) {
  10937. if (LONE_DASH(action))
  10938. action = NULL;
  10939. else
  10940. action = ckstrdup(action);
  10941. }
  10942. free(trap[signo]);
  10943. trap[signo] = action;
  10944. if (signo != 0)
  10945. setsignal(signo);
  10946. INT_ON;
  10947. ap++;
  10948. }
  10949. return 0;
  10950. }
  10951. /* ============ Builtins */
  10952. #if !ENABLE_FEATURE_SH_EXTRA_QUIET
  10953. /*
  10954. * Lists available builtins
  10955. */
  10956. static int
  10957. helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  10958. {
  10959. unsigned col;
  10960. unsigned i;
  10961. out1fmt("\nBuilt-in commands:\n-------------------\n");
  10962. for (col = 0, i = 0; i < ARRAY_SIZE(builtintab); i++) {
  10963. col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
  10964. builtintab[i].name + 1);
  10965. if (col > 60) {
  10966. out1fmt("\n");
  10967. col = 0;
  10968. }
  10969. }
  10970. #if ENABLE_FEATURE_SH_STANDALONE
  10971. {
  10972. const char *a = applet_names;
  10973. while (*a) {
  10974. col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
  10975. if (col > 60) {
  10976. out1fmt("\n");
  10977. col = 0;
  10978. }
  10979. a += strlen(a) + 1;
  10980. }
  10981. }
  10982. #endif
  10983. out1fmt("\n\n");
  10984. return EXIT_SUCCESS;
  10985. }
  10986. #endif /* FEATURE_SH_EXTRA_QUIET */
  10987. /*
  10988. * The export and readonly commands.
  10989. */
  10990. static int
  10991. exportcmd(int argc UNUSED_PARAM, char **argv)
  10992. {
  10993. struct var *vp;
  10994. char *name;
  10995. const char *p;
  10996. char **aptr;
  10997. int flag = argv[0][0] == 'r' ? VREADONLY : VEXPORT;
  10998. if (nextopt("p") != 'p') {
  10999. aptr = argptr;
  11000. name = *aptr;
  11001. if (name) {
  11002. do {
  11003. p = strchr(name, '=');
  11004. if (p != NULL) {
  11005. p++;
  11006. } else {
  11007. vp = *findvar(hashvar(name), name);
  11008. if (vp) {
  11009. vp->flags |= flag;
  11010. continue;
  11011. }
  11012. }
  11013. setvar(name, p, flag);
  11014. } while ((name = *++aptr) != NULL);
  11015. return 0;
  11016. }
  11017. }
  11018. showvars(argv[0], flag, 0);
  11019. return 0;
  11020. }
  11021. /*
  11022. * Delete a function if it exists.
  11023. */
  11024. static void
  11025. unsetfunc(const char *name)
  11026. {
  11027. struct tblentry *cmdp;
  11028. cmdp = cmdlookup(name, 0);
  11029. if (cmdp!= NULL && cmdp->cmdtype == CMDFUNCTION)
  11030. delete_cmd_entry();
  11031. }
  11032. /*
  11033. * The unset builtin command. We unset the function before we unset the
  11034. * variable to allow a function to be unset when there is a readonly variable
  11035. * with the same name.
  11036. */
  11037. static int
  11038. unsetcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  11039. {
  11040. char **ap;
  11041. int i;
  11042. int flag = 0;
  11043. int ret = 0;
  11044. while ((i = nextopt("vf")) != '\0') {
  11045. flag = i;
  11046. }
  11047. for (ap = argptr; *ap; ap++) {
  11048. if (flag != 'f') {
  11049. i = unsetvar(*ap);
  11050. ret |= i;
  11051. if (!(i & 2))
  11052. continue;
  11053. }
  11054. if (flag != 'v')
  11055. unsetfunc(*ap);
  11056. }
  11057. return ret & 1;
  11058. }
  11059. /* setmode.c */
  11060. #include <sys/times.h>
  11061. static const unsigned char timescmd_str[] ALIGN1 = {
  11062. ' ', offsetof(struct tms, tms_utime),
  11063. '\n', offsetof(struct tms, tms_stime),
  11064. ' ', offsetof(struct tms, tms_cutime),
  11065. '\n', offsetof(struct tms, tms_cstime),
  11066. 0
  11067. };
  11068. static int
  11069. timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  11070. {
  11071. long clk_tck, s, t;
  11072. const unsigned char *p;
  11073. struct tms buf;
  11074. clk_tck = sysconf(_SC_CLK_TCK);
  11075. times(&buf);
  11076. p = timescmd_str;
  11077. do {
  11078. t = *(clock_t *)(((char *) &buf) + p[1]);
  11079. s = t / clk_tck;
  11080. out1fmt("%ldm%ld.%.3lds%c",
  11081. s/60, s%60,
  11082. ((t - s * clk_tck) * 1000) / clk_tck,
  11083. p[0]);
  11084. } while (*(p += 2));
  11085. return 0;
  11086. }
  11087. #if ENABLE_ASH_MATH_SUPPORT
  11088. static arith_t
  11089. dash_arith(const char *s)
  11090. {
  11091. arith_t result;
  11092. int errcode = 0;
  11093. INT_OFF;
  11094. result = arith(s, &errcode);
  11095. if (errcode < 0) {
  11096. if (errcode == -3)
  11097. ash_msg_and_raise_error("exponent less than 0");
  11098. if (errcode == -2)
  11099. ash_msg_and_raise_error("divide by zero");
  11100. if (errcode == -5)
  11101. ash_msg_and_raise_error("expression recursion loop detected");
  11102. raise_error_syntax(s);
  11103. }
  11104. INT_ON;
  11105. return result;
  11106. }
  11107. /*
  11108. * The let builtin. partial stolen from GNU Bash, the Bourne Again SHell.
  11109. * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
  11110. *
  11111. * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
  11112. */
  11113. static int
  11114. letcmd(int argc UNUSED_PARAM, char **argv)
  11115. {
  11116. arith_t i;
  11117. argv++;
  11118. if (!*argv)
  11119. ash_msg_and_raise_error("expression expected");
  11120. do {
  11121. i = dash_arith(*argv);
  11122. } while (*++argv);
  11123. return !i;
  11124. }
  11125. #endif /* ASH_MATH_SUPPORT */
  11126. /* ============ miscbltin.c
  11127. *
  11128. * Miscellaneous builtins.
  11129. */
  11130. #undef rflag
  11131. #if defined(__GLIBC__) && __GLIBC__ == 2 && __GLIBC_MINOR__ < 1
  11132. typedef enum __rlimit_resource rlim_t;
  11133. #endif
  11134. /*
  11135. * The read builtin. Options:
  11136. * -r Do not interpret '\' specially
  11137. * -s Turn off echo (tty only)
  11138. * -n NCHARS Read NCHARS max
  11139. * -p PROMPT Display PROMPT on stderr (if input is from tty)
  11140. * -t SECONDS Timeout after SECONDS (tty or pipe only)
  11141. * -u FD Read from given FD instead of fd 0
  11142. * This uses unbuffered input, which may be avoidable in some cases.
  11143. * TODO: bash also has:
  11144. * -a ARRAY Read into array[0],[1],etc
  11145. * -d DELIM End on DELIM char, not newline
  11146. * -e Use line editing (tty only)
  11147. */
  11148. static int
  11149. readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  11150. {
  11151. static const char *const arg_REPLY[] = { "REPLY", NULL };
  11152. char **ap;
  11153. int backslash;
  11154. char c;
  11155. int rflag;
  11156. char *prompt;
  11157. const char *ifs;
  11158. char *p;
  11159. int startword;
  11160. int status;
  11161. int i;
  11162. int fd = 0;
  11163. #if ENABLE_ASH_READ_NCHARS
  11164. int nchars = 0; /* if != 0, -n is in effect */
  11165. int silent = 0;
  11166. struct termios tty, old_tty;
  11167. #endif
  11168. #if ENABLE_ASH_READ_TIMEOUT
  11169. unsigned end_ms = 0;
  11170. unsigned timeout = 0;
  11171. #endif
  11172. rflag = 0;
  11173. prompt = NULL;
  11174. while ((i = nextopt("p:u:r"
  11175. USE_ASH_READ_TIMEOUT("t:")
  11176. USE_ASH_READ_NCHARS("n:s")
  11177. )) != '\0') {
  11178. switch (i) {
  11179. case 'p':
  11180. prompt = optionarg;
  11181. break;
  11182. #if ENABLE_ASH_READ_NCHARS
  11183. case 'n':
  11184. nchars = bb_strtou(optionarg, NULL, 10);
  11185. if (nchars < 0 || errno)
  11186. ash_msg_and_raise_error("invalid count");
  11187. /* nchars == 0: off (bash 3.2 does this too) */
  11188. break;
  11189. case 's':
  11190. silent = 1;
  11191. break;
  11192. #endif
  11193. #if ENABLE_ASH_READ_TIMEOUT
  11194. case 't':
  11195. timeout = bb_strtou(optionarg, NULL, 10);
  11196. if (errno || timeout > UINT_MAX / 2048)
  11197. ash_msg_and_raise_error("invalid timeout");
  11198. timeout *= 1000;
  11199. #if 0 /* even bash have no -t N.NNN support */
  11200. ts.tv_sec = bb_strtou(optionarg, &p, 10);
  11201. ts.tv_usec = 0;
  11202. /* EINVAL means number is ok, but not terminated by NUL */
  11203. if (*p == '.' && errno == EINVAL) {
  11204. char *p2;
  11205. if (*++p) {
  11206. int scale;
  11207. ts.tv_usec = bb_strtou(p, &p2, 10);
  11208. if (errno)
  11209. ash_msg_and_raise_error("invalid timeout");
  11210. scale = p2 - p;
  11211. /* normalize to usec */
  11212. if (scale > 6)
  11213. ash_msg_and_raise_error("invalid timeout");
  11214. while (scale++ < 6)
  11215. ts.tv_usec *= 10;
  11216. }
  11217. } else if (ts.tv_sec < 0 || errno) {
  11218. ash_msg_and_raise_error("invalid timeout");
  11219. }
  11220. if (!(ts.tv_sec | ts.tv_usec)) { /* both are 0? */
  11221. ash_msg_and_raise_error("invalid timeout");
  11222. }
  11223. #endif /* if 0 */
  11224. break;
  11225. #endif
  11226. case 'r':
  11227. rflag = 1;
  11228. break;
  11229. case 'u':
  11230. fd = bb_strtou(optionarg, NULL, 10);
  11231. if (fd < 0 || errno)
  11232. ash_msg_and_raise_error("invalid file descriptor");
  11233. break;
  11234. default:
  11235. break;
  11236. }
  11237. }
  11238. if (prompt && isatty(fd)) {
  11239. out2str(prompt);
  11240. }
  11241. ap = argptr;
  11242. if (*ap == NULL)
  11243. ap = (char**)arg_REPLY;
  11244. ifs = bltinlookup("IFS");
  11245. if (ifs == NULL)
  11246. ifs = defifs;
  11247. #if ENABLE_ASH_READ_NCHARS
  11248. tcgetattr(fd, &tty);
  11249. old_tty = tty;
  11250. if (nchars || silent) {
  11251. if (nchars) {
  11252. tty.c_lflag &= ~ICANON;
  11253. tty.c_cc[VMIN] = nchars < 256 ? nchars : 255;
  11254. }
  11255. if (silent) {
  11256. tty.c_lflag &= ~(ECHO | ECHOK | ECHONL);
  11257. }
  11258. /* if tcgetattr failed, tcsetattr will fail too.
  11259. * Ignoring, it's harmless. */
  11260. tcsetattr(fd, TCSANOW, &tty);
  11261. }
  11262. #endif
  11263. status = 0;
  11264. startword = 1;
  11265. backslash = 0;
  11266. #if ENABLE_ASH_READ_TIMEOUT
  11267. if (timeout) /* NB: ensuring end_ms is nonzero */
  11268. end_ms = ((unsigned)(monotonic_us() / 1000) + timeout) | 1;
  11269. #endif
  11270. STARTSTACKSTR(p);
  11271. do {
  11272. #if ENABLE_ASH_READ_TIMEOUT
  11273. if (end_ms) {
  11274. struct pollfd pfd[1];
  11275. pfd[0].fd = fd;
  11276. pfd[0].events = POLLIN;
  11277. timeout = end_ms - (unsigned)(monotonic_us() / 1000);
  11278. if ((int)timeout <= 0 /* already late? */
  11279. || safe_poll(pfd, 1, timeout) != 1 /* no? wait... */
  11280. ) { /* timed out! */
  11281. #if ENABLE_ASH_READ_NCHARS
  11282. tcsetattr(fd, TCSANOW, &old_tty);
  11283. #endif
  11284. return 1;
  11285. }
  11286. }
  11287. #endif
  11288. if (nonblock_safe_read(fd, &c, 1) != 1) {
  11289. status = 1;
  11290. break;
  11291. }
  11292. if (c == '\0')
  11293. continue;
  11294. if (backslash) {
  11295. backslash = 0;
  11296. if (c != '\n')
  11297. goto put;
  11298. continue;
  11299. }
  11300. if (!rflag && c == '\\') {
  11301. backslash++;
  11302. continue;
  11303. }
  11304. if (c == '\n')
  11305. break;
  11306. if (startword && *ifs == ' ' && strchr(ifs, c)) {
  11307. continue;
  11308. }
  11309. startword = 0;
  11310. if (ap[1] != NULL && strchr(ifs, c) != NULL) {
  11311. STACKSTRNUL(p);
  11312. setvar(*ap, stackblock(), 0);
  11313. ap++;
  11314. startword = 1;
  11315. STARTSTACKSTR(p);
  11316. } else {
  11317. put:
  11318. STPUTC(c, p);
  11319. }
  11320. }
  11321. /* end of do {} while: */
  11322. #if ENABLE_ASH_READ_NCHARS
  11323. while (--nchars);
  11324. #else
  11325. while (1);
  11326. #endif
  11327. #if ENABLE_ASH_READ_NCHARS
  11328. tcsetattr(fd, TCSANOW, &old_tty);
  11329. #endif
  11330. STACKSTRNUL(p);
  11331. /* Remove trailing blanks */
  11332. while ((char *)stackblock() <= --p && strchr(ifs, *p) != NULL)
  11333. *p = '\0';
  11334. setvar(*ap, stackblock(), 0);
  11335. while (*++ap != NULL)
  11336. setvar(*ap, nullstr, 0);
  11337. return status;
  11338. }
  11339. static int
  11340. umaskcmd(int argc UNUSED_PARAM, char **argv)
  11341. {
  11342. static const char permuser[3] ALIGN1 = "ugo";
  11343. static const char permmode[3] ALIGN1 = "rwx";
  11344. static const short permmask[] ALIGN2 = {
  11345. S_IRUSR, S_IWUSR, S_IXUSR,
  11346. S_IRGRP, S_IWGRP, S_IXGRP,
  11347. S_IROTH, S_IWOTH, S_IXOTH
  11348. };
  11349. char *ap;
  11350. mode_t mask;
  11351. int i;
  11352. int symbolic_mode = 0;
  11353. while (nextopt("S") != '\0') {
  11354. symbolic_mode = 1;
  11355. }
  11356. INT_OFF;
  11357. mask = umask(0);
  11358. umask(mask);
  11359. INT_ON;
  11360. ap = *argptr;
  11361. if (ap == NULL) {
  11362. if (symbolic_mode) {
  11363. char buf[18];
  11364. char *p = buf;
  11365. for (i = 0; i < 3; i++) {
  11366. int j;
  11367. *p++ = permuser[i];
  11368. *p++ = '=';
  11369. for (j = 0; j < 3; j++) {
  11370. if ((mask & permmask[3 * i + j]) == 0) {
  11371. *p++ = permmode[j];
  11372. }
  11373. }
  11374. *p++ = ',';
  11375. }
  11376. *--p = 0;
  11377. puts(buf);
  11378. } else {
  11379. out1fmt("%.4o\n", mask);
  11380. }
  11381. } else {
  11382. if (isdigit((unsigned char) *ap)) {
  11383. mask = 0;
  11384. do {
  11385. if (*ap >= '8' || *ap < '0')
  11386. ash_msg_and_raise_error(illnum, argv[1]);
  11387. mask = (mask << 3) + (*ap - '0');
  11388. } while (*++ap != '\0');
  11389. umask(mask);
  11390. } else {
  11391. mask = ~mask & 0777;
  11392. if (!bb_parse_mode(ap, &mask)) {
  11393. ash_msg_and_raise_error("illegal mode: %s", ap);
  11394. }
  11395. umask(~mask & 0777);
  11396. }
  11397. }
  11398. return 0;
  11399. }
  11400. /*
  11401. * ulimit builtin
  11402. *
  11403. * This code, originally by Doug Gwyn, Doug Kingston, Eric Gisin, and
  11404. * Michael Rendell was ripped from pdksh 5.0.8 and hacked for use with
  11405. * ash by J.T. Conklin.
  11406. *
  11407. * Public domain.
  11408. */
  11409. struct limits {
  11410. uint8_t cmd; /* RLIMIT_xxx fit into it */
  11411. uint8_t factor_shift; /* shift by to get rlim_{cur,max} values */
  11412. char option;
  11413. };
  11414. static const struct limits limits_tbl[] = {
  11415. #ifdef RLIMIT_CPU
  11416. { RLIMIT_CPU, 0, 't' },
  11417. #endif
  11418. #ifdef RLIMIT_FSIZE
  11419. { RLIMIT_FSIZE, 9, 'f' },
  11420. #endif
  11421. #ifdef RLIMIT_DATA
  11422. { RLIMIT_DATA, 10, 'd' },
  11423. #endif
  11424. #ifdef RLIMIT_STACK
  11425. { RLIMIT_STACK, 10, 's' },
  11426. #endif
  11427. #ifdef RLIMIT_CORE
  11428. { RLIMIT_CORE, 9, 'c' },
  11429. #endif
  11430. #ifdef RLIMIT_RSS
  11431. { RLIMIT_RSS, 10, 'm' },
  11432. #endif
  11433. #ifdef RLIMIT_MEMLOCK
  11434. { RLIMIT_MEMLOCK, 10, 'l' },
  11435. #endif
  11436. #ifdef RLIMIT_NPROC
  11437. { RLIMIT_NPROC, 0, 'p' },
  11438. #endif
  11439. #ifdef RLIMIT_NOFILE
  11440. { RLIMIT_NOFILE, 0, 'n' },
  11441. #endif
  11442. #ifdef RLIMIT_AS
  11443. { RLIMIT_AS, 10, 'v' },
  11444. #endif
  11445. #ifdef RLIMIT_LOCKS
  11446. { RLIMIT_LOCKS, 0, 'w' },
  11447. #endif
  11448. };
  11449. static const char limits_name[] =
  11450. #ifdef RLIMIT_CPU
  11451. "time(seconds)" "\0"
  11452. #endif
  11453. #ifdef RLIMIT_FSIZE
  11454. "file(blocks)" "\0"
  11455. #endif
  11456. #ifdef RLIMIT_DATA
  11457. "data(kb)" "\0"
  11458. #endif
  11459. #ifdef RLIMIT_STACK
  11460. "stack(kb)" "\0"
  11461. #endif
  11462. #ifdef RLIMIT_CORE
  11463. "coredump(blocks)" "\0"
  11464. #endif
  11465. #ifdef RLIMIT_RSS
  11466. "memory(kb)" "\0"
  11467. #endif
  11468. #ifdef RLIMIT_MEMLOCK
  11469. "locked memory(kb)" "\0"
  11470. #endif
  11471. #ifdef RLIMIT_NPROC
  11472. "process" "\0"
  11473. #endif
  11474. #ifdef RLIMIT_NOFILE
  11475. "nofiles" "\0"
  11476. #endif
  11477. #ifdef RLIMIT_AS
  11478. "vmemory(kb)" "\0"
  11479. #endif
  11480. #ifdef RLIMIT_LOCKS
  11481. "locks" "\0"
  11482. #endif
  11483. ;
  11484. enum limtype { SOFT = 0x1, HARD = 0x2 };
  11485. static void
  11486. printlim(enum limtype how, const struct rlimit *limit,
  11487. const struct limits *l)
  11488. {
  11489. rlim_t val;
  11490. val = limit->rlim_max;
  11491. if (how & SOFT)
  11492. val = limit->rlim_cur;
  11493. if (val == RLIM_INFINITY)
  11494. out1fmt("unlimited\n");
  11495. else {
  11496. val >>= l->factor_shift;
  11497. out1fmt("%lld\n", (long long) val);
  11498. }
  11499. }
  11500. static int
  11501. ulimitcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
  11502. {
  11503. int c;
  11504. rlim_t val = 0;
  11505. enum limtype how = SOFT | HARD;
  11506. const struct limits *l;
  11507. int set, all = 0;
  11508. int optc, what;
  11509. struct rlimit limit;
  11510. what = 'f';
  11511. while ((optc = nextopt("HSa"
  11512. #ifdef RLIMIT_CPU
  11513. "t"
  11514. #endif
  11515. #ifdef RLIMIT_FSIZE
  11516. "f"
  11517. #endif
  11518. #ifdef RLIMIT_DATA
  11519. "d"
  11520. #endif
  11521. #ifdef RLIMIT_STACK
  11522. "s"
  11523. #endif
  11524. #ifdef RLIMIT_CORE
  11525. "c"
  11526. #endif
  11527. #ifdef RLIMIT_RSS
  11528. "m"
  11529. #endif
  11530. #ifdef RLIMIT_MEMLOCK
  11531. "l"
  11532. #endif
  11533. #ifdef RLIMIT_NPROC
  11534. "p"
  11535. #endif
  11536. #ifdef RLIMIT_NOFILE
  11537. "n"
  11538. #endif
  11539. #ifdef RLIMIT_AS
  11540. "v"
  11541. #endif
  11542. #ifdef RLIMIT_LOCKS
  11543. "w"
  11544. #endif
  11545. )) != '\0')
  11546. switch (optc) {
  11547. case 'H':
  11548. how = HARD;
  11549. break;
  11550. case 'S':
  11551. how = SOFT;
  11552. break;
  11553. case 'a':
  11554. all = 1;
  11555. break;
  11556. default:
  11557. what = optc;
  11558. }
  11559. for (l = limits_tbl; l->option != what; l++)
  11560. continue;
  11561. set = *argptr ? 1 : 0;
  11562. if (set) {
  11563. char *p = *argptr;
  11564. if (all || argptr[1])
  11565. ash_msg_and_raise_error("too many arguments");
  11566. if (strncmp(p, "unlimited\n", 9) == 0)
  11567. val = RLIM_INFINITY;
  11568. else {
  11569. val = (rlim_t) 0;
  11570. while ((c = *p++) >= '0' && c <= '9') {
  11571. val = (val * 10) + (long)(c - '0');
  11572. // val is actually 'unsigned long int' and can't get < 0
  11573. if (val < (rlim_t) 0)
  11574. break;
  11575. }
  11576. if (c)
  11577. ash_msg_and_raise_error("bad number");
  11578. val <<= l->factor_shift;
  11579. }
  11580. }
  11581. if (all) {
  11582. const char *lname = limits_name;
  11583. for (l = limits_tbl; l != &limits_tbl[ARRAY_SIZE(limits_tbl)]; l++) {
  11584. getrlimit(l->cmd, &limit);
  11585. out1fmt("%-20s ", lname);
  11586. lname += strlen(lname) + 1;
  11587. printlim(how, &limit, l);
  11588. }
  11589. return 0;
  11590. }
  11591. getrlimit(l->cmd, &limit);
  11592. if (set) {
  11593. if (how & HARD)
  11594. limit.rlim_max = val;
  11595. if (how & SOFT)
  11596. limit.rlim_cur = val;
  11597. if (setrlimit(l->cmd, &limit) < 0)
  11598. ash_msg_and_raise_error("error setting limit (%m)");
  11599. } else {
  11600. printlim(how, &limit, l);
  11601. }
  11602. return 0;
  11603. }
  11604. /* ============ Math support */
  11605. #if ENABLE_ASH_MATH_SUPPORT
  11606. /* Copyright (c) 2001 Aaron Lehmann <aaronl@vitelus.com>
  11607. Permission is hereby granted, free of charge, to any person obtaining
  11608. a copy of this software and associated documentation files (the
  11609. "Software"), to deal in the Software without restriction, including
  11610. without limitation the rights to use, copy, modify, merge, publish,
  11611. distribute, sublicense, and/or sell copies of the Software, and to
  11612. permit persons to whom the Software is furnished to do so, subject to
  11613. the following conditions:
  11614. The above copyright notice and this permission notice shall be
  11615. included in all copies or substantial portions of the Software.
  11616. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  11617. EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  11618. MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  11619. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
  11620. CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
  11621. TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
  11622. SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  11623. */
  11624. /* This is my infix parser/evaluator. It is optimized for size, intended
  11625. * as a replacement for yacc-based parsers. However, it may well be faster
  11626. * than a comparable parser written in yacc. The supported operators are
  11627. * listed in #defines below. Parens, order of operations, and error handling
  11628. * are supported. This code is thread safe. The exact expression format should
  11629. * be that which POSIX specifies for shells. */
  11630. /* The code uses a simple two-stack algorithm. See
  11631. * http://www.onthenet.com.au/~grahamis/int2008/week02/lect02.html
  11632. * for a detailed explanation of the infix-to-postfix algorithm on which
  11633. * this is based (this code differs in that it applies operators immediately
  11634. * to the stack instead of adding them to a queue to end up with an
  11635. * expression). */
  11636. /* To use the routine, call it with an expression string and error return
  11637. * pointer */
  11638. /*
  11639. * Aug 24, 2001 Manuel Novoa III
  11640. *
  11641. * Reduced the generated code size by about 30% (i386) and fixed several bugs.
  11642. *
  11643. * 1) In arith_apply():
  11644. * a) Cached values of *numptr and &(numptr[-1]).
  11645. * b) Removed redundant test for zero denominator.
  11646. *
  11647. * 2) In arith():
  11648. * a) Eliminated redundant code for processing operator tokens by moving
  11649. * to a table-based implementation. Also folded handling of parens
  11650. * into the table.
  11651. * b) Combined all 3 loops which called arith_apply to reduce generated
  11652. * code size at the cost of speed.
  11653. *
  11654. * 3) The following expressions were treated as valid by the original code:
  11655. * 1() , 0! , 1 ( *3 ) .
  11656. * These bugs have been fixed by internally enclosing the expression in
  11657. * parens and then checking that all binary ops and right parens are
  11658. * preceded by a valid expression (NUM_TOKEN).
  11659. *
  11660. * Note: It may be desirable to replace Aaron's test for whitespace with
  11661. * ctype's isspace() if it is used by another busybox applet or if additional
  11662. * whitespace chars should be considered. Look below the "#include"s for a
  11663. * precompiler test.
  11664. */
  11665. /*
  11666. * Aug 26, 2001 Manuel Novoa III
  11667. *
  11668. * Return 0 for null expressions. Pointed out by Vladimir Oleynik.
  11669. *
  11670. * Merge in Aaron's comments previously posted to the busybox list,
  11671. * modified slightly to take account of my changes to the code.
  11672. *
  11673. */
  11674. /*
  11675. * (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
  11676. *
  11677. * - allow access to variable,
  11678. * used recursive find value indirection (c=2*2; a="c"; $((a+=2)) produce 6)
  11679. * - realize assign syntax (VAR=expr, +=, *= etc)
  11680. * - realize exponentiation (** operator)
  11681. * - realize comma separated - expr, expr
  11682. * - realise ++expr --expr expr++ expr--
  11683. * - realise expr ? expr : expr (but, second expr calculate always)
  11684. * - allow hexadecimal and octal numbers
  11685. * - was restored loses XOR operator
  11686. * - remove one goto label, added three ;-)
  11687. * - protect $((num num)) as true zero expr (Manuel`s error)
  11688. * - always use special isspace(), see comment from bash ;-)
  11689. */
  11690. #define arith_isspace(arithval) \
  11691. (arithval == ' ' || arithval == '\n' || arithval == '\t')
  11692. typedef unsigned char operator;
  11693. /* An operator's token id is a bit of a bitfield. The lower 5 bits are the
  11694. * precedence, and 3 high bits are an ID unique across operators of that
  11695. * precedence. The ID portion is so that multiple operators can have the
  11696. * same precedence, ensuring that the leftmost one is evaluated first.
  11697. * Consider * and /. */
  11698. #define tok_decl(prec,id) (((id)<<5)|(prec))
  11699. #define PREC(op) ((op) & 0x1F)
  11700. #define TOK_LPAREN tok_decl(0,0)
  11701. #define TOK_COMMA tok_decl(1,0)
  11702. #define TOK_ASSIGN tok_decl(2,0)
  11703. #define TOK_AND_ASSIGN tok_decl(2,1)
  11704. #define TOK_OR_ASSIGN tok_decl(2,2)
  11705. #define TOK_XOR_ASSIGN tok_decl(2,3)
  11706. #define TOK_PLUS_ASSIGN tok_decl(2,4)
  11707. #define TOK_MINUS_ASSIGN tok_decl(2,5)
  11708. #define TOK_LSHIFT_ASSIGN tok_decl(2,6)
  11709. #define TOK_RSHIFT_ASSIGN tok_decl(2,7)
  11710. #define TOK_MUL_ASSIGN tok_decl(3,0)
  11711. #define TOK_DIV_ASSIGN tok_decl(3,1)
  11712. #define TOK_REM_ASSIGN tok_decl(3,2)
  11713. /* all assign is right associativity and precedence eq, but (7+3)<<5 > 256 */
  11714. #define convert_prec_is_assing(prec) do { if (prec == 3) prec = 2; } while (0)
  11715. /* conditional is right associativity too */
  11716. #define TOK_CONDITIONAL tok_decl(4,0)
  11717. #define TOK_CONDITIONAL_SEP tok_decl(4,1)
  11718. #define TOK_OR tok_decl(5,0)
  11719. #define TOK_AND tok_decl(6,0)
  11720. #define TOK_BOR tok_decl(7,0)
  11721. #define TOK_BXOR tok_decl(8,0)
  11722. #define TOK_BAND tok_decl(9,0)
  11723. #define TOK_EQ tok_decl(10,0)
  11724. #define TOK_NE tok_decl(10,1)
  11725. #define TOK_LT tok_decl(11,0)
  11726. #define TOK_GT tok_decl(11,1)
  11727. #define TOK_GE tok_decl(11,2)
  11728. #define TOK_LE tok_decl(11,3)
  11729. #define TOK_LSHIFT tok_decl(12,0)
  11730. #define TOK_RSHIFT tok_decl(12,1)
  11731. #define TOK_ADD tok_decl(13,0)
  11732. #define TOK_SUB tok_decl(13,1)
  11733. #define TOK_MUL tok_decl(14,0)
  11734. #define TOK_DIV tok_decl(14,1)
  11735. #define TOK_REM tok_decl(14,2)
  11736. /* exponent is right associativity */
  11737. #define TOK_EXPONENT tok_decl(15,1)
  11738. /* For now unary operators. */
  11739. #define UNARYPREC 16
  11740. #define TOK_BNOT tok_decl(UNARYPREC,0)
  11741. #define TOK_NOT tok_decl(UNARYPREC,1)
  11742. #define TOK_UMINUS tok_decl(UNARYPREC+1,0)
  11743. #define TOK_UPLUS tok_decl(UNARYPREC+1,1)
  11744. #define PREC_PRE (UNARYPREC+2)
  11745. #define TOK_PRE_INC tok_decl(PREC_PRE, 0)
  11746. #define TOK_PRE_DEC tok_decl(PREC_PRE, 1)
  11747. #define PREC_POST (UNARYPREC+3)
  11748. #define TOK_POST_INC tok_decl(PREC_POST, 0)
  11749. #define TOK_POST_DEC tok_decl(PREC_POST, 1)
  11750. #define SPEC_PREC (UNARYPREC+4)
  11751. #define TOK_NUM tok_decl(SPEC_PREC, 0)
  11752. #define TOK_RPAREN tok_decl(SPEC_PREC, 1)
  11753. #define NUMPTR (*numstackptr)
  11754. static int
  11755. tok_have_assign(operator op)
  11756. {
  11757. operator prec = PREC(op);
  11758. convert_prec_is_assing(prec);
  11759. return (prec == PREC(TOK_ASSIGN) ||
  11760. prec == PREC_PRE || prec == PREC_POST);
  11761. }
  11762. static int
  11763. is_right_associativity(operator prec)
  11764. {
  11765. return (prec == PREC(TOK_ASSIGN) || prec == PREC(TOK_EXPONENT)
  11766. || prec == PREC(TOK_CONDITIONAL));
  11767. }
  11768. typedef struct {
  11769. arith_t val;
  11770. arith_t contidional_second_val;
  11771. char contidional_second_val_initialized;
  11772. char *var; /* if NULL then is regular number,
  11773. else is variable name */
  11774. } v_n_t;
  11775. typedef struct chk_var_recursive_looped_t {
  11776. const char *var;
  11777. struct chk_var_recursive_looped_t *next;
  11778. } chk_var_recursive_looped_t;
  11779. static chk_var_recursive_looped_t *prev_chk_var_recursive;
  11780. static int
  11781. arith_lookup_val(v_n_t *t)
  11782. {
  11783. if (t->var) {
  11784. const char * p = lookupvar(t->var);
  11785. if (p) {
  11786. int errcode;
  11787. /* recursive try as expression */
  11788. chk_var_recursive_looped_t *cur;
  11789. chk_var_recursive_looped_t cur_save;
  11790. for (cur = prev_chk_var_recursive; cur; cur = cur->next) {
  11791. if (strcmp(cur->var, t->var) == 0) {
  11792. /* expression recursion loop detected */
  11793. return -5;
  11794. }
  11795. }
  11796. /* save current lookuped var name */
  11797. cur = prev_chk_var_recursive;
  11798. cur_save.var = t->var;
  11799. cur_save.next = cur;
  11800. prev_chk_var_recursive = &cur_save;
  11801. t->val = arith (p, &errcode);
  11802. /* restore previous ptr after recursiving */
  11803. prev_chk_var_recursive = cur;
  11804. return errcode;
  11805. }
  11806. /* allow undefined var as 0 */
  11807. t->val = 0;
  11808. }
  11809. return 0;
  11810. }
  11811. /* "applying" a token means performing it on the top elements on the integer
  11812. * stack. For a unary operator it will only change the top element, but a
  11813. * binary operator will pop two arguments and push a result */
  11814. static int
  11815. arith_apply(operator op, v_n_t *numstack, v_n_t **numstackptr)
  11816. {
  11817. v_n_t *numptr_m1;
  11818. arith_t numptr_val, rez;
  11819. int ret_arith_lookup_val;
  11820. /* There is no operator that can work without arguments */
  11821. if (NUMPTR == numstack) goto err;
  11822. numptr_m1 = NUMPTR - 1;
  11823. /* check operand is var with noninteger value */
  11824. ret_arith_lookup_val = arith_lookup_val(numptr_m1);
  11825. if (ret_arith_lookup_val)
  11826. return ret_arith_lookup_val;
  11827. rez = numptr_m1->val;
  11828. if (op == TOK_UMINUS)
  11829. rez *= -1;
  11830. else if (op == TOK_NOT)
  11831. rez = !rez;
  11832. else if (op == TOK_BNOT)
  11833. rez = ~rez;
  11834. else if (op == TOK_POST_INC || op == TOK_PRE_INC)
  11835. rez++;
  11836. else if (op == TOK_POST_DEC || op == TOK_PRE_DEC)
  11837. rez--;
  11838. else if (op != TOK_UPLUS) {
  11839. /* Binary operators */
  11840. /* check and binary operators need two arguments */
  11841. if (numptr_m1 == numstack) goto err;
  11842. /* ... and they pop one */
  11843. --NUMPTR;
  11844. numptr_val = rez;
  11845. if (op == TOK_CONDITIONAL) {
  11846. if (!numptr_m1->contidional_second_val_initialized) {
  11847. /* protect $((expr1 ? expr2)) without ": expr" */
  11848. goto err;
  11849. }
  11850. rez = numptr_m1->contidional_second_val;
  11851. } else if (numptr_m1->contidional_second_val_initialized) {
  11852. /* protect $((expr1 : expr2)) without "expr ? " */
  11853. goto err;
  11854. }
  11855. numptr_m1 = NUMPTR - 1;
  11856. if (op != TOK_ASSIGN) {
  11857. /* check operand is var with noninteger value for not '=' */
  11858. ret_arith_lookup_val = arith_lookup_val(numptr_m1);
  11859. if (ret_arith_lookup_val)
  11860. return ret_arith_lookup_val;
  11861. }
  11862. if (op == TOK_CONDITIONAL) {
  11863. numptr_m1->contidional_second_val = rez;
  11864. }
  11865. rez = numptr_m1->val;
  11866. if (op == TOK_BOR || op == TOK_OR_ASSIGN)
  11867. rez |= numptr_val;
  11868. else if (op == TOK_OR)
  11869. rez = numptr_val || rez;
  11870. else if (op == TOK_BAND || op == TOK_AND_ASSIGN)
  11871. rez &= numptr_val;
  11872. else if (op == TOK_BXOR || op == TOK_XOR_ASSIGN)
  11873. rez ^= numptr_val;
  11874. else if (op == TOK_AND)
  11875. rez = rez && numptr_val;
  11876. else if (op == TOK_EQ)
  11877. rez = (rez == numptr_val);
  11878. else if (op == TOK_NE)
  11879. rez = (rez != numptr_val);
  11880. else if (op == TOK_GE)
  11881. rez = (rez >= numptr_val);
  11882. else if (op == TOK_RSHIFT || op == TOK_RSHIFT_ASSIGN)
  11883. rez >>= numptr_val;
  11884. else if (op == TOK_LSHIFT || op == TOK_LSHIFT_ASSIGN)
  11885. rez <<= numptr_val;
  11886. else if (op == TOK_GT)
  11887. rez = (rez > numptr_val);
  11888. else if (op == TOK_LT)
  11889. rez = (rez < numptr_val);
  11890. else if (op == TOK_LE)
  11891. rez = (rez <= numptr_val);
  11892. else if (op == TOK_MUL || op == TOK_MUL_ASSIGN)
  11893. rez *= numptr_val;
  11894. else if (op == TOK_ADD || op == TOK_PLUS_ASSIGN)
  11895. rez += numptr_val;
  11896. else if (op == TOK_SUB || op == TOK_MINUS_ASSIGN)
  11897. rez -= numptr_val;
  11898. else if (op == TOK_ASSIGN || op == TOK_COMMA)
  11899. rez = numptr_val;
  11900. else if (op == TOK_CONDITIONAL_SEP) {
  11901. if (numptr_m1 == numstack) {
  11902. /* protect $((expr : expr)) without "expr ? " */
  11903. goto err;
  11904. }
  11905. numptr_m1->contidional_second_val_initialized = op;
  11906. numptr_m1->contidional_second_val = numptr_val;
  11907. } else if (op == TOK_CONDITIONAL) {
  11908. rez = rez ?
  11909. numptr_val : numptr_m1->contidional_second_val;
  11910. } else if (op == TOK_EXPONENT) {
  11911. if (numptr_val < 0)
  11912. return -3; /* exponent less than 0 */
  11913. else {
  11914. arith_t c = 1;
  11915. if (numptr_val)
  11916. while (numptr_val--)
  11917. c *= rez;
  11918. rez = c;
  11919. }
  11920. } else if (numptr_val==0) /* zero divisor check */
  11921. return -2;
  11922. else if (op == TOK_DIV || op == TOK_DIV_ASSIGN)
  11923. rez /= numptr_val;
  11924. else if (op == TOK_REM || op == TOK_REM_ASSIGN)
  11925. rez %= numptr_val;
  11926. }
  11927. if (tok_have_assign(op)) {
  11928. char buf[sizeof(arith_t_type)*3 + 2];
  11929. if (numptr_m1->var == NULL) {
  11930. /* Hmm, 1=2 ? */
  11931. goto err;
  11932. }
  11933. /* save to shell variable */
  11934. #if ENABLE_ASH_MATH_SUPPORT_64
  11935. snprintf(buf, sizeof(buf), "%lld", (arith_t_type) rez);
  11936. #else
  11937. snprintf(buf, sizeof(buf), "%ld", (arith_t_type) rez);
  11938. #endif
  11939. setvar(numptr_m1->var, buf, 0);
  11940. /* after saving, make previous value for v++ or v-- */
  11941. if (op == TOK_POST_INC)
  11942. rez--;
  11943. else if (op == TOK_POST_DEC)
  11944. rez++;
  11945. }
  11946. numptr_m1->val = rez;
  11947. /* protect geting var value, is number now */
  11948. numptr_m1->var = NULL;
  11949. return 0;
  11950. err:
  11951. return -1;
  11952. }
  11953. /* longest must be first */
  11954. static const char op_tokens[] ALIGN1 = {
  11955. '<','<','=',0, TOK_LSHIFT_ASSIGN,
  11956. '>','>','=',0, TOK_RSHIFT_ASSIGN,
  11957. '<','<', 0, TOK_LSHIFT,
  11958. '>','>', 0, TOK_RSHIFT,
  11959. '|','|', 0, TOK_OR,
  11960. '&','&', 0, TOK_AND,
  11961. '!','=', 0, TOK_NE,
  11962. '<','=', 0, TOK_LE,
  11963. '>','=', 0, TOK_GE,
  11964. '=','=', 0, TOK_EQ,
  11965. '|','=', 0, TOK_OR_ASSIGN,
  11966. '&','=', 0, TOK_AND_ASSIGN,
  11967. '*','=', 0, TOK_MUL_ASSIGN,
  11968. '/','=', 0, TOK_DIV_ASSIGN,
  11969. '%','=', 0, TOK_REM_ASSIGN,
  11970. '+','=', 0, TOK_PLUS_ASSIGN,
  11971. '-','=', 0, TOK_MINUS_ASSIGN,
  11972. '-','-', 0, TOK_POST_DEC,
  11973. '^','=', 0, TOK_XOR_ASSIGN,
  11974. '+','+', 0, TOK_POST_INC,
  11975. '*','*', 0, TOK_EXPONENT,
  11976. '!', 0, TOK_NOT,
  11977. '<', 0, TOK_LT,
  11978. '>', 0, TOK_GT,
  11979. '=', 0, TOK_ASSIGN,
  11980. '|', 0, TOK_BOR,
  11981. '&', 0, TOK_BAND,
  11982. '*', 0, TOK_MUL,
  11983. '/', 0, TOK_DIV,
  11984. '%', 0, TOK_REM,
  11985. '+', 0, TOK_ADD,
  11986. '-', 0, TOK_SUB,
  11987. '^', 0, TOK_BXOR,
  11988. /* uniq */
  11989. '~', 0, TOK_BNOT,
  11990. ',', 0, TOK_COMMA,
  11991. '?', 0, TOK_CONDITIONAL,
  11992. ':', 0, TOK_CONDITIONAL_SEP,
  11993. ')', 0, TOK_RPAREN,
  11994. '(', 0, TOK_LPAREN,
  11995. 0
  11996. };
  11997. /* ptr to ")" */
  11998. #define endexpression (&op_tokens[sizeof(op_tokens)-7])
  11999. static arith_t
  12000. arith(const char *expr, int *perrcode)
  12001. {
  12002. char arithval; /* Current character under analysis */
  12003. operator lasttok, op;
  12004. operator prec;
  12005. operator *stack, *stackptr;
  12006. const char *p = endexpression;
  12007. int errcode;
  12008. v_n_t *numstack, *numstackptr;
  12009. unsigned datasizes = strlen(expr) + 2;
  12010. /* Stack of integers */
  12011. /* The proof that there can be no more than strlen(startbuf)/2+1 integers
  12012. * in any given correct or incorrect expression is left as an exercise to
  12013. * the reader. */
  12014. numstackptr = numstack = alloca((datasizes / 2) * sizeof(numstack[0]));
  12015. /* Stack of operator tokens */
  12016. stackptr = stack = alloca(datasizes * sizeof(stack[0]));
  12017. *stackptr++ = lasttok = TOK_LPAREN; /* start off with a left paren */
  12018. *perrcode = errcode = 0;
  12019. while (1) {
  12020. arithval = *expr;
  12021. if (arithval == 0) {
  12022. if (p == endexpression) {
  12023. /* Null expression. */
  12024. return 0;
  12025. }
  12026. /* This is only reached after all tokens have been extracted from the
  12027. * input stream. If there are still tokens on the operator stack, they
  12028. * are to be applied in order. At the end, there should be a final
  12029. * result on the integer stack */
  12030. if (expr != endexpression + 1) {
  12031. /* If we haven't done so already, */
  12032. /* append a closing right paren */
  12033. expr = endexpression;
  12034. /* and let the loop process it. */
  12035. continue;
  12036. }
  12037. /* At this point, we're done with the expression. */
  12038. if (numstackptr != numstack+1) {
  12039. /* ... but if there isn't, it's bad */
  12040. err:
  12041. *perrcode = -1;
  12042. return *perrcode;
  12043. }
  12044. if (numstack->var) {
  12045. /* expression is $((var)) only, lookup now */
  12046. errcode = arith_lookup_val(numstack);
  12047. }
  12048. ret:
  12049. *perrcode = errcode;
  12050. return numstack->val;
  12051. }
  12052. /* Continue processing the expression. */
  12053. if (arith_isspace(arithval)) {
  12054. /* Skip whitespace */
  12055. goto prologue;
  12056. }
  12057. p = endofname(expr);
  12058. if (p != expr) {
  12059. size_t var_name_size = (p-expr) + 1; /* trailing zero */
  12060. numstackptr->var = alloca(var_name_size);
  12061. safe_strncpy(numstackptr->var, expr, var_name_size);
  12062. expr = p;
  12063. num:
  12064. numstackptr->contidional_second_val_initialized = 0;
  12065. numstackptr++;
  12066. lasttok = TOK_NUM;
  12067. continue;
  12068. }
  12069. if (isdigit(arithval)) {
  12070. numstackptr->var = NULL;
  12071. #if ENABLE_ASH_MATH_SUPPORT_64
  12072. numstackptr->val = strtoll(expr, (char **) &expr, 0);
  12073. #else
  12074. numstackptr->val = strtol(expr, (char **) &expr, 0);
  12075. #endif
  12076. goto num;
  12077. }
  12078. for (p = op_tokens; ; p++) {
  12079. const char *o;
  12080. if (*p == 0) {
  12081. /* strange operator not found */
  12082. goto err;
  12083. }
  12084. for (o = expr; *p && *o == *p; p++)
  12085. o++;
  12086. if (!*p) {
  12087. /* found */
  12088. expr = o - 1;
  12089. break;
  12090. }
  12091. /* skip tail uncompared token */
  12092. while (*p)
  12093. p++;
  12094. /* skip zero delim */
  12095. p++;
  12096. }
  12097. op = p[1];
  12098. /* post grammar: a++ reduce to num */
  12099. if (lasttok == TOK_POST_INC || lasttok == TOK_POST_DEC)
  12100. lasttok = TOK_NUM;
  12101. /* Plus and minus are binary (not unary) _only_ if the last
  12102. * token was as number, or a right paren (which pretends to be
  12103. * a number, since it evaluates to one). Think about it.
  12104. * It makes sense. */
  12105. if (lasttok != TOK_NUM) {
  12106. switch (op) {
  12107. case TOK_ADD:
  12108. op = TOK_UPLUS;
  12109. break;
  12110. case TOK_SUB:
  12111. op = TOK_UMINUS;
  12112. break;
  12113. case TOK_POST_INC:
  12114. op = TOK_PRE_INC;
  12115. break;
  12116. case TOK_POST_DEC:
  12117. op = TOK_PRE_DEC;
  12118. break;
  12119. }
  12120. }
  12121. /* We don't want a unary operator to cause recursive descent on the
  12122. * stack, because there can be many in a row and it could cause an
  12123. * operator to be evaluated before its argument is pushed onto the
  12124. * integer stack. */
  12125. /* But for binary operators, "apply" everything on the operator
  12126. * stack until we find an operator with a lesser priority than the
  12127. * one we have just extracted. */
  12128. /* Left paren is given the lowest priority so it will never be
  12129. * "applied" in this way.
  12130. * if associativity is right and priority eq, applied also skip
  12131. */
  12132. prec = PREC(op);
  12133. if ((prec > 0 && prec < UNARYPREC) || prec == SPEC_PREC) {
  12134. /* not left paren or unary */
  12135. if (lasttok != TOK_NUM) {
  12136. /* binary op must be preceded by a num */
  12137. goto err;
  12138. }
  12139. while (stackptr != stack) {
  12140. if (op == TOK_RPAREN) {
  12141. /* The algorithm employed here is simple: while we don't
  12142. * hit an open paren nor the bottom of the stack, pop
  12143. * tokens and apply them */
  12144. if (stackptr[-1] == TOK_LPAREN) {
  12145. --stackptr;
  12146. /* Any operator directly after a */
  12147. lasttok = TOK_NUM;
  12148. /* close paren should consider itself binary */
  12149. goto prologue;
  12150. }
  12151. } else {
  12152. operator prev_prec = PREC(stackptr[-1]);
  12153. convert_prec_is_assing(prec);
  12154. convert_prec_is_assing(prev_prec);
  12155. if (prev_prec < prec)
  12156. break;
  12157. /* check right assoc */
  12158. if (prev_prec == prec && is_right_associativity(prec))
  12159. break;
  12160. }
  12161. errcode = arith_apply(*--stackptr, numstack, &numstackptr);
  12162. if (errcode) goto ret;
  12163. }
  12164. if (op == TOK_RPAREN) {
  12165. goto err;
  12166. }
  12167. }
  12168. /* Push this operator to the stack and remember it. */
  12169. *stackptr++ = lasttok = op;
  12170. prologue:
  12171. ++expr;
  12172. } /* while */
  12173. }
  12174. #endif /* ASH_MATH_SUPPORT */
  12175. /* ============ main() and helpers */
  12176. /*
  12177. * Called to exit the shell.
  12178. */
  12179. static void exitshell(void) NORETURN;
  12180. static void
  12181. exitshell(void)
  12182. {
  12183. struct jmploc loc;
  12184. char *p;
  12185. int status;
  12186. status = exitstatus;
  12187. TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
  12188. if (setjmp(loc.loc)) {
  12189. if (exception == EXEXIT)
  12190. /* dash bug: it just does _exit(exitstatus) here
  12191. * but we have to do setjobctl(0) first!
  12192. * (bug is still not fixed in dash-0.5.3 - if you run dash
  12193. * under Midnight Commander, on exit from dash MC is backgrounded) */
  12194. status = exitstatus;
  12195. goto out;
  12196. }
  12197. exception_handler = &loc;
  12198. p = trap[0];
  12199. if (p) {
  12200. trap[0] = NULL;
  12201. evalstring(p, 0);
  12202. }
  12203. flush_stdout_stderr();
  12204. out:
  12205. setjobctl(0);
  12206. _exit(status);
  12207. /* NOTREACHED */
  12208. }
  12209. static void
  12210. init(void)
  12211. {
  12212. /* from input.c: */
  12213. basepf.nextc = basepf.buf = basebuf;
  12214. /* from trap.c: */
  12215. signal(SIGCHLD, SIG_DFL);
  12216. /* from var.c: */
  12217. {
  12218. char **envp;
  12219. char ppid[sizeof(int)*3 + 1];
  12220. const char *p;
  12221. struct stat st1, st2;
  12222. initvar();
  12223. for (envp = environ; envp && *envp; envp++) {
  12224. if (strchr(*envp, '=')) {
  12225. setvareq(*envp, VEXPORT|VTEXTFIXED);
  12226. }
  12227. }
  12228. snprintf(ppid, sizeof(ppid), "%u", (unsigned) getppid());
  12229. setvar("PPID", ppid, 0);
  12230. p = lookupvar("PWD");
  12231. if (p)
  12232. if (*p != '/' || stat(p, &st1) || stat(".", &st2)
  12233. || st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)
  12234. p = '\0';
  12235. setpwd(p, 0);
  12236. }
  12237. }
  12238. /*
  12239. * Process the shell command line arguments.
  12240. */
  12241. static void
  12242. procargs(char **argv)
  12243. {
  12244. int i;
  12245. const char *xminusc;
  12246. char **xargv;
  12247. xargv = argv;
  12248. arg0 = xargv[0];
  12249. /* if (xargv[0]) - mmm, this is always true! */
  12250. xargv++;
  12251. for (i = 0; i < NOPTS; i++)
  12252. optlist[i] = 2;
  12253. argptr = xargv;
  12254. if (options(1)) {
  12255. /* it already printed err message */
  12256. raise_exception(EXERROR);
  12257. }
  12258. xargv = argptr;
  12259. xminusc = minusc;
  12260. if (*xargv == NULL) {
  12261. if (xminusc)
  12262. ash_msg_and_raise_error(bb_msg_requires_arg, "-c");
  12263. sflag = 1;
  12264. }
  12265. if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
  12266. iflag = 1;
  12267. if (mflag == 2)
  12268. mflag = iflag;
  12269. for (i = 0; i < NOPTS; i++)
  12270. if (optlist[i] == 2)
  12271. optlist[i] = 0;
  12272. #if DEBUG == 2
  12273. debug = 1;
  12274. #endif
  12275. /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
  12276. if (xminusc) {
  12277. minusc = *xargv++;
  12278. if (*xargv)
  12279. goto setarg0;
  12280. } else if (!sflag) {
  12281. setinputfile(*xargv, 0);
  12282. setarg0:
  12283. arg0 = *xargv++;
  12284. commandname = arg0;
  12285. }
  12286. shellparam.p = xargv;
  12287. #if ENABLE_ASH_GETOPTS
  12288. shellparam.optind = 1;
  12289. shellparam.optoff = -1;
  12290. #endif
  12291. /* assert(shellparam.malloced == 0 && shellparam.nparam == 0); */
  12292. while (*xargv) {
  12293. shellparam.nparam++;
  12294. xargv++;
  12295. }
  12296. optschanged();
  12297. }
  12298. /*
  12299. * Read /etc/profile or .profile.
  12300. */
  12301. static void
  12302. read_profile(const char *name)
  12303. {
  12304. int skip;
  12305. if (setinputfile(name, INPUT_PUSH_FILE | INPUT_NOFILE_OK) < 0)
  12306. return;
  12307. skip = cmdloop(0);
  12308. popfile();
  12309. if (skip)
  12310. exitshell();
  12311. }
  12312. /*
  12313. * This routine is called when an error or an interrupt occurs in an
  12314. * interactive shell and control is returned to the main command loop.
  12315. */
  12316. static void
  12317. reset(void)
  12318. {
  12319. /* from eval.c: */
  12320. evalskip = 0;
  12321. loopnest = 0;
  12322. /* from input.c: */
  12323. parselleft = parsenleft = 0; /* clear input buffer */
  12324. popallfiles();
  12325. /* from parser.c: */
  12326. tokpushback = 0;
  12327. checkkwd = 0;
  12328. /* from redir.c: */
  12329. clearredir(/*drop:*/ 0);
  12330. }
  12331. #if PROFILE
  12332. static short profile_buf[16384];
  12333. extern int etext();
  12334. #endif
  12335. /*
  12336. * Main routine. We initialize things, parse the arguments, execute
  12337. * profiles if we're a login shell, and then call cmdloop to execute
  12338. * commands. The setjmp call sets up the location to jump to when an
  12339. * exception occurs. When an exception occurs the variable "state"
  12340. * is used to figure out how far we had gotten.
  12341. */
  12342. int ash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  12343. int ash_main(int argc UNUSED_PARAM, char **argv)
  12344. {
  12345. char *shinit;
  12346. volatile int state;
  12347. struct jmploc jmploc;
  12348. struct stackmark smark;
  12349. /* Initialize global data */
  12350. INIT_G_misc();
  12351. INIT_G_memstack();
  12352. INIT_G_var();
  12353. #if ENABLE_ASH_ALIAS
  12354. INIT_G_alias();
  12355. #endif
  12356. INIT_G_cmdtable();
  12357. #if PROFILE
  12358. monitor(4, etext, profile_buf, sizeof(profile_buf), 50);
  12359. #endif
  12360. #if ENABLE_FEATURE_EDITING
  12361. line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
  12362. #endif
  12363. state = 0;
  12364. if (setjmp(jmploc.loc)) {
  12365. int e;
  12366. int s;
  12367. reset();
  12368. e = exception;
  12369. if (e == EXERROR)
  12370. exitstatus = 2;
  12371. s = state;
  12372. if (e == EXEXIT || s == 0 || iflag == 0 || shlvl)
  12373. exitshell();
  12374. if (e == EXINT) {
  12375. outcslow('\n', stderr);
  12376. }
  12377. popstackmark(&smark);
  12378. FORCE_INT_ON; /* enable interrupts */
  12379. if (s == 1)
  12380. goto state1;
  12381. if (s == 2)
  12382. goto state2;
  12383. if (s == 3)
  12384. goto state3;
  12385. goto state4;
  12386. }
  12387. exception_handler = &jmploc;
  12388. #if DEBUG
  12389. opentrace();
  12390. trace_puts("Shell args: ");
  12391. trace_puts_args(argv);
  12392. #endif
  12393. rootpid = getpid();
  12394. #if ENABLE_ASH_RANDOM_SUPPORT
  12395. /* Can use monotonic_ns() for better randomness but for now it is
  12396. * not used anywhere else in busybox... so avoid bloat */
  12397. random_galois_LFSR = random_LCG = rootpid + monotonic_us();
  12398. #endif
  12399. init();
  12400. setstackmark(&smark);
  12401. procargs(argv);
  12402. #if ENABLE_FEATURE_EDITING_SAVEHISTORY
  12403. if (iflag) {
  12404. const char *hp = lookupvar("HISTFILE");
  12405. if (hp == NULL) {
  12406. hp = lookupvar("HOME");
  12407. if (hp != NULL) {
  12408. char *defhp = concat_path_file(hp, ".ash_history");
  12409. setvar("HISTFILE", defhp, 0);
  12410. free(defhp);
  12411. }
  12412. }
  12413. }
  12414. #endif
  12415. if (argv[0] && argv[0][0] == '-')
  12416. isloginsh = 1;
  12417. if (isloginsh) {
  12418. state = 1;
  12419. read_profile("/etc/profile");
  12420. state1:
  12421. state = 2;
  12422. read_profile(".profile");
  12423. }
  12424. state2:
  12425. state = 3;
  12426. if (
  12427. #ifndef linux
  12428. getuid() == geteuid() && getgid() == getegid() &&
  12429. #endif
  12430. iflag
  12431. ) {
  12432. shinit = lookupvar("ENV");
  12433. if (shinit != NULL && *shinit != '\0') {
  12434. read_profile(shinit);
  12435. }
  12436. }
  12437. state3:
  12438. state = 4;
  12439. if (minusc)
  12440. evalstring(minusc, 0);
  12441. if (sflag || minusc == NULL) {
  12442. #if ENABLE_FEATURE_EDITING_SAVEHISTORY
  12443. if (iflag) {
  12444. const char *hp = lookupvar("HISTFILE");
  12445. if (hp != NULL)
  12446. line_input_state->hist_file = hp;
  12447. }
  12448. #endif
  12449. state4: /* XXX ??? - why isn't this before the "if" statement */
  12450. cmdloop(1);
  12451. }
  12452. #if PROFILE
  12453. monitor(0);
  12454. #endif
  12455. #ifdef GPROF
  12456. {
  12457. extern void _mcleanup(void);
  12458. _mcleanup();
  12459. }
  12460. #endif
  12461. exitshell();
  12462. /* NOTREACHED */
  12463. }
  12464. #if DEBUG
  12465. const char *applet_name = "debug stuff usage";
  12466. int main(int argc, char **argv)
  12467. {
  12468. return ash_main(argc, argv);
  12469. }
  12470. #endif
  12471. /*-
  12472. * Copyright (c) 1989, 1991, 1993, 1994
  12473. * The Regents of the University of California. All rights reserved.
  12474. *
  12475. * This code is derived from software contributed to Berkeley by
  12476. * Kenneth Almquist.
  12477. *
  12478. * Redistribution and use in source and binary forms, with or without
  12479. * modification, are permitted provided that the following conditions
  12480. * are met:
  12481. * 1. Redistributions of source code must retain the above copyright
  12482. * notice, this list of conditions and the following disclaimer.
  12483. * 2. Redistributions in binary form must reproduce the above copyright
  12484. * notice, this list of conditions and the following disclaimer in the
  12485. * documentation and/or other materials provided with the distribution.
  12486. * 3. Neither the name of the University nor the names of its contributors
  12487. * may be used to endorse or promote products derived from this software
  12488. * without specific prior written permission.
  12489. *
  12490. * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
  12491. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  12492. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  12493. * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
  12494. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  12495. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  12496. * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  12497. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  12498. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  12499. * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  12500. * SUCH DAMAGE.
  12501. */